diff --git a/main.ts b/main.ts index 2a4f69c..3dec987 100644 --- a/main.ts +++ b/main.ts @@ -22,6 +22,7 @@ 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 { FolderSuggest } from './src/components/FolderSuggest'; import * as path from 'path'; import * as fs from 'fs'; @@ -55,8 +56,108 @@ export class obsidianTypstPDFExport extends Plugin { // Check dependencies on startup (async, don't await) this.checkDependenciesAsync(); + // Cache available fonts (async, don't await) + this.cacheAvailableFonts(); + console.log('Obsidian Typst PDF Export plugin loaded'); } + + /** + * Cache available fonts from typst to a file for quick access + */ + private async cacheAvailableFonts(): Promise { + try { + const { exec } = require('child_process'); + const { promisify } = require('util'); + const execAsync = promisify(exec); + + const typstPath = this.settings.typstPath || 'typst'; + const { stdout } = await execAsync(`${typstPath} fonts`); + + const fonts = stdout + .split('\n') + .map((line: string) => line.trim()) + .filter((line: string) => line.length > 0) + .sort(); + + // Write fonts to cache file in plugin data directory + const cacheData = { + fonts: fonts, + timestamp: Date.now(), + typstPath: typstPath + }; + + await this.app.vault.adapter.write('.obsidian/plugins/obsidian-typst-pdf-export/fonts-cache.json', + JSON.stringify(cacheData, null, 2)); + console.log('Cached', fonts.length, 'fonts from typst'); + } catch (error) { + console.error('Failed to cache fonts from typst:', error); + // Create fallback cache file + const fallbackFonts = [ + 'Times New Roman', + 'Arial', + 'Helvetica', + 'Georgia', + 'Courier New', + 'Monaco', + 'SF Pro Text', + 'SF Mono', + 'Concourse OT', + 'UbuntuMono Nerd Font Mono', + 'Source Code Pro' + ]; + + const cacheData = { + fonts: fallbackFonts, + timestamp: Date.now(), + typstPath: 'fallback', + error: error.message + }; + + await this.app.vault.adapter.write('.obsidian/plugins/obsidian-typst-pdf-export/fonts-cache.json', + JSON.stringify(cacheData, null, 2)); + } + } + + /** + * Get cached fonts list + */ + async getCachedFonts(): Promise { + try { + const cacheContent = await this.app.vault.adapter.read('.obsidian/plugins/obsidian-typst-pdf-export/fonts-cache.json'); + const cacheData = JSON.parse(cacheContent); + + // Check if cache is older than 24 hours or typst path changed + const isStale = Date.now() - cacheData.timestamp > 24 * 60 * 60 * 1000; + const pathChanged = cacheData.typstPath !== (this.settings.typstPath || 'typst'); + + if (isStale || pathChanged) { + // Refresh cache in background + this.cacheAvailableFonts(); + } + + return cacheData.fonts || []; + } catch (error) { + console.error('Failed to read fonts cache:', error); + // Try to recreate cache + await this.cacheAvailableFonts(); + + // Return fallback fonts + return [ + 'Times New Roman', + 'Arial', + 'Helvetica', + 'Georgia', + 'Courier New', + 'Monaco', + 'SF Pro Text', + 'SF Mono', + 'Concourse OT', + 'UbuntuMono Nerd Font Mono', + 'Source Code Pro' + ]; + } + } private registerCommands(): void { // Export current note command @@ -210,38 +311,62 @@ export class obsidianTypstPDFExport extends Plugin { * Show the export configuration modal */ private async showExportModal(view: MarkdownView): Promise { - const file = view.file; - if (!file) { - new Notice('No active file to export'); - return; - } - - // 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() - }; - - // Show modal - const modal = new ExportConfigModal( - this.app, - this, - modalSettings, - async (config: ExportConfig) => { - await this.exportFileWithConfig(file, config); - }, - () => { - this.cancelExport(); - } - ); - - modal.open(); + const file = view.file; + if (!file) { + new Notice('No active file to export'); + return; } + // Get available templates first + const availableTemplates = await this.templateManager.getAvailableTemplates(); + + // Prepare modal settings with hierarchy: plugin defaults as base + const modalSettings: Partial = { + notePath: file.path, + noteTitle: file.basename, + // Plugin defaults from settings tab + template: this.settings.exportDefaults.template, + format: this.settings.exportDefaults.format, + outputFolder: this.settings.outputFolder, + openAfterExport: this.settings.behavior.openAfterExport, + preserveFolderStructure: this.settings.behavior.preserveFolderStructure, + availableTemplates: availableTemplates, + // Template variables from plugin defaults + templateVariables: { + pageSize: this.settings.exportDefaults.pageSize, + orientation: this.settings.exportDefaults.orientation, + flipped: this.settings.exportDefaults.orientation === 'landscape', + marginTop: this.settings.exportDefaults.marginTop, + marginBottom: this.settings.exportDefaults.marginBottom, + marginLeft: this.settings.exportDefaults.marginLeft, + marginRight: this.settings.exportDefaults.marginRight, + bodyFont: this.settings.exportDefaults.bodyFont, + headingFont: this.settings.exportDefaults.headingFont, + monospaceFont: this.settings.exportDefaults.monospaceFont, + bodyFontSize: this.settings.exportDefaults.bodyFontSize, + // Auto-adjust width for single-page landscape mode + ...(this.settings.exportDefaults.orientation === 'landscape' && this.settings.exportDefaults.format === 'single-page' + ? { width: 'auto' } + : {}) + } + }; + + // Show modal - ModalState will handle localStorage hierarchy automatically + 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 */ @@ -250,11 +375,23 @@ export class obsidianTypstPDFExport extends Plugin { 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' - } + templateVariables: { + // Page setup + pageSize: this.settings.exportDefaults.pageSize, + orientation: this.settings.exportDefaults.orientation, + flipped: this.settings.exportDefaults.orientation === 'landscape', + marginTop: this.settings.exportDefaults.marginTop, + marginBottom: this.settings.exportDefaults.marginBottom, + marginLeft: this.settings.exportDefaults.marginLeft, + marginRight: this.settings.exportDefaults.marginRight, + // Typography + bodyFont: this.settings.exportDefaults.bodyFont, + headingFont: this.settings.exportDefaults.headingFont, + monospaceFont: this.settings.exportDefaults.monospaceFont, + bodyFontSize: this.settings.exportDefaults.bodyFontSize + }, + openAfterExport: this.settings.behavior.openAfterExport, + preserveFolderStructure: this.settings.behavior.preserveFolderStructure }; await this.exportFileWithConfig(file, config); @@ -278,9 +415,14 @@ export class obsidianTypstPDFExport extends Plugin { const content = await this.app.vault.read(file); const pluginDir = path.join(vaultPath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export'); - // Create temp directory for processing - const os = require('os'); - const tempDir = os.tmpdir(); + // Create temp directory for processing - use plugin's temp directory + const tempDir = path.join(pluginDir, 'temp-images'); + + // Ensure temp directory exists + const fs = require('fs'); + if (!fs.existsSync(tempDir)) { + fs.mkdirSync(tempDir, { recursive: true }); + } // Preprocess the markdown content using MarkdownPreprocessor const { MarkdownPreprocessor } = await import('./src/MarkdownPreprocessor'); @@ -333,12 +475,7 @@ export class obsidianTypstPDFExport extends Plugin { 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' - }, + variables: config.templateVariables || {}, pluginDir: pluginDir, vaultBasePath: vaultPath }, @@ -821,34 +958,6 @@ ${missingDeps.length > 0 ? /** * Settings Tab */ -class FolderSuggest extends AbstractInputSuggest { - private folders: string[]; - private inputElement: HTMLInputElement; - - constructor(app: App, inputEl: HTMLInputElement) { - super(app, inputEl); - this.inputElement = inputEl; - this.folders = ["/"].concat(this.app.vault.getAllFolders().map(folder => folder.path)); - } - - getSuggestions(inputStr: string): string[] { - const inputLower = inputStr.toLowerCase(); - return this.folders.filter(folder => - folder.toLowerCase().includes(inputLower) - ); - } - - renderSuggestion(folder: string, el: HTMLElement): void { - el.createEl("div", { text: folder }); - } - - selectSuggestion(folder: string): void { - this.inputElement.value = folder; - this.inputElement.dispatchEvent(new Event('input')); - this.close(); - } -} - class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { plugin: obsidianTypstPDFExport; @@ -1194,37 +1303,7 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { // Helper methods for fonts private async getAvailableFonts(): Promise { - try { - const { exec } = require('child_process'); - const { promisify } = require('util'); - const execAsync = promisify(exec); - - const typstPath = this.plugin.settings.typstPath || 'typst'; - const { stdout } = await execAsync(`${typstPath} fonts`); - - const fonts = stdout - .split('\n') - .map((line: string) => line.trim()) - .filter((line: string) => line.length > 0) - .sort(); - - return fonts; - } catch (error) { - console.error('Failed to get fonts from typst:', error); - // Return common fallback fonts - return [ - 'Times New Roman', - 'Arial', - 'Helvetica', - 'Georgia', - 'Courier New', - 'Monaco', - 'SF Pro Text', - 'SF Mono', - 'Concourse OT', - 'UbuntuMono Nerd Font Mono' - ]; - } + return await this.plugin.getCachedFonts(); } // Helper methods for margin conversion diff --git a/src/PdfToImageConverter.ts b/src/PdfToImageConverter.ts index 013acf3..65650d8 100644 --- a/src/PdfToImageConverter.ts +++ b/src/PdfToImageConverter.ts @@ -90,6 +90,11 @@ export class PdfToImageConverter { // Ensure output directory exists await fs.mkdir(outputDir, { recursive: true }); + // Calculate relative path from vault to temp directory for pdf2img + // pdf2img doesn't handle absolute paths correctly, needs relative paths + const vaultPath = process.cwd(); // This should be the vault directory + const relativeOutputDir = path.relative(vaultPath, outputDir); + // Generate output file name for the first page const pdfBaseName = path.basename(pdfPath, path.extname(pdfPath)); // pdf2img uses the pattern: "filename-1.png" for first page @@ -147,7 +152,7 @@ export class PdfToImageConverter { `"${pdf2imgPath}"`, `"${pdfPath}"`, '--scale', opts.scale.toString(), - '--output', `"${outputDir}"`, + '--output', `"${relativeOutputDir}"`, '--pages', '1' // Only convert the first page ].join(' '); @@ -166,7 +171,9 @@ export class PdfToImageConverter { : '') }; - const result = await execAsync(cliCommand, { env }); + const result = await execAsync(cliCommand, { + env + }); console.log(`PDF conversion stdout: ${result.stdout}`); if (result.stderr) { console.warn(`PDF conversion stderr: ${result.stderr}`); @@ -183,16 +190,52 @@ export class PdfToImageConverter { } // Check if the expected output file exists + let actualOutputPath = expectedOutputPath; try { await fs.access(expectedOutputPath); } catch (error) { - return { - imagePath: '', - originalDimensions: { width: 0, height: 0 }, - imageDimensions: { width: 0, height: 0 }, - success: false, - error: `Generated image file not found: ${expectedOutputPath}` - }; + // Debug: List what files are actually in the output directory + try { + const files = await fs.readdir(outputDir); + console.log(`Files in output directory (${outputDir}):`, files); + + // Look for any PNG files that might match + const pngFiles = files.filter(f => f.endsWith('.png')); + if (pngFiles.length > 0) { + console.log(`Found PNG files:`, pngFiles); + + // Try to find a file that matches the pattern (with or without exact name) + // pdf2img might sanitize filenames differently + const matchingFile = pngFiles.find(f => { + // Try exact match first + if (f === expectedOutputFileName) return true; + // Try partial match by removing special characters + const simplifiedExpected = expectedOutputFileName.replace(/[^a-zA-Z0-9.-]/g, ''); + const simplifiedActual = f.replace(/[^a-zA-Z0-9.-]/g, ''); + return simplifiedActual === simplifiedExpected; + }) || pngFiles[0]; // Fallback to first PNG file + + if (matchingFile) { + actualOutputPath = path.join(outputDir, matchingFile); + console.log(`Using found PNG file: ${actualOutputPath}`); + } + } + } catch (listError) { + console.error(`Failed to list output directory:`, listError); + } + + // Final check if we found an alternative file + try { + await fs.access(actualOutputPath); + } catch (finalError) { + return { + imagePath: '', + originalDimensions: { width: 0, height: 0 }, + imageDimensions: { width: 0, height: 0 }, + success: false, + error: `Generated image file not found: ${actualOutputPath}. Expected: ${expectedOutputPath}` + }; + } } // Rename to our desired format if needed @@ -204,17 +247,17 @@ export class PdfToImageConverter { // Convert PNG to JPEG if needed try { const sharp = require('sharp'); - const inputBuffer = await fs.readFile(expectedOutputPath); + const inputBuffer = await fs.readFile(actualOutputPath); buffer = await sharp(inputBuffer) .jpeg({ quality: opts.quality }) .toBuffer(); await fs.writeFile(finalOutputPath, buffer); // Clean up the original PNG - await fs.unlink(expectedOutputPath); + await fs.unlink(actualOutputPath); } catch (sharpError) { console.warn('Sharp not available for JPEG conversion, keeping PNG format'); // Just rename the file - await fs.rename(expectedOutputPath, finalOutputPath); + await fs.rename(actualOutputPath, finalOutputPath); buffer = await fs.readFile(finalOutputPath); } } else { diff --git a/src/converters/PandocTypstConverter.ts b/src/converters/PandocTypstConverter.ts index 5de386f..5c01158 100644 --- a/src/converters/PandocTypstConverter.ts +++ b/src/converters/PandocTypstConverter.ts @@ -255,214 +255,257 @@ export class PandocTypstConverter { * Build pandoc command-line arguments */ private async buildPandocArgs(inputPath: string, outputPath: string): Promise { - const args: string[] = []; + const args: string[] = []; - // Input file - args.push(inputPath); + // Input file + args.push(inputPath); - // Output file - args.push('-o', outputPath); + // Output file + args.push('-o', outputPath); - // Specify input format as markdown with smart extension disabled - args.push('--from', 'markdown-smart'); + // 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'); + // 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); + } + } - // Enable standalone mode (required for PDF output) - args.push('--standalone'); + // 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}`); + } - // Embed resources (images, etc.) directly into the output - args.push('--embed-resources'); + // Add variables from the ExportConfig (these take priority) + // These come from the modal and include all the new template variables + if (this.pandocOptions.variables) { + for (const [key, value] of Object.entries(this.pandocOptions.variables)) { + if (value !== null && value !== undefined && value.toString().trim() !== '') { + // Handle special variable name mappings for Typst compatibility + let variableName = key; + switch (key) { + case 'bodyFont': + variableName = 'font'; + break; + case 'headingFont': + variableName = 'heading_font'; + break; + case 'monospaceFont': + variableName = 'monospace_font'; + break; + case 'bodyFontSize': + variableName = 'fontsize'; + break; + case 'pageSize': + variableName = 'paper'; + break; + case 'marginTop': + variableName = 'margin_top'; + break; + case 'marginBottom': + variableName = 'margin_bottom'; + break; + case 'marginLeft': + variableName = 'margin_left'; + break; + case 'marginRight': + variableName = 'margin_right'; + break; + // Keep other variables as-is (orientation, flipped, width, etc.) + } + + args.push('-V', `${variableName}=${value}`); + } + } + } - // 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); + // Add fallback typography and page setup from plugin settings + // Only add these if not already provided by ExportConfig 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.bodyFont && !existingVars.font && settings.typography.fonts.body) { + args.push('-V', `font=${settings.typography.fonts.body}`); + } + if (!existingVars.headingFont && !existingVars.heading_font && settings.typography.fonts.heading) { + args.push('-V', `heading_font=${settings.typography.fonts.heading}`); + } + if (!existingVars.monospaceFont && !existingVars.monospace_font && settings.typography.fonts.monospace) { + args.push('-V', `monospace_font=${settings.typography.fonts.monospace}`); } } - // Also scan for note-specific attachment folders (Obsidian often creates these) + if (settings.typography.fontSizes) { + if (!existingVars.bodyFontSize && !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 only if not already present + if (settings.pageSetup) { + if (!existingVars.pageSize && !existingVars.paper && settings.pageSetup.size) { + args.push('-V', `paper=${settings.pageSetup.size}`); + } + if (!existingVars.orientation && settings.pageSetup.orientation) { + args.push('-V', `orientation=${settings.pageSetup.orientation}`); + } + + // Add margin fallbacks only if not already specified + if (settings.pageSetup.margins) { + const margins = settings.pageSetup.margins; + if (!existingVars.marginTop && !existingVars.margin_top && margins.top !== undefined) { + const topCm = (margins.top * 0.0352778).toFixed(2); + args.push('-V', `margin_top=${topCm}cm`); + } + if (!existingVars.marginRight && !existingVars.margin_right && margins.right !== undefined) { + const rightCm = (margins.right * 0.0352778).toFixed(2); + args.push('-V', `margin_right=${rightCm}cm`); + } + if (!existingVars.marginBottom && !existingVars.margin_bottom && margins.bottom !== undefined) { + const bottomCm = (margins.bottom * 0.0352778).toFixed(2); + args.push('-V', `margin_bottom=${bottomCm}cm`); + } + if (!existingVars.marginLeft && !existingVars.margin_left && margins.left !== undefined) { + const leftCm = (margins.left * 0.0352778).toFixed(2); + args.push('-V', `margin_left=${leftCm}cm`); + } + } + } + + // Add export format variable + if (!existingVars.export_format && settings.exportDefaults && 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); + + // Also create a copy to keep for debugging + const debugTypstPath = path.join(tempDir, 'debug.typ'); + this.cleanupHandlers.push(() => { 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 - } - } + const fs = require('fs'); + if (fs.existsSync(typstPath)) { + fs.copyFileSync(typstPath, debugTypstPath); } } catch (e) { - console.warn('Could not scan vault for attachment directories:', e); + console.warn('Could not create debug Typst file:', 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; + }); } + // Add working directory for relative paths + if (this.pandocOptions.vaultBasePath) { + process.chdir(this.pandocOptions.vaultBasePath); + } + + return args; +} + /** * Execute pandoc process with the given arguments */ diff --git a/src/modal/ExportConfigModal.ts b/src/modal/ExportConfigModal.ts index c622062..8de4e74 100644 --- a/src/modal/ExportConfigModal.ts +++ b/src/modal/ExportConfigModal.ts @@ -9,7 +9,8 @@ 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 { PageSetupSection } from './sections/PageSetupSection'; +import { BehaviorSection } from './sections/BehaviorSection'; import { TemplateManager } from '../templates/TemplateManager'; export class ExportConfigModal extends Modal { @@ -27,6 +28,7 @@ export class ExportConfigModal extends Modal { private progressText: HTMLElement; private submitButton: HTMLButtonElement; private cancelButton: HTMLButtonElement; + private resetButton: HTMLButtonElement; constructor( app: App, @@ -54,8 +56,9 @@ export class ExportConfigModal extends Modal { // Register all modal sections const sections = [ new GeneralSection(), + new PageSetupSection(), new TypographySection(), - new LayoutSection() + new BehaviorSection() ]; sections.forEach(section => { @@ -110,41 +113,8 @@ export class ExportConfigModal extends Modal { // Render each section this.sections.forEach(section => { - section.render(this.formContainer, this.state); + section.render(this.formContainer, this.state, this.app); }); - - // 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 { @@ -171,15 +141,25 @@ export class ExportConfigModal extends Modal { private createActionButtons(): void { const buttonContainer = this.contentContainer.createDiv('export-config-buttons'); + // Reset button (left side) + this.resetButton = buttonContainer.createEl('button', { + text: 'Reset to Defaults', + cls: 'mod-muted' + }); + this.resetButton.addEventListener('click', () => this.handleReset()); + + // Right side buttons container + const rightButtons = buttonContainer.createDiv('right-buttons'); + // Cancel button - this.cancelButton = buttonContainer.createEl('button', { + this.cancelButton = rightButtons.createEl('button', { text: 'Cancel', cls: 'mod-cancel' }); this.cancelButton.addEventListener('click', () => this.handleCancel()); // Export button - this.submitButton = buttonContainer.createEl('button', { + this.submitButton = rightButtons.createEl('button', { text: 'Export', cls: 'mod-cta' }); @@ -211,6 +191,19 @@ export class ExportConfigModal extends Modal { // This is called whenever the state is updated } + private handleReset(): void { + // Reset state to defaults + this.state.reset(); + + // Re-render sections to update UI + this.renderSections(); + + // Reload templates to update the dropdown + this.loadAvailableTemplates(); + + new Notice('Settings reset to defaults'); + } + private async handleSubmit(): Promise { // Validate all sections const validationResults = this.validateAllSections(); @@ -233,6 +226,7 @@ export class ExportConfigModal extends Modal { // Disable buttons this.submitButton.disabled = true; + this.resetButton.disabled = true; this.cancelButton.textContent = 'Close'; try { @@ -248,6 +242,7 @@ export class ExportConfigModal extends Modal { console.error('Export failed:', error); this.showProgress(`Export failed: ${error.message}`, -1); this.submitButton.disabled = false; + this.resetButton.disabled = false; } } @@ -386,29 +381,6 @@ export class ExportConfigModal extends Modal { 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; @@ -442,7 +414,12 @@ export class ExportConfigModal extends Modal { padding: 20px; border-top: 1px solid var(--background-modifier-border); display: flex; - justify-content: flex-end; + justify-content: space-between; + align-items: center; + } + + .export-config-buttons .right-buttons { + display: flex; gap: 10px; } @@ -463,31 +440,12 @@ export class ExportConfigModal extends Modal { 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); } diff --git a/src/modal/state/ModalState.ts b/src/modal/state/ModalState.ts index 8342168..d6aa94a 100644 --- a/src/modal/state/ModalState.ts +++ b/src/modal/state/ModalState.ts @@ -8,16 +8,16 @@ import { ExportFormat } from '../../core/settings'; export class ModalState implements IModalState { settings: ExportConfigModalSettings; - typography: { - fontFamily: string; - fontSize: string; - lineHeight: string; - }; + templateVariables: Record; private changeListeners: Set<() => void> = new Set(); + private static readonly STORAGE_KEY = 'typst-export-modal-state'; constructor(initialSettings: Partial) { - // Initialize with defaults + // Load from localStorage if available + const savedState = this.loadFromStorage(); + + // Initialize with defaults, then saved state, then passed settings this.settings = { notePath: '', noteTitle: '', @@ -30,25 +30,43 @@ export class ModalState implements IModalState { progressPercent: 0, currentOperation: '', canCancel: false, + openAfterExport: false, + preserveFolderStructure: false, + ...savedState?.settings, ...initialSettings }; - // Initialize typography with defaults that will be passed to template - this.typography = { - fontFamily: 'Concourse OT', - fontSize: '11pt', - lineHeight: '1.5' + // Initialize template variables with defaults, then saved state + this.templateVariables = { + pageSize: 'a4', + orientation: 'portrait', + flipped: false, + marginTop: '1in', + marginBottom: '0.8in', + marginLeft: '1in', + marginRight: '0.6in', + bodyFont: 'Concourse OT', + headingFont: 'Concourse OT', + monospaceFont: 'Source Code Pro', + bodyFontSize: '11pt', + ...savedState?.templateVariables, + ...this.settings.templateVariables }; + + // Update settings to include merged template variables + this.settings.templateVariables = this.templateVariables; } /** - * Update typography settings + * Update template variables */ - updateTypography(updates: Partial): void { - this.typography = { - ...this.typography, + updateTemplateVariables(updates: Record): void { + this.templateVariables = { + ...this.templateVariables, ...updates }; + this.settings.templateVariables = this.templateVariables; + this.saveToStorage(); this.notifyChange(); } @@ -60,19 +78,9 @@ export class ModalState implements IModalState { 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 - } + templateVariables: this.templateVariables, + openAfterExport: this.settings.openAfterExport, + preserveFolderStructure: this.settings.preserveFolderStructure }; return config; @@ -107,17 +115,7 @@ export class ModalState implements IModalState { ...this.settings, ...updates }; - this.notifyChange(); - } - - /** - * Update template variables - */ - updateTemplateVariables(updates: Record): void { - this.settings.templateVariables = { - ...this.settings.templateVariables, - ...updates - }; + this.saveToStorage(); this.notifyChange(); } @@ -134,16 +132,74 @@ export class ModalState implements IModalState { * 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' + // Reset to plugin defaults, not localStorage defaults + this.settings = { + ...this.settings, + template: 'default.typ', + format: ExportFormat.Standard, + outputFolder: 'exports', + templateVariables: {}, + progressPercent: 0, + currentOperation: '', + isExporting: false, + canCancel: false, + openAfterExport: false, + preserveFolderStructure: false }; + + this.templateVariables = { + pageSize: 'a4', + orientation: 'portrait', + flipped: false, + marginTop: '1in', + marginBottom: '0.8in', + marginLeft: '1in', + marginRight: '0.6in', + bodyFont: 'Concourse OT', + headingFont: 'Concourse OT', + monospaceFont: 'Source Code Pro', + bodyFontSize: '11pt' + }; + + this.settings.templateVariables = this.templateVariables; + this.saveToStorage(); this.notifyChange(); } + + /** + * Save current state to localStorage + */ + private saveToStorage(): void { + const stateToSave = { + settings: { + template: this.settings.template, + format: this.settings.format, + outputFolder: this.settings.outputFolder, + openAfterExport: this.settings.openAfterExport, + preserveFolderStructure: this.settings.preserveFolderStructure + }, + templateVariables: this.templateVariables + }; + + try { + localStorage.setItem(ModalState.STORAGE_KEY, JSON.stringify(stateToSave)); + } catch (error) { + console.warn('Failed to save modal state to localStorage:', error); + } + } + + /** + * Load state from localStorage + */ + private loadFromStorage(): { settings: Partial, templateVariables: Record } | null { + try { + const saved = localStorage.getItem(ModalState.STORAGE_KEY); + if (saved) { + return JSON.parse(saved); + } + } catch (error) { + console.warn('Failed to load modal state from localStorage:', error); + } + return null; + } } \ No newline at end of file