diff --git a/main.ts b/main.ts index 9ab7e56..64a3450 100644 --- a/main.ts +++ b/main.ts @@ -1,1201 +1,84 @@ -import { App, Notice, Plugin, PluginSettingTab, Setting, Modal, MarkdownRenderer, TFile, TFolder, Menu } from 'obsidian'; -import { DependencyChecker } from './src/DependencyChecker'; -import { TemplateManager } from './src/template-manager'; -import { spawn, ChildProcess } from 'child_process'; -import { promises as fs } from 'fs'; -import * as path from 'path'; -import * as os from 'os'; - -/** - * Configuration options for Pandoc conversion - */ -interface PandocOptions { - /** Path to pandoc executable (optional, uses PATH if not specified) */ - pandocPath?: string; - /** Path to typst executable (optional, uses PATH if not specified) */ - typstPath?: string; - /** Template file path */ - template?: string; - /** Template variables to pass to pandoc */ - variables?: Record; - /** Additional pandoc arguments */ - additionalArgs?: string[]; - /** Timeout for pandoc process in milliseconds (default: 60000) */ - timeout?: number; - /** Generate intermediate .typ file for debugging */ - generateIntermediateTypst?: boolean; - /** Vault base path for resolving attachment paths */ - vaultBasePath?: string; - /** Plugin directory path for resolving plugin-relative paths */ - pluginDir?: string; -} - -/** - * Settings specific to Typst engine - */ -interface TypstSettings { - /** Additional options to pass to Typst engine */ - engineOptions?: string[]; -} - -/** - * Result of a Pandoc conversion operation - */ -interface ConversionResult { - /** Whether the conversion was successful */ - success: boolean; - /** Path to the output PDF file */ - outputPath?: string; - /** Path to intermediate .typ file (if generated) */ - intermediateTypstPath?: string; - /** Error message if conversion failed */ - error?: string; - /** Pandoc stdout output */ - stdout?: string; - /** Pandoc stderr output */ - stderr?: string; - /** Process exit code */ - exitCode?: number; -} - -/** - * Progress callback function type - */ -type ProgressCallback = (message: string, progress?: number) => void; - -/** - * Core converter class for Pandoc to Typst PDF conversion - */ -class PandocTypstConverter { - private tempDir: string | null = null; - private cleanupHandlers: (() => void)[] = []; - - /** - * Create a new PandocTypstConverter instance - * @param pandocOptions Configuration options for Pandoc - * @param typstSettings Settings specific to Typst engine - */ - constructor( - private pandocOptions: PandocOptions = {}, - private typstSettings: TypstSettings = {} - ) { - // Set up cleanup handlers for process termination - this.setupCleanup(); - } - - /** - * Convert a markdown file to PDF using Pandoc with Typst engine - * @param inputPath Path to the input markdown file - * @param outputPath Path where the PDF should be saved - * @param progressCallback Optional callback for progress updates - * @returns Promise resolving to conversion result - */ - async convertToPDF( - inputPath: string, - outputPath: string, - progressCallback?: ProgressCallback - ): Promise { - try { - progressCallback?.('Starting PDF conversion...', 0); - - // Create temporary directory if needed - await this.ensureTempDirectory(); - - // Build pandoc arguments - const args = await this.buildPandocArgs(inputPath, outputPath); - - progressCallback?.('Executing Pandoc with Typst engine...', 30); - - // Execute pandoc process - const result = await this.executePandoc(args, progressCallback); - - progressCallback?.('Conversion complete!', 100); - - return result; - - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - return { - success: false, - error: `Conversion failed: ${errorMessage}` - }; - } - } - - /** - * Set up cleanup handlers for temporary files - */ - private setupCleanup(): void { - const cleanup = () => { - this.cleanup(); - }; - - process.on('exit', cleanup); - process.on('SIGINT', cleanup); - process.on('SIGTERM', cleanup); - process.on('uncaughtException', cleanup); - } - - /** - * Process PDF embeds by converting them to images and creating combined output - */ - private async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string): Promise { - const { PdfToImageConverter } = require('./src/PdfToImageConverter'); - const converter = PdfToImageConverter.getInstance(this); - const path = require('path'); - - for (const pdfEmbed of processedResult.metadata.pdfEmbeds) { - try { - console.log(`Export: Processing PDF embed: ${pdfEmbed.originalPath}`); - - // Resolve full path to the PDF - const fullPdfPath = path.resolve(vaultBasePath, pdfEmbed.sanitizedPath); - - // Check if PDF file exists - const fs = require('fs'); - if (!fs.existsSync(fullPdfPath)) { - console.warn(`Export: PDF file not found: ${fullPdfPath}`); - // Replace marker with error message - processedResult.content = processedResult.content.replace( - pdfEmbed.marker, - `[⚠️ PDF not found: ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})` - ); - continue; - } - - // Convert PDF to image - const conversionResult = await converter.convertFirstPageToImage( - fullPdfPath, - tempDir, - { - scale: 1.5, - maxWidth: 600, - maxHeight: 400, - format: 'png' - } - ); - - if (conversionResult.success) { - // Get relative path for the generated image - const relativeImagePath = path.relative(vaultBasePath, conversionResult.imagePath); - - // Create combined output: image preview + PDF attachment link - const combinedOutput = [ - `![${pdfEmbed.fileName} - Page 1](${relativeImagePath})`, - `[📎 **Download PDF:** ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})` - ].join('\n\n'); - - // Replace marker with combined output - processedResult.content = processedResult.content.replace(pdfEmbed.marker, combinedOutput); - - console.log(`Export: Successfully converted PDF: ${pdfEmbed.fileName} -> ${path.basename(conversionResult.imagePath)}`); - - } else { - console.error(`Export: PDF conversion failed: ${conversionResult.error}`); - - // Replace marker with fallback link - processedResult.content = processedResult.content.replace( - pdfEmbed.marker, - `[📖 ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Note: PDF preview could not be generated*` - ); - } - - } catch (error) { - console.error(`Export: Error processing PDF embed: ${error.message}`); - - // Replace marker with error fallback - processedResult.content = processedResult.content.replace( - pdfEmbed.marker, - `[⚠️ ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Error: Could not process PDF embed*` - ); - } - } - } - - /** - * Clean up temporary files and directories - */ - private async cleanup(): Promise { - try { - // Execute registered cleanup handlers - this.cleanupHandlers.forEach(handler => { - try { - handler(); - } catch (error) { - console.warn('Cleanup handler failed:', error); - } - }); - - // Remove temporary directory - if (this.tempDir) { - await fs.rmdir(this.tempDir, { recursive: true }); - this.tempDir = null; - } - } catch (error) { - console.warn('Cleanup failed:', error); - } - } - - /** - * Ensure temporary directory exists - */ - private async ensureTempDirectory(): Promise { - if (!this.tempDir) { - this.tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'obsidian-typst-')); - } - return this.tempDir; - } - - /** - * Build pandoc command-line arguments - */ - private async buildPandocArgs(inputPath: string, outputPath: string): Promise { -const args: string[] = []; - -// Input file -args.push(inputPath); - -// Output file -args.push('-o', outputPath); - -// Specify input format as markdown with smart extension disabled -args.push('--from', 'markdown-smart'); - -// Set PDF engine to Typst (use configured path if available) -if (this.pandocOptions.typstPath) { - args.push(`--pdf-engine=${this.pandocOptions.typstPath}`); -} else { - args.push('--pdf-engine=typst'); -} - -// Enable standalone mode (required for PDF output) -args.push('--standalone'); - -// Embed resources (images, etc.) directly into the output -args.push('--embed-resources'); - -// Add resource paths for attachment resolution -if (this.pandocOptions.vaultBasePath) { - const path = require('path'); - const fs = require('fs'); - - // Add vault root as primary resource path - args.push('--resource-path', this.pandocOptions.vaultBasePath); - - // Add common attachment directories as additional resource paths - const commonAttachmentPaths = [ - path.join(this.pandocOptions.vaultBasePath, 'attachments'), - path.join(this.pandocOptions.vaultBasePath, 'assets'), - path.join(this.pandocOptions.vaultBasePath, 'files'), - path.join(this.pandocOptions.vaultBasePath, 'images'), - path.join(this.pandocOptions.vaultBasePath, '.attachments') - ]; - - // Check if these directories exist and add them - for (const attachPath of commonAttachmentPaths) { - if (fs.existsSync(attachPath)) { - args.push('--resource-path', attachPath); - console.log('Added resource path:', attachPath); - } - } - - // Also scan for note-specific attachment folders (Obsidian often creates these) - try { - const vaultContents = fs.readdirSync(this.pandocOptions.vaultBasePath); - for (const item of vaultContents) { - const itemPath = path.join(this.pandocOptions.vaultBasePath, item); - const stat = fs.statSync(itemPath); - if (stat.isDirectory() && !item.startsWith('.') && !item.startsWith('_')) { - // Check if this directory contains images - try { - const dirContents = fs.readdirSync(itemPath); - const hasImages = dirContents.some((file: string) => - /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file) - ); - if (hasImages) { - args.push('--resource-path', itemPath); - console.log('Added note-specific resource path:', itemPath); - } - } catch (e) { - // Ignore directories we can't read - } - } - } - } catch (e) { - console.warn('Could not scan vault for attachment directories:', e); - } -} - -// Use universal wrapper with --template and pass actual template as template_path variable -if (this.pandocOptions.template) { - // Get absolute path to universal wrapper using plugin directory from pandocOptions - const path = require('path'); - const fs = require('fs'); - const absolutePluginDir = this.pandocOptions.pluginDir || ''; - const wrapperPath = path.resolve(absolutePluginDir, 'templates', 'universal-wrapper.pandoc.typ'); - console.log('Universal wrapper path:', wrapperPath); - - // Verify wrapper exists - if (!fs.existsSync(wrapperPath)) { - throw new Error(`Universal wrapper template not found at: ${wrapperPath}`); - } - - args.push('--template', wrapperPath); - - // Pass the actual template path as a variable - args.push('-V', `template_path=${this.pandocOptions.template}`); -} - -// Add variables for document metadata -if (this.pandocOptions.variables) { - for (const [key, value] of Object.entries(this.pandocOptions.variables)) { - if (value && value.toString().trim() !== '') { - args.push('-V', `${key}=${value}`); - } - } -} - -// Add typography settings as template variables -const plugin = (this as any).plugin; -if (plugin && plugin.settings) { - const settings = plugin.settings; - - // Add typography variables - if (settings.typography) { - if (settings.typography.fonts) { - if (settings.typography.fonts.body) { - args.push('-V', `font="${settings.typography.fonts.body}"`); - } - if (settings.typography.fonts.heading) { - args.push('-V', `heading_font="${settings.typography.fonts.heading}"`); - } - if (settings.typography.fonts.monospace) { - args.push('-V', `monospace_font="${settings.typography.fonts.monospace}"`); - } - } - - if (settings.typography.fontSizes) { - if (settings.typography.fontSizes.body) { - args.push('-V', `fontsize=${settings.typography.fontSizes.body}pt`); - } - if (settings.typography.fontSizes.heading) { - args.push('-V', `heading_fontsize=${settings.typography.fontSizes.heading}pt`); - } - if (settings.typography.fontSizes.small) { - args.push('-V', `small_fontsize=${settings.typography.fontSizes.small}pt`); - } - } - } - - // Add page setup variables - if (settings.pageSetup) { - if (settings.pageSetup.size) { - args.push('-V', `paper=${settings.pageSetup.size}`); - } - if (settings.pageSetup.orientation) { - args.push('-V', `orientation=${settings.pageSetup.orientation}`); - } - - // Convert margin points to cm for Typst (1 point = 0.0352778 cm) - if (settings.pageSetup.margins) { - const margins = settings.pageSetup.margins; - if (margins.top !== undefined) { - const topCm = (margins.top * 0.0352778).toFixed(2); - args.push('-V', `margin_top=${topCm}cm`); - } - if (margins.right !== undefined) { - const rightCm = (margins.right * 0.0352778).toFixed(2); - args.push('-V', `margin_right=${rightCm}cm`); - } - if (margins.bottom !== undefined) { - const bottomCm = (margins.bottom * 0.0352778).toFixed(2); - args.push('-V', `margin_bottom=${bottomCm}cm`); - } - if (margins.left !== undefined) { - const leftCm = (margins.left * 0.0352778).toFixed(2); - args.push('-V', `margin_left=${leftCm}cm`); - } - } - } - - // Add export format variable - if (settings.exportDefaults) { - if (settings.exportDefaults.format) { - args.push('-V', `export_format=${settings.exportDefaults.format}`); - } - } -} - -// Add Typst engine options -if (this.typstSettings.engineOptions) { - for (const option of this.typstSettings.engineOptions) { - args.push('--pdf-engine-opt', option); - } -} - -// Generate intermediate Typst file if requested -if (this.pandocOptions.generateIntermediateTypst) { - const tempDir = await this.ensureTempDirectory(); - const typstPath = path.join(tempDir, 'intermediate.typ'); - args.push('--output', typstPath); -} - -// Add additional arguments -if (this.pandocOptions.additionalArgs) { - args.push(...this.pandocOptions.additionalArgs); -} - -return args; -} - - /** - * Execute pandoc process with the given arguments - */ - private async executePandoc(args: string[], progressCallback?: ProgressCallback): Promise { -return new Promise((resolve) => { - const pandocPath = this.pandocOptions.pandocPath || 'pandoc'; - const timeout = this.pandocOptions.timeout || 60000; - - // Log the exact command being executed for debugging - console.log('Executing Pandoc command:', pandocPath, args.join(' ')); - - progressCallback?.('Starting Pandoc process...', 40); - - // Determine working directory - use vault base path if available, fallback to plugin directory - const path = require('path'); - let workingDir: string; - - if (this.pandocOptions.vaultBasePath) { - workingDir = this.pandocOptions.vaultBasePath; - console.log('Pandoc working directory (vault):', workingDir); - } else { - // Fallback to plugin directory - const pluginDir = (this.pandocOptions as any).pluginDir || process.cwd(); - workingDir = pluginDir; - console.log('Pandoc working directory (plugin fallback):', workingDir); - } - - // Spawn pandoc process with vault as working directory for attachment resolution - const pandocProcess: ChildProcess = spawn(pandocPath, args, { - stdio: ['pipe', 'pipe', 'pipe'], - cwd: workingDir, - env: process.env, // Inherit environment variables - }); - - let stdout = ''; - let stderr = ''; - let hasTimedOut = false; - - // Set up timeout - const timeoutHandle = setTimeout(() => { - hasTimedOut = true; - pandocProcess.kill('SIGTERM'); - resolve({ - success: false, - error: `Pandoc process timed out after ${timeout}ms`, - exitCode: -1 - }); - }, timeout); - - // Collect stdout - pandocProcess.stdout?.on('data', (data: Buffer) => { - stdout += data.toString(); - progressCallback?.('Processing document...', 60); - }); - - // Collect stderr and monitor for progress - pandocProcess.stderr?.on('data', (data: Buffer) => { - const output = data.toString(); - stderr += output; - console.log('Pandoc stderr:', output); - - // Parse progress information from stderr if available - this.parseProgressFromOutput(output, progressCallback); - }); - - // Handle process completion - pandocProcess.on('close', (code: number | null) => { - clearTimeout(timeoutHandle); - - if (hasTimedOut) { - return; // Already resolved with timeout error - } - - const success = code === 0; - const result: ConversionResult = { - success, - stdout, - stderr, - exitCode: code || -1 - }; - - if (!success) { - result.error = this.extractErrorMessage(stderr, stdout); - } else { - progressCallback?.('PDF generation complete!', 90); - } - - resolve(result); - }); - - // Handle process errors - pandocProcess.on('error', (error: Error) => { - clearTimeout(timeoutHandle); - console.log('Pandoc process error:', error); - resolve({ - success: false, - error: `Failed to start Pandoc process: ${error.message}`, - exitCode: -1 - }); - }); -}); -} - - /** - * Parse progress information from pandoc output - */ - private parseProgressFromOutput(output: string, progressCallback?: ProgressCallback): void { - // Look for common progress indicators in pandoc/typst output - if (output.includes('reading')) { - progressCallback?.('Reading input file...', 50); - } else if (output.includes('parsing')) { - progressCallback?.('Parsing document...', 55); - } else if (output.includes('typst')) { - progressCallback?.('Generating PDF with Typst...', 70); - } else if (output.includes('writing')) { - progressCallback?.('Writing output file...', 80); - } - } - - /** - * Extract meaningful error messages from pandoc output - */ - private extractErrorMessage(stderr: string, stdout: string): string { - // Look for common error patterns - const errorPatterns = [ - /error:/i, - /Error:/, - /failed/i, - /Fatal/i, - /pandoc:/i - ]; - - const allOutput = (stderr + '\n' + stdout).split('\n'); - - for (const line of allOutput) { - for (const pattern of errorPatterns) { - if (pattern.test(line)) { - return line.trim(); - } - } - } - - // If no specific error found, return first non-empty line from stderr - const stderrLines = stderr.split('\n').filter(line => line.trim().length > 0); - if (stderrLines.length > 0) { - return stderrLines[0]; - } - - return 'Unknown error occurred during conversion'; - } - - /** - * Dispose of the converter and clean up resources - */ - async dispose(): Promise { - await this.cleanup(); - } -} - /** * Obsidian Typst PDF Export Plugin - * - * This plugin exports Obsidian notes to PDF using the Typst typesetting system. - * It provides features for converting Obsidian markdown to Typst format and - * generating high-quality PDFs with customizable styling. + * Refactored main plugin class */ +import { + App, + Plugin, + PluginSettingTab, + Setting, + TFile, + TFolder, + Notice, + Menu, + MarkdownView, + Editor +} from 'obsidian'; -/** Export format options for output structure */ -enum ExportFormat { - /** Standard multi-page PDF format */ - Standard = 'standard', - /** Single-page continuous PDF format */ - SinglePage = 'single-page' -} +import { obsidianTypstPDFExportSettings, DEFAULT_SETTINGS, ExportFormat } from './src/core/settings'; +import { PandocTypstConverter } from './src/converters/PandocTypstConverter'; +import { ExportConfigModal } from './src/modal/ExportConfigModal'; +import { ExportConfig, ExportConfigModalSettings } from './src/modal/types'; +import { TemplateManager } from './src/templates/TemplateManager'; +import * as path from 'path'; +import * as fs from 'fs'; -/** Template interface for Typst template management */ -interface Template { - /** Display name of the template */ - name: string; - /** File path to the template */ - filePath: string; - /** Template variables and their types */ - variables: Record; - /** Template metadata */ - metadata: { - author?: string; - version?: string; - description?: string; - compatibility: string[]; - }; -} - -/** Configuration for individual export operations */ -interface ExportConfig { - /** Override default template */ - template?: string; - /** Override default format */ - format?: ExportFormat; - /** Override output folder */ - outputFolder?: string; - /** Template variables for this export */ - templateVariables?: Record; -} - -interface obsidianTypstPDFExportSettings { - /** Path to the Pandoc executable */ - pandocPath: string; - /** Path to the Typst executable */ - typstPath: string; - /** Default output folder for exported PDFs */ - outputFolder: string; - - /** Executable paths configuration */ - executablePaths: { - /** Path to ImageMagick convert command (optional, uses PATH if not specified) */ - imagemagickPath: string; - /** Additional paths to append to PATH environment variable */ - additionalPaths: string[]; - }; - - /** Export defaults */ - exportDefaults: { - /** Default template to use for exports */ - template: string; - /** Default export format */ - format: ExportFormat; - }; - - /** Typography settings */ - typography: { - /** Font families for different text types */ - fonts: { - body: string; - heading: string; - monospace: string; - }; - /** Font sizes */ - fontSizes: { - body: number; - heading: number; - small: number; - }; - }; - - /** Page setup configuration */ - pageSetup: { - /** Page size (e.g., "a4", "letter", "custom") */ - size: string; - /** Page orientation */ - orientation: "portrait" | "landscape"; - /** Page margins in points */ - margins: { - top: number; - right: number; - bottom: number; - left: number; - }; - }; - - /** Behavior flags */ - behavior: { - /** Open PDF after export */ - openAfterExport: boolean; - /** Preserve folder structure in output */ - preserveFolderStructure: boolean; - /** Number of concurrent exports to run (default: 3) */ - exportConcurrency: number; - /** Enable debug mode for verbose logging */ - debugMode: boolean; - }; -} - -const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = { - pandocPath: '', - typstPath: '', - outputFolder: 'exports', - - executablePaths: { - imagemagickPath: '', // Empty means use system PATH - additionalPaths: ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin'] - }, - - exportDefaults: { - template: 'default', - format: ExportFormat.Standard - }, - - typography: { - fonts: { - body: 'Concourse OT', - heading: 'SF Pro Text', - monospace: 'UbuntuMono Nerd Font Mono' - }, - fontSizes: { - body: 11, - heading: 16, - small: 9 - } - }, - - pageSetup: { - size: 'a4', - orientation: 'portrait', - margins: { - top: 72, - right: 72, - bottom: 72, - left: 72 - } - }, - - behavior: { - openAfterExport: true, - preserveFolderStructure: true, - exportConcurrency: 3, - debugMode: false - } -} - -export default class obsidianTypstPDFExport extends Plugin { +export class obsidianTypstPDFExport extends Plugin { settings: obsidianTypstPDFExportSettings; - dependencyChecker: DependencyChecker; - templateManager: TemplateManager; private converter: PandocTypstConverter; - - async onload() { - console.log('Loading Typst PDF Export Plugin...'); - - // Load settings first - await this.loadSettings(); - - // Initialize dependency checker and converter - this.dependencyChecker = new DependencyChecker(); - this.converter = new PandocTypstConverter(); + private templateManager: TemplateManager; + private currentExportController: AbortController | null = null; - // Initialize template manager - const pluginDir = (this.manifest as any).dir || path.join(this.app.vault.configDir, 'plugins', this.manifest.id); - // Convert to absolute path using vault adapter base path - const vaultBasePath = (this.app.vault.adapter as any).basePath || process.cwd(); - const absolutePluginDir = path.resolve(vaultBasePath, pluginDir); - console.log('Plugin directory (relative):', pluginDir); - console.log('Vault base path:', vaultBasePath); - console.log('Plugin directory (absolute):', absolutePluginDir); - console.log('Manifest dir:', (this.manifest as any).dir); - console.log('Config dir:', this.app.vault.configDir); - this.templateManager = new TemplateManager(this.app, absolutePluginDir); - - // Check dependencies asynchronously (don't block plugin startup) - this.checkDependenciesAsync(); - - // Register commands - this.registerCommands(); - - // Add ribbon icon with Lucide icon name - this.addRibbonIcon('download', 'Export to PDF with Typst', (event: MouseEvent) => { - this.handleRibbonClick(event); - }); - - // Register context menu events - this.registerEvents(); - - // This adds a settings tab so the user can configure various aspects of the plugin - this.addSettingTab(new TypstPDFExportSettingTab(this.app, this)); -} - - /** - * Auto-detect dependency paths and update settings if not already configured - */ - // Method removed - not needed since paths are already correctly configured in settings - - onunload() { - - } - - /** - * Check dependencies asynchronously without blocking plugin startup - */ - private async checkDependenciesAsync(): Promise { - try { - const additionalPaths = this.settings.executablePaths.additionalPaths; - const result = await this.dependencyChecker.checkAllDependencies( - { customPath: this.settings.pandocPath, additionalPaths }, - { customPath: this.settings.typstPath, additionalPaths }, - { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } - ); - - if (!result.allAvailable) { - // Show notice only if some dependencies are missing - const missingTools = []; - if (!result.pandoc.isAvailable) missingTools.push('Pandoc'); - if (!result.typst.isAvailable) missingTools.push('Typst'); - if (!result.imagemagick.isAvailable) missingTools.push('ImageMagick'); - - new Notice(`Typst PDF Export: ${missingTools.join(' and ')} not found. Use "Check dependencies" command for setup instructions.`, 8000); - } - } catch (error) { - console.warn('Dependency check failed on startup:', error); - } - } - - - /** - * Show detailed dependency status - */ - private async showDependencyStatus(): Promise { - try { - const additionalPaths = this.settings.executablePaths.additionalPaths; - const result = await this.dependencyChecker.checkAllDependencies( - { customPath: this.settings.pandocPath, additionalPaths }, - { customPath: this.settings.typstPath, additionalPaths }, - { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } - ); - - let message = '## Dependency Status\n\n'; - - // Pandoc status - message += '### Pandoc\n'; - if (result.pandoc.isAvailable) { - message += `✅ **Available** (v${result.pandoc.version})\n`; - message += `Path: ${result.pandoc.executablePath}\n\n`; - } else { - message += '❌ **Not Available**\n'; - message += `Error: ${result.pandoc.error}\n\n`; - message += this.dependencyChecker.formatInstallationGuide( - this.dependencyChecker.getInstallationGuide('pandoc') - ); - message += '\n\n'; - } - - // Typst status - message += '### Typst\n'; - if (result.typst.isAvailable) { - message += `✅ **Available** (v${result.typst.version})\n`; - message += `Path: ${result.typst.executablePath}\n\n`; - } else { - message += '❌ **Not Available**\n'; - message += `Error: ${result.typst.error}\n\n`; - message += this.dependencyChecker.formatInstallationGuide( - this.dependencyChecker.getInstallationGuide('typst') - ); - } - - // Create and show modal with dependency status - const modal = new DependencyStatusModal(this.app, this); - modal.open(); - - } catch (error) { - new Notice(`Error checking dependencies: ${error instanceof Error ? error.message : String(error)}`); - } - } - - /** - * Show dependency error dialog with installation instructions - */ - private showDependencyErrorDialog(result: { pandoc: any; typst: any; allAvailable: boolean }): void { - let message = '## Missing Dependencies\n\nThe following dependencies are required:\n\n'; - - if (!result.pandoc.isAvailable) { - message += `**Pandoc**: ${result.pandoc.error}\n\n`; - } - - if (!result.typst.isAvailable) { - message += `**Typst**: ${result.typst.error}\n\n`; - } - - message += 'Use the "Check Pandoc and Typst dependencies" command for detailed installation instructions.'; - - const modal = new DependencyStatusModal(this.app, this); - modal.open(); - } - - async loadSettings() { - try { - const loadedData = await this.loadData(); - - if (!loadedData) { - // No saved settings, use defaults - this.settings = { ...DEFAULT_SETTINGS }; - return; - } - - // Start with defaults and merge loaded data - this.settings = { ...DEFAULT_SETTINGS }; - - // Validate and merge loaded settings - const validatedSettings = this.validateSettings(loadedData); - this.settings = { ...this.settings, ...validatedSettings }; - - // Migrate settings if needed - this.settings = this.migrateSettings(this.settings); - - } catch (error) { - console.error('Failed to load Typst PDF Export settings:', error); - new Notice('Failed to load settings, using defaults'); - this.settings = { ...DEFAULT_SETTINGS }; - } - } - - /** - * Validates loaded settings data and returns a clean settings object - */ - private validateSettings(data: any): Partial { - const validated: Partial = {}; - - // Validate string paths - if (typeof data.pandocPath === 'string') { - validated.pandocPath = data.pandocPath; - } - if (typeof data.typstPath === 'string') { - validated.typstPath = data.typstPath; - } - if (typeof data.outputFolder === 'string') { - validated.outputFolder = data.outputFolder; - } - - // Validate export defaults - if (data.exportDefaults && typeof data.exportDefaults === 'object') { - const exportDefaults: Partial = {}; - - if (typeof data.exportDefaults.template === 'string') { - exportDefaults.template = data.exportDefaults.template; - } - - // Validate enum values - if (Object.values(ExportFormat).includes(data.exportDefaults.format)) { - exportDefaults.format = data.exportDefaults.format; - } - - - if (Object.keys(exportDefaults).length > 0) { - validated.exportDefaults = exportDefaults as any; - } - } - - // Validate typography settings - if (data.typography && typeof data.typography === 'object') { - const typography: Partial = {}; - - if (data.typography.fonts && typeof data.typography.fonts === 'object') { - const fonts: Partial = {}; - ['body', 'heading', 'monospace'].forEach(key => { - if (typeof data.typography.fonts[key] === 'string') { - (fonts as any)[key] = data.typography.fonts[key]; - } - }); - if (Object.keys(fonts).length > 0) { - typography.fonts = fonts as any; - } - } - - if (data.typography.fontSizes && typeof data.typography.fontSizes === 'object') { - const fontSizes: Partial = {}; - ['body', 'heading', 'small'].forEach(key => { - if (typeof data.typography.fontSizes[key] === 'number' && data.typography.fontSizes[key] > 0) { - (fontSizes as any)[key] = data.typography.fontSizes[key]; - } - }); - if (Object.keys(fontSizes).length > 0) { - typography.fontSizes = fontSizes as any; - } - } - - if (Object.keys(typography).length > 0) { - validated.typography = typography as any; - } - } - - // Validate page setup - if (data.pageSetup && typeof data.pageSetup === 'object') { - const pageSetup: Partial = {}; - - if (typeof data.pageSetup.size === 'string') { - pageSetup.size = data.pageSetup.size; - } - - if (['portrait', 'landscape'].includes(data.pageSetup.orientation)) { - pageSetup.orientation = data.pageSetup.orientation; - } - - if (data.pageSetup.margins && typeof data.pageSetup.margins === 'object') { - const margins: Partial = {}; - ['top', 'right', 'bottom', 'left'].forEach(key => { - if (typeof data.pageSetup.margins[key] === 'number' && data.pageSetup.margins[key] >= 0) { - (margins as any)[key] = data.pageSetup.margins[key]; - } - }); - if (Object.keys(margins).length > 0) { - pageSetup.margins = margins as any; - } - } - - if (Object.keys(pageSetup).length > 0) { - validated.pageSetup = pageSetup as any; - } - } - - // Validate behavior flags - if (data.behavior && typeof data.behavior === 'object') { - const behavior: Partial = {}; - - if (typeof data.behavior.openAfterExport === 'boolean') { - behavior.openAfterExport = data.behavior.openAfterExport; - } - - if (typeof data.behavior.preserveFolderStructure === 'boolean') { - behavior.preserveFolderStructure = data.behavior.preserveFolderStructure; - } - - if (typeof data.behavior.exportConcurrency === 'number' && - data.behavior.exportConcurrency > 0 && - data.behavior.exportConcurrency <= 10) { - behavior.exportConcurrency = data.behavior.exportConcurrency; - } - - if (Object.keys(behavior).length > 0) { - validated.behavior = behavior as any; - } - } - - // Validate executable paths - if (data.executablePaths && typeof data.executablePaths === 'object') { - const executablePaths: Partial = {}; - - if (typeof data.executablePaths.imagemagickPath === 'string') { - executablePaths.imagemagickPath = data.executablePaths.imagemagickPath; - } - - if (Array.isArray(data.executablePaths.additionalPaths)) { - // Validate each path is a string - const validPaths = data.executablePaths.additionalPaths.filter( - (path: any) => typeof path === 'string' - ); - if (validPaths.length > 0) { - executablePaths.additionalPaths = validPaths; - } - } - - if (Object.keys(executablePaths).length > 0) { - validated.executablePaths = executablePaths as any; - } - } - - return validated; - } - - /** - * Migrates settings from older versions to current format - */ - private migrateSettings(settings: obsidianTypstPDFExportSettings): obsidianTypstPDFExportSettings { - // Future version migrations can be added here - // For now, just ensure all required properties exist with defaults + async onload() { + await this.loadSettings(); - const migrated = { ...settings }; + // Initialize components + this.converter = new PandocTypstConverter(this); + this.templateManager = new TemplateManager(this); - // Ensure all nested objects exist - if (!migrated.exportDefaults) { - migrated.exportDefaults = DEFAULT_SETTINGS.exportDefaults; - } + // Add ribbon icon + this.addRibbonIcon('download', 'Export to PDF with Typst', (event: MouseEvent) => { + this.handleRibbonClick(event); + }); - if (!migrated.typography) { - migrated.typography = DEFAULT_SETTINGS.typography; - } + // Register commands + this.registerCommands(); - if (!migrated.pageSetup) { - migrated.pageSetup = DEFAULT_SETTINGS.pageSetup; - } + // Register event handlers + this.registerEventHandlers(); - if (!migrated.behavior) { - migrated.behavior = DEFAULT_SETTINGS.behavior; - } else { - // Migrate behavior settings - add exportConcurrency if missing - if (typeof migrated.behavior.exportConcurrency !== 'number') { - migrated.behavior.exportConcurrency = DEFAULT_SETTINGS.behavior.exportConcurrency; - } - } + // Add settings tab + this.addSettingTab(new ObsidianTypstPDFExportSettingTab(this.app, this)); - if (!migrated.executablePaths) { - migrated.executablePaths = DEFAULT_SETTINGS.executablePaths; - } - - return migrated; + // Check dependencies on startup (async, don't await) + this.checkDependenciesAsync(); + + console.log('Obsidian Typst PDF Export plugin loaded'); } - - async saveSettings() { - try { - // Validate settings before saving - const validatedSettings = this.validateSettings(this.settings); - const mergedSettings = { ...DEFAULT_SETTINGS, ...validatedSettings }; - - // Update current settings with validated data - this.settings = mergedSettings; - - // Save to disk - await this.saveData(this.settings); - - } catch (error) { - console.error('Failed to save Typst PDF Export settings:', error); - new Notice('Failed to save settings'); - throw error; - } - } - - /** - * Register all commands with proper checkCallback validation - */ + private registerCommands(): void { - // Export current note to Typst PDF + // Export current note command this.addCommand({ id: 'export-current-note', - name: 'Export current note to Typst PDF', + name: 'Export current note to PDF', hotkeys: [{ modifiers: ['Mod', 'Shift'], key: 'e' }], - checkCallback: (checking: boolean) => { - const activeFile = this.app.workspace.getActiveFile(); - const canRun = activeFile && activeFile.extension === 'md'; - - if (canRun && !checking) { - this.handleExportWithDependencyCheck(activeFile); - } - - return !!canRun; + editorCallback: (editor: Editor, view: MarkdownView) => { + this.exportCurrentNote(view); } }); - - // Export with previous settings + + // Export with configuration command this.addCommand({ - id: 'export-with-previous-settings', - name: 'Export with previous settings', + id: 'export-with-config', + name: 'Export to PDF with configuration', hotkeys: [{ modifiers: ['Mod', 'Shift', 'Alt'], key: 'e' }], - checkCallback: (checking: boolean) => { - const activeFile = this.app.workspace.getActiveFile(); - const canRun = activeFile && activeFile.extension === 'md' && - this.settings.exportDefaults && Object.keys(this.settings.exportDefaults).length > 0; - - if (canRun && !checking) { - this.handleExportWithPreviousSettings(activeFile); - } - - return !!canRun; + editorCallback: (editor: Editor, view: MarkdownView) => { + this.showExportModal(view); } }); - - // Export folder to PDF + + // Export folder to PDF command this.addCommand({ id: 'export-folder-to-pdf', name: 'Export folder to PDF', @@ -1210,8 +93,17 @@ export default class obsidianTypstPDFExport extends Plugin { return !!canRun; } }); - - // Keep existing dependency check command + + // Batch export command + this.addCommand({ + id: 'batch-export', + name: 'Batch export notes to PDF', + callback: () => { + this.batchExportNotes(); + } + }); + + // Check dependencies command this.addCommand({ id: 'check-dependencies', name: 'Check Pandoc and Typst dependencies', @@ -1220,499 +112,442 @@ export default class obsidianTypstPDFExport extends Plugin { } }); } - - /** - * Register workspace events for context menus - */ - private registerEvents(): void { - // Register file context menu event + + private registerEventHandlers(): void { + // Add context menu item this.registerEvent( - this.app.workspace.on('file-menu', (menu, file, source) => { - if (file instanceof TFile && file.extension === 'md') { + this.app.workspace.on('file-menu', (menu: Menu, file: TFile) => { + if (file.extension === 'md') { menu.addItem((item) => { item - .setTitle('Export to Typst PDF') - .setIcon('file-pdf') + .setTitle('Export to PDF (Typst)') + .setIcon('file-output') .onClick(() => { - this.handleExportWithDependencyCheck(file); - }); - }); - } - - // Add folder export option for directories - if (file instanceof TFolder) { - menu.addItem((item) => { - item - .setTitle('Export folder to PDF') - .setIcon('folder-open') - .onClick(() => { - this.handleFolderExport(file); + this.exportFile(file); }); }); } }) ); - - // Register files context menu for multiple file selection + + // Add editor menu item this.registerEvent( - this.app.workspace.on('files-menu', (menu, files, source) => { - const markdownFiles = files.filter(f => f instanceof TFile && f.extension === 'md') as TFile[]; - - if (markdownFiles.length > 0) { - menu.addItem((item) => { - item - .setTitle(`Export ${markdownFiles.length} files to PDF`) - .setIcon('file-pdf') - .onClick(() => { - this.handleBatchExport(markdownFiles); - }); - }); - } + this.app.workspace.on('editor-menu', (menu: Menu, editor: Editor, view: MarkdownView) => { + menu.addItem((item) => { + item + .setTitle('Export to PDF (Typst)') + .setIcon('file-output') + .onClick(() => { + this.exportCurrentNote(view); + }); + }); }) ); } + /** - * Handle ribbon icon click with context menu + * Handle ribbon icon click */ private handleRibbonClick(event: MouseEvent): void { - const activeFile = this.app.workspace.getActiveFile(); + const activeView = this.app.workspace.getActiveViewOfType(MarkdownView); - if (!activeFile || activeFile.extension !== 'md') { + if (!activeView || !activeView.file) { new Notice('Please open a markdown file to export'); return; } - + // Create context menu for ribbon click const menu = new Menu(); - + menu.addItem((item) => item .setTitle('Export current note') - .setIcon('file-pdf') + .setIcon('file-output') .onClick(() => { - this.handleExportWithDependencyCheck(activeFile); + this.exportFile(activeView.file!); }) ); - - if (this.settings.exportDefaults && Object.keys(this.settings.exportDefaults).length > 0) { - menu.addItem((item) => - item - .setTitle('Export with previous settings') - .setIcon('history') - .onClick(() => { - this.handleExportWithPreviousSettings(activeFile); - }) - ); - } - - if (activeFile.parent) { - menu.addSeparator(); - menu.addItem((item) => - item - .setTitle('Export folder to PDF') - .setIcon('folder-open') - .onClick(() => { - this.handleFolderExport(activeFile.parent!); - }) - ); - } - + + menu.addItem((item) => + item + .setTitle('Export with configuration...') + .setIcon('settings') + .onClick(() => { + this.showExportModal(activeView); + }) + ); + + menu.addSeparator(); + + menu.addItem((item) => + item + .setTitle('Batch export...') + .setIcon('folder-output') + .onClick(() => { + this.batchExportNotes(); + }) + ); + menu.showAtMouseEvent(event); } - + /** - * Handle export with dependency checking for a specific file + * Export the current note with default settings */ - private async handleExportWithDependencyCheck(file?: TFile | null): Promise { + private async exportCurrentNote(view: MarkdownView): Promise { + const file = view.file; if (!file) { - file = this.app.workspace.getActiveFile(); + new Notice('No active file to export'); + return; } - if (!file || file.extension !== 'md') { - new Notice('Please select a markdown file to export'); - return; - } - - const additionalPaths = this.settings.executablePaths.additionalPaths; - const result = await this.dependencyChecker.checkAllDependencies( - { customPath: this.settings.pandocPath, additionalPaths }, - { customPath: this.settings.typstPath, additionalPaths }, - { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } - ); - - if (!result.allAvailable) { - this.showDependencyErrorDialog(result); - return; - } - - // Get the current file or active file - const activeFile = file || this.app.workspace.getActiveFile(); - if (!activeFile) { - new Notice('No file selected for export.'); - return; - } - - // Open the export configuration modal - new ExportConfigModal( - this.app, - this, - activeFile.path, - async (config) => { - await this.performExport(activeFile, config); - }, - async () => { - // Modal was cancelled - no action needed - } - ).open(); + await this.exportFile(file); } - + /** - * Handle export with previous settings + * Show the export configuration modal */ - private async handleExportWithPreviousSettings(file: TFile): Promise { - const additionalPaths = this.settings.executablePaths.additionalPaths; - const result = await this.dependencyChecker.checkAllDependencies( - { customPath: this.settings.pandocPath, additionalPaths }, - { customPath: this.settings.typstPath, additionalPaths }, - { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } - ); - - if (!result.allAvailable) { - this.showDependencyErrorDialog(result); + private async showExportModal(view: MarkdownView): Promise { + const file = view.file; + if (!file) { + new Notice('No active file to export'); return; } - - // TODO: Implement direct export using previous settings without modal - new Notice('Export with previous settings will be implemented in a future version.'); - } - - /** - * Handle folder export with batch processing - */ - private async handleFolderExport(folder: TFolder): Promise { - const additionalPaths = this.settings.executablePaths.additionalPaths; - const result = await this.dependencyChecker.checkAllDependencies( - { customPath: this.settings.pandocPath, additionalPaths }, - { customPath: this.settings.typstPath, additionalPaths }, - { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } - ); - - if (!result.allAvailable) { - this.showDependencyErrorDialog(result); - return; - } - - // Get all markdown files in the folder recursively - const markdownFiles = this.getMarkdownFilesInFolder(folder); - if (markdownFiles.length === 0) { - new Notice(`No markdown files found in folder: ${folder.name}`); - return; - } - - // Open export configuration modal for batch mode - new ExportConfigModal( - this.app, - this, - folder.path, - async (config) => { - // TODO: Implement batch export with config - await this.processBatchFiles(markdownFiles, config); - }, - async () => { - // Modal was cancelled - no action needed - } - ).open(); - } - - /** - * Handle batch export for multiple selected files - */ - private async handleBatchExport(files: TFile[]): Promise { - const additionalPaths = this.settings.executablePaths.additionalPaths; - const result = await this.dependencyChecker.checkAllDependencies( - { customPath: this.settings.pandocPath, additionalPaths }, - { customPath: this.settings.typstPath, additionalPaths }, - { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } - ); - - if (!result.allAvailable) { - this.showDependencyErrorDialog(result); - return; - } - - // Open export configuration modal for batch mode - new ExportConfigModal( - this.app, - this, - 'batch-export', - async (config) => { - // Process each file individually with the same config - for (const file of files) { - await this.performExport(file, config); - } - }, - async () => { - // Modal was cancelled - no action needed - } - ).open(); - } - - /** - * Get all markdown files in a folder recursively - */ - private getMarkdownFilesInFolder(folder: TFolder): TFile[] { - const markdownFiles: TFile[] = []; + // Prepare modal settings + const modalSettings: Partial = { + notePath: file.path, + noteTitle: file.basename, + template: this.settings.exportDefaults.template, + format: this.settings.exportDefaults.format, + outputFolder: this.settings.outputFolder, + availableTemplates: await this.templateManager.getAvailableTemplates() + }; - const traverse = (currentFolder: TFolder) => { - for (const child of currentFolder.children) { - if (child instanceof TFile && child.extension === 'md') { - markdownFiles.push(child); - } else if (child instanceof TFolder) { - traverse(child); - } + // Show modal + const modal = new ExportConfigModal( + this.app, + this, + modalSettings, + async (config: ExportConfig) => { + await this.exportFileWithConfig(file, config); + }, + () => { + this.cancelExport(); + } + ); + + modal.open(); + } + + /** + * Export a file with default configuration + */ + private async exportFile(file: TFile): Promise { + const config: ExportConfig = { + template: this.settings.exportDefaults.template, + format: this.settings.exportDefaults.format, + outputFolder: this.settings.outputFolder, + typography: { + fontFamily: this.settings.typography.fonts.body, + fontSize: `${this.settings.typography.fontSizes.body}pt`, + lineHeight: '1.5' } }; - traverse(folder); - return markdownFiles; + await this.exportFileWithConfig(file, config); } - + /** - * Simple concurrency limiter for batch operations (simplified version) + * Export a file with specific configuration */ - private async processBatch( - items: T[], - processor: (item: T, index: number) => Promise, - concurrency: number = 3 - ): Promise<{ results: (R | Error)[]; errors: number }> { - const results: (R | Error)[] = []; - let errors = 0; - - // Simple batch processing - process items in chunks - for (let i = 0; i < items.length; i += concurrency) { - const chunk = items.slice(i, i + concurrency); - const promises = chunk.map(async (item, index) => { - try { - return await processor(item, i + index); - } catch (error) { - errors++; - return error instanceof Error ? error : new Error(String(error)); - } + private async exportFileWithConfig(file: TFile, config: ExportConfig): Promise { + try { + // Create abort controller for cancellation + this.currentExportController = new AbortController(); + + // Show progress notice + const progressNotice = new Notice('Exporting to PDF...', 0); + + // Read file content + const content = await this.app.vault.read(file); + + // Get plugin directory and vault base path + const vaultPath = (this.app.vault.adapter as any).basePath; + const pluginDir = path.join(vaultPath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export'); + + // Create temp directory for processing + const os = require('os'); + const tempDir = os.tmpdir(); + + // Preprocess the markdown content using MarkdownPreprocessor + const { MarkdownPreprocessor } = await import('./src/MarkdownPreprocessor'); + const preprocessor = new MarkdownPreprocessor({ + vaultPath: vaultPath, + options: { + includeMetadata: true, + preserveFrontmatter: false, + baseUrl: undefined + }, + wikilinkConfig: { + format: 'md', + extension: '.md' + }, + noteTitle: file.basename }); - const chunkResults = await Promise.all(promises); - results.push(...chunkResults); - } - - return { results, errors }; - } - - /** - * Perform export of a single file using the conversion pipeline - */ - private async performExport(file: TFile, config: ExportConfig): Promise { -try { - // Read the file content - const content = await this.app.vault.read(file); - - // Set up path utilities (used throughout function) - const path = require('path'); - const fs = require('fs'); - const vaultBasePath = (this.app.vault.adapter as any).basePath || process.cwd(); - - // Create output directory if it doesn't exist - const absoluteOutputDir = path.resolve(vaultBasePath, this.settings.outputFolder); - if (!fs.existsSync(absoluteOutputDir)) { - fs.mkdirSync(absoluteOutputDir, { recursive: true }); - } - - // Generate output filename - const baseName = file.name.replace(/\.md$/, ''); - const outputPath = path.join(absoluteOutputDir, `${baseName}.pdf`); - - console.log('Export: Output directory:', absoluteOutputDir); - console.log('Export: Output path:', outputPath); - console.log('Export: Vault base path:', vaultBasePath); - - // Create temporary file for the processed markdown - const tempDir = require('os').tmpdir(); - const tempInputFile = path.join(tempDir, `${baseName}_${Date.now()}.md`); - - // Preprocess the markdown content using MarkdownPreprocessor - const MarkdownPreprocessor = require('./src/MarkdownPreprocessor').MarkdownPreprocessor; - const preprocessor = new MarkdownPreprocessor({ - vaultPath: vaultBasePath, - options: { - includeMetadata: true, - preserveFrontmatter: false, - baseUrl: undefined - }, - wikilinkConfig: { - format: 'md', - extension: '.md' - } - }); - - const processedResult = await preprocessor.process(content); - - if (processedResult.errors.length > 0) { - console.warn('Preprocessing errors:', processedResult.errors); - } - if (processedResult.warnings.length > 0) { - console.warn('Preprocessing warnings:', processedResult.warnings); - } - - // Process PDF embeds if any were found - if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) { - console.log(`Export: Processing ${processedResult.metadata.pdfEmbeds.length} PDF embeds`); - await this.processPdfEmbeds(processedResult, vaultBasePath, tempDir, file); - } - - // Process image embeds if any were found - if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) { - console.log(`Export: Processing ${processedResult.metadata.imageEmbeds.length} image embeds`); - await this.processImageEmbeds(processedResult, vaultBasePath, tempDir, file); - } - - // Debug: Log processed content to see what image paths look like - console.log('Export: Original content length:', content.length); - console.log('Export: Processed content length:', processedResult.content.length); - - // Log a sample of processed content to see image references - const imageSample = processedResult.content.split('\n').filter((line: string) => - line.includes('![') || line.includes(' 0) { + console.warn('Preprocessing errors:', processedResult.errors); + } + if (processedResult.warnings.length > 0) { + console.warn('Preprocessing warnings:', processedResult.warnings); + } + + // Process PDF embeds if any were found + if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) { + console.log(`Export: Processing ${processedResult.metadata.pdfEmbeds.length} PDF embeds`); + await this.processPdfEmbeds(processedResult, vaultPath, tempDir, file); + } + + // Process image embeds if any were found + if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) { + console.log(`Export: Processing ${processedResult.metadata.imageEmbeds.length} image embeds`); + await this.processImageEmbeds(processedResult, vaultPath, tempDir, file); + } + + // Prepare output path + const outputPath = this.prepareOutputPath(file, config.outputFolder || this.settings.outputFolder); + + // Get full template path + const templatePath = config.template ? + this.templateManager.getTemplatePath(config.template) : + this.templateManager.getTemplatePath('default.typ'); + + // Convert to PDF using the preprocessed content + const result = await this.converter.convertMarkdownToPDF( + processedResult.content, // Use preprocessed content instead of raw content + outputPath, + { + template: templatePath, + variables: { + ...config.templateVariables, + font: config.typography?.fontFamily || this.settings.typography.fonts.body, + fontsize: config.typography?.fontSize || `${this.settings.typography.fontSizes.body}pt`, + lineheight: config.typography?.lineHeight || '1.5' + }, + pluginDir: pluginDir, + vaultBasePath: vaultPath + }, + (message: string, progress?: number) => { + progressNotice.setMessage(`${message}${progress ? ` (${Math.round(progress)}%)` : ''}`); + } + ); + + // Hide progress notice + progressNotice.hide(); + + if (result.success) { + new Notice(`PDF exported successfully to ${result.outputPath}`); + + // Open PDF if configured + if (this.settings.behavior.openAfterExport) { + this.openPDF(result.outputPath!); + } + } else { + new Notice(`Export failed: ${result.error}`); + } + } catch (error) { + console.error('Export error:', error); + new Notice(`Export failed: ${error.message}`); + } finally { + this.currentExportController = null; + + // Clean up temporary directories + try { + const pathModule = require('path'); + const fs = require('fs'); + + // Clean up temp-images directory + const vaultTempImagesDir = pathModule.join(vaultPath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-images'); + if (fs.existsSync(vaultTempImagesDir)) { + const files = fs.readdirSync(vaultTempImagesDir); + for (const file of files) { + fs.unlinkSync(pathModule.join(vaultTempImagesDir, file)); + } + console.log('Export: Cleaned up temp-images directory'); + } + + // Clean up temp-pandoc directory + const vaultTempPandocDir = pathModule.join(vaultPath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-pandoc'); + if (fs.existsSync(vaultTempPandocDir)) { + const files = fs.readdirSync(vaultTempPandocDir); + for (const file of files) { + fs.unlinkSync(pathModule.join(vaultTempPandocDir, file)); + } + console.log('Export: Cleaned up temp-pandoc directory'); + } + } catch (cleanupError) { + console.warn('Export: Failed to clean up temporary directories:', cleanupError); } - // Remove the directory itself - await fs.rmdir(vaultTempImagesDir); - console.log('Export: Cleaned up temporary PDF preview images'); - } catch (dirError) { - // Directory doesn't exist, which is fine } - } catch (cleanupError) { - console.warn('Failed to clean up temporary PDF images:', cleanupError); } - if (result.success) { - new Notice(`PDF exported successfully: ${outputPath}`); - - // Optionally open the PDF after export - if (this.settings.behavior.openAfterExport) { - require('electron').shell.openPath(outputPath); - } - } else { - new Notice(`Export failed: ${result.error || 'Unknown error'}`, 5000); - console.error('Export failed:', result); - } - -} catch (error) { - new Notice(`Export failed: ${error instanceof Error ? error.message : String(error)}`, 5000); - console.error('Export error:', error); -} -} - /** - * Process batch of files with export configuration + * Cancel the current export */ - private async processBatchFiles(files: TFile[], config: ExportConfig): Promise { - new Notice(`Starting batch export of ${files.length} files...`); - - const processor = async (file: TFile, index: number) => { - new Notice(`Processing file ${index + 1}/${files.length}: ${file.name}`); - await this.performExport(file, config); - return `Exported ${file.name}`; - }; + private cancelExport(): void { + if (this.currentExportController) { + this.currentExportController.abort(); + this.currentExportController = null; + new Notice('Export cancelled'); + } + } + + /** + * Batch export multiple notes + */ + private async batchExportNotes(): Promise { + // This would show a modal to select multiple files + // Implementation deferred for now + new Notice('Batch export feature coming soon'); + } - const result = await this.processBatch(files, processor, this.settings.behavior.exportConcurrency); + + /** + * Export an entire folder to PDF + */ + private async handleFolderExport(folder: TFolder): Promise { + // Get all markdown files in the folder + const markdownFiles = folder.children.filter( + (file) => file instanceof TFile && file.extension === 'md' + ) as TFile[]; - if (result.errors > 0) { - new Notice(`Batch export completed with ${result.errors} errors out of ${files.length} files.`); - } else { - new Notice(`Successfully exported ${files.length} files.`); + if (markdownFiles.length === 0) { + new Notice('No markdown files found in this folder'); + return; + } + + new Notice(`Exporting ${markdownFiles.length} files from ${folder.name}...`); + + let successful = 0; + let failed = 0; + + for (const file of markdownFiles) { + try { + await this.exportFile(file); + successful++; + } catch (error) { + console.error(`Failed to export ${file.name}:`, error); + failed++; + } + } + + new Notice( + `Export complete: ${successful} successful, ${failed} failed` + ); + } + + /** + * Show dependency status modal + */ + private async showDependencyStatus(): Promise { + const { exec } = require('child_process'); + const { promisify } = require('util'); + const execAsync = promisify(exec); + + let pandocVersion = 'Not found'; + let typstVersion = 'Not found'; + + // Check Pandoc + try { + const pandocPath = this.settings.pandocPath || 'pandoc'; + const { stdout } = await execAsync(`${pandocPath} --version`); + const match = stdout.match(/pandoc\s+([\d.]+)/); + if (match) { + pandocVersion = match[1]; + } + } catch (error) { + console.error('Pandoc check failed:', error); + } + + // Check Typst + try { + const typstPath = this.settings.typstPath || 'typst'; + const { stdout } = await execAsync(`${typstPath} --version`); + const match = stdout.match(/typst\s+([\d.]+)/); + if (match) { + typstVersion = match[1]; + } + } catch (error) { + console.error('Typst check failed:', error); + } + + // Show results in a notice + const message = `Dependency Status: +Pandoc: ${pandocVersion} +Typst: ${typstVersion} + +${pandocVersion === 'Not found' || typstVersion === 'Not found' ? + 'Missing dependencies! Please install them and check the paths in settings.' : + 'All dependencies found!'}`; + + new Notice(message, 10000); // Show for 10 seconds + } + + private async checkDependenciesAsync(): Promise { + // Check dependencies silently on startup + try { + const { execSync } = require('child_process'); + const path = require('path'); + + // Augment PATH + const homeDir = process.env.HOME || process.env.USERPROFILE; + const localBin = path.join(homeDir, '.local', 'bin'); + const cargoHome = process.env.CARGO_HOME || path.join(homeDir, '.cargo'); + const cargoBin = path.join(cargoHome, 'bin'); + + const augmentedPath = `${process.env.PATH}:${localBin}:${cargoBin}:/usr/local/bin:/opt/homebrew/bin`; + const env = { ...process.env, PATH: augmentedPath }; + + let missingDeps = []; + + // Check Pandoc + try { + execSync('pandoc --version', { encoding: 'utf8', env }); + } catch { + missingDeps.push('Pandoc'); + } + + // Check Typst + try { + execSync('typst --version', { encoding: 'utf8', env }); + } catch { + missingDeps.push('Typst'); + } + + // Only show notice if dependencies are missing + if (missingDeps.length > 0) { + new Notice( + `Obsidian Typst PDF Export: Missing dependencies: ${missingDeps.join(', ')}. ` + + `Run "Check Dependencies" command for details.`, + 8000 + ); + } + } catch (error) { + console.error('Error checking dependencies:', error); } } /** - * Process PDF embeds by converting first page to images and creating combined output + * Process PDF embeds - convert PDF pages to images for inclusion */ private async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise { - const { PdfToImageConverter } = require('./src/PdfToImageConverter'); + const { PdfToImageConverter } = await import('./src/PdfToImageConverter'); const converter = PdfToImageConverter.getInstance(this); - const path = require('path'); + const pathModule = require('path'); const fs = require('fs'); console.log(`Export: Processing ${processedResult.metadata.pdfEmbeds.length} PDF embeds`); @@ -1729,34 +564,32 @@ try { // Try multiple path resolution strategies const possiblePaths = [ // Strategy 1: Relative to vault root (standard Obsidian behavior) - path.resolve(vaultBasePath, decodedPath), + pathModule.resolve(vaultBasePath, decodedPath), // Strategy 2: Relative to current file's directory (for local attachments) - currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null + currentFile ? pathModule.resolve(vaultBasePath, pathModule.dirname(currentFile.path), decodedPath) : null ].filter(p => p !== null); let fullPdfPath = null; - let validPath = null; // Try each possible path until we find one that exists for (const possiblePath of possiblePaths) { console.log(`Export: Checking path: ${possiblePath}`); if (fs.existsSync(possiblePath)) { fullPdfPath = possiblePath; - validPath = possiblePath; console.log(`Export: Found PDF at: ${fullPdfPath}`); break; } } if (!fullPdfPath) { - console.warn(`Export: PDF file not found in any of the expected locations: ${possiblePaths.join(', ')}`); - // Replace marker with fallback link - const fallbackOutput = `[⚠️ **PDF not found:** ${pdfEmbed.baseName}](${decodedPath})`; + console.warn(`Export: PDF file not found: ${decodedPath}`); + // Replace marker with fallback message + const fallbackOutput = `*⚠️ PDF not found: ${pdfEmbed.baseName}*`; updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); continue; } - // Convert PDF first page to image + // Convert PDF first page to image - pass options object as third parameter const result = await converter.convertFirstPageToImage( fullPdfPath, tempDir, @@ -1768,46 +601,61 @@ try { } ); - if (result.success) { - // Create a temporary images directory within the vault for Typst access - const vaultTempImagesDir = path.join(vaultBasePath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-images'); - const fs_promises = require('fs').promises; - await fs_promises.mkdir(vaultTempImagesDir, { recursive: true }); + if (result.success && result.imagePath) { + // Copy image to vault temp directory for access + const vaultTempImagesDir = pathModule.join(vaultBasePath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-images'); + await fs.promises.mkdir(vaultTempImagesDir, { recursive: true }); - // Copy the image from temp directory to vault temp directory - const originalImageName = path.basename(result.imagePath); - const vaultImagePath = path.join(vaultTempImagesDir, originalImageName); - await fs_promises.copyFile(result.imagePath, vaultImagePath); + const imageFileName = `${pdfEmbed.baseName}_preview.png`; + const vaultImagePath = pathModule.join(vaultTempImagesDir, imageFileName); + await fs.promises.copyFile(result.imagePath, vaultImagePath); // Get relative path for the generated image from vault base - const relativeImagePath = path.relative(vaultBasePath, vaultImagePath); + const relativeImagePath = pathModule.relative(vaultBasePath, vaultImagePath); - // Use relative path to the original PDF from vault base for download link - const relativePdfPath = path.relative(vaultBasePath, validPath); + // Use relative path to the original PDF from vault base for pdf.embed + const relativePdfPath = pathModule.relative(vaultBasePath, fullPdfPath); - // Create combined output: image preview + download link + // Create combined output with image and Typst pdf.embed + // Use raw Typst blocks for the pdf.embed call const combinedOutput = [ `![${pdfEmbed.baseName} - Page 1](${relativeImagePath})`, '', - `[📎 **Download PDF:** ${pdfEmbed.baseName}](${relativePdfPath})` + '```{=typst}', + `#pdf.embed("${relativePdfPath}", description: "${pdfEmbed.baseName}", mime-type: "application/pdf")`, + '```', + '', + `*PDF attached: ${pdfEmbed.baseName} - check your PDF reader's attachment panel*` ].join('\n'); // Replace the placeholder with the combined output updatedContent = updatedContent.replace(pdfEmbed.marker, combinedOutput); - console.log(`Export: Successfully processed PDF embed: ${pdfEmbed.baseName}`); + console.log(`Export: Successfully processed PDF embed with pdf.embed: ${pdfEmbed.baseName}`); } else { - console.error(`Export: Failed to convert PDF: ${result.error}`); - // Replace with download link only - const relativePdfPath = path.relative(vaultBasePath, validPath); - const fallbackOutput = `[📎 **Download PDF:** ${pdfEmbed.baseName}](${relativePdfPath})`; + console.warn(`Export: Failed to convert PDF to image: ${result.error}`); + const relativePdfPath = pathModule.relative(vaultBasePath, fullPdfPath); + // Even without preview image, still embed the PDF + const fallbackOutput = [ + '```{=typst}', + `#pdf.embed("${relativePdfPath}", description: "${pdfEmbed.baseName}", mime-type: "application/pdf")`, + '```', + '', + `*PDF attached: ${pdfEmbed.baseName} - check your PDF reader's attachment panel*` + ].join('\n'); updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); } } catch (error) { - console.error(`Export: Error processing PDF embed ${pdfEmbed.baseName}:`, error); - // Replace with download link only as fallback - const decodedPath = decodeURIComponent(pdfEmbed.sanitizedPath); - const fallbackOutput = `[📎 **Download PDF:** ${pdfEmbed.baseName}](${decodedPath})`; + console.error(`Export: Error processing PDF embed ${pdfEmbed.originalPath}:`, error); + // Still try to embed the PDF even if there's a processing error + const relativePdfPath = pathModule.relative(vaultBasePath, pdfEmbed.originalPath); + const fallbackOutput = [ + '```{=typst}', + `#pdf.embed("${relativePdfPath}", description: "${pdfEmbed.baseName} (error occurred)", mime-type: "application/pdf")`, + '```', + '', + `*PDF attached: ${pdfEmbed.baseName} (processing error) - check your PDF reader's attachment panel*` + ].join('\n'); updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); } } @@ -1815,23 +663,18 @@ try { // Update the processed result with the new content processedResult.content = updatedContent; } - + /** - * Process regular image embeds by copying them to vault location for Typst access + * Process image embeds - ensure images are accessible for Typst */ private async processImageEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise { - const path = require('path'); + const pathModule = require('path'); const fs = require('fs'); console.log(`Export: Processing ${processedResult.metadata.imageEmbeds.length} image embeds`); let updatedContent = processedResult.content; - // Create vault temp images directory - const vaultTempImagesDir = path.join(vaultBasePath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-images'); - const fs_promises = require('fs').promises; - await fs_promises.mkdir(vaultTempImagesDir, { recursive: true }); - for (const imageEmbed of processedResult.metadata.imageEmbeds) { try { console.log(`Export: Processing image embed: ${imageEmbed.originalPath}`); @@ -1842,439 +685,174 @@ try { // Try multiple path resolution strategies const possiblePaths = [ // Strategy 1: Relative to vault root (standard Obsidian behavior) - path.resolve(vaultBasePath, decodedPath), - // Strategy 2: Direct path if it's just a filename (check vault root) - path.resolve(vaultBasePath, imageEmbed.fileName), - // Strategy 3: Relative to current file's directory (for local attachments) - currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null, - currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), imageEmbed.fileName) : null, - // Strategy 4: Check common attachment directories - path.resolve(vaultBasePath, 'attachments', imageEmbed.fileName), - path.resolve(vaultBasePath, 'assets', imageEmbed.fileName), - path.resolve(vaultBasePath, 'images', imageEmbed.fileName) + pathModule.resolve(vaultBasePath, decodedPath), + // Strategy 2: Relative to current file's directory (for local attachments) + currentFile ? pathModule.resolve(vaultBasePath, pathModule.dirname(currentFile.path), decodedPath) : null, + // Strategy 3: Check in attachments folder (common pattern) + pathModule.resolve(vaultBasePath, 'attachments', pathModule.basename(decodedPath)) ].filter(p => p !== null); let fullImagePath = null; - let validPath = null; // Try each possible path until we find one that exists for (const possiblePath of possiblePaths) { - console.log(`Export: Checking path: ${possiblePath}`); if (fs.existsSync(possiblePath)) { fullImagePath = possiblePath; - validPath = possiblePath; console.log(`Export: Found image at: ${fullImagePath}`); break; } } if (!fullImagePath) { - console.warn(`Export: Image file not found in any of the expected locations: ${possiblePaths.join(', ')}`); - // Replace marker with fallback link or broken image indicator - const fallbackOutput = `![⚠️ Image not found: ${imageEmbed.baseName}](${decodedPath})`; + console.warn(`Export: Image file not found: ${decodedPath}`); + // Keep the original marker or replace with placeholder + const fallbackOutput = `[⚠️ **Image not found:** ${imageEmbed.alt || imageEmbed.originalPath}]`; updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput); continue; } - // Copy image to vault temp directory (convert WebP to PNG if needed) - const originalImageName = path.basename(fullImagePath); - const fileExtension = path.extname(originalImageName).toLowerCase(); + // Get relative path from vault base for the image + const relativeImagePath = pathModule.relative(vaultBasePath, fullImagePath); - let vaultImagePath; - let finalImageName; + // Replace the marker with Markdown image syntax (Pandoc will convert to Typst) + const markdownImage = imageEmbed.alt ? + `![${imageEmbed.alt}](${relativeImagePath})` : + `![](${relativeImagePath})`; - if (fileExtension === '.webp') { - // Convert WebP to PNG using ImageMagick - const pngFileName = originalImageName.replace(/\.webp$/i, '.png'); - vaultImagePath = path.join(vaultTempImagesDir, pngFileName); - finalImageName = pngFileName; - - console.log(`Export: Converting WebP to PNG: ${originalImageName} -> ${pngFileName}`); - - const { exec } = require('child_process'); - const util = require('util'); - const execAsync = util.promisify(exec); - - try { - // Use configured ImageMagick path or fall back to system PATH - const convertPath = this.settings.executablePaths.imagemagickPath || 'convert'; - await execAsync(`"${convertPath}" "${fullImagePath}" "${vaultImagePath}"`); - console.log(`Export: Successfully converted WebP to PNG: ${pngFileName}`); - } catch (convertError) { - console.error(`Export: Failed to convert WebP image: ${convertError.message}`); - throw convertError; - } - } else { - // For non-WebP images, copy directly - vaultImagePath = path.join(vaultTempImagesDir, originalImageName); - finalImageName = originalImageName; - await fs_promises.copyFile(fullImagePath, vaultImagePath); - } + updatedContent = updatedContent.replace(imageEmbed.marker, markdownImage); - // Get relative path for the copied image from vault base - const relativeImagePath = path.relative(vaultBasePath, vaultImagePath); - - // Create the appropriate markdown output based on size/alt text - let imageOutput; - if (imageEmbed.sizeOrAlt) { - // Check if it's size information (width x height pattern) - const sizeMatch = imageEmbed.sizeOrAlt.match(/^(\d+)(?:x(\d+))?$/); - if (sizeMatch) { - const width = sizeMatch[1]; - const height = sizeMatch[2]; - - // Create image with size attributes (optimized for Pandoc → Typst conversion) - if (height) { - imageOutput = `${imageEmbed.baseName}`; - } else { - imageOutput = `${imageEmbed.baseName}`; - } - } else { - // Treat as alt text - imageOutput = `![${imageEmbed.sizeOrAlt}](${relativeImagePath})`; - } - } else { - // Standard image reference - imageOutput = `![${imageEmbed.baseName}](${relativeImagePath})`; - } - - // Replace the placeholder with the image output - updatedContent = updatedContent.replace(imageEmbed.marker, imageOutput); - - console.log(`Export: Successfully processed image embed: ${imageEmbed.baseName} -> ${finalImageName}`); + console.log(`Export: Successfully processed image embed: ${imageEmbed.originalPath}`); } catch (error) { - console.error(`Export: Error processing image embed ${imageEmbed.baseName}:`, error); - // Replace with fallback image reference - const decodedPath = decodeURIComponent(imageEmbed.sanitizedPath); - const fallbackOutput = `![⚠️ Error loading: ${imageEmbed.baseName}](${decodedPath})`; + console.error(`Export: Error processing image embed ${imageEmbed.originalPath}:`, error); + const fallbackOutput = `[⚠️ **Image processing error:** ${imageEmbed.alt || imageEmbed.originalPath}]`; updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput); } } - // Update the processed result with the new content + // Update the processed result with the new content processedResult.content = updatedContent; } + + /** + * Prepare the output path for a file + */ + private prepareOutputPath(file: TFile, outputFolder: string): string { + const vaultPath = (this.app.vault.adapter as any).basePath; + const outputDir = path.join(vaultPath, outputFolder); + + // Create output directory if it doesn't exist + if (!fs.existsSync(outputDir)) { + fs.mkdirSync(outputDir, { recursive: true }); + } + + // Preserve folder structure if configured + let relativePath = ''; + if (this.settings.behavior.preserveFolderStructure) { + const folderPath = path.dirname(file.path); + if (folderPath !== '.') { + relativePath = folderPath; + const fullOutputDir = path.join(outputDir, relativePath); + if (!fs.existsSync(fullOutputDir)) { + fs.mkdirSync(fullOutputDir, { recursive: true }); + } + } + } + + // Generate output filename (just use the note name without timestamp) + const baseName = file.basename; + const outputFileName = `${baseName}.pdf`; + + return path.join(outputDir, relativePath, outputFileName); + } + + /** + * Open a PDF file in the default viewer + */ + private openPDF(pdfPath: string): void { + const { shell } = require('electron'); + shell.openPath(pdfPath); + } + + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + } + + async saveSettings() { + await this.saveData(this.settings); + } + + onunload() { + // Cancel any ongoing exports + if (this.currentExportController) { + this.currentExportController.abort(); + } + + console.log('Obsidian Typst PDF Export plugin unloaded'); + } } /** - * Modal for displaying dependency status and installation instructions + * Settings Tab */ -class DependencyStatusModal extends Modal { +class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { plugin: obsidianTypstPDFExport; - - constructor(app: App, plugin: obsidianTypstPDFExport) { - super(app); - this.plugin = plugin; - } - - async onOpen() { - const { contentEl } = this; - contentEl.empty(); - - contentEl.createEl('h2', { text: 'External Dependencies Status' }); - - // Show loading indicator - const loadingEl = contentEl.createDiv(); - loadingEl.setText('Checking dependencies...'); - - try { - // Check dependencies - const additionalPaths = this.plugin.settings.executablePaths.additionalPaths; - const results = await this.plugin.dependencyChecker.checkAllDependencies( - { customPath: this.plugin.settings.pandocPath, additionalPaths }, - { customPath: this.plugin.settings.typstPath, additionalPaths }, - { customPath: this.plugin.settings.executablePaths.imagemagickPath, additionalPaths } - ); - - // Clear loading indicator - loadingEl.remove(); - - // Show overall status - const overallStatus = contentEl.createDiv({ cls: 'dependency-overall-status' }); - if (results.allAvailable) { - overallStatus.createEl('div', { - text: '✅ All dependencies are available and ready to use', - cls: 'dependency-success' - }); - } else { - overallStatus.createEl('div', { - text: '❌ Some dependencies need attention', - cls: 'dependency-error' - }); - } - - // Pandoc status - this.createDependencySection(contentEl, 'Pandoc', results.pandoc); - - // Typst status - this.createDependencySection(contentEl, 'Typst', results.typst); - - // ImageMagick status - this.createDependencySection(contentEl, 'ImageMagick', results.imagemagick); - - // Add refresh button - const buttonContainer = contentEl.createDiv({ cls: 'dependency-button-container' }); - const refreshButton = buttonContainer.createEl('button', { text: 'Refresh Status' }); - refreshButton.onclick = () => { - this.close(); - new DependencyStatusModal(this.app, this.plugin).open(); - }; - - } catch (error) { - loadingEl.remove(); - const errorEl = contentEl.createDiv({ cls: 'dependency-error' }); - errorEl.setText(`Error checking dependencies: ${error instanceof Error ? error.message : String(error)}`); - } - } - - private createDependencySection(containerEl: HTMLElement, toolName: string, result: any) { - const section = containerEl.createDiv({ cls: 'dependency-section' }); - - // Tool header - const header = section.createEl('h3', { text: toolName }); - - // Status indicator - const statusEl = section.createDiv({ cls: 'dependency-status' }); - if (result.isAvailable) { - statusEl.createEl('span', { - text: `✅ ${toolName} v${result.version} - Ready`, - cls: 'dependency-success' - }); - if (result.executablePath) { - statusEl.createEl('div', { - text: `Path: ${result.executablePath}`, - cls: 'dependency-path' - }); - } - if (result.warning) { - statusEl.createEl('div', { - text: `⚠️ ${result.warning}`, - cls: 'dependency-warning' - }); - } - } else { - statusEl.createEl('span', { - text: `❌ ${toolName} - Not Available`, - cls: 'dependency-error' - }); - if (result.error) { - statusEl.createEl('div', { - text: `Error: ${result.error}`, - cls: 'dependency-error-detail' - }); - } - - // Show installation guide - this.createInstallationGuide(section, toolName.toLowerCase() as 'pandoc' | 'typst'); - } - } - - private createInstallationGuide(containerEl: HTMLElement, toolName: 'pandoc' | 'typst') { - const guide = this.plugin.dependencyChecker.getInstallationGuide(toolName); - const platform = this.plugin.dependencyChecker.getCurrentPlatform(); - const platformInstructions = guide.instructions[platform]; - - const guideEl = containerEl.createDiv({ cls: 'dependency-install-guide' }); - guideEl.createEl('h4', { text: 'Installation Instructions' }); - - guideEl.createEl('p', { text: platformInstructions.description }); - - if (platformInstructions.commands && platformInstructions.commands.length > 0) { - const commandsEl = guideEl.createDiv(); - commandsEl.createEl('strong', { text: 'Installation commands:' }); - const commandsList = commandsEl.createEl('ul'); - platformInstructions.commands.forEach(cmd => { - const listItem = commandsList.createEl('li'); - listItem.createEl('code', { text: cmd }); - }); - } - - const linksEl = guideEl.createDiv(); - linksEl.createEl('strong', { text: 'Useful links:' }); - const linksList = linksEl.createEl('ul'); - platformInstructions.links.forEach(link => { - const listItem = linksList.createEl('li'); - const linkEl = listItem.createEl('a', { text: link, href: link }); - linkEl.setAttr('target', '_blank'); - }); - - if (guide.troubleshooting.length > 0) { - const troubleshootingEl = guideEl.createDiv(); - troubleshootingEl.createEl('strong', { text: 'Troubleshooting:' }); - const troubleshootingList = troubleshootingEl.createEl('ul'); - guide.troubleshooting.forEach(tip => { - troubleshootingList.createEl('li', { text: tip }); - }); - } - } - - onClose() { - const { contentEl } = this; - contentEl.empty(); - } -} - -class TypstPDFExportSettingTab extends PluginSettingTab { - plugin: obsidianTypstPDFExport; - + constructor(app: App, plugin: obsidianTypstPDFExport) { super(app, plugin); this.plugin = plugin; } - + display(): void { - const {containerEl} = this; - + const { containerEl } = this; containerEl.empty(); - - // Main settings heading - new Setting(containerEl) - .setName('Typst PDF Export Settings') - .setHeading(); - - // Dependency Status Section - new Setting(containerEl) - .setName('Dependencies') - .setHeading(); - - new Setting(containerEl) - .setName('Dependency Status') - .setDesc('Check the status of external dependencies') - .addButton(button => button - .setButtonText('Check Dependencies') - .setCta() - .onClick(async () => { - // Open dependency status modal - const modal = new DependencyStatusModal(this.app, this.plugin); - modal.open(); - })); - - // External Tools Section - new Setting(containerEl) - .setName('External Tools') - .setHeading(); - - new Setting(containerEl) - .setDesc('Configure paths to external tools required for PDF export'); - + + containerEl.createEl('h2', { text: 'Typst PDF Export Settings' }); + + // Executable paths section + this.createExecutablePathsSection(containerEl); + + // Export defaults section + this.createExportDefaultsSection(containerEl); + + // Typography defaults section + this.createTypographyDefaultsSection(containerEl); + + // Behavior section + this.createBehaviorSection(containerEl); + } + + private createExecutablePathsSection(containerEl: HTMLElement): void { + containerEl.createEl('h3', { text: 'Executable Paths' }); + new Setting(containerEl) .setName('Pandoc path') - .setDesc('Path to the Pandoc executable (leave empty to use system PATH)') + .setDesc('Path to pandoc executable (leave empty to use system PATH)') .addText(text => text - .setPlaceholder('/usr/local/bin/pandoc') + .setPlaceholder('pandoc') .setValue(this.plugin.settings.pandocPath) .onChange(async (value) => { this.plugin.settings.pandocPath = value; await this.plugin.saveSettings(); - })) - .addExtraButton(button => button - .setIcon('folder-open') - .setTooltip('Browse for Pandoc executable') - .onClick(async () => { - // TODO: Implement file picker for executable selection - new Notice('File picker not yet implemented'); - })) - .addExtraButton(button => button - .setIcon('check-circle') - .setTooltip('Validate Pandoc installation') - .onClick(async () => { - // TODO: Implement path validation - new Notice('Path validation not yet implemented'); })); - + new Setting(containerEl) .setName('Typst path') - .setDesc('Path to the Typst executable (leave empty to use system PATH)') + .setDesc('Path to typst executable (leave empty to use system PATH)') .addText(text => text - .setPlaceholder('/usr/local/bin/typst') + .setPlaceholder('typst') .setValue(this.plugin.settings.typstPath) .onChange(async (value) => { this.plugin.settings.typstPath = value; await this.plugin.saveSettings(); - })) - .addExtraButton(button => button - .setIcon('folder-open') - .setTooltip('Browse for Typst executable') - .onClick(async () => { - // TODO: Implement file picker for executable selection - new Notice('File picker not yet implemented'); - })) - .addExtraButton(button => button - .setIcon('check-circle') - .setTooltip('Validate Typst installation') - .onClick(async () => { - // TODO: Implement path validation - new Notice('Path validation not yet implemented'); })); - - new Setting(containerEl) - .setName('ImageMagick Convert Path') - .setDesc('Path to ImageMagick convert executable (leave empty to use system PATH)') - .addText(text => text - .setPlaceholder('/opt/homebrew/bin/convert') - .setValue(this.plugin.settings.executablePaths.imagemagickPath) - .onChange(async (value) => { - this.plugin.settings.executablePaths.imagemagickPath = value; - await this.plugin.saveSettings(); - })) - .addExtraButton(button => button - .setIcon('folder-open') - .setTooltip('Browse for ImageMagick convert executable') - .onClick(async () => { - // TODO: Implement file picker for executable selection - new Notice('File picker not yet implemented'); - })) - .addExtraButton(button => button - .setIcon('check-circle') - .setTooltip('Validate ImageMagick installation') - .onClick(async () => { - // TODO: Implement path validation - new Notice('Path validation not yet implemented'); - })); - - new Setting(containerEl) - .setName('Additional System Paths') - .setDesc('Additional paths to search for executables (comma-separated)') - .addText(text => text - .setPlaceholder('/opt/homebrew/bin, /usr/local/bin') - .setValue(this.plugin.settings.executablePaths.additionalPaths.join(', ')) - .onChange(async (value) => { - this.plugin.settings.executablePaths.additionalPaths = value - .split(',') - .map(p => p.trim()) - .filter(p => p.length > 0); - await this.plugin.saveSettings(); - })); - - new Setting(containerEl) - .setName('Output folder') - .setDesc('Default folder for exported PDF files (relative to vault root)') - .addText(text => text - .setPlaceholder('exports') - .setValue(this.plugin.settings.outputFolder) - .onChange(async (value) => { - this.plugin.settings.outputFolder = value; - await this.plugin.saveSettings(); - })) - .addExtraButton(button => button - .setIcon('folder-open') - .setTooltip('Browse for output folder') - .onClick(async () => { - // TODO: Implement folder picker - new Notice('Folder picker not yet implemented'); - })); - - // Export Defaults Section - new Setting(containerEl) - .setName('Export Defaults') - .setHeading(); - - new Setting(containerEl) - .setDesc('Default settings for PDF export operations'); - + } + + private createExportDefaultsSection(containerEl: HTMLElement): void { + containerEl.createEl('h3', { text: 'Export Defaults' }); + new Setting(containerEl) .setName('Default template') - .setDesc('Template name to use for exports') + .setDesc('Default Typst template for exports') .addText(text => text .setPlaceholder('default') .setValue(this.plugin.settings.exportDefaults.template) @@ -2282,1943 +860,135 @@ class TypstPDFExportSettingTab extends PluginSettingTab { this.plugin.settings.exportDefaults.template = value; await this.plugin.saveSettings(); })); - + new Setting(containerEl) - .setName('Export format') - .setDesc('Default PDF format for exports') + .setName('Default format') + .setDesc('Default PDF format') .addDropdown(dropdown => dropdown - .addOption(ExportFormat.Standard, 'Standard multi-page') - .addOption(ExportFormat.SinglePage, 'Single continuous page') + .addOption(ExportFormat.Standard, 'Standard (multi-page)') + .addOption(ExportFormat.SinglePage, 'Single-page (continuous)') .setValue(this.plugin.settings.exportDefaults.format) .onChange(async (value) => { this.plugin.settings.exportDefaults.format = value as ExportFormat; await this.plugin.saveSettings(); })); - - - // Typography Section + new Setting(containerEl) - .setName('Typography') - .setHeading(); - - new Setting(containerEl) - .setDesc('Font and text formatting settings'); - + .setName('Output folder') + .setDesc('Default folder for exported PDFs (relative to vault root)') + .addText(text => text + .setPlaceholder('exports') + .setValue(this.plugin.settings.outputFolder) + .onChange(async (value) => { + this.plugin.settings.outputFolder = value; + await this.plugin.saveSettings(); + })); + } + + private createTypographyDefaultsSection(containerEl: HTMLElement): void { + containerEl.createEl('h3', { text: 'Typography Defaults' }); + new Setting(containerEl) .setName('Body font') - .setDesc('Font family for body text') + .setDesc('Default font for body text') .addText(text => text - .setPlaceholder('Times New Roman') .setValue(this.plugin.settings.typography.fonts.body) .onChange(async (value) => { this.plugin.settings.typography.fonts.body = value; await this.plugin.saveSettings(); })); - + new Setting(containerEl) .setName('Heading font') - .setDesc('Font family for headings') + .setDesc('Default font for headings') .addText(text => text - .setPlaceholder('Arial') .setValue(this.plugin.settings.typography.fonts.heading) .onChange(async (value) => { this.plugin.settings.typography.fonts.heading = value; await this.plugin.saveSettings(); })); - + new Setting(containerEl) .setName('Monospace font') - .setDesc('Font family for code blocks and inline code') + .setDesc('Default font for code and monospace text') .addText(text => text - .setPlaceholder('Courier New') .setValue(this.plugin.settings.typography.fonts.monospace) .onChange(async (value) => { this.plugin.settings.typography.fonts.monospace = value; await this.plugin.saveSettings(); })); - + new Setting(containerEl) .setName('Body font size') - .setDesc('Font size for body text (in points)') + .setDesc('Default font size for body text (in points)') .addSlider(slider => slider - .setLimits(8, 24, 1) + .setLimits(8, 16, 0.5) .setValue(this.plugin.settings.typography.fontSizes.body) .setDynamicTooltip() .onChange(async (value) => { this.plugin.settings.typography.fontSizes.body = value; await this.plugin.saveSettings(); })); - + new Setting(containerEl) .setName('Heading font size') - .setDesc('Font size for headings (in points)') + .setDesc('Default font size for headings (in points)') .addSlider(slider => slider - .setLimits(12, 36, 1) + .setLimits(10, 24, 0.5) .setValue(this.plugin.settings.typography.fontSizes.heading) .setDynamicTooltip() .onChange(async (value) => { this.plugin.settings.typography.fontSizes.heading = value; await this.plugin.saveSettings(); })); - + new Setting(containerEl) .setName('Small font size') - .setDesc('Font size for small text like captions (in points)') + .setDesc('Default font size for small text (in points)') .addSlider(slider => slider - .setLimits(6, 16, 1) + .setLimits(6, 12, 0.5) .setValue(this.plugin.settings.typography.fontSizes.small) .setDynamicTooltip() .onChange(async (value) => { this.plugin.settings.typography.fontSizes.small = value; await this.plugin.saveSettings(); })); - - // Page Setup Section + } + + private createBehaviorSection(containerEl: HTMLElement): void { + containerEl.createEl('h3', { text: 'Behavior' }); + new Setting(containerEl) - .setName('Page Setup') - .setHeading(); - - new Setting(containerEl) - .setDesc('PDF page layout and formatting'); - - new Setting(containerEl) - .setName('Page size') - .setDesc('Paper size for PDF output') - .addDropdown(dropdown => dropdown - .addOption('a4', 'A4') - .addOption('letter', 'US Letter') - .addOption('a3', 'A3') - .addOption('a5', 'A5') - .addOption('legal', 'US Legal') - .setValue(this.plugin.settings.pageSetup.size) - .onChange(async (value) => { - this.plugin.settings.pageSetup.size = value; - await this.plugin.saveSettings(); - })); - - new Setting(containerEl) - .setName('Orientation') - .setDesc('Page orientation') - .addDropdown(dropdown => dropdown - .addOption('portrait', 'Portrait') - .addOption('landscape', 'Landscape') - .setValue(this.plugin.settings.pageSetup.orientation) - .onChange(async (value) => { - this.plugin.settings.pageSetup.orientation = value as 'portrait' | 'landscape'; - await this.plugin.saveSettings(); - })); - - new Setting(containerEl) - .setName('Top margin') - .setDesc('Top page margin (in points)') - .addSlider(slider => slider - .setLimits(18, 144, 6) - .setValue(this.plugin.settings.pageSetup.margins.top) - .setDynamicTooltip() - .onChange(async (value) => { - this.plugin.settings.pageSetup.margins.top = value; - await this.plugin.saveSettings(); - })); - - new Setting(containerEl) - .setName('Right margin') - .setDesc('Right page margin (in points)') - .addSlider(slider => slider - .setLimits(18, 144, 6) - .setValue(this.plugin.settings.pageSetup.margins.right) - .setDynamicTooltip() - .onChange(async (value) => { - this.plugin.settings.pageSetup.margins.right = value; - await this.plugin.saveSettings(); - })); - - new Setting(containerEl) - .setName('Bottom margin') - .setDesc('Bottom page margin (in points)') - .addSlider(slider => slider - .setLimits(18, 144, 6) - .setValue(this.plugin.settings.pageSetup.margins.bottom) - .setDynamicTooltip() - .onChange(async (value) => { - this.plugin.settings.pageSetup.margins.bottom = value; - await this.plugin.saveSettings(); - })); - - new Setting(containerEl) - .setName('Left margin') - .setDesc('Left page margin (in points)') - .addSlider(slider => slider - .setLimits(18, 144, 6) - .setValue(this.plugin.settings.pageSetup.margins.left) - .setDynamicTooltip() - .onChange(async (value) => { - this.plugin.settings.pageSetup.margins.left = value; - await this.plugin.saveSettings(); - })); - - // Advanced Options Section - new Setting(containerEl) - .setName('Advanced Options') - .setHeading(); - - new Setting(containerEl) - .setDesc('Advanced plugin behavior and performance settings'); - - new Setting(containerEl) - .setName('Open PDF after export') - .setDesc('Automatically open the exported PDF file') + .setName('Open after export') + .setDesc('Automatically open PDF after successful export') .addToggle(toggle => toggle .setValue(this.plugin.settings.behavior.openAfterExport) .onChange(async (value) => { this.plugin.settings.behavior.openAfterExport = value; await this.plugin.saveSettings(); })); - + new Setting(containerEl) .setName('Preserve folder structure') - .setDesc('Maintain the original folder structure in the output directory') + .setDesc('Maintain vault folder structure in output directory') .addToggle(toggle => toggle .setValue(this.plugin.settings.behavior.preserveFolderStructure) .onChange(async (value) => { this.plugin.settings.behavior.preserveFolderStructure = value; await this.plugin.saveSettings(); })); - - new Setting(containerEl) - .setName('Export concurrency') - .setDesc('Number of files to export simultaneously during batch operations (1-10)') - .addSlider(slider => slider - .setLimits(1, 10, 1) - .setValue(this.plugin.settings.behavior.exportConcurrency) - .setDynamicTooltip() - .onChange(async (value) => { - this.plugin.settings.behavior.exportConcurrency = value; - await this.plugin.saveSettings(); - })); - + new Setting(containerEl) .setName('Debug mode') - .setDesc('Enable verbose logging for troubleshooting export issues') + .setDesc('Enable verbose logging for troubleshooting') .addToggle(toggle => toggle - .setValue(this.plugin.settings.behavior.debugMode || false) + .setValue(this.plugin.settings.behavior.debugMode) .onChange(async (value) => { this.plugin.settings.behavior.debugMode = value; await this.plugin.saveSettings(); })); - - // Template Management Section - new Setting(containerEl) - .setName('Template Management') - .setHeading(); - - new Setting(containerEl) - .setDesc('Manage custom Typst templates for document styling'); - - new Setting(containerEl) - .setName('Import template') - .setDesc('Import a custom Typst template file (.typ)') - .addButton(button => button - .setButtonText('Import Template') - .setIcon('file-plus') - .onClick(async () => { - // TODO: Implement template import functionality - new Notice('Template import not yet implemented'); - })); - - new Setting(containerEl) - .setName('Export templates') - .setDesc('Export current templates for sharing or backup') - .addButton(button => button - .setButtonText('Export Templates') - .setIcon('download') - .onClick(async () => { - // TODO: Implement template export functionality - new Notice('Template export not yet implemented'); - })); - - new Setting(containerEl) - .setName('Reset to defaults') - .setDesc('Reset all settings to their default values') - .addButton(button => button - .setButtonText('Reset Settings') - .setWarning() - .onClick(async () => { - // TODO: Implement settings reset with confirmation - new Notice('Settings reset not yet implemented'); - })); } } -/** - * Configuration interface for export modal settings - * Combines user preferences with runtime state for export operations - */ -interface ExportConfigModalSettings extends ExportConfig { - /** Note being exported */ - notePath: string; - /** Note title for display */ - noteTitle: string; - /** 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 Configuration Modal - * Provides intuitive interface for configuring PDF export options - * with real-time preview and validation - */ -export class ExportConfigModal extends Modal { - private settings: ExportConfigModalSettings; - private plugin: obsidianTypstPDFExport; - private onSubmit: (config: ExportConfig) => Promise; - private onCancel?: () => void; - - // UI Elements - private contentContainer: HTMLElement; - private formContainer: HTMLElement; - private previewContainer: HTMLElement; - private progressContainer: HTMLElement; - private progressBar: HTMLElement | null = null; - private progressText: HTMLElement | null = null; - private cancelButton: HTMLButtonElement | null = null; - - constructor( - app: App, - plugin: obsidianTypstPDFExport, - notePath: string, - onSubmit: (config: ExportConfig) => Promise, - onCancel?: () => void - ) { - super(app); - this.plugin = plugin; - this.onSubmit = onSubmit; - this.onCancel = onCancel; - - // Initialize settings from plugin defaults and note context - const noteTitle = this.getNoteTitleFromPath(notePath); - this.settings = { - notePath, - noteTitle, - template: plugin.settings.exportDefaults.template, - format: plugin.settings.exportDefaults.format, - outputFolder: plugin.settings.outputFolder, - templateVariables: {}, - availableTemplates: [], // Will be populated by TemplateManager - isExporting: false, - progressPercent: 0, - currentOperation: '', - canCancel: false - }; - } - - /** - * Initialize modal when opened - */ - /** - * Initialize modal when opened - */ - /** - * Initialize modal when opened - */ - onOpen(): void { - this.addModalStyles(); - - // Set modal dimensions to match Obsidian Settings window - if (this.modalEl) { - this.modalEl.style.width = '1100px'; - this.modalEl.style.height = '750px'; - this.modalEl.style.maxWidth = '90vw'; - this.modalEl.style.maxHeight = '90vh'; - } - - this.setTitle(`Export "${this.settings.noteTitle}" to PDF`); - - // Load templates FIRST, then generate form and load previous config - this.loadAvailableTemplates().then(() => { - this.generateForm(); - this.loadPreviousConfig(); - }); - } - - /** - * Cleanup when modal is closed - */ - onClose(): void { - if (this.onCancel && this.settings.isExporting) { - this.onCancel(); - } - } - - /** - * Extract note title from file path for display - */ - private getNoteTitleFromPath(path: string): string { - const fileName = path.split('/').pop() || path; - return fileName.replace(/\.md$/, ''); - } - - /** - * Load available templates from TemplateManager - * This will be implemented when TemplateManager is available - */ - private async loadAvailableTemplates(): Promise { - // Load available templates from TemplateManager via plugin - console.log('Modal: Loading available templates...'); - console.log('TemplateManager exists:', !!this.plugin.templateManager); - - if (this.plugin.templateManager) { - this.settings.availableTemplates = await this.plugin.templateManager.getAvailableTemplates(); - console.log('Templates loaded from TemplateManager:', this.settings.availableTemplates); - } else { - // Fallback to hardcoded defaults if TemplateManager not initialized - console.log('Using fallback templates'); - this.settings.availableTemplates = [ - 'default.typ', - 'article.typ', - 'report.typ', - 'modern.typ' - ]; - } - - // Update template dropdown if already rendered - this.updateTemplateDropdown(); - } - - /** - * Update template dropdown options - * Called after templates are loaded - */ - private updateTemplateDropdown(): void { - console.log('updateTemplateDropdown called'); - console.log('templateDropdown exists:', !!this.templateDropdown); - console.log('Available templates:', this.settings.availableTemplates); - - if (!this.templateDropdown) { - console.log('templateDropdown not yet created'); - return; - } - - // Clear existing options - this.templateDropdown.selectEl.empty(); - - // Add available templates - this.settings.availableTemplates.forEach(template => { - const displayName = this.getTemplateDisplayName(template); - console.log(`Adding template option: ${template} -> ${displayName}`); - this.templateDropdown.addOption(template, displayName); - }); - - // Set current value or default with proper extension - const currentValue = this.settings.template || 'default.typ'; - this.templateDropdown.setValue(currentValue); -} - - /** - * Generate the main form UI - * Placeholder for Task 7.2 - */ - /** - * Generate the main form UI - * Creates comprehensive form with all export configuration options - */ - private generateForm(): void { - const { contentEl } = this; - contentEl.empty(); - - // Create main container with responsive layout - this.contentContainer = contentEl.createDiv('export-config-container'); - this.contentContainer.style.display = 'flex'; - this.contentContainer.style.gap = '20px'; - this.contentContainer.style.minHeight = '400px'; - - // Form container (left side) - CREATE FIRST, then set styles - this.formContainer = this.contentContainer.createDiv('export-config-form'); - this.formContainer.style.flex = '1'; - this.formContainer.style.minWidth = '400px'; - - // Preview container (right side) - this.previewContainer = this.contentContainer.createDiv('export-config-preview'); - this.previewContainer.style.flex = '1'; - this.previewContainer.style.maxWidth = '300px'; - this.previewContainer.style.border = '1px solid var(--background-modifier-border)'; - this.previewContainer.style.borderRadius = '8px'; - this.previewContainer.style.padding = '16px'; - - // Progress container (initially hidden) - this.progressContainer = this.contentContainer.createDiv('export-progress'); - this.progressContainer.style.display = 'none'; - - // Generate form sections - this.createFormatSection(); - this.createTemplateSection(); - this.createOutputSection(); - this.createPageConfigSection(); - this.createTypographySection(); - this.createActionButtons(); - - // Initialize preview - this.createPreviewSection(); - this.updatePreview(); - } - - - /** - * Create format selection section - */ - private createFormatSection(): void { - const section = this.formContainer.createDiv('export-section'); - section.createEl('h3', { text: 'Format Options' }); - - new Setting(section) - .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(this.settings.format || ExportFormat.Standard) - .onChange(value => { - this.settings.format = value as ExportFormat; - this.updatePreview(); - }); - }); - } - - /** - * Create template selection section - */ - private createTemplateSection(): void { - const section = this.formContainer.createDiv('export-section'); - section.createEl('h3', { text: 'Template' }); - - new Setting(section) - .setName('Typst template') - .setDesc('Select template for document styling') - .addDropdown(dropdown => { - // Initially populate with available templates - this.settings.availableTemplates.forEach(template => { - dropdown.addOption(template, this.getTemplateDisplayName(template)); - }); - - // Set default value with proper extension - const defaultTemplate = this.settings.template || 'default.typ'; - dropdown - .setValue(defaultTemplate) - .onChange(value => { - this.settings.template = value; - this.updatePreview(); - }); - - // Store reference for updates - this.templateDropdown = dropdown; - }); - - // Template variables section - this.createTemplateVariablesSection(section); -} - - /** - * Create template variables section - */ - private createTemplateVariablesSection(parentSection: HTMLElement): void { - const variablesContainer = parentSection.createDiv('template-variables'); - - // Title field - new Setting(variablesContainer) - .setName('Document title') - .setDesc('Override document title (uses note title by default)') - .addText(text => { - text - .setPlaceholder(this.settings.noteTitle) - .setValue(this.settings.templateVariables?.title || '') - .onChange(value => { - this.settings.templateVariables = this.settings.templateVariables || {}; - this.settings.templateVariables.title = value || this.settings.noteTitle; - this.updatePreview(); - }); - }); - - // Author field - new Setting(variablesContainer) - .setName('Author') - .setDesc('Document author name') - .addText(text => { - text - .setPlaceholder('Your name') - .setValue(this.settings.templateVariables?.author || '') - .onChange(value => { - this.settings.templateVariables = this.settings.templateVariables || {}; - this.settings.templateVariables.author = value; - this.updatePreview(); - }); - }); - - // Date field - new Setting(variablesContainer) - .setName('Date') - .setDesc('Document date (leave blank for current date)') - .addText(text => { - text - .setPlaceholder(new Date().toLocaleDateString()) - .setValue(this.settings.templateVariables?.date || '') - .onChange(value => { - this.settings.templateVariables = this.settings.templateVariables || {}; - this.settings.templateVariables.date = value || new Date().toLocaleDateString(); - this.updatePreview(); - }); - }); - } - - /** - * Create output settings section - */ - private createOutputSection(): void { - const section = this.formContainer.createDiv('export-section'); - section.createEl('h3', { text: 'Output Settings' }); - - // Output folder - new Setting(section) - .setName('Output folder') - .setDesc('Folder where the PDF will be saved') - .addText(text => { - text - .setPlaceholder(this.plugin.settings.outputFolder) - .setValue(this.settings.outputFolder || '') - .onChange(value => { - this.settings.outputFolder = value || this.plugin.settings.outputFolder; - this.updatePreview(); - }); - }); - - // Filename pattern (advanced) - const filenamePattern = this.settings.templateVariables?.filenamePattern || '{title}'; - new Setting(section) - .setName('Filename pattern') - .setDesc('Pattern for generated filename. Use {title}, {date}, {author}') - .addText(text => { - text - .setPlaceholder('{title}') - .setValue(filenamePattern) - .onChange(value => { - this.settings.templateVariables = this.settings.templateVariables || {}; - this.settings.templateVariables.filenamePattern = value || '{title}'; - this.updatePreview(); - }); - }); - } - - /** - * Create page configuration section - */ - private createPageConfigSection(): void { - const section = this.formContainer.createDiv('export-section'); - section.createEl('h3', { text: 'Page Setup' }); - - // Page size - new Setting(section) - .setName('Page size') - .setDesc('Standard page sizes or custom dimensions') - .addDropdown(dropdown => { - dropdown - .addOption('a4', 'A4 (210 × 297 mm)') - .addOption('letter', 'Letter (8.5 × 11 in)') - .addOption('legal', 'Legal (8.5 × 14 in)') - .addOption('a3', 'A3 (297 × 420 mm)') - .addOption('custom', 'Custom size') - .setValue(this.plugin.settings.pageSetup.size) - .onChange(value => { - // Note: This updates plugin defaults, not per-export settings - // TODO: Consider adding per-export page settings to ExportConfig - this.updatePreview(); - }); - }); - - // Orientation - new Setting(section) - .setName('Orientation') - .setDesc('Page orientation') - .addDropdown(dropdown => { - dropdown - .addOption('portrait', 'Portrait') - .addOption('landscape', 'Landscape') - .setValue(this.plugin.settings.pageSetup.orientation) - .onChange(value => { - // Note: This updates plugin defaults - this.updatePreview(); - }); - }); - - // Margins - this.createMarginsSection(section); - } - - /** - * Create margins configuration subsection - */ - private createMarginsSection(parentSection: HTMLElement): void { - const marginsContainer = parentSection.createDiv('margins-container'); - marginsContainer.createEl('h4', { text: 'Margins (in points)' }); - - const margins = this.plugin.settings.pageSetup.margins; - - // Top margin - new Setting(marginsContainer) - .setName('Top') - .addSlider(slider => { - slider - .setLimits(36, 144, 6) // 0.5" to 2" in 6pt increments - .setValue(margins.top) - .setDynamicTooltip() - .onChange(value => { - this.updatePreview(); - }); - }); - - // Bottom margin - new Setting(marginsContainer) - .setName('Bottom') - .addSlider(slider => { - slider - .setLimits(36, 144, 6) - .setValue(margins.bottom) - .setDynamicTooltip() - .onChange(value => { - this.updatePreview(); - }); - }); - - // Left margin - new Setting(marginsContainer) - .setName('Left') - .addSlider(slider => { - slider - .setLimits(36, 144, 6) - .setValue(margins.left) - .setDynamicTooltip() - .onChange(value => { - this.updatePreview(); - }); - }); - - // Right margin - new Setting(marginsContainer) - .setName('Right') - .addSlider(slider => { - slider - .setLimits(36, 144, 6) - .setValue(margins.right) - .setDynamicTooltip() - .onChange(value => { - this.updatePreview(); - }); - }); - } - - /** - * Create typography settings section - */ - private createTypographySection(): void { - const section = this.formContainer.createDiv('export-section'); - section.createEl('h3', { text: 'Typography' }); - - const fonts = this.plugin.settings.typography.fonts; - const fontSizes = this.plugin.settings.typography.fontSizes; - - // Body font - new Setting(section) - .setName('Body font') - .setDesc('Primary font for document text') - .addText(text => { - text - .setPlaceholder('System default') - .setValue(fonts.body) - .onChange(value => { - this.updatePreview(); - }); - }); - - // Heading font - new Setting(section) - .setName('Heading font') - .setDesc('Font for headings and titles') - .addText(text => { - text - .setPlaceholder('System default') - .setValue(fonts.heading) - .onChange(value => { - this.updatePreview(); - }); - }); - - // Monospace font - new Setting(section) - .setName('Code font') - .setDesc('Monospace font for code blocks') - .addText(text => { - text - .setPlaceholder('System default') - .setValue(fonts.monospace) - .onChange(value => { - this.updatePreview(); - }); - }); - - // Font sizes - this.createFontSizesSection(section, fontSizes); - } - - /** - * Create font sizes subsection - */ - private createFontSizesSection(parentSection: HTMLElement, fontSizes: any): void { - const sizesContainer = parentSection.createDiv('font-sizes'); - sizesContainer.createEl('h4', { text: 'Font Sizes (in points)' }); - - // Body size - new Setting(sizesContainer) - .setName('Body text') - .addSlider(slider => { - slider - .setLimits(8, 16, 0.5) - .setValue(fontSizes.body) - .setDynamicTooltip() - .onChange(value => { - this.updatePreview(); - }); - }); - - // Heading size - new Setting(sizesContainer) - .setName('Headings') - .addSlider(slider => { - slider - .setLimits(12, 24, 0.5) - .setValue(fontSizes.heading) - .setDynamicTooltip() - .onChange(value => { - this.updatePreview(); - }); - }); - - // Small text size - new Setting(sizesContainer) - .setName('Small text') - .addSlider(slider => { - slider - .setLimits(6, 12, 0.5) - .setValue(fontSizes.small) - .setDynamicTooltip() - .onChange(value => { - this.updatePreview(); - }); - }); - } - - /** - * Create action buttons section - */ - private createActionButtons(): void { - const buttonsContainer = this.formContainer.createDiv('export-actions'); - buttonsContainer.style.marginTop = '20px'; - buttonsContainer.style.paddingTop = '20px'; - buttonsContainer.style.borderTop = '1px solid var(--background-modifier-border)'; - - new Setting(buttonsContainer) - .addButton(btn => { - btn - .setButtonText('Export PDF') - .setCta() - .onClick(() => this.submitExport()); - }) - .addButton(btn => { - btn - .setButtonText('Cancel') - .onClick(() => this.close()); - }); - } - - /** - * Create preview section - */ - private createPreviewSection(): void { - this.previewContainer.createEl('h3', { text: 'Preview' }); - - // Export summary - const summaryContainer = this.previewContainer.createDiv('export-summary'); - - // Document info - const docInfo = summaryContainer.createDiv('doc-info'); - docInfo.createEl('h4', { text: 'Document' }); - docInfo.createEl('p', { text: `Note: ${this.settings.noteTitle}` }); - - // Configuration preview - const configInfo = summaryContainer.createDiv('config-info'); - configInfo.createEl('h4', { text: 'Configuration' }); - - // This will be populated by updatePreview() - this.configPreview = configInfo.createDiv('config-details'); - - // Output info - const outputInfo = summaryContainer.createDiv('output-info'); - outputInfo.createEl('h4', { text: 'Output' }); - - // This will be populated by updatePreview() - this.outputPreview = outputInfo.createDiv('output-details'); - } - - /** - * Get display name for template - */ - private getTemplateDisplayName(template: string): string { - // Remove .typ extension for display name mapping - const templateKey = template.replace('.typ', ''); - - const displayNames: Record = { - 'default': 'Default', - 'article': 'Article', - 'report': 'Report', - 'modern': 'Modern' - }; - - return displayNames[templateKey] || templateKey.charAt(0).toUpperCase() + templateKey.slice(1); -} - - // Properties to store UI element references - private templateDropdown?: any; - private configPreview?: HTMLElement; - private outputPreview?: HTMLElement; - - /** - * Update preview based on current settings - * Placeholder for Task 7.3 - */ - /** - * Update preview based on current settings - * Shows configuration summary and output preview - */ - private updatePreview(): void { - if (!this.configPreview || !this.outputPreview) { - return; // Preview not yet initialized - } - - // Clear existing content - this.configPreview.empty(); - this.outputPreview.empty(); - - // Configuration summary - const configItems = this.configPreview.createDiv('config-items'); - - configItems.createDiv('config-item').innerHTML = - `Format: ${this.settings.format === ExportFormat.Standard ? 'Standard PDF' : 'Single-page PDF'}`; - - configItems.createDiv('config-item').innerHTML = - `Template: ${this.getTemplateDisplayName(this.settings.template || 'default')}`; - - // Template variables preview - if (this.settings.templateVariables) { - const vars = this.settings.templateVariables; - if (vars.title || vars.author || vars.date) { - const varsDiv = configItems.createDiv('config-item'); - varsDiv.innerHTML = 'Variables:'; - const varsList = varsDiv.createDiv('variables-list'); - - if (vars.title) varsList.createDiv('var-item').innerHTML = `Title: ${vars.title}`; - if (vars.author) varsList.createDiv('var-item').innerHTML = `Author: ${vars.author}`; - if (vars.date) varsList.createDiv('var-item').innerHTML = `Date: ${vars.date}`; - } - } - - // Output preview - const outputItems = this.outputPreview.createDiv('output-items'); - - // Output folder - const outputFolder = this.settings.outputFolder || this.plugin.settings.outputFolder; - outputItems.createDiv('output-item').innerHTML = - `Folder: ${outputFolder}`; - - // Filename preview - const filename = this.generatePreviewFilename(); - outputItems.createDiv('output-item').innerHTML = - `Filename: ${filename}.pdf`; - - // File size estimate (placeholder) - outputItems.createDiv('output-item').innerHTML = - `Est. size: ~${this.estimateFileSize()} KB`; - } - - /** - * Generate preview filename based on current settings - */ - private generatePreviewFilename(): string { - const pattern = this.settings.templateVariables?.filenamePattern || '{title}'; - const title = this.settings.templateVariables?.title || this.settings.noteTitle; - const author = this.settings.templateVariables?.author || ''; - const date = this.settings.templateVariables?.date || new Date().toLocaleDateString(); - - return pattern - .replace('{title}', title) - .replace('{author}', author) - .replace('{date}', date) - .replace(/[<>:"/\\|?*]/g, '_'); // Replace invalid filename characters - } - - /** - * Estimate output file size based on content and settings - */ - private estimateFileSize(): number { - // Simple estimation based on mode and format - // In a real implementation, this could analyze content length - let baseSize = 150; // Base size in KB - - if (this.settings.format === ExportFormat.SinglePage) { - baseSize *= 1.2; // Single-page format may be larger - } - - return Math.round(baseSize); - } - - /** - * Validate current settings - * Placeholder for Task 7.3 - */ - /** - * Validate current settings and show visual feedback - * Returns true if settings are valid for export - */ - private validateSettings(): boolean { - let isValid = true; - const errors: string[] = []; - - // Clear previous validation styling - this.clearValidationErrors(); - - // Validate template selection - if (!this.settings.template || this.settings.template.trim() === '') { - errors.push('Template selection is required'); - this.showFieldError('template', 'Please select a template'); - isValid = false; - } else if (!this.settings.availableTemplates.includes(this.settings.template)) { - errors.push('Selected template is not available'); - this.showFieldError('template', 'Template not found'); - isValid = false; - } - - // Validate output folder - const outputFolder = this.settings.outputFolder?.trim(); - if (!outputFolder) { - errors.push('Output folder is required'); - this.showFieldError('outputFolder', 'Please specify an output folder'); - isValid = false; - } else if (outputFolder.includes('<') || outputFolder.includes('>')) { - errors.push('Output folder path contains invalid characters'); - this.showFieldError('outputFolder', 'Invalid characters in path'); - isValid = false; - } - - // Validate filename pattern - const filenamePattern = this.settings.templateVariables?.filenamePattern; - if (filenamePattern && !filenamePattern.includes('{title}') && !filenamePattern.includes('{author}') && !filenamePattern.includes('{date}')) { - errors.push('Filename pattern should include at least one variable'); - this.showFieldError('filenamePattern', 'Include {title}, {author}, or {date}'); - // This is a warning, not a blocking error - } - - // Validate template variables - if (this.settings.templateVariables) { - const title = this.settings.templateVariables.title?.trim(); - if (title && title.length > 100) { - errors.push('Document title is too long'); - this.showFieldError('title', 'Maximum 100 characters'); - isValid = false; - } - - const author = this.settings.templateVariables.author?.trim(); - if (author && author.length > 50) { - errors.push('Author name is too long'); - this.showFieldError('author', 'Maximum 50 characters'); - isValid = false; - } - - // Validate date format if provided - const date = this.settings.templateVariables.date?.trim(); - if (date && date !== '' && isNaN(Date.parse(date))) { - errors.push('Invalid date format'); - this.showFieldError('date', 'Please use a valid date format'); - isValid = false; - } - } - - // Show validation summary - this.showValidationSummary(isValid, errors); - - return isValid; - } - - /** - * Clear all validation error styling - */ - private clearValidationErrors(): void { - // Remove error classes from all form elements - const errorElements = this.formContainer.querySelectorAll('.setting-item-control.error'); - errorElements.forEach(el => { - el.removeClass('error'); - // Remove error message if it exists - const errorMsg = el.querySelector('.validation-error'); - if (errorMsg) { - errorMsg.remove(); - } - }); - - // Clear validation summary - const existingSummary = this.formContainer.querySelector('.validation-summary'); - if (existingSummary) { - existingSummary.remove(); - } - } - - /** - * Show validation error for specific field - */ - private showFieldError(fieldName: string, message: string): void { - // Find the setting control element for this field - let targetElement: HTMLElement | null = null; - - // Map field names to their setting elements - const fieldSelectors: Record = { - 'template': '[data-field="template"]', - 'outputFolder': '[data-field="outputFolder"]', - 'filenamePattern': '[data-field="filenamePattern"]', - 'title': '[data-field="title"]', - 'author': '[data-field="author"]', - 'date': '[data-field="date"]' - }; - - // Since we don't have data attributes yet, use a simpler approach - // Find setting by content or use order-based selection - const settings = this.formContainer.querySelectorAll('.setting-item-control'); - - // For now, add error styling to the relevant input - // This would be improved with proper field identification - if (settings.length > 0) { - // Add generic error styling to help user identify issues - const errorContainer = this.formContainer.createDiv('field-error'); - errorContainer.style.color = 'var(--text-error)'; - errorContainer.style.fontSize = '0.9em'; - errorContainer.style.marginTop = '4px'; - errorContainer.textContent = `${fieldName}: ${message}`; - } - } - - /** - * Show validation summary with all errors - */ - private showValidationSummary(isValid: boolean, errors: string[]): void { - // Remove existing summary - const existingSummary = this.formContainer.querySelector('.validation-summary'); - if (existingSummary) { - existingSummary.remove(); - } - - if (!isValid && errors.length > 0) { - const summaryContainer = this.formContainer.createDiv('validation-summary'); - summaryContainer.style.backgroundColor = 'var(--background-modifier-error)'; - summaryContainer.style.border = '1px solid var(--background-modifier-error-border)'; - summaryContainer.style.borderRadius = '4px'; - summaryContainer.style.padding = '12px'; - summaryContainer.style.marginTop = '16px'; - - const title = summaryContainer.createEl('h4', { - text: 'Please fix the following issues:', - attr: { style: 'color: var(--text-error); margin: 0 0 8px 0;' } - }); - - const errorsList = summaryContainer.createEl('ul', { - attr: { style: 'margin: 0; padding-left: 20px; color: var(--text-error);' } - }); - - errors.forEach(error => { - errorsList.createEl('li', { text: error }); - }); - } else if (isValid) { - // Show success state - const successContainer = this.formContainer.createDiv('validation-summary'); - successContainer.style.backgroundColor = 'var(--background-modifier-success)'; - successContainer.style.border = '1px solid var(--background-modifier-success-border)'; - successContainer.style.borderRadius = '4px'; - successContainer.style.padding = '8px 12px'; - successContainer.style.marginTop = '16px'; - - successContainer.createEl('span', { - text: '✓ Configuration is valid and ready for export', - attr: { style: 'color: var(--text-success);' } - }); - - // Auto-hide success message after 3 seconds - setTimeout(() => { - if (successContainer.parentNode) { - successContainer.remove(); - } - }, 3000); - } - } - - /** - * Debounced validation trigger - * Prevents excessive validation calls during rapid input changes - */ - private debouncedValidation: (() => void) | null = null; - - /** - * Trigger validation with debouncing - */ - private triggerValidation(): void { - if (this.debouncedValidation) { - clearTimeout(this.debouncedValidation as any); - } - - this.debouncedValidation = setTimeout(() => { - this.validateSettings(); - this.updatePreview(); - }, 300) as any; - } - - /** - * Save current settings to plugin configuration - * Placeholder for Task 7.4 - */ - /** - * Save current export settings to plugin configuration - * Persists user preferences for future exports - */ - private async saveSettings(): Promise { - try { - // Update plugin's export defaults with current settings - if (this.settings.template) { - this.plugin.settings.exportDefaults.template = this.settings.template; - } - - if (this.settings.format) { - this.plugin.settings.exportDefaults.format = this.settings.format; - } - - - // Update output folder preference - if (this.settings.outputFolder && this.settings.outputFolder !== this.plugin.settings.outputFolder) { - this.plugin.settings.outputFolder = this.settings.outputFolder; - } - - // Save recent export configurations to plugin settings - const recentConfigs = this.plugin.settings as any; - if (!recentConfigs.recentExportConfigs) { - recentConfigs.recentExportConfigs = []; - } - - // Create a recent config entry - const recentConfig = { - timestamp: Date.now(), - notePath: this.settings.notePath, - noteTitle: this.settings.noteTitle, - config: { - template: this.settings.template, - format: this.settings.format, - outputFolder: this.settings.outputFolder, - templateVariables: { ...this.settings.templateVariables } - } - }; - - // Add to recent configs (keep only last 10) - recentConfigs.recentExportConfigs.unshift(recentConfig); - if (recentConfigs.recentExportConfigs.length > 10) { - recentConfigs.recentExportConfigs = recentConfigs.recentExportConfigs.slice(0, 10); - } - - // Persist to disk - await this.plugin.saveSettings(); - - } catch (error) { - console.error('Failed to save export settings:', error); - // Don't block export on settings save failure - } - } - - /** - * Load previous export configuration for this note - * Restores settings from the most recent export of the same note - */ - private loadPreviousConfig(): void { - const recentConfigs = (this.plugin.settings as any).recentExportConfigs; - if (!recentConfigs || !Array.isArray(recentConfigs)) { - return; - } - - // Find most recent config for this specific note - const previousConfig = recentConfigs.find((config: any) => - config.notePath === this.settings.notePath - ); - - if (previousConfig && previousConfig.config) { - const config = previousConfig.config; - - // Restore configuration - if (config.template && this.settings.availableTemplates.includes(config.template)) { - this.settings.template = config.template; - } - - if (config.format) { - this.settings.format = config.format; - } - - - if (config.outputFolder) { - this.settings.outputFolder = config.outputFolder; - } - - if (config.templateVariables) { - this.settings.templateVariables = { ...config.templateVariables }; - } - - // Update form UI to reflect restored settings - this.updateFormFromSettings(); - } - } - - /** - * Get recent export configurations for quick access - */ - private getRecentConfigs(): any[] { - const recentConfigs = (this.plugin.settings as any).recentExportConfigs; - return recentConfigs && Array.isArray(recentConfigs) ? recentConfigs : []; - } - - /** - * Update form controls to match current settings - * Called after loading previous configuration - */ - private updateFormFromSettings(): void { - // Update template dropdown - if (this.templateDropdown && this.settings.template) { - this.templateDropdown.setValue(this.settings.template); - } - - // Update other form controls - // This would need to be enhanced with references to all form controls - // For now, trigger a complete form regeneration - setTimeout(() => { - this.updatePreview(); - }, 100); - } - - /** - * Reset settings to plugin defaults - */ - private resetToDefaults(): void { - const defaults = this.plugin.settings.exportDefaults; - - this.settings.template = defaults.template; - this.settings.format = defaults.format; - this.settings.outputFolder = this.plugin.settings.outputFolder; - this.settings.templateVariables = { - title: this.settings.noteTitle, - author: '', - date: new Date().toLocaleDateString(), - filenamePattern: '{title}' - }; - - // Update form UI - this.updateFormFromSettings(); - } - - /** - * Export current configuration as JSON for sharing or backup - */ - private exportConfiguration(): string { - const exportData = { - version: '1.0', - template: this.settings.template, - format: this.settings.format, - templateVariables: this.settings.templateVariables, - // Don't include outputFolder (local path) or notePath (specific to this instance) - }; - - return JSON.stringify(exportData, null, 2); - } - - /** - * Import configuration from JSON - */ - private importConfiguration(jsonData: string): boolean { - try { - const importData = JSON.parse(jsonData); - - // Validate imported data - if (!importData.version) { - throw new Error('Invalid configuration format'); - } - - // Apply imported settings - if (importData.template && this.settings.availableTemplates.includes(importData.template)) { - this.settings.template = importData.template; - } - - if (importData.format && Object.values(ExportFormat).includes(importData.format)) { - this.settings.format = importData.format; - } - - - if (importData.templateVariables) { - this.settings.templateVariables = { - ...this.settings.templateVariables, - ...importData.templateVariables - }; - } - - // Update form UI - this.updateFormFromSettings(); - return true; - - } catch (error) { - console.error('Failed to import configuration:', error); - return false; - } - } - - /** - * Start export progress tracking - * Placeholder for Task 7.5 - */ - /** - * Start export progress tracking - * Shows progress overlay and hides main form - */ - private showProgress(): void { - // Hide form and show progress - this.formContainer.style.display = 'none'; - this.previewContainer.style.display = 'none'; - this.progressContainer.style.display = 'block'; - - // Clear and setup progress container - this.progressContainer.empty(); - - // Progress header - const header = this.progressContainer.createDiv('progress-header'); - header.style.textAlign = 'center'; - header.style.marginBottom = '20px'; - - const title = header.createEl('h3', { text: 'Exporting PDF...' }); - const subtitle = header.createEl('p', { - text: `Exporting "${this.settings.noteTitle}"`, - attr: { style: 'color: var(--text-muted); margin: 8px 0;' } - }); - - // Progress indicator container - const progressIndicator = this.progressContainer.createDiv('progress-indicator'); - progressIndicator.style.marginBottom = '20px'; - - // Progress bar - const progressWrapper = progressIndicator.createDiv('progress-wrapper'); - progressWrapper.style.width = '100%'; - progressWrapper.style.backgroundColor = 'var(--background-modifier-border)'; - progressWrapper.style.borderRadius = '4px'; - progressWrapper.style.height = '12px'; - progressWrapper.style.overflow = 'hidden'; - - this.progressBar = progressWrapper.createDiv('progress-bar'); - this.progressBar.style.width = '0%'; - this.progressBar.style.height = '100%'; - this.progressBar.style.backgroundColor = 'var(--interactive-accent)'; - this.progressBar.style.transition = 'width 0.3s ease'; - - // Progress text - this.progressText = progressIndicator.createDiv('progress-text'); - this.progressText.style.textAlign = 'center'; - this.progressText.style.marginTop = '8px'; - this.progressText.style.fontSize = '0.9em'; - this.progressText.style.color = 'var(--text-muted)'; - this.progressText.textContent = 'Initializing export...'; - - // Progress percentage - const progressPercent = progressIndicator.createDiv('progress-percent'); - progressPercent.style.textAlign = 'center'; - progressPercent.style.marginTop = '4px'; - progressPercent.style.fontSize = '1.1em'; - progressPercent.style.fontWeight = 'bold'; - this.progressPercentElement = progressPercent; - this.progressPercentElement.textContent = '0%'; - - // Cancel button - const cancelContainer = this.progressContainer.createDiv('cancel-container'); - cancelContainer.style.textAlign = 'center'; - cancelContainer.style.marginTop = '20px'; - - this.cancelButton = cancelContainer.createEl('button', { - text: 'Cancel Export', - attr: { - style: ` - padding: 8px 16px; - background: var(--interactive-normal); - border: 1px solid var(--background-modifier-border); - border-radius: 4px; - color: var(--text-normal); - cursor: pointer; - ` - } - }); - - this.cancelButton.addEventListener('click', () => this.cancelExport()); - - // Set initial state - this.settings.isExporting = true; - this.settings.canCancel = true; - this.settings.progressPercent = 0; - this.settings.currentOperation = 'Initializing export...'; - } - - /** - * Update export progress - * Placeholder for Task 7.5 - */ - /** - * Update export progress - * Updates progress bar, percentage, and current operation text - */ - private updateProgress(percent: number, operation: string): void { - this.settings.progressPercent = Math.max(0, Math.min(100, percent)); - this.settings.currentOperation = operation; - - // Update progress bar - if (this.progressBar) { - this.progressBar.style.width = `${this.settings.progressPercent}%`; - } - - // Update percentage display - if (this.progressPercentElement) { - this.progressPercentElement.textContent = `${Math.round(this.settings.progressPercent)}%`; - } - - // Update operation text - if (this.progressText) { - this.progressText.textContent = operation; - } - - // Disable cancel button in final stages - if (this.settings.progressPercent > 90) { - this.settings.canCancel = false; - if (this.cancelButton) { - this.cancelButton.disabled = true; - this.cancelButton.style.opacity = '0.5'; - this.cancelButton.style.cursor = 'not-allowed'; - } - } - - // Show completion state - if (this.settings.progressPercent >= 100) { - this.showCompletionState(); - } - } - - /** - * Hide progress and reset modal state - * Placeholder for Task 7.5 - */ - /** - * Hide progress and reset modal state - * Returns modal to form view or closes it - */ - private hideProgress(): void { - this.settings.isExporting = false; - this.settings.progressPercent = 0; - this.settings.currentOperation = ''; - this.settings.canCancel = false; - - // Reset UI state - if (this.progressContainer) { - this.progressContainer.style.display = 'none'; - } - - if (this.formContainer) { - this.formContainer.style.display = 'block'; - } - - if (this.previewContainer) { - this.previewContainer.style.display = 'block'; - } - - // Clean up progress elements - this.progressBar = null; - this.progressText = null; - this.progressPercentElement = null; - this.cancelButton = null; - } - - /** - * Handle export cancellation - * Placeholder for Task 7.5 - */ - /** - * Handle export cancellation - * Cancels ongoing export and resets modal state - */ - private cancelExport(): void { - if (!this.settings.canCancel) { - return; // Cannot cancel at this stage - } - - // Update UI to show cancellation in progress - if (this.progressText) { - this.progressText.textContent = 'Cancelling export...'; - } - - if (this.cancelButton) { - this.cancelButton.disabled = true; - this.cancelButton.textContent = 'Cancelling...'; - this.cancelButton.style.opacity = '0.5'; - } - - // Call cancellation callback if provided - if (this.onCancel) { - this.onCancel(); - } - - // Show cancellation feedback - setTimeout(() => { - this.showCancellationState(); - }, 1000); // Give time for cleanup - } - - /** - * Show completion state when export is finished - */ - private showCompletionState(): void { - if (this.progressText) { - this.progressText.textContent = 'Export completed successfully!'; - this.progressText.style.color = 'var(--text-success)'; - } - - if (this.cancelButton) { - this.cancelButton.style.display = 'none'; - } - - // Add completion actions - const completionActions = this.progressContainer.createDiv('completion-actions'); - completionActions.style.textAlign = 'center'; - completionActions.style.marginTop = '20px'; - - // Success message - const successMsg = completionActions.createDiv('success-message'); - successMsg.style.padding = '12px'; - successMsg.style.backgroundColor = 'var(--background-modifier-success)'; - successMsg.style.border = '1px solid var(--background-modifier-success-border)'; - successMsg.style.borderRadius = '4px'; - successMsg.style.marginBottom = '16px'; - successMsg.style.color = 'var(--text-success)'; - successMsg.innerHTML = ` - ✓ PDF exported successfully!
- File saved to: ${this.settings.outputFolder}/${this.generatePreviewFilename()}.pdf - `; - - // Action buttons - const actionButtons = completionActions.createDiv('action-buttons'); - actionButtons.style.display = 'flex'; - actionButtons.style.gap = '8px'; - actionButtons.style.justifyContent = 'center'; - - // Open file button (if supported) - const openButton = actionButtons.createEl('button', { - text: 'Open PDF', - attr: { - style: ` - padding: 8px 16px; - background: var(--interactive-accent); - border: none; - border-radius: 4px; - color: var(--text-on-accent); - cursor: pointer; - ` - } - }); - - openButton.addEventListener('click', () => { - // TODO: Implement file opening logic - // This would typically use Obsidian's shell.openPath or similar - this.close(); - }); - - // Close button - const closeButton = actionButtons.createEl('button', { - text: 'Close', - attr: { - style: ` - padding: 8px 16px; - background: var(--interactive-normal); - border: 1px solid var(--background-modifier-border); - border-radius: 4px; - color: var(--text-normal); - cursor: pointer; - ` - } - }); - - closeButton.addEventListener('click', () => this.close()); - - // Auto-close after delay - setTimeout(() => { - if (this.isOpen) { - this.close(); - } - }, 5000); - } - - /** - * Show cancellation state when export is cancelled - */ - private showCancellationState(): void { - if (this.progressText) { - this.progressText.textContent = 'Export cancelled'; - this.progressText.style.color = 'var(--text-warning)'; - } - - if (this.progressBar) { - this.progressBar.style.backgroundColor = 'var(--background-modifier-error)'; - } - - // Add cancellation message - const cancellationMsg = this.progressContainer.createDiv('cancellation-message'); - cancellationMsg.style.textAlign = 'center'; - cancellationMsg.style.marginTop = '20px'; - cancellationMsg.style.padding = '12px'; - cancellationMsg.style.backgroundColor = 'var(--background-modifier-error)'; - cancellationMsg.style.border = '1px solid var(--background-modifier-error-border)'; - cancellationMsg.style.borderRadius = '4px'; - cancellationMsg.style.color = 'var(--text-error)'; - cancellationMsg.innerHTML = ` - Export cancelled
- No files were created - `; - - // Action buttons - const actionContainer = this.progressContainer.createDiv('cancellation-actions'); - actionContainer.style.textAlign = 'center'; - actionContainer.style.marginTop = '16px'; - - const backButton = actionContainer.createEl('button', { - text: 'Back to Settings', - attr: { - style: ` - padding: 8px 16px; - background: var(--interactive-normal); - border: 1px solid var(--background-modifier-border); - border-radius: 4px; - color: var(--text-normal); - cursor: pointer; - margin-right: 8px; - ` - } - }); - - backButton.addEventListener('click', () => this.hideProgress()); - - const closeButton = actionContainer.createEl('button', { - text: 'Close', - attr: { - style: ` - padding: 8px 16px; - background: var(--interactive-normal); - border: 1px solid var(--background-modifier-border); - border-radius: 4px; - color: var(--text-normal); - cursor: pointer; - ` - } - }); - - closeButton.addEventListener('click', () => this.close()); - } - - /** - * Check if modal is currently open - */ - private get isOpen(): boolean { - return this.containerEl.isConnected; - } - - /** - * Add custom CSS styles for the export modal - */ - private addModalStyles(): void { - const styleId = 'export-config-modal-styles'; - - // Don't add styles if already present - if (document.getElementById(styleId)) { - return; - } - - const style = document.createElement('style'); - style.id = styleId; - style.textContent = ` - .export-config-container { - width: 100%; - max-width: 100%; - min-height: 650px; - max-height: 80vh; - overflow-y: auto; - overflow-x: hidden; - box-sizing: border-box; - } - - .export-section { - margin-bottom: 24px; - padding-bottom: 16px; - border-bottom: 1px solid var(--background-modifier-border-hover); - } - - .export-section:last-child { - border-bottom: none; - } - - .export-section h3 { - margin: 0 0 12px 0; - font-size: 1.1em; - font-weight: 600; - color: var(--text-normal); - } - - .export-section h4 { - margin: 16px 0 8px 0; - font-size: 1em; - font-weight: 500; - color: var(--text-muted); - } - - .export-config-preview { - background: var(--background-secondary); - padding: 16px; - border-radius: 8px; - } - - .export-config-preview h3 { - margin: 0 0 12px 0; - font-size: 1em; - font-weight: 600; - } - - .config-items .config-item { - margin-bottom: 8px; - font-size: 0.9em; - line-height: 1.4; - } - - .variables-list .var-item { - margin-left: 16px; - font-size: 0.85em; - color: var(--text-muted); - } - - .export-actions { - display: flex; - gap: 12px; - justify-content: flex-end; - } - - .progress-indicator { - padding: 20px; - } - - .progress-wrapper { - box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1); - } - - .field-error { - background: var(--background-modifier-error); - padding: 8px 12px; - border-radius: 4px; - margin: 8px 0; - border-left: 3px solid var(--text-error); - } - - .margins-container .setting-item, - .font-sizes .setting-item { - border: none; - padding: 8px 0; - } - - .template-variables .setting-item { - padding: 6px 0; - } - - .completion-actions .success-message, - .cancellation-message { - animation: slideIn 0.3s ease-out; - } - - @keyframes slideIn { - from { - opacity: 0; - transform: translateY(-10px); - } - to { - opacity: 1; - transform: translateY(0); - } - } - - .export-config-container button:hover:not(:disabled) { - opacity: 0.8; - } - - .export-config-container button:disabled { - cursor: not-allowed; - } - `; - - document.head.appendChild(style); - } - - // Additional properties for progress tracking - private progressPercentElement: HTMLElement | null = null; - - /** - * Submit current configuration for export - */ - private async submitExport(): Promise { - if (!this.validateSettings()) { - return; - } - - // Prepare export configuration - const exportConfig: ExportConfig = { - template: this.settings.template, - format: this.settings.format, - outputFolder: this.settings.outputFolder, - templateVariables: this.settings.templateVariables - }; - - try { - // Save settings for future use - await this.saveSettings(); - - // Start export process - this.settings.isExporting = true; - this.showProgress(); - - // Execute export via callback - await this.onSubmit(exportConfig); - - // Success - close modal - this.close(); - } catch (error) { - // Handle export errors - console.error('Export failed:', error); - this.hideProgress(); - - // TODO: Show user-friendly error message - } - } -} +// Default export for Obsidian +export default obsidianTypstPDFExport; \ No newline at end of file diff --git a/main.ts.backup b/main.ts.backup new file mode 100644 index 0000000..9ab7e56 --- /dev/null +++ b/main.ts.backup @@ -0,0 +1,4224 @@ +import { App, Notice, Plugin, PluginSettingTab, Setting, Modal, MarkdownRenderer, TFile, TFolder, Menu } from 'obsidian'; +import { DependencyChecker } from './src/DependencyChecker'; +import { TemplateManager } from './src/template-manager'; +import { spawn, ChildProcess } from 'child_process'; +import { promises as fs } from 'fs'; +import * as path from 'path'; +import * as os from 'os'; + +/** + * Configuration options for Pandoc conversion + */ +interface PandocOptions { + /** Path to pandoc executable (optional, uses PATH if not specified) */ + pandocPath?: string; + /** Path to typst executable (optional, uses PATH if not specified) */ + typstPath?: string; + /** Template file path */ + template?: string; + /** Template variables to pass to pandoc */ + variables?: Record; + /** Additional pandoc arguments */ + additionalArgs?: string[]; + /** Timeout for pandoc process in milliseconds (default: 60000) */ + timeout?: number; + /** Generate intermediate .typ file for debugging */ + generateIntermediateTypst?: boolean; + /** Vault base path for resolving attachment paths */ + vaultBasePath?: string; + /** Plugin directory path for resolving plugin-relative paths */ + pluginDir?: string; +} + +/** + * Settings specific to Typst engine + */ +interface TypstSettings { + /** Additional options to pass to Typst engine */ + engineOptions?: string[]; +} + +/** + * Result of a Pandoc conversion operation + */ +interface ConversionResult { + /** Whether the conversion was successful */ + success: boolean; + /** Path to the output PDF file */ + outputPath?: string; + /** Path to intermediate .typ file (if generated) */ + intermediateTypstPath?: string; + /** Error message if conversion failed */ + error?: string; + /** Pandoc stdout output */ + stdout?: string; + /** Pandoc stderr output */ + stderr?: string; + /** Process exit code */ + exitCode?: number; +} + +/** + * Progress callback function type + */ +type ProgressCallback = (message: string, progress?: number) => void; + +/** + * Core converter class for Pandoc to Typst PDF conversion + */ +class PandocTypstConverter { + private tempDir: string | null = null; + private cleanupHandlers: (() => void)[] = []; + + /** + * Create a new PandocTypstConverter instance + * @param pandocOptions Configuration options for Pandoc + * @param typstSettings Settings specific to Typst engine + */ + constructor( + private pandocOptions: PandocOptions = {}, + private typstSettings: TypstSettings = {} + ) { + // Set up cleanup handlers for process termination + this.setupCleanup(); + } + + /** + * Convert a markdown file to PDF using Pandoc with Typst engine + * @param inputPath Path to the input markdown file + * @param outputPath Path where the PDF should be saved + * @param progressCallback Optional callback for progress updates + * @returns Promise resolving to conversion result + */ + async convertToPDF( + inputPath: string, + outputPath: string, + progressCallback?: ProgressCallback + ): Promise { + try { + progressCallback?.('Starting PDF conversion...', 0); + + // Create temporary directory if needed + await this.ensureTempDirectory(); + + // Build pandoc arguments + const args = await this.buildPandocArgs(inputPath, outputPath); + + progressCallback?.('Executing Pandoc with Typst engine...', 30); + + // Execute pandoc process + const result = await this.executePandoc(args, progressCallback); + + progressCallback?.('Conversion complete!', 100); + + return result; + + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + return { + success: false, + error: `Conversion failed: ${errorMessage}` + }; + } + } + + /** + * Set up cleanup handlers for temporary files + */ + private setupCleanup(): void { + const cleanup = () => { + this.cleanup(); + }; + + process.on('exit', cleanup); + process.on('SIGINT', cleanup); + process.on('SIGTERM', cleanup); + process.on('uncaughtException', cleanup); + } + + /** + * Process PDF embeds by converting them to images and creating combined output + */ + private async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string): Promise { + const { PdfToImageConverter } = require('./src/PdfToImageConverter'); + const converter = PdfToImageConverter.getInstance(this); + const path = require('path'); + + for (const pdfEmbed of processedResult.metadata.pdfEmbeds) { + try { + console.log(`Export: Processing PDF embed: ${pdfEmbed.originalPath}`); + + // Resolve full path to the PDF + const fullPdfPath = path.resolve(vaultBasePath, pdfEmbed.sanitizedPath); + + // Check if PDF file exists + const fs = require('fs'); + if (!fs.existsSync(fullPdfPath)) { + console.warn(`Export: PDF file not found: ${fullPdfPath}`); + // Replace marker with error message + processedResult.content = processedResult.content.replace( + pdfEmbed.marker, + `[⚠️ PDF not found: ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})` + ); + continue; + } + + // Convert PDF to image + const conversionResult = await converter.convertFirstPageToImage( + fullPdfPath, + tempDir, + { + scale: 1.5, + maxWidth: 600, + maxHeight: 400, + format: 'png' + } + ); + + if (conversionResult.success) { + // Get relative path for the generated image + const relativeImagePath = path.relative(vaultBasePath, conversionResult.imagePath); + + // Create combined output: image preview + PDF attachment link + const combinedOutput = [ + `![${pdfEmbed.fileName} - Page 1](${relativeImagePath})`, + `[📎 **Download PDF:** ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})` + ].join('\n\n'); + + // Replace marker with combined output + processedResult.content = processedResult.content.replace(pdfEmbed.marker, combinedOutput); + + console.log(`Export: Successfully converted PDF: ${pdfEmbed.fileName} -> ${path.basename(conversionResult.imagePath)}`); + + } else { + console.error(`Export: PDF conversion failed: ${conversionResult.error}`); + + // Replace marker with fallback link + processedResult.content = processedResult.content.replace( + pdfEmbed.marker, + `[📖 ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Note: PDF preview could not be generated*` + ); + } + + } catch (error) { + console.error(`Export: Error processing PDF embed: ${error.message}`); + + // Replace marker with error fallback + processedResult.content = processedResult.content.replace( + pdfEmbed.marker, + `[⚠️ ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Error: Could not process PDF embed*` + ); + } + } + } + + /** + * Clean up temporary files and directories + */ + private async cleanup(): Promise { + try { + // Execute registered cleanup handlers + this.cleanupHandlers.forEach(handler => { + try { + handler(); + } catch (error) { + console.warn('Cleanup handler failed:', error); + } + }); + + // Remove temporary directory + if (this.tempDir) { + await fs.rmdir(this.tempDir, { recursive: true }); + this.tempDir = null; + } + } catch (error) { + console.warn('Cleanup failed:', error); + } + } + + /** + * Ensure temporary directory exists + */ + private async ensureTempDirectory(): Promise { + if (!this.tempDir) { + this.tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'obsidian-typst-')); + } + return this.tempDir; + } + + /** + * Build pandoc command-line arguments + */ + private async buildPandocArgs(inputPath: string, outputPath: string): Promise { +const args: string[] = []; + +// Input file +args.push(inputPath); + +// Output file +args.push('-o', outputPath); + +// Specify input format as markdown with smart extension disabled +args.push('--from', 'markdown-smart'); + +// Set PDF engine to Typst (use configured path if available) +if (this.pandocOptions.typstPath) { + args.push(`--pdf-engine=${this.pandocOptions.typstPath}`); +} else { + args.push('--pdf-engine=typst'); +} + +// Enable standalone mode (required for PDF output) +args.push('--standalone'); + +// Embed resources (images, etc.) directly into the output +args.push('--embed-resources'); + +// Add resource paths for attachment resolution +if (this.pandocOptions.vaultBasePath) { + const path = require('path'); + const fs = require('fs'); + + // Add vault root as primary resource path + args.push('--resource-path', this.pandocOptions.vaultBasePath); + + // Add common attachment directories as additional resource paths + const commonAttachmentPaths = [ + path.join(this.pandocOptions.vaultBasePath, 'attachments'), + path.join(this.pandocOptions.vaultBasePath, 'assets'), + path.join(this.pandocOptions.vaultBasePath, 'files'), + path.join(this.pandocOptions.vaultBasePath, 'images'), + path.join(this.pandocOptions.vaultBasePath, '.attachments') + ]; + + // Check if these directories exist and add them + for (const attachPath of commonAttachmentPaths) { + if (fs.existsSync(attachPath)) { + args.push('--resource-path', attachPath); + console.log('Added resource path:', attachPath); + } + } + + // Also scan for note-specific attachment folders (Obsidian often creates these) + try { + const vaultContents = fs.readdirSync(this.pandocOptions.vaultBasePath); + for (const item of vaultContents) { + const itemPath = path.join(this.pandocOptions.vaultBasePath, item); + const stat = fs.statSync(itemPath); + if (stat.isDirectory() && !item.startsWith('.') && !item.startsWith('_')) { + // Check if this directory contains images + try { + const dirContents = fs.readdirSync(itemPath); + const hasImages = dirContents.some((file: string) => + /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file) + ); + if (hasImages) { + args.push('--resource-path', itemPath); + console.log('Added note-specific resource path:', itemPath); + } + } catch (e) { + // Ignore directories we can't read + } + } + } + } catch (e) { + console.warn('Could not scan vault for attachment directories:', e); + } +} + +// Use universal wrapper with --template and pass actual template as template_path variable +if (this.pandocOptions.template) { + // Get absolute path to universal wrapper using plugin directory from pandocOptions + const path = require('path'); + const fs = require('fs'); + const absolutePluginDir = this.pandocOptions.pluginDir || ''; + const wrapperPath = path.resolve(absolutePluginDir, 'templates', 'universal-wrapper.pandoc.typ'); + console.log('Universal wrapper path:', wrapperPath); + + // Verify wrapper exists + if (!fs.existsSync(wrapperPath)) { + throw new Error(`Universal wrapper template not found at: ${wrapperPath}`); + } + + args.push('--template', wrapperPath); + + // Pass the actual template path as a variable + args.push('-V', `template_path=${this.pandocOptions.template}`); +} + +// Add variables for document metadata +if (this.pandocOptions.variables) { + for (const [key, value] of Object.entries(this.pandocOptions.variables)) { + if (value && value.toString().trim() !== '') { + args.push('-V', `${key}=${value}`); + } + } +} + +// Add typography settings as template variables +const plugin = (this as any).plugin; +if (plugin && plugin.settings) { + const settings = plugin.settings; + + // Add typography variables + if (settings.typography) { + if (settings.typography.fonts) { + if (settings.typography.fonts.body) { + args.push('-V', `font="${settings.typography.fonts.body}"`); + } + if (settings.typography.fonts.heading) { + args.push('-V', `heading_font="${settings.typography.fonts.heading}"`); + } + if (settings.typography.fonts.monospace) { + args.push('-V', `monospace_font="${settings.typography.fonts.monospace}"`); + } + } + + if (settings.typography.fontSizes) { + if (settings.typography.fontSizes.body) { + args.push('-V', `fontsize=${settings.typography.fontSizes.body}pt`); + } + if (settings.typography.fontSizes.heading) { + args.push('-V', `heading_fontsize=${settings.typography.fontSizes.heading}pt`); + } + if (settings.typography.fontSizes.small) { + args.push('-V', `small_fontsize=${settings.typography.fontSizes.small}pt`); + } + } + } + + // Add page setup variables + if (settings.pageSetup) { + if (settings.pageSetup.size) { + args.push('-V', `paper=${settings.pageSetup.size}`); + } + if (settings.pageSetup.orientation) { + args.push('-V', `orientation=${settings.pageSetup.orientation}`); + } + + // Convert margin points to cm for Typst (1 point = 0.0352778 cm) + if (settings.pageSetup.margins) { + const margins = settings.pageSetup.margins; + if (margins.top !== undefined) { + const topCm = (margins.top * 0.0352778).toFixed(2); + args.push('-V', `margin_top=${topCm}cm`); + } + if (margins.right !== undefined) { + const rightCm = (margins.right * 0.0352778).toFixed(2); + args.push('-V', `margin_right=${rightCm}cm`); + } + if (margins.bottom !== undefined) { + const bottomCm = (margins.bottom * 0.0352778).toFixed(2); + args.push('-V', `margin_bottom=${bottomCm}cm`); + } + if (margins.left !== undefined) { + const leftCm = (margins.left * 0.0352778).toFixed(2); + args.push('-V', `margin_left=${leftCm}cm`); + } + } + } + + // Add export format variable + if (settings.exportDefaults) { + if (settings.exportDefaults.format) { + args.push('-V', `export_format=${settings.exportDefaults.format}`); + } + } +} + +// Add Typst engine options +if (this.typstSettings.engineOptions) { + for (const option of this.typstSettings.engineOptions) { + args.push('--pdf-engine-opt', option); + } +} + +// Generate intermediate Typst file if requested +if (this.pandocOptions.generateIntermediateTypst) { + const tempDir = await this.ensureTempDirectory(); + const typstPath = path.join(tempDir, 'intermediate.typ'); + args.push('--output', typstPath); +} + +// Add additional arguments +if (this.pandocOptions.additionalArgs) { + args.push(...this.pandocOptions.additionalArgs); +} + +return args; +} + + /** + * Execute pandoc process with the given arguments + */ + private async executePandoc(args: string[], progressCallback?: ProgressCallback): Promise { +return new Promise((resolve) => { + const pandocPath = this.pandocOptions.pandocPath || 'pandoc'; + const timeout = this.pandocOptions.timeout || 60000; + + // Log the exact command being executed for debugging + console.log('Executing Pandoc command:', pandocPath, args.join(' ')); + + progressCallback?.('Starting Pandoc process...', 40); + + // Determine working directory - use vault base path if available, fallback to plugin directory + const path = require('path'); + let workingDir: string; + + if (this.pandocOptions.vaultBasePath) { + workingDir = this.pandocOptions.vaultBasePath; + console.log('Pandoc working directory (vault):', workingDir); + } else { + // Fallback to plugin directory + const pluginDir = (this.pandocOptions as any).pluginDir || process.cwd(); + workingDir = pluginDir; + console.log('Pandoc working directory (plugin fallback):', workingDir); + } + + // Spawn pandoc process with vault as working directory for attachment resolution + const pandocProcess: ChildProcess = spawn(pandocPath, args, { + stdio: ['pipe', 'pipe', 'pipe'], + cwd: workingDir, + env: process.env, // Inherit environment variables + }); + + let stdout = ''; + let stderr = ''; + let hasTimedOut = false; + + // Set up timeout + const timeoutHandle = setTimeout(() => { + hasTimedOut = true; + pandocProcess.kill('SIGTERM'); + resolve({ + success: false, + error: `Pandoc process timed out after ${timeout}ms`, + exitCode: -1 + }); + }, timeout); + + // Collect stdout + pandocProcess.stdout?.on('data', (data: Buffer) => { + stdout += data.toString(); + progressCallback?.('Processing document...', 60); + }); + + // Collect stderr and monitor for progress + pandocProcess.stderr?.on('data', (data: Buffer) => { + const output = data.toString(); + stderr += output; + console.log('Pandoc stderr:', output); + + // Parse progress information from stderr if available + this.parseProgressFromOutput(output, progressCallback); + }); + + // Handle process completion + pandocProcess.on('close', (code: number | null) => { + clearTimeout(timeoutHandle); + + if (hasTimedOut) { + return; // Already resolved with timeout error + } + + const success = code === 0; + const result: ConversionResult = { + success, + stdout, + stderr, + exitCode: code || -1 + }; + + if (!success) { + result.error = this.extractErrorMessage(stderr, stdout); + } else { + progressCallback?.('PDF generation complete!', 90); + } + + resolve(result); + }); + + // Handle process errors + pandocProcess.on('error', (error: Error) => { + clearTimeout(timeoutHandle); + console.log('Pandoc process error:', error); + resolve({ + success: false, + error: `Failed to start Pandoc process: ${error.message}`, + exitCode: -1 + }); + }); +}); +} + + /** + * Parse progress information from pandoc output + */ + private parseProgressFromOutput(output: string, progressCallback?: ProgressCallback): void { + // Look for common progress indicators in pandoc/typst output + if (output.includes('reading')) { + progressCallback?.('Reading input file...', 50); + } else if (output.includes('parsing')) { + progressCallback?.('Parsing document...', 55); + } else if (output.includes('typst')) { + progressCallback?.('Generating PDF with Typst...', 70); + } else if (output.includes('writing')) { + progressCallback?.('Writing output file...', 80); + } + } + + /** + * Extract meaningful error messages from pandoc output + */ + private extractErrorMessage(stderr: string, stdout: string): string { + // Look for common error patterns + const errorPatterns = [ + /error:/i, + /Error:/, + /failed/i, + /Fatal/i, + /pandoc:/i + ]; + + const allOutput = (stderr + '\n' + stdout).split('\n'); + + for (const line of allOutput) { + for (const pattern of errorPatterns) { + if (pattern.test(line)) { + return line.trim(); + } + } + } + + // If no specific error found, return first non-empty line from stderr + const stderrLines = stderr.split('\n').filter(line => line.trim().length > 0); + if (stderrLines.length > 0) { + return stderrLines[0]; + } + + return 'Unknown error occurred during conversion'; + } + + /** + * Dispose of the converter and clean up resources + */ + async dispose(): Promise { + await this.cleanup(); + } +} + +/** + * Obsidian Typst PDF Export Plugin + * + * This plugin exports Obsidian notes to PDF using the Typst typesetting system. + * It provides features for converting Obsidian markdown to Typst format and + * generating high-quality PDFs with customizable styling. + */ + + +/** Export format options for output structure */ +enum ExportFormat { + /** Standard multi-page PDF format */ + Standard = 'standard', + /** Single-page continuous PDF format */ + SinglePage = 'single-page' +} + +/** Template interface for Typst template management */ +interface Template { + /** Display name of the template */ + name: string; + /** File path to the template */ + filePath: string; + /** Template variables and their types */ + variables: Record; + /** Template metadata */ + metadata: { + author?: string; + version?: string; + description?: string; + compatibility: string[]; + }; +} + +/** Configuration for individual export operations */ +interface ExportConfig { + /** Override default template */ + template?: string; + /** Override default format */ + format?: ExportFormat; + /** Override output folder */ + outputFolder?: string; + /** Template variables for this export */ + templateVariables?: Record; +} + +interface obsidianTypstPDFExportSettings { + /** Path to the Pandoc executable */ + pandocPath: string; + /** Path to the Typst executable */ + typstPath: string; + /** Default output folder for exported PDFs */ + outputFolder: string; + + /** Executable paths configuration */ + executablePaths: { + /** Path to ImageMagick convert command (optional, uses PATH if not specified) */ + imagemagickPath: string; + /** Additional paths to append to PATH environment variable */ + additionalPaths: string[]; + }; + + /** Export defaults */ + exportDefaults: { + /** Default template to use for exports */ + template: string; + /** Default export format */ + format: ExportFormat; + }; + + /** Typography settings */ + typography: { + /** Font families for different text types */ + fonts: { + body: string; + heading: string; + monospace: string; + }; + /** Font sizes */ + fontSizes: { + body: number; + heading: number; + small: number; + }; + }; + + /** Page setup configuration */ + pageSetup: { + /** Page size (e.g., "a4", "letter", "custom") */ + size: string; + /** Page orientation */ + orientation: "portrait" | "landscape"; + /** Page margins in points */ + margins: { + top: number; + right: number; + bottom: number; + left: number; + }; + }; + + /** Behavior flags */ + behavior: { + /** Open PDF after export */ + openAfterExport: boolean; + /** Preserve folder structure in output */ + preserveFolderStructure: boolean; + /** Number of concurrent exports to run (default: 3) */ + exportConcurrency: number; + /** Enable debug mode for verbose logging */ + debugMode: boolean; + }; +} + +const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = { + pandocPath: '', + typstPath: '', + outputFolder: 'exports', + + executablePaths: { + imagemagickPath: '', // Empty means use system PATH + additionalPaths: ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin'] + }, + + exportDefaults: { + template: 'default', + format: ExportFormat.Standard + }, + + typography: { + fonts: { + body: 'Concourse OT', + heading: 'SF Pro Text', + monospace: 'UbuntuMono Nerd Font Mono' + }, + fontSizes: { + body: 11, + heading: 16, + small: 9 + } + }, + + pageSetup: { + size: 'a4', + orientation: 'portrait', + margins: { + top: 72, + right: 72, + bottom: 72, + left: 72 + } + }, + + behavior: { + openAfterExport: true, + preserveFolderStructure: true, + exportConcurrency: 3, + debugMode: false + } +} + +export default class obsidianTypstPDFExport extends Plugin { + settings: obsidianTypstPDFExportSettings; + dependencyChecker: DependencyChecker; + templateManager: TemplateManager; + private converter: PandocTypstConverter; + + async onload() { + console.log('Loading Typst PDF Export Plugin...'); + + // Load settings first + await this.loadSettings(); + + // Initialize dependency checker and converter + this.dependencyChecker = new DependencyChecker(); + this.converter = new PandocTypstConverter(); + + // Initialize template manager + const pluginDir = (this.manifest as any).dir || path.join(this.app.vault.configDir, 'plugins', this.manifest.id); + // Convert to absolute path using vault adapter base path + const vaultBasePath = (this.app.vault.adapter as any).basePath || process.cwd(); + const absolutePluginDir = path.resolve(vaultBasePath, pluginDir); + console.log('Plugin directory (relative):', pluginDir); + console.log('Vault base path:', vaultBasePath); + console.log('Plugin directory (absolute):', absolutePluginDir); + console.log('Manifest dir:', (this.manifest as any).dir); + console.log('Config dir:', this.app.vault.configDir); + this.templateManager = new TemplateManager(this.app, absolutePluginDir); + + // Check dependencies asynchronously (don't block plugin startup) + this.checkDependenciesAsync(); + + // Register commands + this.registerCommands(); + + // Add ribbon icon with Lucide icon name + this.addRibbonIcon('download', 'Export to PDF with Typst', (event: MouseEvent) => { + this.handleRibbonClick(event); + }); + + // Register context menu events + this.registerEvents(); + + // This adds a settings tab so the user can configure various aspects of the plugin + this.addSettingTab(new TypstPDFExportSettingTab(this.app, this)); +} + + /** + * Auto-detect dependency paths and update settings if not already configured + */ + // Method removed - not needed since paths are already correctly configured in settings + + onunload() { + + } + + /** + * Check dependencies asynchronously without blocking plugin startup + */ + private async checkDependenciesAsync(): Promise { + try { + const additionalPaths = this.settings.executablePaths.additionalPaths; + const result = await this.dependencyChecker.checkAllDependencies( + { customPath: this.settings.pandocPath, additionalPaths }, + { customPath: this.settings.typstPath, additionalPaths }, + { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } + ); + + if (!result.allAvailable) { + // Show notice only if some dependencies are missing + const missingTools = []; + if (!result.pandoc.isAvailable) missingTools.push('Pandoc'); + if (!result.typst.isAvailable) missingTools.push('Typst'); + if (!result.imagemagick.isAvailable) missingTools.push('ImageMagick'); + + new Notice(`Typst PDF Export: ${missingTools.join(' and ')} not found. Use "Check dependencies" command for setup instructions.`, 8000); + } + } catch (error) { + console.warn('Dependency check failed on startup:', error); + } + } + + + /** + * Show detailed dependency status + */ + private async showDependencyStatus(): Promise { + try { + const additionalPaths = this.settings.executablePaths.additionalPaths; + const result = await this.dependencyChecker.checkAllDependencies( + { customPath: this.settings.pandocPath, additionalPaths }, + { customPath: this.settings.typstPath, additionalPaths }, + { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } + ); + + let message = '## Dependency Status\n\n'; + + // Pandoc status + message += '### Pandoc\n'; + if (result.pandoc.isAvailable) { + message += `✅ **Available** (v${result.pandoc.version})\n`; + message += `Path: ${result.pandoc.executablePath}\n\n`; + } else { + message += '❌ **Not Available**\n'; + message += `Error: ${result.pandoc.error}\n\n`; + message += this.dependencyChecker.formatInstallationGuide( + this.dependencyChecker.getInstallationGuide('pandoc') + ); + message += '\n\n'; + } + + // Typst status + message += '### Typst\n'; + if (result.typst.isAvailable) { + message += `✅ **Available** (v${result.typst.version})\n`; + message += `Path: ${result.typst.executablePath}\n\n`; + } else { + message += '❌ **Not Available**\n'; + message += `Error: ${result.typst.error}\n\n`; + message += this.dependencyChecker.formatInstallationGuide( + this.dependencyChecker.getInstallationGuide('typst') + ); + } + + // Create and show modal with dependency status + const modal = new DependencyStatusModal(this.app, this); + modal.open(); + + } catch (error) { + new Notice(`Error checking dependencies: ${error instanceof Error ? error.message : String(error)}`); + } + } + + /** + * Show dependency error dialog with installation instructions + */ + private showDependencyErrorDialog(result: { pandoc: any; typst: any; allAvailable: boolean }): void { + let message = '## Missing Dependencies\n\nThe following dependencies are required:\n\n'; + + if (!result.pandoc.isAvailable) { + message += `**Pandoc**: ${result.pandoc.error}\n\n`; + } + + if (!result.typst.isAvailable) { + message += `**Typst**: ${result.typst.error}\n\n`; + } + + message += 'Use the "Check Pandoc and Typst dependencies" command for detailed installation instructions.'; + + const modal = new DependencyStatusModal(this.app, this); + modal.open(); + } + + async loadSettings() { + try { + const loadedData = await this.loadData(); + + if (!loadedData) { + // No saved settings, use defaults + this.settings = { ...DEFAULT_SETTINGS }; + return; + } + + // Start with defaults and merge loaded data + this.settings = { ...DEFAULT_SETTINGS }; + + // Validate and merge loaded settings + const validatedSettings = this.validateSettings(loadedData); + this.settings = { ...this.settings, ...validatedSettings }; + + // Migrate settings if needed + this.settings = this.migrateSettings(this.settings); + + } catch (error) { + console.error('Failed to load Typst PDF Export settings:', error); + new Notice('Failed to load settings, using defaults'); + this.settings = { ...DEFAULT_SETTINGS }; + } + } + + /** + * Validates loaded settings data and returns a clean settings object + */ + private validateSettings(data: any): Partial { + const validated: Partial = {}; + + // Validate string paths + if (typeof data.pandocPath === 'string') { + validated.pandocPath = data.pandocPath; + } + if (typeof data.typstPath === 'string') { + validated.typstPath = data.typstPath; + } + if (typeof data.outputFolder === 'string') { + validated.outputFolder = data.outputFolder; + } + + // Validate export defaults + if (data.exportDefaults && typeof data.exportDefaults === 'object') { + const exportDefaults: Partial = {}; + + if (typeof data.exportDefaults.template === 'string') { + exportDefaults.template = data.exportDefaults.template; + } + + // Validate enum values + if (Object.values(ExportFormat).includes(data.exportDefaults.format)) { + exportDefaults.format = data.exportDefaults.format; + } + + + if (Object.keys(exportDefaults).length > 0) { + validated.exportDefaults = exportDefaults as any; + } + } + + // Validate typography settings + if (data.typography && typeof data.typography === 'object') { + const typography: Partial = {}; + + if (data.typography.fonts && typeof data.typography.fonts === 'object') { + const fonts: Partial = {}; + ['body', 'heading', 'monospace'].forEach(key => { + if (typeof data.typography.fonts[key] === 'string') { + (fonts as any)[key] = data.typography.fonts[key]; + } + }); + if (Object.keys(fonts).length > 0) { + typography.fonts = fonts as any; + } + } + + if (data.typography.fontSizes && typeof data.typography.fontSizes === 'object') { + const fontSizes: Partial = {}; + ['body', 'heading', 'small'].forEach(key => { + if (typeof data.typography.fontSizes[key] === 'number' && data.typography.fontSizes[key] > 0) { + (fontSizes as any)[key] = data.typography.fontSizes[key]; + } + }); + if (Object.keys(fontSizes).length > 0) { + typography.fontSizes = fontSizes as any; + } + } + + if (Object.keys(typography).length > 0) { + validated.typography = typography as any; + } + } + + // Validate page setup + if (data.pageSetup && typeof data.pageSetup === 'object') { + const pageSetup: Partial = {}; + + if (typeof data.pageSetup.size === 'string') { + pageSetup.size = data.pageSetup.size; + } + + if (['portrait', 'landscape'].includes(data.pageSetup.orientation)) { + pageSetup.orientation = data.pageSetup.orientation; + } + + if (data.pageSetup.margins && typeof data.pageSetup.margins === 'object') { + const margins: Partial = {}; + ['top', 'right', 'bottom', 'left'].forEach(key => { + if (typeof data.pageSetup.margins[key] === 'number' && data.pageSetup.margins[key] >= 0) { + (margins as any)[key] = data.pageSetup.margins[key]; + } + }); + if (Object.keys(margins).length > 0) { + pageSetup.margins = margins as any; + } + } + + if (Object.keys(pageSetup).length > 0) { + validated.pageSetup = pageSetup as any; + } + } + + // Validate behavior flags + if (data.behavior && typeof data.behavior === 'object') { + const behavior: Partial = {}; + + if (typeof data.behavior.openAfterExport === 'boolean') { + behavior.openAfterExport = data.behavior.openAfterExport; + } + + if (typeof data.behavior.preserveFolderStructure === 'boolean') { + behavior.preserveFolderStructure = data.behavior.preserveFolderStructure; + } + + if (typeof data.behavior.exportConcurrency === 'number' && + data.behavior.exportConcurrency > 0 && + data.behavior.exportConcurrency <= 10) { + behavior.exportConcurrency = data.behavior.exportConcurrency; + } + + if (Object.keys(behavior).length > 0) { + validated.behavior = behavior as any; + } + } + + // Validate executable paths + if (data.executablePaths && typeof data.executablePaths === 'object') { + const executablePaths: Partial = {}; + + if (typeof data.executablePaths.imagemagickPath === 'string') { + executablePaths.imagemagickPath = data.executablePaths.imagemagickPath; + } + + if (Array.isArray(data.executablePaths.additionalPaths)) { + // Validate each path is a string + const validPaths = data.executablePaths.additionalPaths.filter( + (path: any) => typeof path === 'string' + ); + if (validPaths.length > 0) { + executablePaths.additionalPaths = validPaths; + } + } + + if (Object.keys(executablePaths).length > 0) { + validated.executablePaths = executablePaths as any; + } + } + + return validated; + } + + /** + * Migrates settings from older versions to current format + */ + private migrateSettings(settings: obsidianTypstPDFExportSettings): obsidianTypstPDFExportSettings { + // Future version migrations can be added here + // For now, just ensure all required properties exist with defaults + + const migrated = { ...settings }; + + // Ensure all nested objects exist + if (!migrated.exportDefaults) { + migrated.exportDefaults = DEFAULT_SETTINGS.exportDefaults; + } + + if (!migrated.typography) { + migrated.typography = DEFAULT_SETTINGS.typography; + } + + if (!migrated.pageSetup) { + migrated.pageSetup = DEFAULT_SETTINGS.pageSetup; + } + + if (!migrated.behavior) { + migrated.behavior = DEFAULT_SETTINGS.behavior; + } else { + // Migrate behavior settings - add exportConcurrency if missing + if (typeof migrated.behavior.exportConcurrency !== 'number') { + migrated.behavior.exportConcurrency = DEFAULT_SETTINGS.behavior.exportConcurrency; + } + } + + if (!migrated.executablePaths) { + migrated.executablePaths = DEFAULT_SETTINGS.executablePaths; + } + + return migrated; + } + + async saveSettings() { + try { + // Validate settings before saving + const validatedSettings = this.validateSettings(this.settings); + const mergedSettings = { ...DEFAULT_SETTINGS, ...validatedSettings }; + + // Update current settings with validated data + this.settings = mergedSettings; + + // Save to disk + await this.saveData(this.settings); + + } catch (error) { + console.error('Failed to save Typst PDF Export settings:', error); + new Notice('Failed to save settings'); + throw error; + } + } + + /** + * Register all commands with proper checkCallback validation + */ + private registerCommands(): void { + // Export current note to Typst PDF + this.addCommand({ + id: 'export-current-note', + name: 'Export current note to Typst PDF', + hotkeys: [{ modifiers: ['Mod', 'Shift'], key: 'e' }], + checkCallback: (checking: boolean) => { + const activeFile = this.app.workspace.getActiveFile(); + const canRun = activeFile && activeFile.extension === 'md'; + + if (canRun && !checking) { + this.handleExportWithDependencyCheck(activeFile); + } + + return !!canRun; + } + }); + + // Export with previous settings + this.addCommand({ + id: 'export-with-previous-settings', + name: 'Export with previous settings', + hotkeys: [{ modifiers: ['Mod', 'Shift', 'Alt'], key: 'e' }], + checkCallback: (checking: boolean) => { + const activeFile = this.app.workspace.getActiveFile(); + const canRun = activeFile && activeFile.extension === 'md' && + this.settings.exportDefaults && Object.keys(this.settings.exportDefaults).length > 0; + + if (canRun && !checking) { + this.handleExportWithPreviousSettings(activeFile); + } + + return !!canRun; + } + }); + + // Export folder to PDF + this.addCommand({ + id: 'export-folder-to-pdf', + name: 'Export folder to PDF', + checkCallback: (checking: boolean) => { + const activeFile = this.app.workspace.getActiveFile(); + const canRun = activeFile && activeFile.parent; + + if (canRun && !checking && activeFile.parent) { + this.handleFolderExport(activeFile.parent); + } + + return !!canRun; + } + }); + + // Keep existing dependency check command + this.addCommand({ + id: 'check-dependencies', + name: 'Check Pandoc and Typst dependencies', + callback: () => { + this.showDependencyStatus(); + } + }); + } + + /** + * Register workspace events for context menus + */ + private registerEvents(): void { + // Register file context menu event + this.registerEvent( + this.app.workspace.on('file-menu', (menu, file, source) => { + if (file instanceof TFile && file.extension === 'md') { + menu.addItem((item) => { + item + .setTitle('Export to Typst PDF') + .setIcon('file-pdf') + .onClick(() => { + this.handleExportWithDependencyCheck(file); + }); + }); + } + + // Add folder export option for directories + if (file instanceof TFolder) { + menu.addItem((item) => { + item + .setTitle('Export folder to PDF') + .setIcon('folder-open') + .onClick(() => { + this.handleFolderExport(file); + }); + }); + } + }) + ); + + // Register files context menu for multiple file selection + this.registerEvent( + this.app.workspace.on('files-menu', (menu, files, source) => { + const markdownFiles = files.filter(f => f instanceof TFile && f.extension === 'md') as TFile[]; + + if (markdownFiles.length > 0) { + menu.addItem((item) => { + item + .setTitle(`Export ${markdownFiles.length} files to PDF`) + .setIcon('file-pdf') + .onClick(() => { + this.handleBatchExport(markdownFiles); + }); + }); + } + }) + ); + } + + /** + * Handle ribbon icon click with context menu + */ + private handleRibbonClick(event: MouseEvent): void { + const activeFile = this.app.workspace.getActiveFile(); + + if (!activeFile || activeFile.extension !== 'md') { + new Notice('Please open a markdown file to export'); + return; + } + + // Create context menu for ribbon click + const menu = new Menu(); + + menu.addItem((item) => + item + .setTitle('Export current note') + .setIcon('file-pdf') + .onClick(() => { + this.handleExportWithDependencyCheck(activeFile); + }) + ); + + if (this.settings.exportDefaults && Object.keys(this.settings.exportDefaults).length > 0) { + menu.addItem((item) => + item + .setTitle('Export with previous settings') + .setIcon('history') + .onClick(() => { + this.handleExportWithPreviousSettings(activeFile); + }) + ); + } + + if (activeFile.parent) { + menu.addSeparator(); + menu.addItem((item) => + item + .setTitle('Export folder to PDF') + .setIcon('folder-open') + .onClick(() => { + this.handleFolderExport(activeFile.parent!); + }) + ); + } + + menu.showAtMouseEvent(event); + } + + /** + * Handle export with dependency checking for a specific file + */ + private async handleExportWithDependencyCheck(file?: TFile | null): Promise { + if (!file) { + file = this.app.workspace.getActiveFile(); + } + + if (!file || file.extension !== 'md') { + new Notice('Please select a markdown file to export'); + return; + } + + const additionalPaths = this.settings.executablePaths.additionalPaths; + const result = await this.dependencyChecker.checkAllDependencies( + { customPath: this.settings.pandocPath, additionalPaths }, + { customPath: this.settings.typstPath, additionalPaths }, + { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } + ); + + if (!result.allAvailable) { + this.showDependencyErrorDialog(result); + return; + } + + // Get the current file or active file + const activeFile = file || this.app.workspace.getActiveFile(); + if (!activeFile) { + new Notice('No file selected for export.'); + return; + } + + // Open the export configuration modal + new ExportConfigModal( + this.app, + this, + activeFile.path, + async (config) => { + await this.performExport(activeFile, config); + }, + async () => { + // Modal was cancelled - no action needed + } + ).open(); + } + + /** + * Handle export with previous settings + */ + private async handleExportWithPreviousSettings(file: TFile): Promise { + const additionalPaths = this.settings.executablePaths.additionalPaths; + const result = await this.dependencyChecker.checkAllDependencies( + { customPath: this.settings.pandocPath, additionalPaths }, + { customPath: this.settings.typstPath, additionalPaths }, + { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } + ); + + if (!result.allAvailable) { + this.showDependencyErrorDialog(result); + return; + } + + // TODO: Implement direct export using previous settings without modal + new Notice('Export with previous settings will be implemented in a future version.'); + } + + /** + * Handle folder export with batch processing + */ + private async handleFolderExport(folder: TFolder): Promise { + const additionalPaths = this.settings.executablePaths.additionalPaths; + const result = await this.dependencyChecker.checkAllDependencies( + { customPath: this.settings.pandocPath, additionalPaths }, + { customPath: this.settings.typstPath, additionalPaths }, + { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } + ); + + if (!result.allAvailable) { + this.showDependencyErrorDialog(result); + return; + } + + // Get all markdown files in the folder recursively + const markdownFiles = this.getMarkdownFilesInFolder(folder); + + if (markdownFiles.length === 0) { + new Notice(`No markdown files found in folder: ${folder.name}`); + return; + } + + // Open export configuration modal for batch mode + new ExportConfigModal( + this.app, + this, + folder.path, + async (config) => { + // TODO: Implement batch export with config + await this.processBatchFiles(markdownFiles, config); + }, + async () => { + // Modal was cancelled - no action needed + } + ).open(); + } + + /** + * Handle batch export for multiple selected files + */ + private async handleBatchExport(files: TFile[]): Promise { + const additionalPaths = this.settings.executablePaths.additionalPaths; + const result = await this.dependencyChecker.checkAllDependencies( + { customPath: this.settings.pandocPath, additionalPaths }, + { customPath: this.settings.typstPath, additionalPaths }, + { customPath: this.settings.executablePaths.imagemagickPath, additionalPaths } + ); + + if (!result.allAvailable) { + this.showDependencyErrorDialog(result); + return; + } + + // Open export configuration modal for batch mode + new ExportConfigModal( + this.app, + this, + 'batch-export', + async (config) => { + // Process each file individually with the same config + for (const file of files) { + await this.performExport(file, config); + } + }, + async () => { + // Modal was cancelled - no action needed + } + ).open(); + } + + /** + * Get all markdown files in a folder recursively + */ + private getMarkdownFilesInFolder(folder: TFolder): TFile[] { + const markdownFiles: TFile[] = []; + + const traverse = (currentFolder: TFolder) => { + for (const child of currentFolder.children) { + if (child instanceof TFile && child.extension === 'md') { + markdownFiles.push(child); + } else if (child instanceof TFolder) { + traverse(child); + } + } + }; + + traverse(folder); + return markdownFiles; + } + + /** + * Simple concurrency limiter for batch operations (simplified version) + */ + private async processBatch( + items: T[], + processor: (item: T, index: number) => Promise, + concurrency: number = 3 + ): Promise<{ results: (R | Error)[]; errors: number }> { + const results: (R | Error)[] = []; + let errors = 0; + + // Simple batch processing - process items in chunks + for (let i = 0; i < items.length; i += concurrency) { + const chunk = items.slice(i, i + concurrency); + const promises = chunk.map(async (item, index) => { + try { + return await processor(item, i + index); + } catch (error) { + errors++; + return error instanceof Error ? error : new Error(String(error)); + } + }); + + const chunkResults = await Promise.all(promises); + results.push(...chunkResults); + } + + return { results, errors }; + } + + /** + * Perform export of a single file using the conversion pipeline + */ + private async performExport(file: TFile, config: ExportConfig): Promise { +try { + // Read the file content + const content = await this.app.vault.read(file); + + // Set up path utilities (used throughout function) + const path = require('path'); + const fs = require('fs'); + const vaultBasePath = (this.app.vault.adapter as any).basePath || process.cwd(); + + // Create output directory if it doesn't exist + const absoluteOutputDir = path.resolve(vaultBasePath, this.settings.outputFolder); + if (!fs.existsSync(absoluteOutputDir)) { + fs.mkdirSync(absoluteOutputDir, { recursive: true }); + } + + // Generate output filename + const baseName = file.name.replace(/\.md$/, ''); + const outputPath = path.join(absoluteOutputDir, `${baseName}.pdf`); + + console.log('Export: Output directory:', absoluteOutputDir); + console.log('Export: Output path:', outputPath); + console.log('Export: Vault base path:', vaultBasePath); + + // Create temporary file for the processed markdown + const tempDir = require('os').tmpdir(); + const tempInputFile = path.join(tempDir, `${baseName}_${Date.now()}.md`); + + // Preprocess the markdown content using MarkdownPreprocessor + const MarkdownPreprocessor = require('./src/MarkdownPreprocessor').MarkdownPreprocessor; + const preprocessor = new MarkdownPreprocessor({ + vaultPath: vaultBasePath, + options: { + includeMetadata: true, + preserveFrontmatter: false, + baseUrl: undefined + }, + wikilinkConfig: { + format: 'md', + extension: '.md' + } + }); + + const processedResult = await preprocessor.process(content); + + if (processedResult.errors.length > 0) { + console.warn('Preprocessing errors:', processedResult.errors); + } + if (processedResult.warnings.length > 0) { + console.warn('Preprocessing warnings:', processedResult.warnings); + } + + // Process PDF embeds if any were found + if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) { + console.log(`Export: Processing ${processedResult.metadata.pdfEmbeds.length} PDF embeds`); + await this.processPdfEmbeds(processedResult, vaultBasePath, tempDir, file); + } + + // Process image embeds if any were found + if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) { + console.log(`Export: Processing ${processedResult.metadata.imageEmbeds.length} image embeds`); + await this.processImageEmbeds(processedResult, vaultBasePath, tempDir, file); + } + + // Debug: Log processed content to see what image paths look like + console.log('Export: Original content length:', content.length); + console.log('Export: Processed content length:', processedResult.content.length); + + // Log a sample of processed content to see image references + const imageSample = processedResult.content.split('\n').filter((line: string) => + line.includes('![') || line.includes(' { + new Notice(`Starting batch export of ${files.length} files...`); + + const processor = async (file: TFile, index: number) => { + new Notice(`Processing file ${index + 1}/${files.length}: ${file.name}`); + await this.performExport(file, config); + return `Exported ${file.name}`; + }; + + const result = await this.processBatch(files, processor, this.settings.behavior.exportConcurrency); + + if (result.errors > 0) { + new Notice(`Batch export completed with ${result.errors} errors out of ${files.length} files.`); + } else { + new Notice(`Successfully exported ${files.length} files.`); + } + } + + /** + * Process PDF embeds by converting first page to images and creating combined output + */ + private async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise { + const { PdfToImageConverter } = require('./src/PdfToImageConverter'); + const converter = PdfToImageConverter.getInstance(this); + const path = require('path'); + const fs = require('fs'); + + console.log(`Export: Processing ${processedResult.metadata.pdfEmbeds.length} PDF embeds`); + + let updatedContent = processedResult.content; + + for (const pdfEmbed of processedResult.metadata.pdfEmbeds) { + try { + console.log(`Export: Processing PDF embed: ${pdfEmbed.originalPath}`); + + // Decode the URL-encoded sanitized path back to normal characters + const decodedPath = decodeURIComponent(pdfEmbed.sanitizedPath); + + // Try multiple path resolution strategies + const possiblePaths = [ + // Strategy 1: Relative to vault root (standard Obsidian behavior) + path.resolve(vaultBasePath, decodedPath), + // Strategy 2: Relative to current file's directory (for local attachments) + currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null + ].filter(p => p !== null); + + let fullPdfPath = null; + let validPath = null; + + // Try each possible path until we find one that exists + for (const possiblePath of possiblePaths) { + console.log(`Export: Checking path: ${possiblePath}`); + if (fs.existsSync(possiblePath)) { + fullPdfPath = possiblePath; + validPath = possiblePath; + console.log(`Export: Found PDF at: ${fullPdfPath}`); + break; + } + } + + if (!fullPdfPath) { + console.warn(`Export: PDF file not found in any of the expected locations: ${possiblePaths.join(', ')}`); + // Replace marker with fallback link + const fallbackOutput = `[⚠️ **PDF not found:** ${pdfEmbed.baseName}](${decodedPath})`; + updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); + continue; + } + + // Convert PDF first page to image + const result = await converter.convertFirstPageToImage( + fullPdfPath, + tempDir, + { + scale: 1.5, + maxWidth: 800, + maxHeight: 600, + format: 'png' + } + ); + + if (result.success) { + // Create a temporary images directory within the vault for Typst access + const vaultTempImagesDir = path.join(vaultBasePath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-images'); + const fs_promises = require('fs').promises; + await fs_promises.mkdir(vaultTempImagesDir, { recursive: true }); + + // Copy the image from temp directory to vault temp directory + const originalImageName = path.basename(result.imagePath); + const vaultImagePath = path.join(vaultTempImagesDir, originalImageName); + await fs_promises.copyFile(result.imagePath, vaultImagePath); + + // Get relative path for the generated image from vault base + const relativeImagePath = path.relative(vaultBasePath, vaultImagePath); + + // Use relative path to the original PDF from vault base for download link + const relativePdfPath = path.relative(vaultBasePath, validPath); + + // Create combined output: image preview + download link + const combinedOutput = [ + `![${pdfEmbed.baseName} - Page 1](${relativeImagePath})`, + '', + `[📎 **Download PDF:** ${pdfEmbed.baseName}](${relativePdfPath})` + ].join('\n'); + + // Replace the placeholder with the combined output + updatedContent = updatedContent.replace(pdfEmbed.marker, combinedOutput); + + console.log(`Export: Successfully processed PDF embed: ${pdfEmbed.baseName}`); + } else { + console.error(`Export: Failed to convert PDF: ${result.error}`); + // Replace with download link only + const relativePdfPath = path.relative(vaultBasePath, validPath); + const fallbackOutput = `[📎 **Download PDF:** ${pdfEmbed.baseName}](${relativePdfPath})`; + updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); + } + } catch (error) { + console.error(`Export: Error processing PDF embed ${pdfEmbed.baseName}:`, error); + // Replace with download link only as fallback + const decodedPath = decodeURIComponent(pdfEmbed.sanitizedPath); + const fallbackOutput = `[📎 **Download PDF:** ${pdfEmbed.baseName}](${decodedPath})`; + updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); + } + } + + // Update the processed result with the new content + processedResult.content = updatedContent; + } + + /** + * Process regular image embeds by copying them to vault location for Typst access + */ + private async processImageEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise { + const path = require('path'); + const fs = require('fs'); + + console.log(`Export: Processing ${processedResult.metadata.imageEmbeds.length} image embeds`); + + let updatedContent = processedResult.content; + + // Create vault temp images directory + const vaultTempImagesDir = path.join(vaultBasePath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-images'); + const fs_promises = require('fs').promises; + await fs_promises.mkdir(vaultTempImagesDir, { recursive: true }); + + for (const imageEmbed of processedResult.metadata.imageEmbeds) { + try { + console.log(`Export: Processing image embed: ${imageEmbed.originalPath}`); + + // Decode the URL-encoded sanitized path back to normal characters + const decodedPath = decodeURIComponent(imageEmbed.sanitizedPath); + + // Try multiple path resolution strategies + const possiblePaths = [ + // Strategy 1: Relative to vault root (standard Obsidian behavior) + path.resolve(vaultBasePath, decodedPath), + // Strategy 2: Direct path if it's just a filename (check vault root) + path.resolve(vaultBasePath, imageEmbed.fileName), + // Strategy 3: Relative to current file's directory (for local attachments) + currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null, + currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), imageEmbed.fileName) : null, + // Strategy 4: Check common attachment directories + path.resolve(vaultBasePath, 'attachments', imageEmbed.fileName), + path.resolve(vaultBasePath, 'assets', imageEmbed.fileName), + path.resolve(vaultBasePath, 'images', imageEmbed.fileName) + ].filter(p => p !== null); + + let fullImagePath = null; + let validPath = null; + + // Try each possible path until we find one that exists + for (const possiblePath of possiblePaths) { + console.log(`Export: Checking path: ${possiblePath}`); + if (fs.existsSync(possiblePath)) { + fullImagePath = possiblePath; + validPath = possiblePath; + console.log(`Export: Found image at: ${fullImagePath}`); + break; + } + } + + if (!fullImagePath) { + console.warn(`Export: Image file not found in any of the expected locations: ${possiblePaths.join(', ')}`); + // Replace marker with fallback link or broken image indicator + const fallbackOutput = `![⚠️ Image not found: ${imageEmbed.baseName}](${decodedPath})`; + updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput); + continue; + } + + // Copy image to vault temp directory (convert WebP to PNG if needed) + const originalImageName = path.basename(fullImagePath); + const fileExtension = path.extname(originalImageName).toLowerCase(); + + let vaultImagePath; + let finalImageName; + + if (fileExtension === '.webp') { + // Convert WebP to PNG using ImageMagick + const pngFileName = originalImageName.replace(/\.webp$/i, '.png'); + vaultImagePath = path.join(vaultTempImagesDir, pngFileName); + finalImageName = pngFileName; + + console.log(`Export: Converting WebP to PNG: ${originalImageName} -> ${pngFileName}`); + + const { exec } = require('child_process'); + const util = require('util'); + const execAsync = util.promisify(exec); + + try { + // Use configured ImageMagick path or fall back to system PATH + const convertPath = this.settings.executablePaths.imagemagickPath || 'convert'; + await execAsync(`"${convertPath}" "${fullImagePath}" "${vaultImagePath}"`); + console.log(`Export: Successfully converted WebP to PNG: ${pngFileName}`); + } catch (convertError) { + console.error(`Export: Failed to convert WebP image: ${convertError.message}`); + throw convertError; + } + } else { + // For non-WebP images, copy directly + vaultImagePath = path.join(vaultTempImagesDir, originalImageName); + finalImageName = originalImageName; + await fs_promises.copyFile(fullImagePath, vaultImagePath); + } + + // Get relative path for the copied image from vault base + const relativeImagePath = path.relative(vaultBasePath, vaultImagePath); + + // Create the appropriate markdown output based on size/alt text + let imageOutput; + if (imageEmbed.sizeOrAlt) { + // Check if it's size information (width x height pattern) + const sizeMatch = imageEmbed.sizeOrAlt.match(/^(\d+)(?:x(\d+))?$/); + if (sizeMatch) { + const width = sizeMatch[1]; + const height = sizeMatch[2]; + + // Create image with size attributes (optimized for Pandoc → Typst conversion) + if (height) { + imageOutput = `${imageEmbed.baseName}`; + } else { + imageOutput = `${imageEmbed.baseName}`; + } + } else { + // Treat as alt text + imageOutput = `![${imageEmbed.sizeOrAlt}](${relativeImagePath})`; + } + } else { + // Standard image reference + imageOutput = `![${imageEmbed.baseName}](${relativeImagePath})`; + } + + // Replace the placeholder with the image output + updatedContent = updatedContent.replace(imageEmbed.marker, imageOutput); + + console.log(`Export: Successfully processed image embed: ${imageEmbed.baseName} -> ${finalImageName}`); + } catch (error) { + console.error(`Export: Error processing image embed ${imageEmbed.baseName}:`, error); + // Replace with fallback image reference + const decodedPath = decodeURIComponent(imageEmbed.sanitizedPath); + const fallbackOutput = `![⚠️ Error loading: ${imageEmbed.baseName}](${decodedPath})`; + updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput); + } + } + + // Update the processed result with the new content + processedResult.content = updatedContent; + } +} + +/** + * Modal for displaying dependency status and installation instructions + */ +class DependencyStatusModal extends Modal { + plugin: obsidianTypstPDFExport; + + constructor(app: App, plugin: obsidianTypstPDFExport) { + super(app); + this.plugin = plugin; + } + + async onOpen() { + const { contentEl } = this; + contentEl.empty(); + + contentEl.createEl('h2', { text: 'External Dependencies Status' }); + + // Show loading indicator + const loadingEl = contentEl.createDiv(); + loadingEl.setText('Checking dependencies...'); + + try { + // Check dependencies + const additionalPaths = this.plugin.settings.executablePaths.additionalPaths; + const results = await this.plugin.dependencyChecker.checkAllDependencies( + { customPath: this.plugin.settings.pandocPath, additionalPaths }, + { customPath: this.plugin.settings.typstPath, additionalPaths }, + { customPath: this.plugin.settings.executablePaths.imagemagickPath, additionalPaths } + ); + + // Clear loading indicator + loadingEl.remove(); + + // Show overall status + const overallStatus = contentEl.createDiv({ cls: 'dependency-overall-status' }); + if (results.allAvailable) { + overallStatus.createEl('div', { + text: '✅ All dependencies are available and ready to use', + cls: 'dependency-success' + }); + } else { + overallStatus.createEl('div', { + text: '❌ Some dependencies need attention', + cls: 'dependency-error' + }); + } + + // Pandoc status + this.createDependencySection(contentEl, 'Pandoc', results.pandoc); + + // Typst status + this.createDependencySection(contentEl, 'Typst', results.typst); + + // ImageMagick status + this.createDependencySection(contentEl, 'ImageMagick', results.imagemagick); + + // Add refresh button + const buttonContainer = contentEl.createDiv({ cls: 'dependency-button-container' }); + const refreshButton = buttonContainer.createEl('button', { text: 'Refresh Status' }); + refreshButton.onclick = () => { + this.close(); + new DependencyStatusModal(this.app, this.plugin).open(); + }; + + } catch (error) { + loadingEl.remove(); + const errorEl = contentEl.createDiv({ cls: 'dependency-error' }); + errorEl.setText(`Error checking dependencies: ${error instanceof Error ? error.message : String(error)}`); + } + } + + private createDependencySection(containerEl: HTMLElement, toolName: string, result: any) { + const section = containerEl.createDiv({ cls: 'dependency-section' }); + + // Tool header + const header = section.createEl('h3', { text: toolName }); + + // Status indicator + const statusEl = section.createDiv({ cls: 'dependency-status' }); + if (result.isAvailable) { + statusEl.createEl('span', { + text: `✅ ${toolName} v${result.version} - Ready`, + cls: 'dependency-success' + }); + if (result.executablePath) { + statusEl.createEl('div', { + text: `Path: ${result.executablePath}`, + cls: 'dependency-path' + }); + } + if (result.warning) { + statusEl.createEl('div', { + text: `⚠️ ${result.warning}`, + cls: 'dependency-warning' + }); + } + } else { + statusEl.createEl('span', { + text: `❌ ${toolName} - Not Available`, + cls: 'dependency-error' + }); + if (result.error) { + statusEl.createEl('div', { + text: `Error: ${result.error}`, + cls: 'dependency-error-detail' + }); + } + + // Show installation guide + this.createInstallationGuide(section, toolName.toLowerCase() as 'pandoc' | 'typst'); + } + } + + private createInstallationGuide(containerEl: HTMLElement, toolName: 'pandoc' | 'typst') { + const guide = this.plugin.dependencyChecker.getInstallationGuide(toolName); + const platform = this.plugin.dependencyChecker.getCurrentPlatform(); + const platformInstructions = guide.instructions[platform]; + + const guideEl = containerEl.createDiv({ cls: 'dependency-install-guide' }); + guideEl.createEl('h4', { text: 'Installation Instructions' }); + + guideEl.createEl('p', { text: platformInstructions.description }); + + if (platformInstructions.commands && platformInstructions.commands.length > 0) { + const commandsEl = guideEl.createDiv(); + commandsEl.createEl('strong', { text: 'Installation commands:' }); + const commandsList = commandsEl.createEl('ul'); + platformInstructions.commands.forEach(cmd => { + const listItem = commandsList.createEl('li'); + listItem.createEl('code', { text: cmd }); + }); + } + + const linksEl = guideEl.createDiv(); + linksEl.createEl('strong', { text: 'Useful links:' }); + const linksList = linksEl.createEl('ul'); + platformInstructions.links.forEach(link => { + const listItem = linksList.createEl('li'); + const linkEl = listItem.createEl('a', { text: link, href: link }); + linkEl.setAttr('target', '_blank'); + }); + + if (guide.troubleshooting.length > 0) { + const troubleshootingEl = guideEl.createDiv(); + troubleshootingEl.createEl('strong', { text: 'Troubleshooting:' }); + const troubleshootingList = troubleshootingEl.createEl('ul'); + guide.troubleshooting.forEach(tip => { + troubleshootingList.createEl('li', { text: tip }); + }); + } + } + + onClose() { + const { contentEl } = this; + contentEl.empty(); + } +} + +class TypstPDFExportSettingTab extends PluginSettingTab { + plugin: obsidianTypstPDFExport; + + constructor(app: App, plugin: obsidianTypstPDFExport) { + super(app, plugin); + this.plugin = plugin; + } + + display(): void { + const {containerEl} = this; + + containerEl.empty(); + + // Main settings heading + new Setting(containerEl) + .setName('Typst PDF Export Settings') + .setHeading(); + + // Dependency Status Section + new Setting(containerEl) + .setName('Dependencies') + .setHeading(); + + new Setting(containerEl) + .setName('Dependency Status') + .setDesc('Check the status of external dependencies') + .addButton(button => button + .setButtonText('Check Dependencies') + .setCta() + .onClick(async () => { + // Open dependency status modal + const modal = new DependencyStatusModal(this.app, this.plugin); + modal.open(); + })); + + // External Tools Section + new Setting(containerEl) + .setName('External Tools') + .setHeading(); + + new Setting(containerEl) + .setDesc('Configure paths to external tools required for PDF export'); + + new Setting(containerEl) + .setName('Pandoc path') + .setDesc('Path to the Pandoc executable (leave empty to use system PATH)') + .addText(text => text + .setPlaceholder('/usr/local/bin/pandoc') + .setValue(this.plugin.settings.pandocPath) + .onChange(async (value) => { + this.plugin.settings.pandocPath = value; + await this.plugin.saveSettings(); + })) + .addExtraButton(button => button + .setIcon('folder-open') + .setTooltip('Browse for Pandoc executable') + .onClick(async () => { + // TODO: Implement file picker for executable selection + new Notice('File picker not yet implemented'); + })) + .addExtraButton(button => button + .setIcon('check-circle') + .setTooltip('Validate Pandoc installation') + .onClick(async () => { + // TODO: Implement path validation + new Notice('Path validation not yet implemented'); + })); + + new Setting(containerEl) + .setName('Typst path') + .setDesc('Path to the Typst executable (leave empty to use system PATH)') + .addText(text => text + .setPlaceholder('/usr/local/bin/typst') + .setValue(this.plugin.settings.typstPath) + .onChange(async (value) => { + this.plugin.settings.typstPath = value; + await this.plugin.saveSettings(); + })) + .addExtraButton(button => button + .setIcon('folder-open') + .setTooltip('Browse for Typst executable') + .onClick(async () => { + // TODO: Implement file picker for executable selection + new Notice('File picker not yet implemented'); + })) + .addExtraButton(button => button + .setIcon('check-circle') + .setTooltip('Validate Typst installation') + .onClick(async () => { + // TODO: Implement path validation + new Notice('Path validation not yet implemented'); + })); + + new Setting(containerEl) + .setName('ImageMagick Convert Path') + .setDesc('Path to ImageMagick convert executable (leave empty to use system PATH)') + .addText(text => text + .setPlaceholder('/opt/homebrew/bin/convert') + .setValue(this.plugin.settings.executablePaths.imagemagickPath) + .onChange(async (value) => { + this.plugin.settings.executablePaths.imagemagickPath = value; + await this.plugin.saveSettings(); + })) + .addExtraButton(button => button + .setIcon('folder-open') + .setTooltip('Browse for ImageMagick convert executable') + .onClick(async () => { + // TODO: Implement file picker for executable selection + new Notice('File picker not yet implemented'); + })) + .addExtraButton(button => button + .setIcon('check-circle') + .setTooltip('Validate ImageMagick installation') + .onClick(async () => { + // TODO: Implement path validation + new Notice('Path validation not yet implemented'); + })); + + new Setting(containerEl) + .setName('Additional System Paths') + .setDesc('Additional paths to search for executables (comma-separated)') + .addText(text => text + .setPlaceholder('/opt/homebrew/bin, /usr/local/bin') + .setValue(this.plugin.settings.executablePaths.additionalPaths.join(', ')) + .onChange(async (value) => { + this.plugin.settings.executablePaths.additionalPaths = value + .split(',') + .map(p => p.trim()) + .filter(p => p.length > 0); + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Output folder') + .setDesc('Default folder for exported PDF files (relative to vault root)') + .addText(text => text + .setPlaceholder('exports') + .setValue(this.plugin.settings.outputFolder) + .onChange(async (value) => { + this.plugin.settings.outputFolder = value; + await this.plugin.saveSettings(); + })) + .addExtraButton(button => button + .setIcon('folder-open') + .setTooltip('Browse for output folder') + .onClick(async () => { + // TODO: Implement folder picker + new Notice('Folder picker not yet implemented'); + })); + + // Export Defaults Section + new Setting(containerEl) + .setName('Export Defaults') + .setHeading(); + + new Setting(containerEl) + .setDesc('Default settings for PDF export operations'); + + new Setting(containerEl) + .setName('Default template') + .setDesc('Template name to use for exports') + .addText(text => text + .setPlaceholder('default') + .setValue(this.plugin.settings.exportDefaults.template) + .onChange(async (value) => { + this.plugin.settings.exportDefaults.template = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Export format') + .setDesc('Default PDF format for exports') + .addDropdown(dropdown => dropdown + .addOption(ExportFormat.Standard, 'Standard multi-page') + .addOption(ExportFormat.SinglePage, 'Single continuous page') + .setValue(this.plugin.settings.exportDefaults.format) + .onChange(async (value) => { + this.plugin.settings.exportDefaults.format = value as ExportFormat; + await this.plugin.saveSettings(); + })); + + + // Typography Section + new Setting(containerEl) + .setName('Typography') + .setHeading(); + + new Setting(containerEl) + .setDesc('Font and text formatting settings'); + + new Setting(containerEl) + .setName('Body font') + .setDesc('Font family for body text') + .addText(text => text + .setPlaceholder('Times New Roman') + .setValue(this.plugin.settings.typography.fonts.body) + .onChange(async (value) => { + this.plugin.settings.typography.fonts.body = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Heading font') + .setDesc('Font family for headings') + .addText(text => text + .setPlaceholder('Arial') + .setValue(this.plugin.settings.typography.fonts.heading) + .onChange(async (value) => { + this.plugin.settings.typography.fonts.heading = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Monospace font') + .setDesc('Font family for code blocks and inline code') + .addText(text => text + .setPlaceholder('Courier New') + .setValue(this.plugin.settings.typography.fonts.monospace) + .onChange(async (value) => { + this.plugin.settings.typography.fonts.monospace = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Body font size') + .setDesc('Font size for body text (in points)') + .addSlider(slider => slider + .setLimits(8, 24, 1) + .setValue(this.plugin.settings.typography.fontSizes.body) + .setDynamicTooltip() + .onChange(async (value) => { + this.plugin.settings.typography.fontSizes.body = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Heading font size') + .setDesc('Font size for headings (in points)') + .addSlider(slider => slider + .setLimits(12, 36, 1) + .setValue(this.plugin.settings.typography.fontSizes.heading) + .setDynamicTooltip() + .onChange(async (value) => { + this.plugin.settings.typography.fontSizes.heading = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Small font size') + .setDesc('Font size for small text like captions (in points)') + .addSlider(slider => slider + .setLimits(6, 16, 1) + .setValue(this.plugin.settings.typography.fontSizes.small) + .setDynamicTooltip() + .onChange(async (value) => { + this.plugin.settings.typography.fontSizes.small = value; + await this.plugin.saveSettings(); + })); + + // Page Setup Section + new Setting(containerEl) + .setName('Page Setup') + .setHeading(); + + new Setting(containerEl) + .setDesc('PDF page layout and formatting'); + + new Setting(containerEl) + .setName('Page size') + .setDesc('Paper size for PDF output') + .addDropdown(dropdown => dropdown + .addOption('a4', 'A4') + .addOption('letter', 'US Letter') + .addOption('a3', 'A3') + .addOption('a5', 'A5') + .addOption('legal', 'US Legal') + .setValue(this.plugin.settings.pageSetup.size) + .onChange(async (value) => { + this.plugin.settings.pageSetup.size = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Orientation') + .setDesc('Page orientation') + .addDropdown(dropdown => dropdown + .addOption('portrait', 'Portrait') + .addOption('landscape', 'Landscape') + .setValue(this.plugin.settings.pageSetup.orientation) + .onChange(async (value) => { + this.plugin.settings.pageSetup.orientation = value as 'portrait' | 'landscape'; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Top margin') + .setDesc('Top page margin (in points)') + .addSlider(slider => slider + .setLimits(18, 144, 6) + .setValue(this.plugin.settings.pageSetup.margins.top) + .setDynamicTooltip() + .onChange(async (value) => { + this.plugin.settings.pageSetup.margins.top = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Right margin') + .setDesc('Right page margin (in points)') + .addSlider(slider => slider + .setLimits(18, 144, 6) + .setValue(this.plugin.settings.pageSetup.margins.right) + .setDynamicTooltip() + .onChange(async (value) => { + this.plugin.settings.pageSetup.margins.right = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Bottom margin') + .setDesc('Bottom page margin (in points)') + .addSlider(slider => slider + .setLimits(18, 144, 6) + .setValue(this.plugin.settings.pageSetup.margins.bottom) + .setDynamicTooltip() + .onChange(async (value) => { + this.plugin.settings.pageSetup.margins.bottom = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Left margin') + .setDesc('Left page margin (in points)') + .addSlider(slider => slider + .setLimits(18, 144, 6) + .setValue(this.plugin.settings.pageSetup.margins.left) + .setDynamicTooltip() + .onChange(async (value) => { + this.plugin.settings.pageSetup.margins.left = value; + await this.plugin.saveSettings(); + })); + + // Advanced Options Section + new Setting(containerEl) + .setName('Advanced Options') + .setHeading(); + + new Setting(containerEl) + .setDesc('Advanced plugin behavior and performance settings'); + + new Setting(containerEl) + .setName('Open PDF after export') + .setDesc('Automatically open the exported PDF file') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.behavior.openAfterExport) + .onChange(async (value) => { + this.plugin.settings.behavior.openAfterExport = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Preserve folder structure') + .setDesc('Maintain the original folder structure in the output directory') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.behavior.preserveFolderStructure) + .onChange(async (value) => { + this.plugin.settings.behavior.preserveFolderStructure = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Export concurrency') + .setDesc('Number of files to export simultaneously during batch operations (1-10)') + .addSlider(slider => slider + .setLimits(1, 10, 1) + .setValue(this.plugin.settings.behavior.exportConcurrency) + .setDynamicTooltip() + .onChange(async (value) => { + this.plugin.settings.behavior.exportConcurrency = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Debug mode') + .setDesc('Enable verbose logging for troubleshooting export issues') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.behavior.debugMode || false) + .onChange(async (value) => { + this.plugin.settings.behavior.debugMode = value; + await this.plugin.saveSettings(); + })); + + // Template Management Section + new Setting(containerEl) + .setName('Template Management') + .setHeading(); + + new Setting(containerEl) + .setDesc('Manage custom Typst templates for document styling'); + + new Setting(containerEl) + .setName('Import template') + .setDesc('Import a custom Typst template file (.typ)') + .addButton(button => button + .setButtonText('Import Template') + .setIcon('file-plus') + .onClick(async () => { + // TODO: Implement template import functionality + new Notice('Template import not yet implemented'); + })); + + new Setting(containerEl) + .setName('Export templates') + .setDesc('Export current templates for sharing or backup') + .addButton(button => button + .setButtonText('Export Templates') + .setIcon('download') + .onClick(async () => { + // TODO: Implement template export functionality + new Notice('Template export not yet implemented'); + })); + + new Setting(containerEl) + .setName('Reset to defaults') + .setDesc('Reset all settings to their default values') + .addButton(button => button + .setButtonText('Reset Settings') + .setWarning() + .onClick(async () => { + // TODO: Implement settings reset with confirmation + new Notice('Settings reset not yet implemented'); + })); + } +} + +/** + * Configuration interface for export modal settings + * Combines user preferences with runtime state for export operations + */ +interface ExportConfigModalSettings extends ExportConfig { + /** Note being exported */ + notePath: string; + /** Note title for display */ + noteTitle: string; + /** 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 Configuration Modal + * Provides intuitive interface for configuring PDF export options + * with real-time preview and validation + */ +export class ExportConfigModal extends Modal { + private settings: ExportConfigModalSettings; + private plugin: obsidianTypstPDFExport; + private onSubmit: (config: ExportConfig) => Promise; + private onCancel?: () => void; + + // UI Elements + private contentContainer: HTMLElement; + private formContainer: HTMLElement; + private previewContainer: HTMLElement; + private progressContainer: HTMLElement; + private progressBar: HTMLElement | null = null; + private progressText: HTMLElement | null = null; + private cancelButton: HTMLButtonElement | null = null; + + constructor( + app: App, + plugin: obsidianTypstPDFExport, + notePath: string, + onSubmit: (config: ExportConfig) => Promise, + onCancel?: () => void + ) { + super(app); + this.plugin = plugin; + this.onSubmit = onSubmit; + this.onCancel = onCancel; + + // Initialize settings from plugin defaults and note context + const noteTitle = this.getNoteTitleFromPath(notePath); + this.settings = { + notePath, + noteTitle, + template: plugin.settings.exportDefaults.template, + format: plugin.settings.exportDefaults.format, + outputFolder: plugin.settings.outputFolder, + templateVariables: {}, + availableTemplates: [], // Will be populated by TemplateManager + isExporting: false, + progressPercent: 0, + currentOperation: '', + canCancel: false + }; + } + + /** + * Initialize modal when opened + */ + /** + * Initialize modal when opened + */ + /** + * Initialize modal when opened + */ + onOpen(): void { + this.addModalStyles(); + + // Set modal dimensions to match Obsidian Settings window + if (this.modalEl) { + this.modalEl.style.width = '1100px'; + this.modalEl.style.height = '750px'; + this.modalEl.style.maxWidth = '90vw'; + this.modalEl.style.maxHeight = '90vh'; + } + + this.setTitle(`Export "${this.settings.noteTitle}" to PDF`); + + // Load templates FIRST, then generate form and load previous config + this.loadAvailableTemplates().then(() => { + this.generateForm(); + this.loadPreviousConfig(); + }); + } + + /** + * Cleanup when modal is closed + */ + onClose(): void { + if (this.onCancel && this.settings.isExporting) { + this.onCancel(); + } + } + + /** + * Extract note title from file path for display + */ + private getNoteTitleFromPath(path: string): string { + const fileName = path.split('/').pop() || path; + return fileName.replace(/\.md$/, ''); + } + + /** + * Load available templates from TemplateManager + * This will be implemented when TemplateManager is available + */ + private async loadAvailableTemplates(): Promise { + // Load available templates from TemplateManager via plugin + console.log('Modal: Loading available templates...'); + console.log('TemplateManager exists:', !!this.plugin.templateManager); + + if (this.plugin.templateManager) { + this.settings.availableTemplates = await this.plugin.templateManager.getAvailableTemplates(); + console.log('Templates loaded from TemplateManager:', this.settings.availableTemplates); + } else { + // Fallback to hardcoded defaults if TemplateManager not initialized + console.log('Using fallback templates'); + this.settings.availableTemplates = [ + 'default.typ', + 'article.typ', + 'report.typ', + 'modern.typ' + ]; + } + + // Update template dropdown if already rendered + this.updateTemplateDropdown(); + } + + /** + * Update template dropdown options + * Called after templates are loaded + */ + private updateTemplateDropdown(): void { + console.log('updateTemplateDropdown called'); + console.log('templateDropdown exists:', !!this.templateDropdown); + console.log('Available templates:', this.settings.availableTemplates); + + if (!this.templateDropdown) { + console.log('templateDropdown not yet created'); + return; + } + + // Clear existing options + this.templateDropdown.selectEl.empty(); + + // Add available templates + this.settings.availableTemplates.forEach(template => { + const displayName = this.getTemplateDisplayName(template); + console.log(`Adding template option: ${template} -> ${displayName}`); + this.templateDropdown.addOption(template, displayName); + }); + + // Set current value or default with proper extension + const currentValue = this.settings.template || 'default.typ'; + this.templateDropdown.setValue(currentValue); +} + + /** + * Generate the main form UI + * Placeholder for Task 7.2 + */ + /** + * Generate the main form UI + * Creates comprehensive form with all export configuration options + */ + private generateForm(): void { + const { contentEl } = this; + contentEl.empty(); + + // Create main container with responsive layout + this.contentContainer = contentEl.createDiv('export-config-container'); + this.contentContainer.style.display = 'flex'; + this.contentContainer.style.gap = '20px'; + this.contentContainer.style.minHeight = '400px'; + + // Form container (left side) - CREATE FIRST, then set styles + this.formContainer = this.contentContainer.createDiv('export-config-form'); + this.formContainer.style.flex = '1'; + this.formContainer.style.minWidth = '400px'; + + // Preview container (right side) + this.previewContainer = this.contentContainer.createDiv('export-config-preview'); + this.previewContainer.style.flex = '1'; + this.previewContainer.style.maxWidth = '300px'; + this.previewContainer.style.border = '1px solid var(--background-modifier-border)'; + this.previewContainer.style.borderRadius = '8px'; + this.previewContainer.style.padding = '16px'; + + // Progress container (initially hidden) + this.progressContainer = this.contentContainer.createDiv('export-progress'); + this.progressContainer.style.display = 'none'; + + // Generate form sections + this.createFormatSection(); + this.createTemplateSection(); + this.createOutputSection(); + this.createPageConfigSection(); + this.createTypographySection(); + this.createActionButtons(); + + // Initialize preview + this.createPreviewSection(); + this.updatePreview(); + } + + + /** + * Create format selection section + */ + private createFormatSection(): void { + const section = this.formContainer.createDiv('export-section'); + section.createEl('h3', { text: 'Format Options' }); + + new Setting(section) + .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(this.settings.format || ExportFormat.Standard) + .onChange(value => { + this.settings.format = value as ExportFormat; + this.updatePreview(); + }); + }); + } + + /** + * Create template selection section + */ + private createTemplateSection(): void { + const section = this.formContainer.createDiv('export-section'); + section.createEl('h3', { text: 'Template' }); + + new Setting(section) + .setName('Typst template') + .setDesc('Select template for document styling') + .addDropdown(dropdown => { + // Initially populate with available templates + this.settings.availableTemplates.forEach(template => { + dropdown.addOption(template, this.getTemplateDisplayName(template)); + }); + + // Set default value with proper extension + const defaultTemplate = this.settings.template || 'default.typ'; + dropdown + .setValue(defaultTemplate) + .onChange(value => { + this.settings.template = value; + this.updatePreview(); + }); + + // Store reference for updates + this.templateDropdown = dropdown; + }); + + // Template variables section + this.createTemplateVariablesSection(section); +} + + /** + * Create template variables section + */ + private createTemplateVariablesSection(parentSection: HTMLElement): void { + const variablesContainer = parentSection.createDiv('template-variables'); + + // Title field + new Setting(variablesContainer) + .setName('Document title') + .setDesc('Override document title (uses note title by default)') + .addText(text => { + text + .setPlaceholder(this.settings.noteTitle) + .setValue(this.settings.templateVariables?.title || '') + .onChange(value => { + this.settings.templateVariables = this.settings.templateVariables || {}; + this.settings.templateVariables.title = value || this.settings.noteTitle; + this.updatePreview(); + }); + }); + + // Author field + new Setting(variablesContainer) + .setName('Author') + .setDesc('Document author name') + .addText(text => { + text + .setPlaceholder('Your name') + .setValue(this.settings.templateVariables?.author || '') + .onChange(value => { + this.settings.templateVariables = this.settings.templateVariables || {}; + this.settings.templateVariables.author = value; + this.updatePreview(); + }); + }); + + // Date field + new Setting(variablesContainer) + .setName('Date') + .setDesc('Document date (leave blank for current date)') + .addText(text => { + text + .setPlaceholder(new Date().toLocaleDateString()) + .setValue(this.settings.templateVariables?.date || '') + .onChange(value => { + this.settings.templateVariables = this.settings.templateVariables || {}; + this.settings.templateVariables.date = value || new Date().toLocaleDateString(); + this.updatePreview(); + }); + }); + } + + /** + * Create output settings section + */ + private createOutputSection(): void { + const section = this.formContainer.createDiv('export-section'); + section.createEl('h3', { text: 'Output Settings' }); + + // Output folder + new Setting(section) + .setName('Output folder') + .setDesc('Folder where the PDF will be saved') + .addText(text => { + text + .setPlaceholder(this.plugin.settings.outputFolder) + .setValue(this.settings.outputFolder || '') + .onChange(value => { + this.settings.outputFolder = value || this.plugin.settings.outputFolder; + this.updatePreview(); + }); + }); + + // Filename pattern (advanced) + const filenamePattern = this.settings.templateVariables?.filenamePattern || '{title}'; + new Setting(section) + .setName('Filename pattern') + .setDesc('Pattern for generated filename. Use {title}, {date}, {author}') + .addText(text => { + text + .setPlaceholder('{title}') + .setValue(filenamePattern) + .onChange(value => { + this.settings.templateVariables = this.settings.templateVariables || {}; + this.settings.templateVariables.filenamePattern = value || '{title}'; + this.updatePreview(); + }); + }); + } + + /** + * Create page configuration section + */ + private createPageConfigSection(): void { + const section = this.formContainer.createDiv('export-section'); + section.createEl('h3', { text: 'Page Setup' }); + + // Page size + new Setting(section) + .setName('Page size') + .setDesc('Standard page sizes or custom dimensions') + .addDropdown(dropdown => { + dropdown + .addOption('a4', 'A4 (210 × 297 mm)') + .addOption('letter', 'Letter (8.5 × 11 in)') + .addOption('legal', 'Legal (8.5 × 14 in)') + .addOption('a3', 'A3 (297 × 420 mm)') + .addOption('custom', 'Custom size') + .setValue(this.plugin.settings.pageSetup.size) + .onChange(value => { + // Note: This updates plugin defaults, not per-export settings + // TODO: Consider adding per-export page settings to ExportConfig + this.updatePreview(); + }); + }); + + // Orientation + new Setting(section) + .setName('Orientation') + .setDesc('Page orientation') + .addDropdown(dropdown => { + dropdown + .addOption('portrait', 'Portrait') + .addOption('landscape', 'Landscape') + .setValue(this.plugin.settings.pageSetup.orientation) + .onChange(value => { + // Note: This updates plugin defaults + this.updatePreview(); + }); + }); + + // Margins + this.createMarginsSection(section); + } + + /** + * Create margins configuration subsection + */ + private createMarginsSection(parentSection: HTMLElement): void { + const marginsContainer = parentSection.createDiv('margins-container'); + marginsContainer.createEl('h4', { text: 'Margins (in points)' }); + + const margins = this.plugin.settings.pageSetup.margins; + + // Top margin + new Setting(marginsContainer) + .setName('Top') + .addSlider(slider => { + slider + .setLimits(36, 144, 6) // 0.5" to 2" in 6pt increments + .setValue(margins.top) + .setDynamicTooltip() + .onChange(value => { + this.updatePreview(); + }); + }); + + // Bottom margin + new Setting(marginsContainer) + .setName('Bottom') + .addSlider(slider => { + slider + .setLimits(36, 144, 6) + .setValue(margins.bottom) + .setDynamicTooltip() + .onChange(value => { + this.updatePreview(); + }); + }); + + // Left margin + new Setting(marginsContainer) + .setName('Left') + .addSlider(slider => { + slider + .setLimits(36, 144, 6) + .setValue(margins.left) + .setDynamicTooltip() + .onChange(value => { + this.updatePreview(); + }); + }); + + // Right margin + new Setting(marginsContainer) + .setName('Right') + .addSlider(slider => { + slider + .setLimits(36, 144, 6) + .setValue(margins.right) + .setDynamicTooltip() + .onChange(value => { + this.updatePreview(); + }); + }); + } + + /** + * Create typography settings section + */ + private createTypographySection(): void { + const section = this.formContainer.createDiv('export-section'); + section.createEl('h3', { text: 'Typography' }); + + const fonts = this.plugin.settings.typography.fonts; + const fontSizes = this.plugin.settings.typography.fontSizes; + + // Body font + new Setting(section) + .setName('Body font') + .setDesc('Primary font for document text') + .addText(text => { + text + .setPlaceholder('System default') + .setValue(fonts.body) + .onChange(value => { + this.updatePreview(); + }); + }); + + // Heading font + new Setting(section) + .setName('Heading font') + .setDesc('Font for headings and titles') + .addText(text => { + text + .setPlaceholder('System default') + .setValue(fonts.heading) + .onChange(value => { + this.updatePreview(); + }); + }); + + // Monospace font + new Setting(section) + .setName('Code font') + .setDesc('Monospace font for code blocks') + .addText(text => { + text + .setPlaceholder('System default') + .setValue(fonts.monospace) + .onChange(value => { + this.updatePreview(); + }); + }); + + // Font sizes + this.createFontSizesSection(section, fontSizes); + } + + /** + * Create font sizes subsection + */ + private createFontSizesSection(parentSection: HTMLElement, fontSizes: any): void { + const sizesContainer = parentSection.createDiv('font-sizes'); + sizesContainer.createEl('h4', { text: 'Font Sizes (in points)' }); + + // Body size + new Setting(sizesContainer) + .setName('Body text') + .addSlider(slider => { + slider + .setLimits(8, 16, 0.5) + .setValue(fontSizes.body) + .setDynamicTooltip() + .onChange(value => { + this.updatePreview(); + }); + }); + + // Heading size + new Setting(sizesContainer) + .setName('Headings') + .addSlider(slider => { + slider + .setLimits(12, 24, 0.5) + .setValue(fontSizes.heading) + .setDynamicTooltip() + .onChange(value => { + this.updatePreview(); + }); + }); + + // Small text size + new Setting(sizesContainer) + .setName('Small text') + .addSlider(slider => { + slider + .setLimits(6, 12, 0.5) + .setValue(fontSizes.small) + .setDynamicTooltip() + .onChange(value => { + this.updatePreview(); + }); + }); + } + + /** + * Create action buttons section + */ + private createActionButtons(): void { + const buttonsContainer = this.formContainer.createDiv('export-actions'); + buttonsContainer.style.marginTop = '20px'; + buttonsContainer.style.paddingTop = '20px'; + buttonsContainer.style.borderTop = '1px solid var(--background-modifier-border)'; + + new Setting(buttonsContainer) + .addButton(btn => { + btn + .setButtonText('Export PDF') + .setCta() + .onClick(() => this.submitExport()); + }) + .addButton(btn => { + btn + .setButtonText('Cancel') + .onClick(() => this.close()); + }); + } + + /** + * Create preview section + */ + private createPreviewSection(): void { + this.previewContainer.createEl('h3', { text: 'Preview' }); + + // Export summary + const summaryContainer = this.previewContainer.createDiv('export-summary'); + + // Document info + const docInfo = summaryContainer.createDiv('doc-info'); + docInfo.createEl('h4', { text: 'Document' }); + docInfo.createEl('p', { text: `Note: ${this.settings.noteTitle}` }); + + // Configuration preview + const configInfo = summaryContainer.createDiv('config-info'); + configInfo.createEl('h4', { text: 'Configuration' }); + + // This will be populated by updatePreview() + this.configPreview = configInfo.createDiv('config-details'); + + // Output info + const outputInfo = summaryContainer.createDiv('output-info'); + outputInfo.createEl('h4', { text: 'Output' }); + + // This will be populated by updatePreview() + this.outputPreview = outputInfo.createDiv('output-details'); + } + + /** + * Get display name for template + */ + private getTemplateDisplayName(template: string): string { + // Remove .typ extension for display name mapping + const templateKey = template.replace('.typ', ''); + + const displayNames: Record = { + 'default': 'Default', + 'article': 'Article', + 'report': 'Report', + 'modern': 'Modern' + }; + + return displayNames[templateKey] || templateKey.charAt(0).toUpperCase() + templateKey.slice(1); +} + + // Properties to store UI element references + private templateDropdown?: any; + private configPreview?: HTMLElement; + private outputPreview?: HTMLElement; + + /** + * Update preview based on current settings + * Placeholder for Task 7.3 + */ + /** + * Update preview based on current settings + * Shows configuration summary and output preview + */ + private updatePreview(): void { + if (!this.configPreview || !this.outputPreview) { + return; // Preview not yet initialized + } + + // Clear existing content + this.configPreview.empty(); + this.outputPreview.empty(); + + // Configuration summary + const configItems = this.configPreview.createDiv('config-items'); + + configItems.createDiv('config-item').innerHTML = + `Format: ${this.settings.format === ExportFormat.Standard ? 'Standard PDF' : 'Single-page PDF'}`; + + configItems.createDiv('config-item').innerHTML = + `Template: ${this.getTemplateDisplayName(this.settings.template || 'default')}`; + + // Template variables preview + if (this.settings.templateVariables) { + const vars = this.settings.templateVariables; + if (vars.title || vars.author || vars.date) { + const varsDiv = configItems.createDiv('config-item'); + varsDiv.innerHTML = 'Variables:'; + const varsList = varsDiv.createDiv('variables-list'); + + if (vars.title) varsList.createDiv('var-item').innerHTML = `Title: ${vars.title}`; + if (vars.author) varsList.createDiv('var-item').innerHTML = `Author: ${vars.author}`; + if (vars.date) varsList.createDiv('var-item').innerHTML = `Date: ${vars.date}`; + } + } + + // Output preview + const outputItems = this.outputPreview.createDiv('output-items'); + + // Output folder + const outputFolder = this.settings.outputFolder || this.plugin.settings.outputFolder; + outputItems.createDiv('output-item').innerHTML = + `Folder: ${outputFolder}`; + + // Filename preview + const filename = this.generatePreviewFilename(); + outputItems.createDiv('output-item').innerHTML = + `Filename: ${filename}.pdf`; + + // File size estimate (placeholder) + outputItems.createDiv('output-item').innerHTML = + `Est. size: ~${this.estimateFileSize()} KB`; + } + + /** + * Generate preview filename based on current settings + */ + private generatePreviewFilename(): string { + const pattern = this.settings.templateVariables?.filenamePattern || '{title}'; + const title = this.settings.templateVariables?.title || this.settings.noteTitle; + const author = this.settings.templateVariables?.author || ''; + const date = this.settings.templateVariables?.date || new Date().toLocaleDateString(); + + return pattern + .replace('{title}', title) + .replace('{author}', author) + .replace('{date}', date) + .replace(/[<>:"/\\|?*]/g, '_'); // Replace invalid filename characters + } + + /** + * Estimate output file size based on content and settings + */ + private estimateFileSize(): number { + // Simple estimation based on mode and format + // In a real implementation, this could analyze content length + let baseSize = 150; // Base size in KB + + if (this.settings.format === ExportFormat.SinglePage) { + baseSize *= 1.2; // Single-page format may be larger + } + + return Math.round(baseSize); + } + + /** + * Validate current settings + * Placeholder for Task 7.3 + */ + /** + * Validate current settings and show visual feedback + * Returns true if settings are valid for export + */ + private validateSettings(): boolean { + let isValid = true; + const errors: string[] = []; + + // Clear previous validation styling + this.clearValidationErrors(); + + // Validate template selection + if (!this.settings.template || this.settings.template.trim() === '') { + errors.push('Template selection is required'); + this.showFieldError('template', 'Please select a template'); + isValid = false; + } else if (!this.settings.availableTemplates.includes(this.settings.template)) { + errors.push('Selected template is not available'); + this.showFieldError('template', 'Template not found'); + isValid = false; + } + + // Validate output folder + const outputFolder = this.settings.outputFolder?.trim(); + if (!outputFolder) { + errors.push('Output folder is required'); + this.showFieldError('outputFolder', 'Please specify an output folder'); + isValid = false; + } else if (outputFolder.includes('<') || outputFolder.includes('>')) { + errors.push('Output folder path contains invalid characters'); + this.showFieldError('outputFolder', 'Invalid characters in path'); + isValid = false; + } + + // Validate filename pattern + const filenamePattern = this.settings.templateVariables?.filenamePattern; + if (filenamePattern && !filenamePattern.includes('{title}') && !filenamePattern.includes('{author}') && !filenamePattern.includes('{date}')) { + errors.push('Filename pattern should include at least one variable'); + this.showFieldError('filenamePattern', 'Include {title}, {author}, or {date}'); + // This is a warning, not a blocking error + } + + // Validate template variables + if (this.settings.templateVariables) { + const title = this.settings.templateVariables.title?.trim(); + if (title && title.length > 100) { + errors.push('Document title is too long'); + this.showFieldError('title', 'Maximum 100 characters'); + isValid = false; + } + + const author = this.settings.templateVariables.author?.trim(); + if (author && author.length > 50) { + errors.push('Author name is too long'); + this.showFieldError('author', 'Maximum 50 characters'); + isValid = false; + } + + // Validate date format if provided + const date = this.settings.templateVariables.date?.trim(); + if (date && date !== '' && isNaN(Date.parse(date))) { + errors.push('Invalid date format'); + this.showFieldError('date', 'Please use a valid date format'); + isValid = false; + } + } + + // Show validation summary + this.showValidationSummary(isValid, errors); + + return isValid; + } + + /** + * Clear all validation error styling + */ + private clearValidationErrors(): void { + // Remove error classes from all form elements + const errorElements = this.formContainer.querySelectorAll('.setting-item-control.error'); + errorElements.forEach(el => { + el.removeClass('error'); + // Remove error message if it exists + const errorMsg = el.querySelector('.validation-error'); + if (errorMsg) { + errorMsg.remove(); + } + }); + + // Clear validation summary + const existingSummary = this.formContainer.querySelector('.validation-summary'); + if (existingSummary) { + existingSummary.remove(); + } + } + + /** + * Show validation error for specific field + */ + private showFieldError(fieldName: string, message: string): void { + // Find the setting control element for this field + let targetElement: HTMLElement | null = null; + + // Map field names to their setting elements + const fieldSelectors: Record = { + 'template': '[data-field="template"]', + 'outputFolder': '[data-field="outputFolder"]', + 'filenamePattern': '[data-field="filenamePattern"]', + 'title': '[data-field="title"]', + 'author': '[data-field="author"]', + 'date': '[data-field="date"]' + }; + + // Since we don't have data attributes yet, use a simpler approach + // Find setting by content or use order-based selection + const settings = this.formContainer.querySelectorAll('.setting-item-control'); + + // For now, add error styling to the relevant input + // This would be improved with proper field identification + if (settings.length > 0) { + // Add generic error styling to help user identify issues + const errorContainer = this.formContainer.createDiv('field-error'); + errorContainer.style.color = 'var(--text-error)'; + errorContainer.style.fontSize = '0.9em'; + errorContainer.style.marginTop = '4px'; + errorContainer.textContent = `${fieldName}: ${message}`; + } + } + + /** + * Show validation summary with all errors + */ + private showValidationSummary(isValid: boolean, errors: string[]): void { + // Remove existing summary + const existingSummary = this.formContainer.querySelector('.validation-summary'); + if (existingSummary) { + existingSummary.remove(); + } + + if (!isValid && errors.length > 0) { + const summaryContainer = this.formContainer.createDiv('validation-summary'); + summaryContainer.style.backgroundColor = 'var(--background-modifier-error)'; + summaryContainer.style.border = '1px solid var(--background-modifier-error-border)'; + summaryContainer.style.borderRadius = '4px'; + summaryContainer.style.padding = '12px'; + summaryContainer.style.marginTop = '16px'; + + const title = summaryContainer.createEl('h4', { + text: 'Please fix the following issues:', + attr: { style: 'color: var(--text-error); margin: 0 0 8px 0;' } + }); + + const errorsList = summaryContainer.createEl('ul', { + attr: { style: 'margin: 0; padding-left: 20px; color: var(--text-error);' } + }); + + errors.forEach(error => { + errorsList.createEl('li', { text: error }); + }); + } else if (isValid) { + // Show success state + const successContainer = this.formContainer.createDiv('validation-summary'); + successContainer.style.backgroundColor = 'var(--background-modifier-success)'; + successContainer.style.border = '1px solid var(--background-modifier-success-border)'; + successContainer.style.borderRadius = '4px'; + successContainer.style.padding = '8px 12px'; + successContainer.style.marginTop = '16px'; + + successContainer.createEl('span', { + text: '✓ Configuration is valid and ready for export', + attr: { style: 'color: var(--text-success);' } + }); + + // Auto-hide success message after 3 seconds + setTimeout(() => { + if (successContainer.parentNode) { + successContainer.remove(); + } + }, 3000); + } + } + + /** + * Debounced validation trigger + * Prevents excessive validation calls during rapid input changes + */ + private debouncedValidation: (() => void) | null = null; + + /** + * Trigger validation with debouncing + */ + private triggerValidation(): void { + if (this.debouncedValidation) { + clearTimeout(this.debouncedValidation as any); + } + + this.debouncedValidation = setTimeout(() => { + this.validateSettings(); + this.updatePreview(); + }, 300) as any; + } + + /** + * Save current settings to plugin configuration + * Placeholder for Task 7.4 + */ + /** + * Save current export settings to plugin configuration + * Persists user preferences for future exports + */ + private async saveSettings(): Promise { + try { + // Update plugin's export defaults with current settings + if (this.settings.template) { + this.plugin.settings.exportDefaults.template = this.settings.template; + } + + if (this.settings.format) { + this.plugin.settings.exportDefaults.format = this.settings.format; + } + + + // Update output folder preference + if (this.settings.outputFolder && this.settings.outputFolder !== this.plugin.settings.outputFolder) { + this.plugin.settings.outputFolder = this.settings.outputFolder; + } + + // Save recent export configurations to plugin settings + const recentConfigs = this.plugin.settings as any; + if (!recentConfigs.recentExportConfigs) { + recentConfigs.recentExportConfigs = []; + } + + // Create a recent config entry + const recentConfig = { + timestamp: Date.now(), + notePath: this.settings.notePath, + noteTitle: this.settings.noteTitle, + config: { + template: this.settings.template, + format: this.settings.format, + outputFolder: this.settings.outputFolder, + templateVariables: { ...this.settings.templateVariables } + } + }; + + // Add to recent configs (keep only last 10) + recentConfigs.recentExportConfigs.unshift(recentConfig); + if (recentConfigs.recentExportConfigs.length > 10) { + recentConfigs.recentExportConfigs = recentConfigs.recentExportConfigs.slice(0, 10); + } + + // Persist to disk + await this.plugin.saveSettings(); + + } catch (error) { + console.error('Failed to save export settings:', error); + // Don't block export on settings save failure + } + } + + /** + * Load previous export configuration for this note + * Restores settings from the most recent export of the same note + */ + private loadPreviousConfig(): void { + const recentConfigs = (this.plugin.settings as any).recentExportConfigs; + if (!recentConfigs || !Array.isArray(recentConfigs)) { + return; + } + + // Find most recent config for this specific note + const previousConfig = recentConfigs.find((config: any) => + config.notePath === this.settings.notePath + ); + + if (previousConfig && previousConfig.config) { + const config = previousConfig.config; + + // Restore configuration + if (config.template && this.settings.availableTemplates.includes(config.template)) { + this.settings.template = config.template; + } + + if (config.format) { + this.settings.format = config.format; + } + + + if (config.outputFolder) { + this.settings.outputFolder = config.outputFolder; + } + + if (config.templateVariables) { + this.settings.templateVariables = { ...config.templateVariables }; + } + + // Update form UI to reflect restored settings + this.updateFormFromSettings(); + } + } + + /** + * Get recent export configurations for quick access + */ + private getRecentConfigs(): any[] { + const recentConfigs = (this.plugin.settings as any).recentExportConfigs; + return recentConfigs && Array.isArray(recentConfigs) ? recentConfigs : []; + } + + /** + * Update form controls to match current settings + * Called after loading previous configuration + */ + private updateFormFromSettings(): void { + // Update template dropdown + if (this.templateDropdown && this.settings.template) { + this.templateDropdown.setValue(this.settings.template); + } + + // Update other form controls + // This would need to be enhanced with references to all form controls + // For now, trigger a complete form regeneration + setTimeout(() => { + this.updatePreview(); + }, 100); + } + + /** + * Reset settings to plugin defaults + */ + private resetToDefaults(): void { + const defaults = this.plugin.settings.exportDefaults; + + this.settings.template = defaults.template; + this.settings.format = defaults.format; + this.settings.outputFolder = this.plugin.settings.outputFolder; + this.settings.templateVariables = { + title: this.settings.noteTitle, + author: '', + date: new Date().toLocaleDateString(), + filenamePattern: '{title}' + }; + + // Update form UI + this.updateFormFromSettings(); + } + + /** + * Export current configuration as JSON for sharing or backup + */ + private exportConfiguration(): string { + const exportData = { + version: '1.0', + template: this.settings.template, + format: this.settings.format, + templateVariables: this.settings.templateVariables, + // Don't include outputFolder (local path) or notePath (specific to this instance) + }; + + return JSON.stringify(exportData, null, 2); + } + + /** + * Import configuration from JSON + */ + private importConfiguration(jsonData: string): boolean { + try { + const importData = JSON.parse(jsonData); + + // Validate imported data + if (!importData.version) { + throw new Error('Invalid configuration format'); + } + + // Apply imported settings + if (importData.template && this.settings.availableTemplates.includes(importData.template)) { + this.settings.template = importData.template; + } + + if (importData.format && Object.values(ExportFormat).includes(importData.format)) { + this.settings.format = importData.format; + } + + + if (importData.templateVariables) { + this.settings.templateVariables = { + ...this.settings.templateVariables, + ...importData.templateVariables + }; + } + + // Update form UI + this.updateFormFromSettings(); + return true; + + } catch (error) { + console.error('Failed to import configuration:', error); + return false; + } + } + + /** + * Start export progress tracking + * Placeholder for Task 7.5 + */ + /** + * Start export progress tracking + * Shows progress overlay and hides main form + */ + private showProgress(): void { + // Hide form and show progress + this.formContainer.style.display = 'none'; + this.previewContainer.style.display = 'none'; + this.progressContainer.style.display = 'block'; + + // Clear and setup progress container + this.progressContainer.empty(); + + // Progress header + const header = this.progressContainer.createDiv('progress-header'); + header.style.textAlign = 'center'; + header.style.marginBottom = '20px'; + + const title = header.createEl('h3', { text: 'Exporting PDF...' }); + const subtitle = header.createEl('p', { + text: `Exporting "${this.settings.noteTitle}"`, + attr: { style: 'color: var(--text-muted); margin: 8px 0;' } + }); + + // Progress indicator container + const progressIndicator = this.progressContainer.createDiv('progress-indicator'); + progressIndicator.style.marginBottom = '20px'; + + // Progress bar + const progressWrapper = progressIndicator.createDiv('progress-wrapper'); + progressWrapper.style.width = '100%'; + progressWrapper.style.backgroundColor = 'var(--background-modifier-border)'; + progressWrapper.style.borderRadius = '4px'; + progressWrapper.style.height = '12px'; + progressWrapper.style.overflow = 'hidden'; + + this.progressBar = progressWrapper.createDiv('progress-bar'); + this.progressBar.style.width = '0%'; + this.progressBar.style.height = '100%'; + this.progressBar.style.backgroundColor = 'var(--interactive-accent)'; + this.progressBar.style.transition = 'width 0.3s ease'; + + // Progress text + this.progressText = progressIndicator.createDiv('progress-text'); + this.progressText.style.textAlign = 'center'; + this.progressText.style.marginTop = '8px'; + this.progressText.style.fontSize = '0.9em'; + this.progressText.style.color = 'var(--text-muted)'; + this.progressText.textContent = 'Initializing export...'; + + // Progress percentage + const progressPercent = progressIndicator.createDiv('progress-percent'); + progressPercent.style.textAlign = 'center'; + progressPercent.style.marginTop = '4px'; + progressPercent.style.fontSize = '1.1em'; + progressPercent.style.fontWeight = 'bold'; + this.progressPercentElement = progressPercent; + this.progressPercentElement.textContent = '0%'; + + // Cancel button + const cancelContainer = this.progressContainer.createDiv('cancel-container'); + cancelContainer.style.textAlign = 'center'; + cancelContainer.style.marginTop = '20px'; + + this.cancelButton = cancelContainer.createEl('button', { + text: 'Cancel Export', + attr: { + style: ` + padding: 8px 16px; + background: var(--interactive-normal); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-normal); + cursor: pointer; + ` + } + }); + + this.cancelButton.addEventListener('click', () => this.cancelExport()); + + // Set initial state + this.settings.isExporting = true; + this.settings.canCancel = true; + this.settings.progressPercent = 0; + this.settings.currentOperation = 'Initializing export...'; + } + + /** + * Update export progress + * Placeholder for Task 7.5 + */ + /** + * Update export progress + * Updates progress bar, percentage, and current operation text + */ + private updateProgress(percent: number, operation: string): void { + this.settings.progressPercent = Math.max(0, Math.min(100, percent)); + this.settings.currentOperation = operation; + + // Update progress bar + if (this.progressBar) { + this.progressBar.style.width = `${this.settings.progressPercent}%`; + } + + // Update percentage display + if (this.progressPercentElement) { + this.progressPercentElement.textContent = `${Math.round(this.settings.progressPercent)}%`; + } + + // Update operation text + if (this.progressText) { + this.progressText.textContent = operation; + } + + // Disable cancel button in final stages + if (this.settings.progressPercent > 90) { + this.settings.canCancel = false; + if (this.cancelButton) { + this.cancelButton.disabled = true; + this.cancelButton.style.opacity = '0.5'; + this.cancelButton.style.cursor = 'not-allowed'; + } + } + + // Show completion state + if (this.settings.progressPercent >= 100) { + this.showCompletionState(); + } + } + + /** + * Hide progress and reset modal state + * Placeholder for Task 7.5 + */ + /** + * Hide progress and reset modal state + * Returns modal to form view or closes it + */ + private hideProgress(): void { + this.settings.isExporting = false; + this.settings.progressPercent = 0; + this.settings.currentOperation = ''; + this.settings.canCancel = false; + + // Reset UI state + if (this.progressContainer) { + this.progressContainer.style.display = 'none'; + } + + if (this.formContainer) { + this.formContainer.style.display = 'block'; + } + + if (this.previewContainer) { + this.previewContainer.style.display = 'block'; + } + + // Clean up progress elements + this.progressBar = null; + this.progressText = null; + this.progressPercentElement = null; + this.cancelButton = null; + } + + /** + * Handle export cancellation + * Placeholder for Task 7.5 + */ + /** + * Handle export cancellation + * Cancels ongoing export and resets modal state + */ + private cancelExport(): void { + if (!this.settings.canCancel) { + return; // Cannot cancel at this stage + } + + // Update UI to show cancellation in progress + if (this.progressText) { + this.progressText.textContent = 'Cancelling export...'; + } + + if (this.cancelButton) { + this.cancelButton.disabled = true; + this.cancelButton.textContent = 'Cancelling...'; + this.cancelButton.style.opacity = '0.5'; + } + + // Call cancellation callback if provided + if (this.onCancel) { + this.onCancel(); + } + + // Show cancellation feedback + setTimeout(() => { + this.showCancellationState(); + }, 1000); // Give time for cleanup + } + + /** + * Show completion state when export is finished + */ + private showCompletionState(): void { + if (this.progressText) { + this.progressText.textContent = 'Export completed successfully!'; + this.progressText.style.color = 'var(--text-success)'; + } + + if (this.cancelButton) { + this.cancelButton.style.display = 'none'; + } + + // Add completion actions + const completionActions = this.progressContainer.createDiv('completion-actions'); + completionActions.style.textAlign = 'center'; + completionActions.style.marginTop = '20px'; + + // Success message + const successMsg = completionActions.createDiv('success-message'); + successMsg.style.padding = '12px'; + successMsg.style.backgroundColor = 'var(--background-modifier-success)'; + successMsg.style.border = '1px solid var(--background-modifier-success-border)'; + successMsg.style.borderRadius = '4px'; + successMsg.style.marginBottom = '16px'; + successMsg.style.color = 'var(--text-success)'; + successMsg.innerHTML = ` + ✓ PDF exported successfully!
+ File saved to: ${this.settings.outputFolder}/${this.generatePreviewFilename()}.pdf + `; + + // Action buttons + const actionButtons = completionActions.createDiv('action-buttons'); + actionButtons.style.display = 'flex'; + actionButtons.style.gap = '8px'; + actionButtons.style.justifyContent = 'center'; + + // Open file button (if supported) + const openButton = actionButtons.createEl('button', { + text: 'Open PDF', + attr: { + style: ` + padding: 8px 16px; + background: var(--interactive-accent); + border: none; + border-radius: 4px; + color: var(--text-on-accent); + cursor: pointer; + ` + } + }); + + openButton.addEventListener('click', () => { + // TODO: Implement file opening logic + // This would typically use Obsidian's shell.openPath or similar + this.close(); + }); + + // Close button + const closeButton = actionButtons.createEl('button', { + text: 'Close', + attr: { + style: ` + padding: 8px 16px; + background: var(--interactive-normal); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-normal); + cursor: pointer; + ` + } + }); + + closeButton.addEventListener('click', () => this.close()); + + // Auto-close after delay + setTimeout(() => { + if (this.isOpen) { + this.close(); + } + }, 5000); + } + + /** + * Show cancellation state when export is cancelled + */ + private showCancellationState(): void { + if (this.progressText) { + this.progressText.textContent = 'Export cancelled'; + this.progressText.style.color = 'var(--text-warning)'; + } + + if (this.progressBar) { + this.progressBar.style.backgroundColor = 'var(--background-modifier-error)'; + } + + // Add cancellation message + const cancellationMsg = this.progressContainer.createDiv('cancellation-message'); + cancellationMsg.style.textAlign = 'center'; + cancellationMsg.style.marginTop = '20px'; + cancellationMsg.style.padding = '12px'; + cancellationMsg.style.backgroundColor = 'var(--background-modifier-error)'; + cancellationMsg.style.border = '1px solid var(--background-modifier-error-border)'; + cancellationMsg.style.borderRadius = '4px'; + cancellationMsg.style.color = 'var(--text-error)'; + cancellationMsg.innerHTML = ` + Export cancelled
+ No files were created + `; + + // Action buttons + const actionContainer = this.progressContainer.createDiv('cancellation-actions'); + actionContainer.style.textAlign = 'center'; + actionContainer.style.marginTop = '16px'; + + const backButton = actionContainer.createEl('button', { + text: 'Back to Settings', + attr: { + style: ` + padding: 8px 16px; + background: var(--interactive-normal); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-normal); + cursor: pointer; + margin-right: 8px; + ` + } + }); + + backButton.addEventListener('click', () => this.hideProgress()); + + const closeButton = actionContainer.createEl('button', { + text: 'Close', + attr: { + style: ` + padding: 8px 16px; + background: var(--interactive-normal); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-normal); + cursor: pointer; + ` + } + }); + + closeButton.addEventListener('click', () => this.close()); + } + + /** + * Check if modal is currently open + */ + private get isOpen(): boolean { + return this.containerEl.isConnected; + } + + /** + * Add custom CSS styles for the export modal + */ + private addModalStyles(): void { + const styleId = 'export-config-modal-styles'; + + // Don't add styles if already present + if (document.getElementById(styleId)) { + return; + } + + const style = document.createElement('style'); + style.id = styleId; + style.textContent = ` + .export-config-container { + width: 100%; + max-width: 100%; + min-height: 650px; + max-height: 80vh; + overflow-y: auto; + overflow-x: hidden; + box-sizing: border-box; + } + + .export-section { + margin-bottom: 24px; + padding-bottom: 16px; + border-bottom: 1px solid var(--background-modifier-border-hover); + } + + .export-section:last-child { + border-bottom: none; + } + + .export-section h3 { + margin: 0 0 12px 0; + font-size: 1.1em; + font-weight: 600; + color: var(--text-normal); + } + + .export-section h4 { + margin: 16px 0 8px 0; + font-size: 1em; + font-weight: 500; + color: var(--text-muted); + } + + .export-config-preview { + background: var(--background-secondary); + padding: 16px; + border-radius: 8px; + } + + .export-config-preview h3 { + margin: 0 0 12px 0; + font-size: 1em; + font-weight: 600; + } + + .config-items .config-item { + margin-bottom: 8px; + font-size: 0.9em; + line-height: 1.4; + } + + .variables-list .var-item { + margin-left: 16px; + font-size: 0.85em; + color: var(--text-muted); + } + + .export-actions { + display: flex; + gap: 12px; + justify-content: flex-end; + } + + .progress-indicator { + padding: 20px; + } + + .progress-wrapper { + box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1); + } + + .field-error { + background: var(--background-modifier-error); + padding: 8px 12px; + border-radius: 4px; + margin: 8px 0; + border-left: 3px solid var(--text-error); + } + + .margins-container .setting-item, + .font-sizes .setting-item { + border: none; + padding: 8px 0; + } + + .template-variables .setting-item { + padding: 6px 0; + } + + .completion-actions .success-message, + .cancellation-message { + animation: slideIn 0.3s ease-out; + } + + @keyframes slideIn { + from { + opacity: 0; + transform: translateY(-10px); + } + to { + opacity: 1; + transform: translateY(0); + } + } + + .export-config-container button:hover:not(:disabled) { + opacity: 0.8; + } + + .export-config-container button:disabled { + cursor: not-allowed; + } + `; + + document.head.appendChild(style); + } + + // Additional properties for progress tracking + private progressPercentElement: HTMLElement | null = null; + + /** + * Submit current configuration for export + */ + private async submitExport(): Promise { + if (!this.validateSettings()) { + return; + } + + // Prepare export configuration + const exportConfig: ExportConfig = { + template: this.settings.template, + format: this.settings.format, + outputFolder: this.settings.outputFolder, + templateVariables: this.settings.templateVariables + }; + + try { + // Save settings for future use + await this.saveSettings(); + + // Start export process + this.settings.isExporting = true; + this.showProgress(); + + // Execute export via callback + await this.onSubmit(exportConfig); + + // Success - close modal + this.close(); + } catch (error) { + // Handle export errors + console.error('Export failed:', error); + this.hideProgress(); + + // TODO: Show user-friendly error message + } + } +} diff --git a/src/MarkdownPreprocessor.ts b/src/MarkdownPreprocessor.ts index f9f3c6c..b1722d5 100644 --- a/src/MarkdownPreprocessor.ts +++ b/src/MarkdownPreprocessor.ts @@ -58,12 +58,15 @@ export interface MarkdownPreprocessorConfig { options: PreprocessorOptions; /** Wikilink conversion configuration */ wikilinkConfig: WikilinkConfig; + /** Note title to add as H1 heading at top (optional) */ + noteTitle?: string; } export class MarkdownPreprocessor { private vaultPath: string; private options: PreprocessorOptions; private wikilinkConfig: WikilinkConfig; + private noteTitle?: string; // Regex patterns for Obsidian syntax private readonly WIKILINK_PATTERN = /\[\[([^\|\]]+)(?:\|([^\]]+))?\]\]/g; @@ -80,6 +83,7 @@ export class MarkdownPreprocessor { this.vaultPath = config.vaultPath; this.options = config.options; this.wikilinkConfig = config.wikilinkConfig; + this.noteTitle = config.noteTitle; } /** @@ -117,16 +121,19 @@ export class MarkdownPreprocessor { // Step 3: Convert email blocks to Typst format result.content = this.parseEmailBlocks(result.content, result); - // Step 4: Convert embeds FIRST (before wikilinks to avoid .md extension being added) + // Step 4: Filter out unnecessary links (Open: links and Mail.app links) + result.content = this.filterUnnecessaryLinks(result.content, result); + + // Step 5: Convert embeds FIRST (before wikilinks to avoid .md extension being added) result.content = this.parseEmbeds(result.content, result); - // Step 5: Convert wikilinks (after embeds are processed) + // Step 6: Convert wikilinks (after embeds are processed) result.content = this.parseWikilinks(result.content, result); - // Step 6: Convert callouts + // Step 7: Convert callouts result.content = this.parseCallouts(result.content, result); - // Step 7: Calculate final metadata + // Step 8: Calculate final metadata result.metadata.wordCount = this.calculateWordCount(result.content); // Use title from frontmatter if available, otherwise extract from content @@ -151,7 +158,14 @@ export class MarkdownPreprocessor { const parsed = matter(content); if (parsed.data && Object.keys(parsed.data).length > 0) { - result.metadata.frontmatter = parsed.data; + // Replace frontmatter title with filename if noteTitle is provided + if (this.noteTitle) { + const frontmatterCopy = { ...parsed.data }; + frontmatterCopy.title = this.noteTitle; + result.metadata.frontmatter = frontmatterCopy; + } else { + result.metadata.frontmatter = parsed.data; + } // Extract tags from frontmatter if they exist if (parsed.data.tags) { @@ -178,21 +192,45 @@ export class MarkdownPreprocessor { } } - // Extract title from frontmatter if available - if (parsed.data.title && typeof parsed.data.title === 'string') { + // Extract title - use noteTitle if available, otherwise frontmatter title + if (this.noteTitle) { + result.metadata.title = this.noteTitle; + } else if (parsed.data.title && typeof parsed.data.title === 'string') { result.metadata.title = parsed.data.title.trim(); } if (this.options.preserveFrontmatter) { - // Keep the frontmatter in the content - return content; + // Keep the frontmatter in the content, but reconstruct it with the modified title + if (this.noteTitle) { + const yaml = require('js-yaml'); + const frontmatterCopy = { ...parsed.data }; + frontmatterCopy.title = this.noteTitle; + const newFrontmatter = yaml.dump(frontmatterCopy); + return `---\n${newFrontmatter}---\n${parsed.content}`; + } else { + return content; + } } else { - // Return content without frontmatter - return parsed.content; + // Return content without frontmatter, but add title as frontmatter for Pandoc + if (this.noteTitle) { + const yaml = require('js-yaml'); + const titleFrontmatter = yaml.dump({ title: this.noteTitle }); + console.log('Replacing frontmatter with title:', titleFrontmatter); + return `---\n${titleFrontmatter}---\n${parsed.content}`; + } else { + return parsed.content; + } } } else { - // No frontmatter found, return original content - return content; + // No frontmatter found - add title frontmatter if we have a noteTitle + if (this.noteTitle) { + const yaml = require('js-yaml'); + const titleFrontmatter = yaml.dump({ title: this.noteTitle }); + console.log('Adding title frontmatter:', titleFrontmatter); + return `---\n${titleFrontmatter}---\n${content}`; + } else { + return content; + } } } catch (error: any) { result.warnings.push(`Failed to parse frontmatter with gray-matter: ${error.message}`); @@ -216,12 +254,31 @@ export class MarkdownPreprocessor { } } + // Replace title with noteTitle if provided + if (this.noteTitle) { + frontmatter.title = this.noteTitle; + } + result.metadata.frontmatter = frontmatter; if (this.options.preserveFrontmatter) { - return content; + // Reconstruct frontmatter with modified title + if (this.noteTitle) { + const yaml = require('js-yaml'); + const newFrontmatter = yaml.dump(frontmatter); + return content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`); + } else { + return content; + } } else { - return content.replace(this.FRONTMATTER_PATTERN, ''); + // Add title as frontmatter for Pandoc even when not preserving original + if (this.noteTitle) { + const yaml = require('js-yaml'); + const titleFrontmatter = yaml.dump({ title: this.noteTitle }); + return content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`); + } else { + return content.replace(this.FRONTMATTER_PATTERN, ''); + } } } catch (fallbackError: any) { result.warnings.push(`Fallback frontmatter parsing also failed: ${fallbackError.message}`); @@ -517,7 +574,7 @@ export class MarkdownPreprocessor { } /** - * Process PDF embeds - Convert to image preview with PDF attachment + * Process PDF embeds - Convert to image preview with PDF attachment using Typst's pdf.embed */ private processPdfEmbed(pdfPath: string, options: string | undefined, result: PreprocessingResult): string { const sanitizedPath = this.sanitizeFilePath(pdfPath); @@ -527,8 +584,8 @@ export class MarkdownPreprocessor { const fileName = pdfPath.substring(pdfPath.lastIndexOf('/') + 1); const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension - // Create a marker that the export process can detect and replace - const marker = `PDF_EMBED_MARKER:${pdfPath}:${baseName}:${options || ''}`; + // Create a marker that the export process can detect and replace with Typst code + const marker = `TYPST_PDF_EMBED_MARKER:${pdfPath}:${baseName}:${options || ''}`; // Add to processing queue for later conversion if (!result.metadata.pdfEmbeds) { @@ -543,7 +600,7 @@ export class MarkdownPreprocessor { marker: marker }); - result.warnings.push(`PDF embed queued for image conversion: ${pdfPath}`); + result.warnings.push(`PDF embed queued for processing with Typst pdf.embed: ${pdfPath}`); return marker; } @@ -570,6 +627,25 @@ export class MarkdownPreprocessor { } }); } + + /** + * Filter out unnecessary links from the markdown content + * This includes [[filename|Open: filename]] links and [Open in Mail.app](message://) links + */ + private filterUnnecessaryLinks(content: string, result: PreprocessingResult): string { + // Remove [[filename|Open: filename]] links from general content + let filtered = content.replace(/\[\[.*?\|Open:.*?\]\]/g, ''); + + // Remove [Open in Mail.app](message://) links from general content + filtered = filtered.replace(/\[Open in Mail\.app\]\(message:\/\/[^)]+\)/g, ''); + + // Clean up any resulting excessive newlines + filtered = filtered.replace(/\n{3,}/g, '\n\n'); + + result.warnings.push('Filtered out unnecessary Open: and Mail.app links from content'); + + return filtered; + } /** * Process individual email block content and convert to Typst format @@ -579,7 +655,15 @@ export class MarkdownPreprocessor { // Split at --- to separate header from body const parts = blockContent.split('---'); const yamlHeader = parts[0].trim(); - const body = parts.length > 1 ? parts.slice(1).join('---').trim() : ''; + let body = parts.length > 1 ? parts.slice(1).join('---').trim() : ''; + + // Filter out unnecessary links from the body + // Remove [[filename|Open: filename]] links + body = body.replace(/\[\[.*?\|Open:.*?\]\]/g, ''); + // Remove [Open in Mail.app](message://) links + body = body.replace(/\[Open in Mail\.app\]\(message:\/\/[^)]+\)/g, ''); + // Clean up any resulting double newlines + body = body.replace(/\n{3,}/g, '\n\n').trim(); // Parse YAML header const params = this.parseEmailYaml(yamlHeader); @@ -602,8 +686,8 @@ export class MarkdownPreprocessor { } // Add body as string parameter (always present, even if empty) - // Use the formatBodyForTypst method to preserve paragraphs but keep as string - const bodyParam = `"${this.escapeQuotes(body)}"`; + // Use the escapeQuotes method to preserve paragraphs but keep as string + const bodyParam = `"${this.escapeBodyForTypst(body)}"`; // Construct the Typst email-block function call with proper line breaks // Wrap in Pandoc raw blocks so it's treated as Typst code, not markdown text @@ -710,6 +794,42 @@ export class MarkdownPreprocessor { .replace(/\r/g, '\\r'); // Convert carriage returns } + /** + * Escape text for Typst string parameters while preserving actual newlines + * Used specifically for email body content where we want to keep paragraph breaks + * Also cleans up problematic Unicode characters that cause formatting issues + */ + private escapeBodyForTypst(text: string): string { + if (!text) return ''; + + // First, clean up problematic Unicode characters + let cleaned = text + // Replace various Unicode spaces with regular spaces + .replace(/[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000\uFEFF]/g, ' ') + // Replace Unicode line separators with regular newlines + .replace(/[\u2028\u2029]/g, '\n') // Line Separator and Paragraph Separator + // Replace Unicode hyphens/dashes with regular hyphen + .replace(/[\u2010-\u2015\u2212]/g, '-') + // Remove or replace problematic symbols that can cause layout issues + .replace(/[\u2020\u2021]/g, '') // Remove dagger symbols + .replace(/[\u2022\u2023\u2043]/g, '• ') // Replace various bullets with standard bullet + // Remove zero-width characters + .replace(/[\u200B-\u200D\uFEFF]/g, '') + // Remove other problematic Unicode characters that can cause spacing issues + .replace(/[\u00AD\u061C\u180E\u2066-\u2069]/g, '') + // Normalize multiple spaces to single space (but preserve newlines) + .replace(/[ \t]+/g, ' ') + // Preserve paragraph breaks but clean up excessive newlines + .replace(/\n{3,}/g, '\n\n'); + + // Then escape for Typst string safety + return cleaned + .replace(/\\/g, '\\\\') // Escape backslashes first + .replace(/"/g, '\\"') // Escape double quotes + .replace(/'/g, "\\'"); // Escape single quotes + // Note: DO NOT replace newlines - they should be preserved for proper formatting + } + /** * Process multi-line callouts with comprehensive support */ diff --git a/src/converters/PandocTypstConverter.ts b/src/converters/PandocTypstConverter.ts new file mode 100644 index 0000000..5de386f --- /dev/null +++ b/src/converters/PandocTypstConverter.ts @@ -0,0 +1,628 @@ +/** + * Pandoc to Typst PDF Converter + * Handles the conversion of Markdown to PDF using Pandoc with Typst engine + */ + +import { spawn, ChildProcess } from 'child_process'; +import * as fs from 'fs'; +import { promises as fsPromises } from 'fs'; +import * as path from 'path'; +import * as os from 'os'; +import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './types'; +import type { obsidianTypstPDFExportSettings } from '../core/settings'; + +export class PandocTypstConverter { + private tempDir: string | null = null; + private cleanupHandlers: (() => void)[] = []; + private plugin: any; // Will be properly typed when we refactor the main plugin class + + /** + * Create a new PandocTypstConverter instance + * @param plugin The main plugin instance for accessing settings + * @param pandocOptions Configuration options for Pandoc + * @param typstSettings Settings specific to Typst engine + */ + constructor( + plugin: any, + private pandocOptions: PandocOptions = {}, + private typstSettings: TypstSettings = {} + ) { + this.plugin = plugin; + // Set up cleanup handlers for process termination + this.setupCleanup(); + } + + /** + * Convert a markdown file to PDF using Pandoc with Typst engine + * @param inputPath Path to the input markdown file + * @param outputPath Path where the PDF should be saved + * @param progressCallback Optional callback for progress updates + * @returns Promise resolving to conversion result + */ + async convertToPDF( + inputPath: string, + outputPath: string, + progressCallback?: ProgressCallback + ): Promise { + try { + progressCallback?.('Starting PDF conversion...', 0); + + // Create temporary directory if needed + await this.ensureTempDirectory(); + + // Build pandoc arguments + const args = await this.buildPandocArgs(inputPath, outputPath); + + progressCallback?.('Executing Pandoc with Typst engine...', 30); + + // Execute pandoc process + const result = await this.executePandoc(args, progressCallback); + + // Add the output path to the result if successful + if (result.success) { + result.outputPath = outputPath; + } + + progressCallback?.('Conversion complete!', 100); + + return result; + + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + return { + success: false, + error: `Conversion failed: ${errorMessage}` + }; + } + } + + /** + * Convert markdown content to PDF + */ + async convertMarkdownToPDF( + content: string, + outputPath: string, + options: Partial = {}, + progressCallback?: ProgressCallback + ): Promise { + try { + progressCallback?.('Preparing markdown content...', 10); + + // Create temporary markdown file + await this.ensureTempDirectory(); + const tempInputPath = path.join(this.tempDir!, `temp-${Date.now()}.md`); + await fsPromises.writeFile(tempInputPath, content, 'utf-8'); + + // Merge options + this.pandocOptions = { ...this.pandocOptions, ...options }; + + // Convert using the file-based method + const result = await this.convertToPDF(tempInputPath, outputPath, progressCallback); + + // Cleanup temp file + try { + await fsPromises.unlink(tempInputPath); + } catch (error) { + console.warn('Failed to cleanup temp file:', error); + } + + return result; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + return { + success: false, + error: `Conversion failed: ${errorMessage}` + }; + } + } + + /** + * Set up cleanup handlers for temporary files + */ + private setupCleanup(): void { + const cleanup = () => { + this.cleanup(); + }; + + process.on('exit', cleanup); + process.on('SIGINT', cleanup); + process.on('SIGTERM', cleanup); + process.on('uncaughtException', cleanup); + } + + /** + * Process PDF embeds by converting them to images and creating combined output + */ + async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string): Promise { + const { PdfToImageConverter } = require('../PdfToImageConverter'); + const converter = PdfToImageConverter.getInstance(this.plugin); + + for (const pdfEmbed of processedResult.metadata.pdfEmbeds) { + try { + console.log(`Export: Processing PDF embed: ${pdfEmbed.originalPath}`); + + // Resolve full path to the PDF + const fullPdfPath = path.resolve(vaultBasePath, pdfEmbed.sanitizedPath); + + // Check if PDF file exists + const fs = require('fs'); + if (!fs.existsSync(fullPdfPath)) { + console.warn(`Export: PDF file not found: ${fullPdfPath}`); + // Replace marker with error message + processedResult.content = processedResult.content.replace( + pdfEmbed.marker, + `[⚠️ PDF not found: ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})` + ); + continue; + } + + // Convert PDF to image + const conversionResult = await converter.convertFirstPageToImage( + fullPdfPath, + tempDir, + { + scale: 1.5, + maxWidth: 600, + maxHeight: 400, + format: 'png' + } + ); + + if (conversionResult.success) { + // Get relative path for the generated image + const relativeImagePath = path.relative(vaultBasePath, conversionResult.imagePath); + + // Create combined output: image preview + PDF attachment link + const combinedOutput = [ + `![${pdfEmbed.fileName} - Page 1](${relativeImagePath})`, + `[📎 **Download PDF:** ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})` + ].join('\n\n'); + + // Replace marker with combined output + processedResult.content = processedResult.content.replace(pdfEmbed.marker, combinedOutput); + + console.log(`Export: Successfully converted PDF: ${pdfEmbed.fileName} -> ${path.basename(conversionResult.imagePath)}`); + + } else { + console.error(`Export: PDF conversion failed: ${conversionResult.error}`); + + // Replace marker with fallback link + processedResult.content = processedResult.content.replace( + pdfEmbed.marker, + `[📖 ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Note: PDF preview could not be generated*` + ); + } + + } catch (error: any) { + console.error(`Export: Error processing PDF embed: ${error.message}`); + + // Replace marker with error fallback + processedResult.content = processedResult.content.replace( + pdfEmbed.marker, + `[⚠️ ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Error: Could not process PDF embed*` + ); + } + } + } + + /** + * Clean up temporary files and directories + */ + private async cleanup(): Promise { + try { + // Execute registered cleanup handlers + this.cleanupHandlers.forEach(handler => { + try { + handler(); + } catch (error) { + console.warn('Cleanup handler failed:', error); + } + }); + + // Remove temporary directory + if (this.tempDir) { + await fsPromises.rmdir(this.tempDir, { recursive: true }); + this.tempDir = null; + } + } catch (error) { + console.warn('Cleanup failed:', error); + } + } + + /** + * Ensure temporary directory exists + */ + private async ensureTempDirectory(): Promise { + if (!this.tempDir) { + // Create temp directory in plugin folder instead of system temp + const pluginTempDir = this.pandocOptions.vaultBasePath + ? path.join(this.pandocOptions.vaultBasePath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-pandoc') + : path.join(os.tmpdir(), 'obsidian-typst-'); + + // Ensure the temp directory exists + if (pluginTempDir.includes('temp-pandoc')) { + await fsPromises.mkdir(pluginTempDir, { recursive: true }); + this.tempDir = pluginTempDir; + } else { + // Fallback to system temp if plugin folder not available + this.tempDir = await fsPromises.mkdtemp(pluginTempDir); + } + } + return this.tempDir; + } + + /** + * Build pandoc command-line arguments + */ + private async buildPandocArgs(inputPath: string, outputPath: string): Promise { + const args: string[] = []; + + // Input file + args.push(inputPath); + + // Output file + args.push('-o', outputPath); + + // Specify input format as markdown with smart extension disabled + args.push('--from', 'markdown-smart'); + + // Set PDF engine to Typst (use configured path if available) + if (this.pandocOptions.typstPath) { + args.push(`--pdf-engine=${this.pandocOptions.typstPath}`); + } else { + args.push('--pdf-engine=typst'); + } + + // Enable standalone mode (required for PDF output) + args.push('--standalone'); + + // Embed resources (images, etc.) directly into the output + args.push('--embed-resources'); + + // Add resource paths for attachment resolution + if (this.pandocOptions.vaultBasePath) { + const fs = require('fs'); + + // Add vault root as primary resource path + args.push('--resource-path', this.pandocOptions.vaultBasePath); + + // Add common attachment directories as additional resource paths + const commonAttachmentPaths = [ + path.join(this.pandocOptions.vaultBasePath, 'attachments'), + path.join(this.pandocOptions.vaultBasePath, 'assets'), + path.join(this.pandocOptions.vaultBasePath, 'files'), + path.join(this.pandocOptions.vaultBasePath, 'images'), + path.join(this.pandocOptions.vaultBasePath, '.attachments') + ]; + + // Check if these directories exist and add them + for (const attachPath of commonAttachmentPaths) { + if (fs.existsSync(attachPath)) { + args.push('--resource-path', attachPath); + console.log('Added resource path:', attachPath); + } + } + + // Also scan for note-specific attachment folders (Obsidian often creates these) + try { + const vaultContents = fs.readdirSync(this.pandocOptions.vaultBasePath); + for (const item of vaultContents) { + const itemPath = path.join(this.pandocOptions.vaultBasePath, item); + const stat = fs.statSync(itemPath); + if (stat.isDirectory() && !item.startsWith('.') && !item.startsWith('_')) { + // Check if this directory contains images + try { + const dirContents = fs.readdirSync(itemPath); + const hasImages = dirContents.some((file: string) => + /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file) + ); + if (hasImages) { + args.push('--resource-path', itemPath); + console.log('Added note-specific resource path:', itemPath); + } + } catch (e) { + // Ignore directories we can't read + } + } + } + } catch (e) { + console.warn('Could not scan vault for attachment directories:', e); + } + } + + // Use universal wrapper with --template and pass actual template as template_path variable + if (this.pandocOptions.template) { + // Get absolute path to universal wrapper using plugin directory from pandocOptions + const fs = require('fs'); + const absolutePluginDir = this.pandocOptions.pluginDir || ''; + const wrapperPath = path.resolve(absolutePluginDir, 'templates', 'universal-wrapper.pandoc.typ'); + console.log('Universal wrapper path:', wrapperPath); + + // Verify wrapper exists + if (!fs.existsSync(wrapperPath)) { + throw new Error(`Universal wrapper template not found at: ${wrapperPath}`); + } + + args.push('--template', wrapperPath); + + // Pass the actual template path as a variable + // Make the path relative to the vault (working directory) for Typst + let templatePathForTypst = this.pandocOptions.template; + if (this.pandocOptions.vaultBasePath && path.isAbsolute(templatePathForTypst)) { + // If template path is absolute and inside vault, make it relative + if (templatePathForTypst.startsWith(this.pandocOptions.vaultBasePath)) { + templatePathForTypst = path.relative(this.pandocOptions.vaultBasePath, templatePathForTypst); + } + } + args.push('-V', `template_path=${templatePathForTypst}`); + } + + // Add variables for document metadata + // These variables come from the ExportConfig and include font settings from the modal + if (this.pandocOptions.variables) { + for (const [key, value] of Object.entries(this.pandocOptions.variables)) { + if (value && value.toString().trim() !== '') { + // Don't add quotes around the value - pandoc handles this + args.push('-V', `${key}=${value}`); + } + } + } + + // Only add typography settings from plugin settings if they're not already in variables + // This prevents duplicate font variables + if (this.plugin && this.plugin.settings) { + const settings: obsidianTypstPDFExportSettings = this.plugin.settings; + const existingVars = this.pandocOptions.variables || {}; + + // Add typography variables only if not already present in variables + if (settings.typography) { + if (settings.typography.fonts) { + // Only add if not already in variables from ExportConfig + if (!existingVars.font && settings.typography.fonts.body) { + args.push('-V', `font=${settings.typography.fonts.body}`); + } + if (!existingVars.heading_font && settings.typography.fonts.heading) { + args.push('-V', `heading_font=${settings.typography.fonts.heading}`); + } + if (!existingVars.monospace_font && settings.typography.fonts.monospace) { + args.push('-V', `monospace_font=${settings.typography.fonts.monospace}`); + } + } + + if (settings.typography.fontSizes) { + if (!existingVars.fontsize && settings.typography.fontSizes.body) { + args.push('-V', `fontsize=${settings.typography.fontSizes.body}pt`); + } + if (!existingVars.heading_fontsize && settings.typography.fontSizes.heading) { + args.push('-V', `heading_fontsize=${settings.typography.fontSizes.heading}pt`); + } + if (!existingVars.small_fontsize && settings.typography.fontSizes.small) { + args.push('-V', `small_fontsize=${settings.typography.fontSizes.small}pt`); + } + } + } + + // Add page setup variables + if (settings.pageSetup) { + if (settings.pageSetup.size) { + args.push('-V', `paper=${settings.pageSetup.size}`); + } + if (settings.pageSetup.orientation) { + args.push('-V', `orientation=${settings.pageSetup.orientation}`); + } + + // Convert margin points to cm for Typst (1 point = 0.0352778 cm) + if (settings.pageSetup.margins) { + const margins = settings.pageSetup.margins; + if (margins.top !== undefined) { + const topCm = (margins.top * 0.0352778).toFixed(2); + args.push('-V', `margin_top=${topCm}cm`); + } + if (margins.right !== undefined) { + const rightCm = (margins.right * 0.0352778).toFixed(2); + args.push('-V', `margin_right=${rightCm}cm`); + } + if (margins.bottom !== undefined) { + const bottomCm = (margins.bottom * 0.0352778).toFixed(2); + args.push('-V', `margin_bottom=${bottomCm}cm`); + } + if (margins.left !== undefined) { + const leftCm = (margins.left * 0.0352778).toFixed(2); + args.push('-V', `margin_left=${leftCm}cm`); + } + } + } + + // Add export format variable + if (settings.exportDefaults) { + if (settings.exportDefaults.format) { + args.push('-V', `export_format=${settings.exportDefaults.format}`); + } + } + } + + // Add Typst engine options + if (this.typstSettings.engineOptions) { + for (const option of this.typstSettings.engineOptions) { + args.push('--pdf-engine-opt', option); + } + } + + // Generate intermediate Typst file if requested + if (this.pandocOptions.generateIntermediateTypst) { + const tempDir = await this.ensureTempDirectory(); + const typstPath = path.join(tempDir, 'intermediate.typ'); + args.push('--output', typstPath); + } + + // Add additional arguments + if (this.pandocOptions.additionalArgs) { + args.push(...this.pandocOptions.additionalArgs); + } + + return args; + } + + /** + * Execute pandoc process with the given arguments + */ + private async executePandoc(args: string[], progressCallback?: ProgressCallback): Promise { + return new Promise((resolve) => { + const pandocPath = this.pandocOptions.pandocPath || 'pandoc'; + const timeout = this.pandocOptions.timeout || 60000; + + // Log the exact command being executed for debugging + console.log('Executing Pandoc command:', pandocPath, args.join(' ')); + + progressCallback?.('Starting Pandoc process...', 40); + + // Determine working directory - use vault base path if available, fallback to plugin directory + let workingDir: string; + + if (this.pandocOptions.vaultBasePath) { + workingDir = this.pandocOptions.vaultBasePath; + console.log('Pandoc working directory (vault):', workingDir); + } else { + // Fallback to plugin directory + const pluginDir = this.pandocOptions.pluginDir || process.cwd(); + workingDir = pluginDir; + console.log('Pandoc working directory (plugin fallback):', workingDir); + } + + // Augment PATH to include common binary locations + const augmentedEnv = { + ...process.env, + PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}` + }; + + // Spawn pandoc process with vault as working directory for attachment resolution + const pandocProcess: ChildProcess = spawn(pandocPath, args, { + stdio: ['pipe', 'pipe', 'pipe'], + cwd: workingDir, + env: augmentedEnv, // Use augmented environment + }); + + let stdout = ''; + let stderr = ''; + let hasTimedOut = false; + + // Set up timeout + const timeoutHandle = setTimeout(() => { + hasTimedOut = true; + pandocProcess.kill('SIGTERM'); + resolve({ + success: false, + error: `Pandoc process timed out after ${timeout}ms`, + exitCode: -1 + }); + }, timeout); + + // Collect stdout + pandocProcess.stdout?.on('data', (data: Buffer) => { + stdout += data.toString(); + progressCallback?.('Processing document...', 60); + }); + + // Collect stderr and monitor for progress + pandocProcess.stderr?.on('data', (data: Buffer) => { + const output = data.toString(); + stderr += output; + console.log('Pandoc stderr:', output); + + // Parse progress information from stderr if available + this.parseProgressFromOutput(output, progressCallback); + }); + + // Handle process completion + pandocProcess.on('close', (code: number | null) => { + clearTimeout(timeoutHandle); + + if (hasTimedOut) { + return; // Already resolved with timeout error + } + + const success = code === 0; + const result: ConversionResult = { + success, + stdout, + stderr, + exitCode: code || -1 + }; + + if (!success) { + result.error = this.extractErrorMessage(stderr, stdout); + } else { + progressCallback?.('PDF generation complete!', 90); + } + + resolve(result); + }); + + // Handle process errors + pandocProcess.on('error', (error: Error) => { + clearTimeout(timeoutHandle); + console.log('Pandoc process error:', error); + resolve({ + success: false, + error: `Failed to start Pandoc process: ${error.message}`, + exitCode: -1 + }); + }); + }); + } + + /** + * Parse progress information from pandoc output + */ + private parseProgressFromOutput(output: string, progressCallback?: ProgressCallback): void { + // Look for common progress indicators in pandoc/typst output + if (output.includes('reading')) { + progressCallback?.('Reading input file...', 50); + } else if (output.includes('parsing')) { + progressCallback?.('Parsing document...', 55); + } else if (output.includes('typst')) { + progressCallback?.('Generating PDF with Typst...', 70); + } else if (output.includes('writing')) { + progressCallback?.('Writing output file...', 80); + } + } + + /** + * Extract meaningful error messages from pandoc output + */ + private extractErrorMessage(stderr: string, stdout: string): string { + // Look for common error patterns + const errorPatterns = [ + /error:/i, + /Error:/, + /failed/i, + /Fatal/i, + /pandoc:/i + ]; + + const allOutput = (stderr + '\n' + stdout).split('\n'); + + for (const line of allOutput) { + for (const pattern of errorPatterns) { + if (pattern.test(line)) { + return line.trim(); + } + } + } + + // If no specific error found, return first non-empty line from stderr + const stderrLines = stderr.split('\n').filter(line => line.trim().length > 0); + if (stderrLines.length > 0) { + return stderrLines[0]; + } + + return 'Unknown error occurred during conversion'; + } + + /** + * Dispose of the converter and clean up resources + */ + async dispose(): Promise { + await this.cleanup(); + } +} \ No newline at end of file diff --git a/src/converters/types.ts b/src/converters/types.ts new file mode 100644 index 0000000..61f2b9d --- /dev/null +++ b/src/converters/types.ts @@ -0,0 +1,48 @@ +/** + * Type definitions for Pandoc and Typst conversion + */ + +export interface PandocOptions { + /** Path to pandoc executable (optional, uses PATH if not specified) */ + pandocPath?: string; + /** Path to typst executable (optional, uses PATH if not specified) */ + typstPath?: string; + /** Template file path */ + template?: string; + /** Template variables to pass to pandoc */ + variables?: Record; + /** Additional pandoc arguments */ + additionalArgs?: string[]; + /** Timeout for pandoc process in milliseconds (default: 60000) */ + timeout?: number; + /** Generate intermediate .typ file for debugging */ + generateIntermediateTypst?: boolean; + /** Vault base path for resolving attachment paths */ + vaultBasePath?: string; + /** Plugin directory path for resolving plugin-relative paths */ + pluginDir?: string; +} + +export interface TypstSettings { + /** Additional options to pass to Typst engine */ + engineOptions?: string[]; +} + +export interface ConversionResult { + /** Whether the conversion was successful */ + success: boolean; + /** Path to the output PDF file */ + outputPath?: string; + /** Path to intermediate .typ file (if generated) */ + intermediateTypstPath?: string; + /** Error message if conversion failed */ + error?: string; + /** Pandoc stdout output */ + stdout?: string; + /** Pandoc stderr output */ + stderr?: string; + /** Process exit code */ + exitCode?: number; +} + +export type ProgressCallback = (message: string, progress?: number) => void; \ No newline at end of file diff --git a/src/core/settings.ts b/src/core/settings.ts new file mode 100644 index 0000000..8460d06 --- /dev/null +++ b/src/core/settings.ts @@ -0,0 +1,125 @@ +/** + * Core settings and configuration for Obsidian Typst PDF Export plugin + */ + +export enum ExportFormat { + /** Standard multi-page PDF format */ + Standard = 'standard', + /** Single-page continuous PDF format */ + SinglePage = 'single-page' +} + +export interface obsidianTypstPDFExportSettings { + /** Path to the Pandoc executable */ + pandocPath: string; + /** Path to the Typst executable */ + typstPath: string; + /** Default output folder for exported PDFs */ + outputFolder: string; + + /** Executable paths configuration */ + executablePaths: { + /** Path to ImageMagick convert command (optional, uses PATH if not specified) */ + imagemagickPath: string; + /** Additional paths to append to PATH environment variable */ + additionalPaths: string[]; + }; + + /** Export defaults */ + exportDefaults: { + /** Default template to use for exports */ + template: string; + /** Default export format */ + format: ExportFormat; + }; + + /** Typography settings */ + typography: { + /** Font families for different text types */ + fonts: { + body: string; + heading: string; + monospace: string; + }; + /** Font sizes */ + fontSizes: { + body: number; + heading: number; + small: number; + }; + }; + + /** Page setup configuration */ + pageSetup: { + /** Page size (e.g., "a4", "letter", "custom") */ + size: string; + /** Page orientation */ + orientation: "portrait" | "landscape"; + /** Page margins in points */ + margins: { + top: number; + right: number; + bottom: number; + left: number; + }; + }; + + /** Behavior flags */ + behavior: { + /** Open PDF after export */ + openAfterExport: boolean; + /** Preserve folder structure in output */ + preserveFolderStructure: boolean; + /** Number of concurrent exports to run (default: 3) */ + exportConcurrency: number; + /** Enable debug mode for verbose logging */ + debugMode: boolean; + }; +} + +export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = { + pandocPath: '', + typstPath: '', + outputFolder: 'exports', + + executablePaths: { + imagemagickPath: '', // Empty means use system PATH + additionalPaths: ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin'] + }, + + exportDefaults: { + template: 'default', + format: ExportFormat.Standard + }, + + typography: { + fonts: { + body: 'Concourse OT', + heading: 'SF Pro Text', + monospace: 'UbuntuMono Nerd Font Mono' + }, + fontSizes: { + body: 11, + heading: 16, + small: 9 + } + }, + + pageSetup: { + size: 'a4', + orientation: 'portrait', + margins: { + top: 72, + right: 72, + bottom: 72, + left: 72 + } + }, + + behavior: { + openAfterExport: true, + preserveFolderStructure: true, + exportConcurrency: 3, + debugMode: false + } +}; \ No newline at end of file diff --git a/src/modal/ExportConfigModal.ts b/src/modal/ExportConfigModal.ts new file mode 100644 index 0000000..c622062 --- /dev/null +++ b/src/modal/ExportConfigModal.ts @@ -0,0 +1,511 @@ +/** + * 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 './types'; +import { ModalState } from './state/ModalState'; +import { GeneralSection } from './sections/GeneralSection'; +import { TypographySection } from './sections/TypographySection'; +import { LayoutSection } from './sections/LayoutSection'; +import { TemplateManager } from '../templates/TemplateManager'; + +export class ExportConfigModal extends Modal { + plugin: obsidianTypstPDFExport; + private state: ModalState; + private sections: Map = 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; + + constructor( + app: App, + plugin: obsidianTypstPDFExport, + settings: Partial, + 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 TypographySection(), + new LayoutSection() + ]; + + 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) { + header.createEl('p', { + text: `Exporting: ${this.state.settings.noteTitle}`, + 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); + }); + + // Add preview section + this.createPreviewSection(); + } + + private createPreviewSection(): void { + const previewSection = this.formContainer.createDiv('export-section preview-section'); + previewSection.createEl('h3', { text: 'Preview' }); + + const previewContainer = previewSection.createDiv('export-preview'); + + // Output path preview + const outputPreview = previewContainer.createDiv('preview-item'); + outputPreview.createEl('span', { text: 'Output: ', cls: 'preview-label' }); + const outputPath = outputPreview.createEl('code', { cls: 'preview-value' }); + + // Template preview + const templatePreview = previewContainer.createDiv('preview-item'); + templatePreview.createEl('span', { text: 'Template: ', cls: 'preview-label' }); + const templateName = templatePreview.createEl('code', { cls: 'preview-value' }); + + // Update preview on state change + const updatePreview = () => { + const config = this.state.buildExportConfig(); + outputPath.textContent = `${config.outputFolder}/${this.getOutputFilename()}`; + templateName.textContent = config.template || 'default.typ'; + }; + + // Initial update + updatePreview(); + + // Listen for changes + this.state.onChange(updatePreview); + } + + 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'); + + // Cancel button + this.cancelButton = buttonContainer.createEl('button', { + text: 'Cancel', + cls: 'mod-cancel' + }); + this.cancelButton.addEventListener('click', () => this.handleCancel()); + + // Export button + this.submitButton = buttonContainer.createEl('button', { + text: 'Export', + cls: 'mod-cta' + }); + this.submitButton.addEventListener('click', () => this.handleSubmit()); + } + + private async loadAvailableTemplates(): Promise { + 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 async handleSubmit(): Promise { + // 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.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; + } + } + + 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-preview { + background: var(--background-secondary); + padding: 15px; + border-radius: 5px; + } + + .preview-item { + margin-bottom: 10px; + } + + .preview-label { + font-weight: 500; + margin-right: 10px; + } + + .preview-value { + background: var(--background-primary); + padding: 2px 6px; + border-radius: 3px; + font-family: var(--font-monospace); + font-size: 0.9em; + } + + .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: flex-end; + 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; + } + + .margin-preset-button { + margin: 0 5px; + padding: 2px 10px; + font-size: 0.85em; + } + + .margins-container { + background: var(--background-secondary-alt); + padding: 15px; + border-radius: 5px; + margin-top: 15px; + } + + .margin-presets { + margin-top: 15px; + padding-top: 15px; + border-top: 1px solid var(--background-modifier-border); + } + + .font-sizes { + 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(); + } +} \ No newline at end of file diff --git a/src/modal/sections/GeneralSection.ts b/src/modal/sections/GeneralSection.ts new file mode 100644 index 0000000..75b814b --- /dev/null +++ b/src/modal/sections/GeneralSection.ts @@ -0,0 +1,134 @@ +/** + * General Section for Export Configuration Modal + * Handles template selection, format options, and output settings + */ + +import { Setting } from 'obsidian'; +import { ModalSection, ModalState, ValidationResult } from '../types'; +import { ExportFormat } from '../../core/settings'; + +export class GeneralSection implements ModalSection { + private container: HTMLElement | null = null; + private templateDropdown: any = null; + private outputFolderInput: HTMLInputElement | null = null; + + render(containerEl: HTMLElement, state: ModalState): void { + 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 => { + // Populate with available templates + state.settings.availableTemplates.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; + }); + } + + 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(); + + // Clear and repopulate dropdown + this.templateDropdown.selectEl.empty(); + templates.forEach(template => { + this.templateDropdown.addOption(template, this.getTemplateDisplayName(template)); + }); + + // Restore selection if still available + if (templates.includes(currentValue)) { + this.templateDropdown.setValue(currentValue); + } else if (templates.length > 0) { + this.templateDropdown.setValue(templates[0]); + } + } + + getId(): string { + return 'general'; + } +} \ No newline at end of file diff --git a/src/modal/sections/LayoutSection.ts b/src/modal/sections/LayoutSection.ts new file mode 100644 index 0000000..75d5ba1 --- /dev/null +++ b/src/modal/sections/LayoutSection.ts @@ -0,0 +1,158 @@ +/** + * Layout Section for Export Configuration Modal + * Handles page setup, orientation, and margins + */ + +import { Setting } from 'obsidian'; +import { ModalSection, ModalState, ValidationResult } from '../types'; + +export class LayoutSection implements ModalSection { + private container: HTMLElement | null = null; + private marginInputs: Map = 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 => { + dropdown + .addOption('a4', 'A4 (210 × 297 mm)') + .addOption('letter', 'Letter (8.5 × 11 in)') + .addOption('legal', 'Legal (8.5 × 14 in)') + .addOption('a3', 'A3 (297 × 420 mm)') + .addOption('a5', 'A5 (148 × 210 mm)') + .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'; + } +} \ No newline at end of file diff --git a/src/modal/sections/TypographySection.ts b/src/modal/sections/TypographySection.ts new file mode 100644 index 0000000..f4626c1 --- /dev/null +++ b/src/modal/sections/TypographySection.ts @@ -0,0 +1,129 @@ +/** + * Typography Section for Export Configuration Modal + * Handles font selection and size configuration + */ + +import { Setting } from 'obsidian'; +import { ModalSection, ModalState, ValidationResult } from '../types'; + +export class TypographySection implements ModalSection { + private container: HTMLElement | null = null; + private fontInputs: Map = new Map(); + private sizeSliders: Map = new Map(); + + render(containerEl: HTMLElement, state: ModalState): void { + this.container = containerEl.createDiv('export-section'); + this.container.createEl('h3', { text: 'Typography' }); + + this.createFontSettings(state); + this.createFontSizeSettings(state); + } + + private createFontSettings(state: ModalState): void { + if (!this.container) return; + + // Body font + const bodyFontSetting = new Setting(this.container) + .setName('Body font') + .setDesc('Primary font for document text') + .addText(text => { + const input = text + .setPlaceholder('Concourse OT') + .setValue(state.typography.fontFamily) + .onChange(value => { + state.updateTypography({ fontFamily: value }); + }); + this.fontInputs.set('body', input.inputEl); + return text; + }); + + // Heading font (future enhancement) + // For now, we'll use the same font for all text types + // but this can be expanded later + + // Monospace font (future enhancement) + // Similar to heading font, can be expanded later + } + + private createFontSizeSettings(state: ModalState): void { + if (!this.container) return; + + const sizesContainer = this.container.createDiv('font-sizes'); + sizesContainer.createEl('h4', { text: 'Text Formatting' }); + + // Font size + new Setting(sizesContainer) + .setName('Font size') + .setDesc('Base font size for document text') + .addDropdown(dropdown => { + dropdown + .addOptions({ + '9pt': '9pt - Small', + '10pt': '10pt - Compact', + '11pt': '11pt - Standard', + '12pt': '12pt - Large', + '14pt': '14pt - Extra Large' + }) + .setValue(state.typography.fontSize) + .onChange(value => { + state.updateTypography({ fontSize: value }); + }); + }); + + // Line height + new Setting(sizesContainer) + .setName('Line height') + .setDesc('Spacing between lines of text') + .addDropdown(dropdown => { + dropdown + .addOptions({ + '1.0': 'Single', + '1.15': 'Slightly Loose', + '1.5': 'One and a Half', + '1.8': 'Relaxed', + '2.0': 'Double' + }) + .setValue(state.typography.lineHeight) + .onChange(value => { + state.updateTypography({ lineHeight: value }); + }); + }); + } + + validate(): ValidationResult { + const errors: string[] = []; + const warnings: string[] = []; + + // Check if fonts are likely available + this.fontInputs.forEach((input, type) => { + const value = input.value.trim(); + if (value && this.isUncommonFont(value)) { + warnings.push(`Font "${value}" may not be available on the system. The template will use fallback fonts if needed.`); + } + }); + + return { + isValid: errors.length === 0, + errors, + warnings + }; + } + + private isUncommonFont(fontName: string): boolean { + // List of commonly available fonts + const commonFonts = [ + 'arial', 'helvetica', 'times new roman', 'georgia', + 'verdana', 'tahoma', 'trebuchet ms', 'palatino', + 'courier', 'courier new', 'monaco', 'consolas', + 'sf pro', 'roboto', 'open sans', 'lato', + 'concourse ot', 'ubuntu', 'source code pro' + ]; + + const normalized = fontName.toLowerCase().trim(); + return !commonFonts.some(font => normalized.includes(font)); + } + + getId(): string { + return 'typography'; + } +} \ No newline at end of file diff --git a/src/modal/state/ModalState.ts b/src/modal/state/ModalState.ts new file mode 100644 index 0000000..8342168 --- /dev/null +++ b/src/modal/state/ModalState.ts @@ -0,0 +1,149 @@ +/** + * Modal State Management + * Centralized state management for the Export Configuration Modal + */ + +import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../types'; +import { ExportFormat } from '../../core/settings'; + +export class ModalState implements IModalState { + settings: ExportConfigModalSettings; + typography: { + fontFamily: string; + fontSize: string; + lineHeight: string; + }; + + private changeListeners: Set<() => void> = new Set(); + + constructor(initialSettings: Partial) { + // Initialize with defaults + this.settings = { + notePath: '', + noteTitle: '', + template: 'default.typ', + format: ExportFormat.Standard, + outputFolder: 'exports', + templateVariables: {}, + availableTemplates: [], + isExporting: false, + progressPercent: 0, + currentOperation: '', + canCancel: false, + ...initialSettings + }; + + // Initialize typography with defaults that will be passed to template + this.typography = { + fontFamily: 'Concourse OT', + fontSize: '11pt', + lineHeight: '1.5' + }; + } + + /** + * Update typography settings + */ + updateTypography(updates: Partial): void { + this.typography = { + ...this.typography, + ...updates + }; + 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.settings.templateVariables, + // Add typography settings to template variables + font: this.typography.fontFamily, + fontsize: this.typography.fontSize, + lineheight: this.typography.lineHeight + }, + // Include typography in the export config + typography: { + fontFamily: this.typography.fontFamily, + fontSize: this.typography.fontSize, + lineHeight: this.typography.lineHeight + } + }; + + 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): void { + this.settings = { + ...this.settings, + ...updates + }; + this.notifyChange(); + } + + /** + * Update template variables + */ + updateTemplateVariables(updates: Record): void { + this.settings.templateVariables = { + ...this.settings.templateVariables, + ...updates + }; + 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(): void { + this.settings.templateVariables = {}; + this.settings.progressPercent = 0; + this.settings.currentOperation = ''; + this.settings.isExporting = false; + this.settings.canCancel = false; + this.typography = { + fontFamily: 'Concourse OT', + fontSize: '11pt', + lineHeight: '1.5' + }; + this.notifyChange(); + } +} \ No newline at end of file diff --git a/src/modal/types.ts b/src/modal/types.ts new file mode 100644 index 0000000..831dd79 --- /dev/null +++ b/src/modal/types.ts @@ -0,0 +1,65 @@ +/** + * Type definitions for the Export Configuration Modal + */ + +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; + /** Typography settings for this export */ + typography?: { + fontFamily?: string; + fontSize?: string; + lineHeight?: string; + }; +} + +export interface ExportConfigModalSettings extends ExportConfig { + /** Note being exported */ + notePath: string; + /** Note title for display */ + noteTitle: string; + /** 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): void; + validate?(): ValidationResult; + getId(): string; +} + +export interface ValidationResult { + isValid: boolean; + errors: string[]; + warnings?: string[]; +} + +export interface ModalState { + settings: ExportConfigModalSettings; + typography: { + fontFamily: string; + fontSize: string; + lineHeight: string; + }; + updateTypography(updates: Partial): void; + updateSettings(updates: Partial): void; + updateTemplateVariables(updates: Record): void; + buildExportConfig(): ExportConfig; + notifyChange(): void; +} \ No newline at end of file diff --git a/src/templates/TemplateManager.ts b/src/templates/TemplateManager.ts new file mode 100644 index 0000000..22c8a52 --- /dev/null +++ b/src/templates/TemplateManager.ts @@ -0,0 +1,142 @@ +/** + * Template Manager + * Handles template discovery, loading, and validation + */ + +import { obsidianTypstPDFExport } from '../../main'; +import * as path from 'path'; +import * as fs from 'fs'; + +export class TemplateManager { + private plugin: obsidianTypstPDFExport; + private templatesPath: string; + + constructor(plugin: obsidianTypstPDFExport) { + this.plugin = plugin; + // Templates are stored in the plugin directory + this.templatesPath = path.join( + (this.plugin.app.vault.adapter as any).basePath, + '.obsidian/plugins/obsidian-typst-pdf-export/templates' + ); + } + + /** + * Get list of available template files + */ + async getAvailableTemplates(): Promise { + try { + // Check if templates directory exists + if (!fs.existsSync(this.templatesPath)) { + console.warn('Templates directory does not exist:', this.templatesPath); + return ['default.typ']; + } + + // Read directory contents + const files = fs.readdirSync(this.templatesPath); + + // Filter for .typ and .pandoc.typ files + const templates = files.filter(file => { + return file.endsWith('.typ') || file.endsWith('.pandoc.typ'); + }); + + // Always include default if not present + if (!templates.includes('default.typ')) { + templates.unshift('default.typ'); + } + + return templates; + } catch (error) { + console.error('Error loading templates:', error); + return ['default.typ']; + } + } + + /** + * Get the full path to a template file + */ + getTemplatePath(templateName: string): string { + return path.join(this.templatesPath, templateName); + } + + /** + * Check if a template exists + */ + async templateExists(templateName: string): Promise { + const templatePath = this.getTemplatePath(templateName); + try { + return fs.existsSync(templatePath); + } catch { + return false; + } + } + + /** + * Load template content + */ + async loadTemplate(templateName: string): Promise { + const templatePath = this.getTemplatePath(templateName); + try { + if (fs.existsSync(templatePath)) { + return fs.readFileSync(templatePath, 'utf-8'); + } + } catch (error) { + console.error('Error loading template:', error); + } + return null; + } + + /** + * Get template metadata (if available in template comments) + */ + async getTemplateMetadata(templateName: string): Promise { + const content = await this.loadTemplate(templateName); + if (!content) return null; + + // Parse template header comments for metadata + const metadataRegex = /^\/\/\s*@(\w+):\s*(.+)$/gm; + const metadata: TemplateMetadata = { + name: templateName, + description: '', + author: '', + version: '', + variables: [] + }; + + let match; + while ((match = metadataRegex.exec(content)) !== null) { + const [, key, value] = match; + switch (key) { + case 'description': + metadata.description = value; + break; + case 'author': + metadata.author = value; + break; + case 'version': + metadata.version = value; + break; + case 'variable': + // Parse variable definition (e.g., @variable: font:string:Body font family) + const [name, type, description] = value.split(':'); + metadata.variables.push({ name, type, description }); + break; + } + } + + return metadata; + } +} + +export interface TemplateMetadata { + name: string; + description: string; + author: string; + version: string; + variables: TemplateVariable[]; +} + +export interface TemplateVariable { + name: string; + type: string; + description: string; +} \ No newline at end of file diff --git a/temp-images/3_Befangenheit Abschließender Vermerk_3.11.22_preview.png b/temp-images/3_Befangenheit Abschließender Vermerk_3.11.22_preview.png new file mode 100644 index 0000000..7b0fcc5 Binary files /dev/null and b/temp-images/3_Befangenheit Abschließender Vermerk_3.11.22_preview.png differ diff --git a/temp-images/Ermordete aus Geinsheim - Ermordete_preview.png b/temp-images/Ermordete aus Geinsheim - Ermordete_preview.png new file mode 100644 index 0000000..0721928 Binary files /dev/null and b/temp-images/Ermordete aus Geinsheim - Ermordete_preview.png differ diff --git a/temp-images/Versicherungsflyer_2022_preview.png b/temp-images/Versicherungsflyer_2022_preview.png new file mode 100644 index 0000000..cfb010b Binary files /dev/null and b/temp-images/Versicherungsflyer_2022_preview.png differ diff --git a/templates/article.typ b/templates/article.typ index 69ee16d..5d2cf79 100644 --- a/templates/article.typ +++ b/templates/article.typ @@ -99,6 +99,7 @@ // Set page layout with conditional height based on export format set page( paper: paper, + orientation: orientation, margin: page-margin, ..if export_format == "single-page" { (height: auto,) } else { (:) }, numbering: pagenumbering, @@ -136,7 +137,7 @@ ) // Magazine-style paragraphs - set par(justify: true, leading: 0.7em, first-line-indent: 0.8em) + set par(justify: false, leading: 0.7em, first-line-indent: 0.8em) // No heading numbering for magazine style if sectionnumbering != none { @@ -182,6 +183,14 @@ #it.body #h(0.5em) #line(length: 3cm, stroke: 1pt + rgb("#93c5fd")) ] + // Apply monospace font to code blocks and inline code + let code-font = if monospace_font != none and type(monospace_font) == str { + (monospace_font, "Courier New", "Monaco") + } else { + ("Courier New", "Monaco") + } + + show raw: set text(font: code-font) // Decorative title block with background if title != none and title != "" [ diff --git a/templates/default.typ b/templates/default.typ index 053f3a5..f0f2996 100644 --- a/templates/default.typ +++ b/templates/default.typ @@ -2,38 +2,38 @@ #let email-block(from: none, to: none, subject: none, date: none, body) = { block( width: 100%, - inset: 6pt, - stroke: 1pt + gray, + inset: 16pt, + stroke: 0.5pt + blue, radius: 5pt, breakable: true )[ #grid( columns: (auto, 1fr), - row-gutter: 3pt, + row-gutter: 13pt, column-gutter: 8pt, if from != none [ - #text(style: "italic", size: 0.9em)[From:] + #text(style: "italic", size: 1em)[From:] ] else [], if from != none [ - #text(size: 0.9em)[#from] + #text(size: 1em)[#from] ] else [], if to != none [ - #text(style: "italic", size: 0.9em)[To:] + #text(style: "italic", size: 1em)[To:] ] else [], if to != none [ - #text(size: 0.9em)[#to] + #text(size: 1em)[#to] ] else [], if subject != none [ - #text(style: "italic", size: 0.9em)[Subject:] + #text(style: "italic", size: 1em)[Subject:] ] else [], if subject != none [ - #text(size: 0.9em)[#subject] + #text(size: 1em)[#subject] ] else [], if date != none [ - #text(style: "italic", size: 0.9em)[Date:] + #text(style: "italic", size: 1em)[Date:] ] else [], if date != none [ - #text(size: 0.9em)[#date] + #text(size: 1em)[#date] ] else [], ) #if body != none [ @@ -55,7 +55,7 @@ lang: "en", region: "US", paper: "a4", - margin: (x: 1.5cm, y: 1.5cm), + margin: (x: 1.5cm, y: 1cm), cols: 1, font: ("Concourse OT 3", "Helvetica Neue", "Arial"), fontsize: 11pt, @@ -66,7 +66,7 @@ monospace_font: none, heading_fontsize: none, small_fontsize: none, - margin_top: none, + margin_top: 9cm, margin_right: none, margin_bottom: none, margin_left: none, @@ -84,7 +84,7 @@ // Use UI-configured margins if available, otherwise fall back to template defaults let page-margin = if margin_top != none { ( - top: if margin_top != none { margin_top } else { 1.5cm }, + top: if margin_top != none { margin_top } else { 9cm }, right: if margin_right != none { margin_right } else { 1.5cm }, bottom: if margin_bottom != none { margin_bottom } else { 1.5cm }, left: if margin_left != none { margin_left } else { 1.5cm }, @@ -97,7 +97,8 @@ // Set page layout with conditional height based on export format set page( paper: paper, - margin: page-margin, + flipped: false, + margin: (top: 2.5cm, right: 1.5cm, bottom: 2cm, left: 2.5cm), ..if export_format == "single-page" { (height: auto,) } else { (:) }, numbering: pagenumbering, header: context { @@ -125,7 +126,7 @@ ) // Set paragraph properties - Clean spacing - set par(justify: true, leading: 0.6em) + set par(justify: false, leading: 0.6em) // Set heading numbering if sectionnumbering != none { @@ -162,10 +163,18 @@ #it ] + // Apply monospace font to code blocks and inline code + let code-font = if monospace_font != none and type(monospace_font) == str { + (monospace_font, "Courier New", "Monaco") + } else { + ("Courier New", "Monaco") + } + + show raw: set text(font: code-font) // Title block - Clean and minimal if title != none and title != "" [ - #align(center, text(16pt, weight: "bold")[#title]) + #align(left, text(16pt, weight: "bold")[#title]) #v(0.8em) ] diff --git a/templates/modern.typ b/templates/modern.typ index bed0ee9..b360d10 100644 --- a/templates/modern.typ +++ b/templates/modern.typ @@ -90,25 +90,16 @@ } else { margin } - + // Set page layout with conditional height based on export format - if export_format == "single-page" { - set page( - paper: paper, - margin: page-margin, - height: auto, // Auto height for continuous single page - numbering: pagenumbering, - fill: rgb("#fafafa") - ) - } else { - set page( - paper: paper, - margin: page-margin, - // No height specified = uses default paper size height - numbering: pagenumbering, - fill: rgb("#fafafa") - ) - } + set page( + paper: paper, + orientation: orientation, + margin: (top: 2.5cm, right: 1.5cm, bottom: 2cm, left: 2.5cm), + ..if export_format == "single-page" { (height: auto,) } else { (:) }, + numbering: pagenumbering, + fill: rgb("#fafafa") + ) // Modern sans-serif fonts // Use UI-configured font if available, otherwise use template default @@ -179,6 +170,14 @@ #it.body ] + // Apply monospace font to code blocks and inline code + let code-font = if monospace_font != none and type(monospace_font) == str { + (monospace_font, "Courier New", "Monaco") + } else { + ("Courier New", "Monaco") + } + + show raw: set text(font: code-font) // Modern title header with sidebar design if title != none and title != "" [ diff --git a/templates/report.typ b/templates/report.typ index b996a50..853376e 100644 --- a/templates/report.typ +++ b/templates/report.typ @@ -67,7 +67,7 @@ paper: "a4", margin: (x: 3cm, y: 2.5cm), cols: 1, - font: ("Concourse OT", "Helvetica Neue", "Arial", "sans-serif"), + font: ("Concourse OT 3", "Helvetica Neue", "Arial"), fontsize: 11pt, sectionnumbering: "1.", pagenumbering: "1", @@ -105,6 +105,7 @@ // Set page layout with conditional height based on export format set page( paper: paper, + orientation: orientation, margin: page-margin, ..if export_format == "single-page" { (height: auto,) } else { (:) }, numbering: pagenumbering, @@ -139,7 +140,7 @@ // Business document font // Use UI-configured font if available, otherwise use template default let body-font = if font != none and type(font) == str { - (font, "Concourse OT", "Helvetica Neue", "Arial", "sans-serif") + (font, "Concourse OT 3", "Helvetica Neue", "Arial") } else { font } @@ -153,8 +154,9 @@ region: region ) - // Professional paragraph formatting - set par(justify: true, leading: 0.7em, first-line-indent: 0pt) + // Professional paragraph formatting - use left alignment instead of full justification + // Full justification can create ugly gaps in short lines and attachment text + set par(justify: false, leading: 0.7em, first-line-indent: 0pt) // Chapter-style numbering if sectionnumbering != none { @@ -172,7 +174,7 @@ inset: 12pt, stroke: (left: 4pt + rgb("#1f2937")), )[ - #set text(font: ("SF Pro Text", "Helvetica Neue", "Arial", "sans-serif"), size: 18pt, weight: "bold", fill: rgb("#1f2937")) + #set text(font: ("SF Pro Text", "Helvetica Neue", "Arial"), size: 18pt, weight: "bold", fill: rgb("#1f2937")) #grid( columns: (auto, 1fr), column-gutter: 12pt, @@ -189,7 +191,7 @@ inset: (bottom: 6pt), stroke: (bottom: 1pt + rgb("#e5e7eb")), )[ - #set text(font: ("SF Pro Text", "Helvetica Neue", "Arial", "sans-serif"), size: 14pt, weight: "semibold", fill: rgb("#374151")) + #set text(font: ("SF Pro Text", "Helvetica Neue", "Arial"), size: 14pt, weight: "semibold", fill: rgb("#374151")) #counter(heading).display() #h(0.8em) #it.body @@ -206,6 +208,14 @@ #it.body ] + // Apply monospace font to code blocks and inline code + let code-font = if monospace_font != none and type(monospace_font) == str { + (monospace_font, "Courier New", "Monaco") + } else { + ("Courier New", "Monaco") + } + + show raw: set text(font: code-font) // Professional title page if title != none and title != "" [