Refactors project structure for improved modularity

Moves components and modules to more appropriate directories.

This change improves project organization and maintainability by grouping related files into logical directories, enhancing code discoverability and reducing potential naming conflicts.
This commit is contained in:
AlexKucera committed 2025-09-03 22:05:45 +02:00
1 parent f05ffa8bc8
commit 3f8f2b2089
16 files changed
+21 -21

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
/**
* Behavior Section for Export Configuration Modal
* Handles export behavior options like opening after export and preserving folder structure
*/
import { Setting } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
export class BehaviorSection implements ModalSection {
private container: HTMLElement | null = null;
render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Export Behavior' });
this.createBehaviorToggles(state);
}
private createBehaviorToggles(state: ModalState): void {
if (!this.container) return;
// Open after export toggle
new Setting(this.container)
.setName('Open after export')
.setDesc('Automatically open the PDF file after successful export')
.addToggle(toggle => {
toggle
.setValue(state.settings.openAfterExport || false)
.onChange(value => {
state.updateSettings({ openAfterExport: value });
});
});
// Preserve folder structure toggle
new Setting(this.container)
.setName('Preserve folder structure')
.setDesc('Maintain the original folder structure when exporting multiple files')
.addToggle(toggle => {
toggle
.setValue(state.settings.preserveFolderStructure || false)
.onChange(value => {
state.updateSettings({ preserveFolderStructure: value });
});
});
}
validate(): ValidationResult {
const errors: string[] = [];
const warnings: string[] = [];
// No validation needed for simple boolean toggles
return {
isValid: errors.length === 0,
errors,
warnings
};
}
getId(): string {
return 'behavior';
}
}
+147
View File
@@ -0,0 +1,147 @@
/**
* General Section for Export Configuration Modal
* Handles template selection, format options, and output settings
*/
import { Setting, App } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
import { ExportFormat } from '../../../core/settings';
import { FolderSuggest } from '../../components/FolderSuggest';
export class GeneralSection implements ModalSection {
private container: HTMLElement | null = null;
private templateDropdown: any = null;
private outputFolderInput: HTMLInputElement | null = null;
private app: App;
render(containerEl: HTMLElement, state: ModalState, app?: App): void {
if (app) this.app = app;
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'General Settings' });
this.createTemplateSelection(state);
this.createFormatSelection(state);
this.createOutputSettings(state);
}
private createTemplateSelection(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('Typst template')
.setDesc('Select template for document styling')
.addDropdown(dropdown => {
// Filter out universal-wrapper.pandoc.typ and populate with available templates
const filteredTemplates = state.settings.availableTemplates
.filter(template => template !== 'universal-wrapper.pandoc.typ');
filteredTemplates.forEach(template => {
dropdown.addOption(template, this.getTemplateDisplayName(template));
});
dropdown
.setValue(state.settings.template || 'default.typ')
.onChange(value => {
state.updateSettings({ template: value });
});
this.templateDropdown = dropdown;
});
}
private createFormatSelection(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('PDF format')
.setDesc('Choose document layout format')
.addDropdown(dropdown => {
dropdown
.addOption(ExportFormat.Standard, 'Standard (multi-page PDF)')
.addOption(ExportFormat.SinglePage, 'Single-page (continuous layout)')
.setValue(state.settings.format || ExportFormat.Standard)
.onChange(value => {
state.updateSettings({ format: value as ExportFormat });
});
});
}
private createOutputSettings(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('Output folder')
.setDesc('Folder where PDFs will be saved (relative to vault root)')
.addText(text => {
const input = text
.setPlaceholder('exports')
.setValue(state.settings.outputFolder || 'exports')
.onChange(value => {
state.updateSettings({ outputFolder: value });
});
this.outputFolderInput = input.inputEl;
// Add folder autosuggest
if (this.app) {
new FolderSuggest(this.app, input.inputEl);
}
});
}
private getTemplateDisplayName(template: string): string {
// Remove extension and capitalize
const name = template.replace(/\.(typ|pandoc\.typ)$/, '');
return name.charAt(0).toUpperCase() + name.slice(1).replace(/-/g, ' ');
}
validate(): ValidationResult {
const errors: string[] = [];
const warnings: string[] = [];
// Validate output folder
if (this.outputFolderInput) {
const value = this.outputFolderInput.value.trim();
if (!value) {
errors.push('Output folder is required');
} else if (value.startsWith('/') || value.startsWith('\\')) {
warnings.push('Output folder should be relative to vault root');
}
}
// Check template selection
if (!this.templateDropdown || !this.templateDropdown.getValue()) {
errors.push('Template selection is required');
}
return {
isValid: errors.length === 0,
errors,
warnings
};
}
updateAvailableTemplates(templates: string[]): void {
if (!this.templateDropdown) return;
const currentValue = this.templateDropdown.getValue();
// Filter out universal-wrapper.pandoc.typ and clear/repopulate dropdown
const filteredTemplates = templates.filter(template => template !== 'universal-wrapper.pandoc.typ');
this.templateDropdown.selectEl.empty();
filteredTemplates.forEach(template => {
this.templateDropdown.addOption(template, this.getTemplateDisplayName(template));
});
// Restore selection if still available
if (filteredTemplates.includes(currentValue)) {
this.templateDropdown.setValue(currentValue);
} else if (filteredTemplates.length > 0) {
this.templateDropdown.setValue(filteredTemplates[0]);
}
}
getId(): string {
return 'general';
}
}
+159
View File
@@ -0,0 +1,159 @@
/**
* Layout Section for Export Configuration Modal
* Handles page setup, orientation, and margins
*/
import { Setting } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
import { SUPPORTED_PAPER_SIZES } from '../../../utils/paperSizeMapper';
export class LayoutSection implements ModalSection {
private container: HTMLElement | null = null;
private marginInputs: Map<string, number> = new Map();
render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Page Layout' });
this.createPageSizeSettings(state);
this.createOrientationSettings(state);
this.createMarginSettings(state);
}
private createPageSizeSettings(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('Page size')
.setDesc('Standard page sizes for the PDF document')
.addDropdown(dropdown => {
// Add all supported paper sizes
SUPPORTED_PAPER_SIZES.forEach(paperSize => {
dropdown.addOption(paperSize.key, paperSize.displayName);
});
dropdown
.setValue('a4') // Default to A4
.onChange(value => {
state.updateTemplateVariables({ pageSize: value });
});
});
}
private createOrientationSettings(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('Orientation')
.setDesc('Page orientation for the document')
.addDropdown(dropdown => {
dropdown
.addOption('portrait', 'Portrait')
.addOption('landscape', 'Landscape')
.setValue('portrait')
.onChange(value => {
state.updateTemplateVariables({ orientation: value });
});
});
}
private createMarginSettings(state: ModalState): void {
if (!this.container) return;
const marginsContainer = this.container.createDiv('margins-container');
marginsContainer.createEl('h4', { text: 'Margins' });
const marginDefaults = {
top: 72,
bottom: 57,
left: 72,
right: 43
};
// Create margin sliders
['top', 'bottom', 'left', 'right'].forEach(side => {
new Setting(marginsContainer)
.setName(side.charAt(0).toUpperCase() + side.slice(1))
.setDesc(`${side} margin in points`)
.addSlider(slider => {
slider
.setLimits(36, 144, 6) // 0.5" to 2" in 6pt increments
.setValue(marginDefaults[side as keyof typeof marginDefaults])
.setDynamicTooltip()
.onChange(value => {
this.marginInputs.set(side, value);
this.updateMargins(state);
});
// Set initial value
this.marginInputs.set(side, marginDefaults[side as keyof typeof marginDefaults]);
});
});
// Add preset buttons
const presetContainer = marginsContainer.createDiv('margin-presets');
presetContainer.createEl('span', { text: 'Presets: ' });
const presets = [
{ name: 'Narrow', values: { top: 36, bottom: 36, left: 36, right: 36 } },
{ name: 'Normal', values: { top: 72, bottom: 72, left: 72, right: 72 } },
{ name: 'Wide', values: { top: 108, bottom: 108, left: 108, right: 108 } }
];
presets.forEach(preset => {
const button = presetContainer.createEl('button', {
text: preset.name,
cls: 'margin-preset-button'
});
button.addEventListener('click', () => {
Object.entries(preset.values).forEach(([side, value]) => {
this.marginInputs.set(side, value);
});
this.updateMargins(state);
// Would need to update slider UI here in real implementation
state.notifyChange(); // Trigger UI refresh
});
});
}
private updateMargins(state: ModalState): void {
const margins = {
top: this.marginInputs.get('top') || 72,
bottom: this.marginInputs.get('bottom') || 72,
left: this.marginInputs.get('left') || 72,
right: this.marginInputs.get('right') || 72
};
// Convert points to Typst measurements
const typstMargins = {
marginTop: `${margins.top}pt`,
marginBottom: `${margins.bottom}pt`,
marginLeft: `${margins.left}pt`,
marginRight: `${margins.right}pt`
};
state.updateTemplateVariables(typstMargins);
}
validate(): ValidationResult {
const errors: string[] = [];
const warnings: string[] = [];
// Check for extremely small margins
this.marginInputs.forEach((value, side) => {
if (value < 36) {
warnings.push(`${side} margin is very small and may cause content to be cut off`);
}
});
return {
isValid: errors.length === 0,
errors,
warnings
};
}
getId(): string {
return 'layout';
}
}
+135
View File
@@ -0,0 +1,135 @@
/**
* Page Setup Section for Export Configuration Modal
* Handles page size, orientation with Typst flipped property, and text margin fields
*/
import { Setting } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
import { SUPPORTED_PAPER_SIZES } from '../../../utils/paperSizeMapper';
export class PageSetupSection implements ModalSection {
private container: HTMLElement | null = null;
private marginInputs: Map<string, HTMLInputElement> = new Map();
render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Page Setup' });
this.createPageSizeSettings(state);
this.createOrientationSettings(state);
this.createMarginSettings(state);
}
private createPageSizeSettings(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('Page size')
.setDesc('Standard page sizes for the PDF document')
.addDropdown(dropdown => {
// Add all supported paper sizes
SUPPORTED_PAPER_SIZES.forEach(paperSize => {
dropdown.addOption(paperSize.key, paperSize.displayName);
});
dropdown
.setValue(state.templateVariables.pageSize || 'a4')
.onChange(value => {
state.updateTemplateVariables({ pageSize: value });
});
});
}
private createOrientationSettings(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('Page orientation')
.setDesc('Portrait (tall) or landscape (wide) page layout')
.addDropdown(dropdown => {
dropdown
.addOption('portrait', 'Portrait')
.addOption('landscape', 'Landscape')
.setValue(state.templateVariables.orientation || 'portrait')
.onChange(value => {
const isLandscape = value === 'landscape';
state.updateTemplateVariables({
orientation: value,
flipped: isLandscape,
// Auto-adjust width for single-page mode when flipped
...(isLandscape && state.settings.format === 'single-page'
? { width: 'auto' }
: {})
});
});
});
}
private createMarginSettings(state: ModalState): void {
if (!this.container) return;
const marginsContainer = this.container.createDiv('margins-container');
marginsContainer.createEl('h4', { text: 'Text Margins' });
marginsContainer.createEl('p', {
text: 'Enter margins in centimeters (e.g., "2.5", "1.8", "3.0")',
cls: 'setting-item-description'
});
const marginDefaults = {
top: '2.5',
bottom: '2.0',
left: '2.5',
right: '1.5'
};
// Create margin text inputs
['top', 'bottom', 'left', 'right'].forEach(side => {
new Setting(marginsContainer)
.setName(`${side.charAt(0).toUpperCase() + side.slice(1)} margin`)
.setDesc(`${side} text margin in centimeters`)
.addText(text => {
const input = text
.setPlaceholder(marginDefaults[side as keyof typeof marginDefaults])
.setValue(state.templateVariables[`margin${side.charAt(0).toUpperCase() + side.slice(1)}`] || marginDefaults[side as keyof typeof marginDefaults])
.onChange(value => {
const marginKey = `margin${side.charAt(0).toUpperCase() + side.slice(1)}`;
state.updateTemplateVariables({ [marginKey]: value });
});
this.marginInputs.set(side, input.inputEl);
});
});
}
validate(): ValidationResult {
const errors: string[] = [];
const warnings: string[] = [];
// Validate margin formats
this.marginInputs.forEach((input, side) => {
const value = input.value.trim();
if (value) {
// Check for valid margin format (number only, centimeters assumed)
const marginRegex = /^\d*\.?\d+$/;
if (!marginRegex.test(value)) {
errors.push(`${side.charAt(0).toUpperCase() + side.slice(1)} margin must be a number in centimeters (e.g., "2.5")`);
} else {
const num = parseFloat(value);
if (num <= 0) {
errors.push(`${side.charAt(0).toUpperCase() + side.slice(1)} margin must be greater than 0`);
}
}
}
});
return {
isValid: errors.length === 0,
errors,
warnings
};
}
getId(): string {
return 'page-setup';
}
}
+224
View File
@@ -0,0 +1,224 @@
/**
* Typography Section for Export Configuration Modal
* Handles font selection and size configuration
*/
import { Setting, App } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
export class TypographySection implements ModalSection {
private container: HTMLElement | null = null;
private app: App | null = null;
render(containerEl: HTMLElement, state: ModalState, app?: App): void {
if (app) this.app = app;
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Typography' });
// Create font settings asynchronously
this.createFontSettings(state);
this.createFontSizeSettings(state);
}
private async createFontSettings(state: ModalState): Promise<void> {
if (!this.container) return;
// Get available fonts from cache
const availableFonts = await this.getAvailableFonts(state);
// Body font dropdown
new Setting(this.container)
.setName('Body font')
.setDesc('Primary font for document text')
.addDropdown(dropdown => {
const currentFont = state.templateVariables.bodyFont || 'Times New Roman';
// Add all available fonts
availableFonts.forEach(font => {
dropdown.addOption(font, font);
});
// Add current font if it's not in the list
if (!availableFonts.includes(currentFont)) {
dropdown.addOption(currentFont, currentFont);
}
// Set current value and change handler
dropdown
.setValue(currentFont)
.onChange(value => {
state.updateTemplateVariables({ bodyFont: value });
});
});
// Heading font dropdown
new Setting(this.container)
.setName('Heading font')
.setDesc('Font for headings and titles')
.addDropdown(dropdown => {
const currentFont = state.templateVariables.headingFont || 'Times New Roman';
// Add all available fonts
availableFonts.forEach(font => {
dropdown.addOption(font, font);
});
// Add current font if it's not in the list
if (!availableFonts.includes(currentFont)) {
dropdown.addOption(currentFont, currentFont);
}
// Set current value and change handler
dropdown
.setValue(currentFont)
.onChange(value => {
state.updateTemplateVariables({ headingFont: value });
});
});
// Monospace font dropdown
new Setting(this.container)
.setName('Monospace font')
.setDesc('Font for code blocks and inline code')
.addDropdown(dropdown => {
const currentFont = state.templateVariables.monospaceFont || 'Courier New';
// Add all available fonts
availableFonts.forEach(font => {
dropdown.addOption(font, font);
});
// Add current font if it's not in the list
if (!availableFonts.includes(currentFont)) {
dropdown.addOption(currentFont, currentFont);
}
// Set current value and change handler
dropdown
.setValue(currentFont)
.onChange(value => {
state.updateTemplateVariables({ monospaceFont: value });
});
});
}
private createFontSizeSettings(state: ModalState): void {
if (!this.container) return;
// Body font size
new Setting(this.container)
.setName('Body font size')
.setDesc('Base font size for document text (in points)')
.addSlider(slider => slider
.setLimits(8, 16, 0.5)
.setValue(state.templateVariables.bodyFontSize || 11)
.setDynamicTooltip()
.onChange(value => {
state.updateTemplateVariables({ bodyFontSize: value });
}));
}
// Helper methods for fonts - similar to settings tab
private async getAvailableFonts(state: ModalState): Promise<string[]> {
try {
// Access the plugin instance through the app
// @ts-ignore - accessing private plugin manager
const plugin = this.app?.plugins?.plugins?.['obsidian-typst-pdf-export'];
if (plugin && plugin.getCachedFonts) {
return await plugin.getCachedFonts();
}
// Fallback to hardcoded fonts if plugin not accessible
return [
'Times New Roman',
'Arial',
'Helvetica',
'Georgia',
'Courier New',
'Monaco',
'SF Pro Text',
'SF Mono',
'Concourse OT',
'UbuntuMono Nerd Font Mono',
'Source Code Pro'
];
} catch (error) {
console.error('Failed to get cached fonts:', error);
// Return common fallback fonts
return [
'Times New Roman',
'Arial',
'Helvetica',
'Georgia',
'Courier New',
'Monaco',
'SF Pro Text',
'SF Mono',
'Concourse OT',
'UbuntuMono Nerd Font Mono',
'Source Code Pro'
];
}
}
private addFallbackBodyFonts(dropdown: any, state: ModalState, fontType: 'body' | 'heading'): void {
dropdown
.addOption('Concourse OT', 'Concourse OT')
.addOption('Times New Roman', 'Times New Roman')
.addOption('Georgia', 'Georgia')
.addOption('Arial', 'Arial')
.addOption('Helvetica', 'Helvetica')
.addOption('Calibri', 'Calibri')
.addOption('Cambria', 'Cambria')
.addOption('Palatino', 'Palatino')
.addOption('Book Antiqua', 'Book Antiqua');
// Set the appropriate value based on font type
const currentValue = fontType === 'body'
? state.templateVariables.bodyFont
: state.templateVariables.headingFont;
dropdown
.setValue(currentValue || 'Concourse OT')
.onChange((value: string) => {
if (fontType === 'body') {
state.updateTemplateVariables({ bodyFont: value });
} else {
state.updateTemplateVariables({ headingFont: value });
}
});
}
private addFallbackMonospaceFonts(dropdown: any, state: ModalState): void {
dropdown
.addOption('Source Code Pro', 'Source Code Pro')
.addOption('Courier New', 'Courier New')
.addOption('Monaco', 'Monaco')
.addOption('Consolas', 'Consolas')
.addOption('Menlo', 'Menlo')
.addOption('DejaVu Sans Mono', 'DejaVu Sans Mono')
.addOption('Liberation Mono', 'Liberation Mono')
.addOption('Ubuntu Mono', 'Ubuntu Mono')
.setValue(state.templateVariables.monospaceFont || 'Source Code Pro')
.onChange((value: string) => {
state.updateTemplateVariables({ monospaceFont: value });
});
}
validate(): ValidationResult {
const errors: string[] = [];
const warnings: string[] = [];
// No validation needed for dropdowns with predefined options
return {
isValid: errors.length === 0,
errors,
warnings
};
}
getId(): string {
return 'typography';
}
}