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

+34
View File
@@ -0,0 +1,34 @@
/**
* Folder suggestion component for folder path inputs
* Provides autocomplete for existing vault folders
*/
import { App, AbstractInputSuggest } from 'obsidian';
export class FolderSuggest extends AbstractInputSuggest<string> {
private folders: string[];
private inputElement: HTMLInputElement;
constructor(app: App, inputEl: HTMLInputElement) {
super(app, inputEl);
this.inputElement = inputEl;
this.folders = ["/"].concat(this.app.vault.getAllFolders().map(folder => folder.path));
}
getSuggestions(inputStr: string): string[] {
const inputLower = inputStr.toLowerCase();
return this.folders.filter(folder =>
folder.toLowerCase().includes(inputLower)
);
}
renderSuggestion(folder: string, el: HTMLElement): void {
el.createEl("div", { text: folder });
}
selectSuggestion(folder: string): void {
this.inputElement.value = folder;
this.inputElement.dispatchEvent(new Event('input'));
this.close();
}
}
+493
View File
@@ -0,0 +1,493 @@
/**
* Export Configuration Modal
* Refactored modular version that uses section components
*/
import { Modal, App, Notice } from 'obsidian';
import { obsidianTypstPDFExport } from '../../../main';
import { ExportConfig, ExportConfigModalSettings, ModalSection } from './modalTypes';
import { ModalState } from './state/ModalState';
import { GeneralSection } from './sections/GeneralSection';
import { TypographySection } from './sections/TypographySection';
import { PageSetupSection } from './sections/PageSetupSection';
import { BehaviorSection } from './sections/BehaviorSection';
import { TemplateManager } from '../../templates/TemplateManager';
export class ExportConfigModal extends Modal {
plugin: obsidianTypstPDFExport;
private state: ModalState;
private sections: Map<string, ModalSection> = new Map();
private onSubmit: (config: ExportConfig) => void;
private onCancel?: () => void;
// UI elements
private contentContainer: HTMLElement;
private formContainer: HTMLElement;
private progressContainer: HTMLElement;
private progressBar: HTMLElement;
private progressText: HTMLElement;
private submitButton: HTMLButtonElement;
private cancelButton: HTMLButtonElement;
private resetButton: HTMLButtonElement;
constructor(
app: App,
plugin: obsidianTypstPDFExport,
settings: Partial<ExportConfigModalSettings>,
onSubmit: (config: ExportConfig) => void,
onCancel?: () => void
) {
super(app);
this.plugin = plugin;
this.onSubmit = onSubmit;
this.onCancel = onCancel;
// Initialize state
this.state = new ModalState(settings);
// Register sections
this.registerSections();
// Listen for state changes
this.state.onChange(() => this.handleStateChange());
}
private registerSections(): void {
// Register all modal sections
const sections = [
new GeneralSection(),
new PageSetupSection(),
new TypographySection(),
new BehaviorSection()
];
sections.forEach(section => {
this.sections.set(section.getId(), section);
});
}
onOpen(): void {
const { contentEl } = this;
contentEl.addClass('export-config-modal');
// Add styles
this.addModalStyles();
// Create main container
this.contentContainer = contentEl.createDiv('export-config-container');
// Create header
this.createHeader();
// Create form container
this.formContainer = this.contentContainer.createDiv('export-config-form');
// Render sections
this.renderSections();
// Create progress container (initially hidden)
this.createProgressContainer();
// Create action buttons
this.createActionButtons();
// Load available templates
this.loadAvailableTemplates();
}
private createHeader(): void {
const header = this.contentContainer.createDiv('export-config-header');
header.createEl('h2', { text: 'Export to PDF' });
if (this.state.settings.noteTitle) {
const isMultiFile = this.state.settings.files && this.state.settings.files.length > 1;
const displayText = isMultiFile
? `Exporting ${this.state.settings.files!.length} files`
: `Exporting: ${this.state.settings.noteTitle}`;
header.createEl('p', {
text: displayText,
cls: 'export-note-title'
});
}
}
private renderSections(): void {
// Clear existing content
this.formContainer.empty();
// Render each section
this.sections.forEach(section => {
section.render(this.formContainer, this.state, this.app);
});
}
private createProgressContainer(): void {
this.progressContainer = this.contentContainer.createDiv('export-progress-container');
this.progressContainer.style.display = 'none';
// Progress text
this.progressText = this.progressContainer.createEl('div', {
cls: 'export-progress-text',
text: 'Preparing export...'
});
// Progress bar container
const progressBarContainer = this.progressContainer.createDiv('export-progress-bar-container');
this.progressBar = progressBarContainer.createDiv('export-progress-bar');
// Progress percentage
const progressPercent = this.progressContainer.createEl('div', {
cls: 'export-progress-percent',
text: '0%'
});
}
private createActionButtons(): void {
const buttonContainer = this.contentContainer.createDiv('export-config-buttons');
// Reset button (left side)
this.resetButton = buttonContainer.createEl('button', {
text: 'Reset to Defaults',
cls: 'mod-muted'
});
this.resetButton.addEventListener('click', () => this.handleReset());
// Right side buttons container
const rightButtons = buttonContainer.createDiv('right-buttons');
// Cancel button
this.cancelButton = rightButtons.createEl('button', {
text: 'Cancel',
cls: 'mod-cancel'
});
this.cancelButton.addEventListener('click', () => this.handleCancel());
// Export button
this.submitButton = rightButtons.createEl('button', {
text: 'Export',
cls: 'mod-cta'
});
this.submitButton.addEventListener('click', () => this.handleSubmit());
}
private async loadAvailableTemplates(): Promise<void> {
try {
const templateManager = new TemplateManager(this.plugin);
const templates = await templateManager.getAvailableTemplates();
this.state.updateSettings({
availableTemplates: templates
});
// Update the general section's template dropdown
const generalSection = this.sections.get('general') as GeneralSection;
if (generalSection && generalSection.updateAvailableTemplates) {
generalSection.updateAvailableTemplates(templates);
}
} catch (error) {
console.error('Failed to load templates:', error);
new Notice('Failed to load available templates');
}
}
private handleStateChange(): void {
// State change handler for any UI updates needed
// This is called whenever the state is updated
}
private handleReset(): void {
// Create plugin defaults object from settings tab values
const pluginDefaults = {
template: this.plugin.settings.exportDefaults.template,
format: this.plugin.settings.exportDefaults.format,
outputFolder: this.plugin.settings.outputFolder,
openAfterExport: this.plugin.settings.behavior.openAfterExport,
preserveFolderStructure: this.plugin.settings.behavior.preserveFolderStructure,
pageSize: this.plugin.settings.pageSetup.size,
orientation: this.plugin.settings.pageSetup.orientation,
marginTop: this.plugin.settings.pageSetup.margins.top.toString(),
marginBottom: this.plugin.settings.pageSetup.margins.bottom.toString(),
marginLeft: this.plugin.settings.pageSetup.margins.left.toString(),
marginRight: this.plugin.settings.pageSetup.margins.right.toString(),
bodyFont: this.plugin.settings.typography.fonts.body,
headingFont: this.plugin.settings.typography.fonts.heading,
monospaceFont: this.plugin.settings.typography.fonts.monospace,
bodyFontSize: this.plugin.settings.typography.fontSizes.body
};
// Reset state to plugin defaults
this.state.reset(pluginDefaults);
// Re-render sections to update UI
this.renderSections();
// Reload templates to update the dropdown
this.loadAvailableTemplates();
new Notice('Settings reset to defaults');
}
private async handleSubmit(): Promise<void> {
// Validate all sections
const validationResults = this.validateAllSections();
if (!validationResults.isValid) {
this.showValidationErrors(validationResults.errors);
return;
}
// Show any warnings
if (validationResults.warnings.length > 0) {
this.showValidationWarnings(validationResults.warnings);
}
// Build export configuration
const config = this.state.buildExportConfig();
// Show progress
this.showProgress('Starting export...', 0);
// Disable buttons
this.submitButton.disabled = true;
this.resetButton.disabled = true;
this.cancelButton.textContent = 'Close';
try {
// Call the submit handler
await this.onSubmit(config);
// Show success
this.showProgress('Export completed successfully!', 100);
// Auto-close after delay
setTimeout(() => this.close(), 2000);
} catch (error) {
console.error('Export failed:', error);
this.showProgress(`Export failed: ${error.message}`, -1);
this.submitButton.disabled = false;
this.resetButton.disabled = false;
}
}
private handleCancel(): void {
if (this.state.settings.isExporting && this.state.settings.canCancel) {
// Cancel ongoing export
if (this.onCancel) {
this.onCancel();
}
this.showProgress('Export cancelled', -1);
} else {
// Close modal
this.close();
}
}
private validateAllSections(): { isValid: boolean; errors: string[]; warnings: string[] } {
const errors: string[] = [];
const warnings: string[] = [];
this.sections.forEach(section => {
if (section.validate) {
const result = section.validate();
errors.push(...result.errors);
if (result.warnings) {
warnings.push(...result.warnings);
}
}
});
return {
isValid: errors.length === 0,
errors,
warnings
};
}
private showValidationErrors(errors: string[]): void {
const errorContainer = this.formContainer.createDiv('validation-errors');
errorContainer.createEl('h4', { text: 'Validation Errors', cls: 'error-title' });
const errorList = errorContainer.createEl('ul');
errors.forEach(error => {
errorList.createEl('li', { text: error });
});
// Remove after 5 seconds
setTimeout(() => errorContainer.remove(), 5000);
}
private showValidationWarnings(warnings: string[]): void {
warnings.forEach(warning => {
new Notice(`Warning: ${warning}`, 3000);
});
}
private showProgress(message: string, percent: number): void {
this.progressContainer.style.display = 'block';
this.formContainer.style.display = 'none';
this.progressText.textContent = message;
if (percent >= 0) {
this.progressBar.style.width = `${percent}%`;
const percentEl = this.progressContainer.querySelector('.export-progress-percent');
if (percentEl) {
percentEl.textContent = `${Math.round(percent)}%`;
}
}
// Update state
this.state.setProgress(percent, message);
}
updateProgress(message: string, percent: number): void {
this.showProgress(message, percent);
}
private getOutputFilename(): string {
const noteName = this.state.settings.noteTitle || 'document';
return `${noteName}.pdf`;
}
private addModalStyles(): void {
// Add custom styles for the modal
const style = document.createElement('style');
style.textContent = `
.export-config-modal {
width: 90vw;
max-width: 520px;
height: 80vh;
max-height: 600px;
}
.export-config-container {
display: flex;
flex-direction: column;
height: 100%;
}
.export-config-header {
padding: 20px;
border-bottom: 1px solid var(--background-modifier-border);
}
.export-config-header h2 {
margin: 0;
}
.export-note-title {
margin: 10px 0 0 0;
color: var(--text-muted);
font-size: 0.9em;
}
.export-config-form {
flex: 1;
overflow-y: auto;
padding: 20px;
}
.export-section {
margin-bottom: 30px;
}
.export-section h3 {
margin-bottom: 15px;
font-size: 1.1em;
font-weight: 600;
}
.export-section h4 {
margin: 15px 0 10px 0;
font-size: 0.95em;
font-weight: 500;
color: var(--text-muted);
}
.export-progress-container {
padding: 40px;
text-align: center;
}
.export-progress-text {
margin-bottom: 20px;
font-size: 1.1em;
}
.export-progress-bar-container {
width: 100%;
height: 20px;
background: var(--background-secondary);
border-radius: 10px;
overflow: hidden;
}
.export-progress-bar {
height: 100%;
background: var(--interactive-accent);
transition: width 0.3s ease;
}
.export-progress-percent {
margin-top: 10px;
color: var(--text-muted);
}
.export-config-buttons {
padding: 20px;
border-top: 1px solid var(--background-modifier-border);
display: flex;
justify-content: space-between;
align-items: center;
}
.export-config-buttons .right-buttons {
display: flex;
gap: 10px;
}
.validation-errors {
background: var(--background-modifier-error);
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.error-title {
color: var(--text-error);
margin: 0 0 10px 0;
}
.validation-errors ul {
margin: 0;
padding-left: 20px;
}
.margins-container {
background: var(--background-secondary-alt);
padding: 15px;
border-radius: 5px;
margin-top: 15px;
}
`;
document.head.appendChild(style);
}
onClose(): void {
// Clean up state listeners
this.state.onChange(() => {}); // Remove listener
// Clear sections
this.sections.clear();
// Remove added styles
const style = document.querySelector('style');
if (style && style.textContent?.includes('export-config-modal')) {
style.remove();
}
const { contentEl } = this;
contentEl.empty();
}
}
+64
View File
@@ -0,0 +1,64 @@
/**
* Type definitions for the Export Configuration Modal
*/
import { TFile } from 'obsidian';
import { ExportFormat } from '../../core/settings';
export interface ExportConfig {
/** Override default template */
template?: string;
/** Override default format */
format?: ExportFormat;
/** Override output folder */
outputFolder?: string;
/** Template variables for this export */
templateVariables?: Record<string, any>;
/** Open PDF after export */
openAfterExport?: boolean;
/** Preserve folder structure when exporting */
preserveFolderStructure?: boolean;
}
export interface ExportConfigModalSettings extends ExportConfig {
/** Note being exported */
notePath: string;
/** Note title for display */
noteTitle: string;
/** Files being exported (for multi-file export) */
files?: TFile[];
/** Available templates from TemplateManager */
availableTemplates: string[];
/** Current export in progress */
isExporting: boolean;
/** Progress percentage (0-100) */
progressPercent: number;
/** Current operation description */
currentOperation: string;
/** Whether export can be cancelled */
canCancel: boolean;
}
export interface ModalSection {
render(containerEl: HTMLElement, state: ModalState, app?: any): void;
validate?(): ValidationResult;
getId(): string;
}
export interface ValidationResult {
isValid: boolean;
errors: string[];
warnings?: string[];
}
export interface ModalState {
settings: ExportConfigModalSettings;
templateVariables: Record<string, any>;
updateSettings(updates: Partial<ExportConfigModalSettings>): void;
updateTemplateVariables(updates: Record<string, any>): void;
buildExportConfig(): ExportConfig;
notifyChange(): void;
setProgress(percent: number, operation: string): void;
reset(pluginDefaults: any): void;
onChange(listener: () => void): void;
}
+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';
}
}
+209
View File
@@ -0,0 +1,209 @@
/**
* Modal State Management
* Centralized state management for the Export Configuration Modal
*/
import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../modalTypes';
import { ExportFormat } from '../../../core/settings';
export class ModalState implements IModalState {
settings: ExportConfigModalSettings;
templateVariables: Record<string, any>;
private changeListeners: Set<() => void> = new Set();
private static readonly STORAGE_KEY = 'typst-export-modal-state';
constructor(initialSettings: Partial<ExportConfigModalSettings>) {
// Load from localStorage if available
const savedState = this.loadFromStorage();
// Initialize with defaults, then saved state, then passed settings
this.settings = {
notePath: '',
noteTitle: '',
template: 'default.typ',
format: ExportFormat.Standard,
outputFolder: 'exports',
templateVariables: {},
availableTemplates: [],
isExporting: false,
progressPercent: 0,
currentOperation: '',
canCancel: false,
openAfterExport: false,
preserveFolderStructure: false,
...savedState?.settings,
...initialSettings
};
// Use ONLY the passed templateVariables, with minimal fallbacks
// Priority: initialSettings > savedState > absolute minimal fallbacks
this.templateVariables = {
// Only provide absolute minimal fallbacks for required fields
pageSize: 'a4',
orientation: 'portrait',
flipped: false,
marginTop: '1in',
marginBottom: '0.8in',
marginLeft: '1in',
marginRight: '0.6in',
bodyFont: 'Times New Roman', // Generic fallback
headingFont: 'Times New Roman', // Generic fallback
monospaceFont: 'Courier New', // Generic fallback
bodyFontSize: '11pt',
// Apply saved state if any
...savedState?.templateVariables,
// Apply passed settings (this should be the plugin defaults)
...initialSettings.templateVariables
};
// Update settings to include merged template variables
this.settings.templateVariables = this.templateVariables;
}
/**
* Update template variables
*/
updateTemplateVariables(updates: Record<string, any>): void {
this.templateVariables = {
...this.templateVariables,
...updates
};
this.settings.templateVariables = this.templateVariables;
this.saveToStorage();
this.notifyChange();
}
/**
* Build export configuration from current state
*/
buildExportConfig(): ExportConfig {
const config: ExportConfig = {
template: this.settings.template,
format: this.settings.format,
outputFolder: this.settings.outputFolder,
templateVariables: this.templateVariables,
openAfterExport: this.settings.openAfterExport,
preserveFolderStructure: this.settings.preserveFolderStructure
};
return config;
}
/**
* Register a change listener
*/
onChange(listener: () => void): void {
this.changeListeners.add(listener);
}
/**
* Unregister a change listener
*/
offChange(listener: () => void): void {
this.changeListeners.delete(listener);
}
/**
* Notify all listeners of state change
*/
notifyChange(): void {
this.changeListeners.forEach(listener => listener());
}
/**
* Update settings
*/
updateSettings(updates: Partial<ExportConfigModalSettings>): void {
this.settings = {
...this.settings,
...updates
};
this.saveToStorage();
this.notifyChange();
}
/**
* Set export progress
*/
setProgress(percent: number, operation: string): void {
this.settings.progressPercent = percent;
this.settings.currentOperation = operation;
this.notifyChange();
}
/**
* Reset state to defaults
*/
reset(pluginDefaults: any): void {
// Reset to plugin defaults, not hardcoded defaults
this.settings = {
...this.settings,
template: pluginDefaults.template,
format: pluginDefaults.format,
outputFolder: pluginDefaults.outputFolder || 'exports',
templateVariables: {},
progressPercent: 0,
currentOperation: '',
isExporting: false,
canCancel: false,
openAfterExport: pluginDefaults.openAfterExport || false,
preserveFolderStructure: pluginDefaults.preserveFolderStructure || false
};
this.templateVariables = {
pageSize: pluginDefaults.pageSize,
orientation: pluginDefaults.orientation,
flipped: pluginDefaults.orientation === 'landscape',
marginTop: pluginDefaults.marginTop,
marginBottom: pluginDefaults.marginBottom,
marginLeft: pluginDefaults.marginLeft,
marginRight: pluginDefaults.marginRight,
bodyFont: pluginDefaults.bodyFont,
headingFont: pluginDefaults.headingFont,
monospaceFont: pluginDefaults.monospaceFont,
bodyFontSize: pluginDefaults.bodyFontSize
};
this.settings.templateVariables = this.templateVariables;
this.saveToStorage();
this.notifyChange();
}
/**
* Save current state to localStorage
*/
private saveToStorage(): void {
const stateToSave = {
settings: {
template: this.settings.template,
format: this.settings.format,
outputFolder: this.settings.outputFolder,
openAfterExport: this.settings.openAfterExport,
preserveFolderStructure: this.settings.preserveFolderStructure
},
templateVariables: this.templateVariables
};
try {
localStorage.setItem(ModalState.STORAGE_KEY, JSON.stringify(stateToSave));
} catch (error) {
console.warn('Failed to save modal state to localStorage:', error);
}
}
/**
* Load state from localStorage
*/
private loadFromStorage(): { settings: Partial<ExportConfigModalSettings>, templateVariables: Record<string, any> } | null {
try {
const saved = localStorage.getItem(ModalState.STORAGE_KEY);
if (saved) {
return JSON.parse(saved);
}
} catch (error) {
console.warn('Failed to load modal state from localStorage:', error);
}
return null;
}
}