fix: resolve export modal and PDF embed processing issues
- Fix font size duplication bug (11pt11pt) in exportFileWithConfig - Fix modal settings not being respected by removing conditional fallbacks - Fix Export Current Note to include complete template variables - Fix PDF embed processing temp directory from system temp to plugin temp - Fix pdf2img to use relative paths instead of absolute paths for proper file creation - Ensure temp-images directory exists before PDF processing The export modal now properly respects all user settings and PDF embeds are correctly processed and found during export operations. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
5 files changed
+614
-435
No files matched your search
@@ -22,6 +22,7 @@ import { PandocTypstConverter } from './src/converters/PandocTypstConverter';
|
|||||||
import { ExportConfigModal } from './src/modal/ExportConfigModal';
|
import { ExportConfigModal } from './src/modal/ExportConfigModal';
|
||||||
import { ExportConfig, ExportConfigModalSettings } from './src/modal/types';
|
import { ExportConfig, ExportConfigModalSettings } from './src/modal/types';
|
||||||
import { TemplateManager } from './src/templates/TemplateManager';
|
import { TemplateManager } from './src/templates/TemplateManager';
|
||||||
|
import { FolderSuggest } from './src/components/FolderSuggest';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
|
|
||||||
@@ -55,8 +56,108 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
// Check dependencies on startup (async, don't await)
|
// Check dependencies on startup (async, don't await)
|
||||||
this.checkDependenciesAsync();
|
this.checkDependenciesAsync();
|
||||||
|
|
||||||
|
// Cache available fonts (async, don't await)
|
||||||
|
this.cacheAvailableFonts();
|
||||||
|
|
||||||
console.log('Obsidian Typst PDF Export plugin loaded');
|
console.log('Obsidian Typst PDF Export plugin loaded');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache available fonts from typst to a file for quick access
|
||||||
|
*/
|
||||||
|
private async cacheAvailableFonts(): Promise<void> {
|
||||||
|
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<string[]> {
|
||||||
|
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 {
|
private registerCommands(): void {
|
||||||
// Export current note command
|
// Export current note command
|
||||||
@@ -210,38 +311,62 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
* Show the export configuration modal
|
* Show the export configuration modal
|
||||||
*/
|
*/
|
||||||
private async showExportModal(view: MarkdownView): Promise<void> {
|
private async showExportModal(view: MarkdownView): Promise<void> {
|
||||||
const file = view.file;
|
const file = view.file;
|
||||||
if (!file) {
|
if (!file) {
|
||||||
new Notice('No active file to export');
|
new Notice('No active file to export');
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
|
|
||||||
// Prepare modal settings
|
|
||||||
const modalSettings: Partial<ExportConfigModalSettings> = {
|
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get available templates first
|
||||||
|
const availableTemplates = await this.templateManager.getAvailableTemplates();
|
||||||
|
|
||||||
|
// Prepare modal settings with hierarchy: plugin defaults as base
|
||||||
|
const modalSettings: Partial<ExportConfigModalSettings> = {
|
||||||
|
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
|
* Export a file with default configuration
|
||||||
*/
|
*/
|
||||||
@@ -250,11 +375,23 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
template: this.settings.exportDefaults.template,
|
template: this.settings.exportDefaults.template,
|
||||||
format: this.settings.exportDefaults.format,
|
format: this.settings.exportDefaults.format,
|
||||||
outputFolder: this.settings.outputFolder,
|
outputFolder: this.settings.outputFolder,
|
||||||
typography: {
|
templateVariables: {
|
||||||
fontFamily: this.settings.typography.fonts.body,
|
// Page setup
|
||||||
fontSize: `${this.settings.typography.fontSizes.body}pt`,
|
pageSize: this.settings.exportDefaults.pageSize,
|
||||||
lineHeight: '1.5'
|
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);
|
await this.exportFileWithConfig(file, config);
|
||||||
@@ -278,9 +415,14 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
const content = await this.app.vault.read(file);
|
const content = await this.app.vault.read(file);
|
||||||
const pluginDir = path.join(vaultPath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export');
|
const pluginDir = path.join(vaultPath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export');
|
||||||
|
|
||||||
// Create temp directory for processing
|
// Create temp directory for processing - use plugin's temp directory
|
||||||
const os = require('os');
|
const tempDir = path.join(pluginDir, 'temp-images');
|
||||||
const tempDir = os.tmpdir();
|
|
||||||
|
// Ensure temp directory exists
|
||||||
|
const fs = require('fs');
|
||||||
|
if (!fs.existsSync(tempDir)) {
|
||||||
|
fs.mkdirSync(tempDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
// Preprocess the markdown content using MarkdownPreprocessor
|
// Preprocess the markdown content using MarkdownPreprocessor
|
||||||
const { MarkdownPreprocessor } = await import('./src/MarkdownPreprocessor');
|
const { MarkdownPreprocessor } = await import('./src/MarkdownPreprocessor');
|
||||||
@@ -333,12 +475,7 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
outputPath,
|
outputPath,
|
||||||
{
|
{
|
||||||
template: templatePath,
|
template: templatePath,
|
||||||
variables: {
|
variables: config.templateVariables || {},
|
||||||
...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,
|
pluginDir: pluginDir,
|
||||||
vaultBasePath: vaultPath
|
vaultBasePath: vaultPath
|
||||||
},
|
},
|
||||||
@@ -821,34 +958,6 @@ ${missingDeps.length > 0 ?
|
|||||||
/**
|
/**
|
||||||
* Settings Tab
|
* Settings Tab
|
||||||
*/
|
*/
|
||||||
class FolderSuggest extends AbstractInputSuggest<string> {
|
|
||||||
private folders: string[];
|
|
||||||
private inputElement: HTMLInputElement;
|
|
||||||
|
|
||||||
constructor(app: App, inputEl: HTMLInputElement) {
|
|
||||||
super(app, inputEl);
|
|
||||||
this.inputElement = inputEl;
|
|
||||||
this.folders = ["/"].concat(this.app.vault.getAllFolders().map(folder => folder.path));
|
|
||||||
}
|
|
||||||
|
|
||||||
getSuggestions(inputStr: string): string[] {
|
|
||||||
const inputLower = inputStr.toLowerCase();
|
|
||||||
return this.folders.filter(folder =>
|
|
||||||
folder.toLowerCase().includes(inputLower)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderSuggestion(folder: string, el: HTMLElement): void {
|
|
||||||
el.createEl("div", { text: folder });
|
|
||||||
}
|
|
||||||
|
|
||||||
selectSuggestion(folder: string): void {
|
|
||||||
this.inputElement.value = folder;
|
|
||||||
this.inputElement.dispatchEvent(new Event('input'));
|
|
||||||
this.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||||
plugin: obsidianTypstPDFExport;
|
plugin: obsidianTypstPDFExport;
|
||||||
|
|
||||||
@@ -1194,37 +1303,7 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
|||||||
|
|
||||||
// Helper methods for fonts
|
// Helper methods for fonts
|
||||||
private async getAvailableFonts(): Promise<string[]> {
|
private async getAvailableFonts(): Promise<string[]> {
|
||||||
try {
|
return await this.plugin.getCachedFonts();
|
||||||
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'
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper methods for margin conversion
|
// Helper methods for margin conversion
|
||||||
|
|||||||
+55
-12
@@ -90,6 +90,11 @@ export class PdfToImageConverter {
|
|||||||
// Ensure output directory exists
|
// Ensure output directory exists
|
||||||
await fs.mkdir(outputDir, { recursive: true });
|
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
|
// Generate output file name for the first page
|
||||||
const pdfBaseName = path.basename(pdfPath, path.extname(pdfPath));
|
const pdfBaseName = path.basename(pdfPath, path.extname(pdfPath));
|
||||||
// pdf2img uses the pattern: "filename-1.png" for first page
|
// pdf2img uses the pattern: "filename-1.png" for first page
|
||||||
@@ -147,7 +152,7 @@ export class PdfToImageConverter {
|
|||||||
`"${pdf2imgPath}"`,
|
`"${pdf2imgPath}"`,
|
||||||
`"${pdfPath}"`,
|
`"${pdfPath}"`,
|
||||||
'--scale', opts.scale.toString(),
|
'--scale', opts.scale.toString(),
|
||||||
'--output', `"${outputDir}"`,
|
'--output', `"${relativeOutputDir}"`,
|
||||||
'--pages', '1' // Only convert the first page
|
'--pages', '1' // Only convert the first page
|
||||||
].join(' ');
|
].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}`);
|
console.log(`PDF conversion stdout: ${result.stdout}`);
|
||||||
if (result.stderr) {
|
if (result.stderr) {
|
||||||
console.warn(`PDF conversion stderr: ${result.stderr}`);
|
console.warn(`PDF conversion stderr: ${result.stderr}`);
|
||||||
@@ -183,16 +190,52 @@ export class PdfToImageConverter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check if the expected output file exists
|
// Check if the expected output file exists
|
||||||
|
let actualOutputPath = expectedOutputPath;
|
||||||
try {
|
try {
|
||||||
await fs.access(expectedOutputPath);
|
await fs.access(expectedOutputPath);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return {
|
// Debug: List what files are actually in the output directory
|
||||||
imagePath: '',
|
try {
|
||||||
originalDimensions: { width: 0, height: 0 },
|
const files = await fs.readdir(outputDir);
|
||||||
imageDimensions: { width: 0, height: 0 },
|
console.log(`Files in output directory (${outputDir}):`, files);
|
||||||
success: false,
|
|
||||||
error: `Generated image file not found: ${expectedOutputPath}`
|
// 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
|
// Rename to our desired format if needed
|
||||||
@@ -204,17 +247,17 @@ export class PdfToImageConverter {
|
|||||||
// Convert PNG to JPEG if needed
|
// Convert PNG to JPEG if needed
|
||||||
try {
|
try {
|
||||||
const sharp = require('sharp');
|
const sharp = require('sharp');
|
||||||
const inputBuffer = await fs.readFile(expectedOutputPath);
|
const inputBuffer = await fs.readFile(actualOutputPath);
|
||||||
buffer = await sharp(inputBuffer)
|
buffer = await sharp(inputBuffer)
|
||||||
.jpeg({ quality: opts.quality })
|
.jpeg({ quality: opts.quality })
|
||||||
.toBuffer();
|
.toBuffer();
|
||||||
await fs.writeFile(finalOutputPath, buffer);
|
await fs.writeFile(finalOutputPath, buffer);
|
||||||
// Clean up the original PNG
|
// Clean up the original PNG
|
||||||
await fs.unlink(expectedOutputPath);
|
await fs.unlink(actualOutputPath);
|
||||||
} catch (sharpError) {
|
} catch (sharpError) {
|
||||||
console.warn('Sharp not available for JPEG conversion, keeping PNG format');
|
console.warn('Sharp not available for JPEG conversion, keeping PNG format');
|
||||||
// Just rename the file
|
// Just rename the file
|
||||||
await fs.rename(expectedOutputPath, finalOutputPath);
|
await fs.rename(actualOutputPath, finalOutputPath);
|
||||||
buffer = await fs.readFile(finalOutputPath);
|
buffer = await fs.readFile(finalOutputPath);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -255,214 +255,257 @@ export class PandocTypstConverter {
|
|||||||
* Build pandoc command-line arguments
|
* Build pandoc command-line arguments
|
||||||
*/
|
*/
|
||||||
private async buildPandocArgs(inputPath: string, outputPath: string): Promise<string[]> {
|
private async buildPandocArgs(inputPath: string, outputPath: string): Promise<string[]> {
|
||||||
const args: string[] = [];
|
const args: string[] = [];
|
||||||
|
|
||||||
// Input file
|
// Input file
|
||||||
args.push(inputPath);
|
args.push(inputPath);
|
||||||
|
|
||||||
// Output file
|
// Output file
|
||||||
args.push('-o', outputPath);
|
args.push('-o', outputPath);
|
||||||
|
|
||||||
// Specify input format as markdown with smart extension disabled
|
// Specify input format as markdown with smart extension disabled
|
||||||
args.push('--from', 'markdown-smart');
|
args.push('--from', 'markdown-smart');
|
||||||
|
|
||||||
// Set PDF engine to Typst (use configured path if available)
|
// Set PDF engine to Typst (use configured path if available)
|
||||||
if (this.pandocOptions.typstPath) {
|
if (this.pandocOptions.typstPath) {
|
||||||
args.push(`--pdf-engine=${this.pandocOptions.typstPath}`);
|
args.push(`--pdf-engine=${this.pandocOptions.typstPath}`);
|
||||||
} else {
|
} else {
|
||||||
args.push('--pdf-engine=typst');
|
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)
|
// Use universal wrapper with --template and pass actual template as template_path variable
|
||||||
args.push('--standalone');
|
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
|
// Add variables from the ExportConfig (these take priority)
|
||||||
args.push('--embed-resources');
|
// 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
|
// Add fallback typography and page setup from plugin settings
|
||||||
if (this.pandocOptions.vaultBasePath) {
|
// Only add these if not already provided by ExportConfig variables
|
||||||
const fs = require('fs');
|
if (this.plugin && this.plugin.settings) {
|
||||||
|
const settings: obsidianTypstPDFExportSettings = this.plugin.settings;
|
||||||
// Add vault root as primary resource path
|
const existingVars = this.pandocOptions.variables || {};
|
||||||
args.push('--resource-path', this.pandocOptions.vaultBasePath);
|
|
||||||
|
// Add typography variables only if not already present in variables
|
||||||
// Add common attachment directories as additional resource paths
|
if (settings.typography) {
|
||||||
const commonAttachmentPaths = [
|
if (settings.typography.fonts) {
|
||||||
path.join(this.pandocOptions.vaultBasePath, 'attachments'),
|
// Only add if not already in variables from ExportConfig
|
||||||
path.join(this.pandocOptions.vaultBasePath, 'assets'),
|
if (!existingVars.bodyFont && !existingVars.font && settings.typography.fonts.body) {
|
||||||
path.join(this.pandocOptions.vaultBasePath, 'files'),
|
args.push('-V', `font=${settings.typography.fonts.body}`);
|
||||||
path.join(this.pandocOptions.vaultBasePath, 'images'),
|
}
|
||||||
path.join(this.pandocOptions.vaultBasePath, '.attachments')
|
if (!existingVars.headingFont && !existingVars.heading_font && settings.typography.fonts.heading) {
|
||||||
];
|
args.push('-V', `heading_font=${settings.typography.fonts.heading}`);
|
||||||
|
}
|
||||||
// Check if these directories exist and add them
|
if (!existingVars.monospaceFont && !existingVars.monospace_font && settings.typography.fonts.monospace) {
|
||||||
for (const attachPath of commonAttachmentPaths) {
|
args.push('-V', `monospace_font=${settings.typography.fonts.monospace}`);
|
||||||
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)
|
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 {
|
try {
|
||||||
const vaultContents = fs.readdirSync(this.pandocOptions.vaultBasePath);
|
const fs = require('fs');
|
||||||
for (const item of vaultContents) {
|
if (fs.existsSync(typstPath)) {
|
||||||
const itemPath = path.join(this.pandocOptions.vaultBasePath, item);
|
fs.copyFileSync(typstPath, debugTypstPath);
|
||||||
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) {
|
} 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
|
* Execute pandoc process with the given arguments
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ import { ExportConfig, ExportConfigModalSettings, ModalSection } from './types';
|
|||||||
import { ModalState } from './state/ModalState';
|
import { ModalState } from './state/ModalState';
|
||||||
import { GeneralSection } from './sections/GeneralSection';
|
import { GeneralSection } from './sections/GeneralSection';
|
||||||
import { TypographySection } from './sections/TypographySection';
|
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';
|
import { TemplateManager } from '../templates/TemplateManager';
|
||||||
|
|
||||||
export class ExportConfigModal extends Modal {
|
export class ExportConfigModal extends Modal {
|
||||||
@@ -27,6 +28,7 @@ export class ExportConfigModal extends Modal {
|
|||||||
private progressText: HTMLElement;
|
private progressText: HTMLElement;
|
||||||
private submitButton: HTMLButtonElement;
|
private submitButton: HTMLButtonElement;
|
||||||
private cancelButton: HTMLButtonElement;
|
private cancelButton: HTMLButtonElement;
|
||||||
|
private resetButton: HTMLButtonElement;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
app: App,
|
app: App,
|
||||||
@@ -54,8 +56,9 @@ export class ExportConfigModal extends Modal {
|
|||||||
// Register all modal sections
|
// Register all modal sections
|
||||||
const sections = [
|
const sections = [
|
||||||
new GeneralSection(),
|
new GeneralSection(),
|
||||||
|
new PageSetupSection(),
|
||||||
new TypographySection(),
|
new TypographySection(),
|
||||||
new LayoutSection()
|
new BehaviorSection()
|
||||||
];
|
];
|
||||||
|
|
||||||
sections.forEach(section => {
|
sections.forEach(section => {
|
||||||
@@ -110,41 +113,8 @@ export class ExportConfigModal extends Modal {
|
|||||||
|
|
||||||
// Render each section
|
// Render each section
|
||||||
this.sections.forEach(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 {
|
private createProgressContainer(): void {
|
||||||
@@ -171,15 +141,25 @@ export class ExportConfigModal extends Modal {
|
|||||||
private createActionButtons(): void {
|
private createActionButtons(): void {
|
||||||
const buttonContainer = this.contentContainer.createDiv('export-config-buttons');
|
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
|
// Cancel button
|
||||||
this.cancelButton = buttonContainer.createEl('button', {
|
this.cancelButton = rightButtons.createEl('button', {
|
||||||
text: 'Cancel',
|
text: 'Cancel',
|
||||||
cls: 'mod-cancel'
|
cls: 'mod-cancel'
|
||||||
});
|
});
|
||||||
this.cancelButton.addEventListener('click', () => this.handleCancel());
|
this.cancelButton.addEventListener('click', () => this.handleCancel());
|
||||||
|
|
||||||
// Export button
|
// Export button
|
||||||
this.submitButton = buttonContainer.createEl('button', {
|
this.submitButton = rightButtons.createEl('button', {
|
||||||
text: 'Export',
|
text: 'Export',
|
||||||
cls: 'mod-cta'
|
cls: 'mod-cta'
|
||||||
});
|
});
|
||||||
@@ -211,6 +191,19 @@ export class ExportConfigModal extends Modal {
|
|||||||
// This is called whenever the state is updated
|
// 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<void> {
|
private async handleSubmit(): Promise<void> {
|
||||||
// Validate all sections
|
// Validate all sections
|
||||||
const validationResults = this.validateAllSections();
|
const validationResults = this.validateAllSections();
|
||||||
@@ -233,6 +226,7 @@ export class ExportConfigModal extends Modal {
|
|||||||
|
|
||||||
// Disable buttons
|
// Disable buttons
|
||||||
this.submitButton.disabled = true;
|
this.submitButton.disabled = true;
|
||||||
|
this.resetButton.disabled = true;
|
||||||
this.cancelButton.textContent = 'Close';
|
this.cancelButton.textContent = 'Close';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -248,6 +242,7 @@ export class ExportConfigModal extends Modal {
|
|||||||
console.error('Export failed:', error);
|
console.error('Export failed:', error);
|
||||||
this.showProgress(`Export failed: ${error.message}`, -1);
|
this.showProgress(`Export failed: ${error.message}`, -1);
|
||||||
this.submitButton.disabled = false;
|
this.submitButton.disabled = false;
|
||||||
|
this.resetButton.disabled = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -386,29 +381,6 @@ export class ExportConfigModal extends Modal {
|
|||||||
color: var(--text-muted);
|
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 {
|
.export-progress-container {
|
||||||
padding: 40px;
|
padding: 40px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
@@ -442,7 +414,12 @@ export class ExportConfigModal extends Modal {
|
|||||||
padding: 20px;
|
padding: 20px;
|
||||||
border-top: 1px solid var(--background-modifier-border);
|
border-top: 1px solid var(--background-modifier-border);
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: flex-end;
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-config-buttons .right-buttons {
|
||||||
|
display: flex;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -463,31 +440,12 @@ export class ExportConfigModal extends Modal {
|
|||||||
padding-left: 20px;
|
padding-left: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.margin-preset-button {
|
|
||||||
margin: 0 5px;
|
|
||||||
padding: 2px 10px;
|
|
||||||
font-size: 0.85em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.margins-container {
|
.margins-container {
|
||||||
background: var(--background-secondary-alt);
|
background: var(--background-secondary-alt);
|
||||||
padding: 15px;
|
padding: 15px;
|
||||||
border-radius: 5px;
|
border-radius: 5px;
|
||||||
margin-top: 15px;
|
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);
|
document.head.appendChild(style);
|
||||||
}
|
}
|
||||||
|
|||||||
+104
-48
@@ -8,16 +8,16 @@ import { ExportFormat } from '../../core/settings';
|
|||||||
|
|
||||||
export class ModalState implements IModalState {
|
export class ModalState implements IModalState {
|
||||||
settings: ExportConfigModalSettings;
|
settings: ExportConfigModalSettings;
|
||||||
typography: {
|
templateVariables: Record<string, any>;
|
||||||
fontFamily: string;
|
|
||||||
fontSize: string;
|
|
||||||
lineHeight: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
private changeListeners: Set<() => void> = new Set();
|
private changeListeners: Set<() => void> = new Set();
|
||||||
|
private static readonly STORAGE_KEY = 'typst-export-modal-state';
|
||||||
|
|
||||||
constructor(initialSettings: Partial<ExportConfigModalSettings>) {
|
constructor(initialSettings: Partial<ExportConfigModalSettings>) {
|
||||||
// Initialize with defaults
|
// Load from localStorage if available
|
||||||
|
const savedState = this.loadFromStorage();
|
||||||
|
|
||||||
|
// Initialize with defaults, then saved state, then passed settings
|
||||||
this.settings = {
|
this.settings = {
|
||||||
notePath: '',
|
notePath: '',
|
||||||
noteTitle: '',
|
noteTitle: '',
|
||||||
@@ -30,25 +30,43 @@ export class ModalState implements IModalState {
|
|||||||
progressPercent: 0,
|
progressPercent: 0,
|
||||||
currentOperation: '',
|
currentOperation: '',
|
||||||
canCancel: false,
|
canCancel: false,
|
||||||
|
openAfterExport: false,
|
||||||
|
preserveFolderStructure: false,
|
||||||
|
...savedState?.settings,
|
||||||
...initialSettings
|
...initialSettings
|
||||||
};
|
};
|
||||||
|
|
||||||
// Initialize typography with defaults that will be passed to template
|
// Initialize template variables with defaults, then saved state
|
||||||
this.typography = {
|
this.templateVariables = {
|
||||||
fontFamily: 'Concourse OT',
|
pageSize: 'a4',
|
||||||
fontSize: '11pt',
|
orientation: 'portrait',
|
||||||
lineHeight: '1.5'
|
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<ModalState['typography']>): void {
|
updateTemplateVariables(updates: Record<string, any>): void {
|
||||||
this.typography = {
|
this.templateVariables = {
|
||||||
...this.typography,
|
...this.templateVariables,
|
||||||
...updates
|
...updates
|
||||||
};
|
};
|
||||||
|
this.settings.templateVariables = this.templateVariables;
|
||||||
|
this.saveToStorage();
|
||||||
this.notifyChange();
|
this.notifyChange();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,19 +78,9 @@ export class ModalState implements IModalState {
|
|||||||
template: this.settings.template,
|
template: this.settings.template,
|
||||||
format: this.settings.format,
|
format: this.settings.format,
|
||||||
outputFolder: this.settings.outputFolder,
|
outputFolder: this.settings.outputFolder,
|
||||||
templateVariables: {
|
templateVariables: this.templateVariables,
|
||||||
...this.settings.templateVariables,
|
openAfterExport: this.settings.openAfterExport,
|
||||||
// Add typography settings to template variables
|
preserveFolderStructure: this.settings.preserveFolderStructure
|
||||||
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;
|
return config;
|
||||||
@@ -107,17 +115,7 @@ export class ModalState implements IModalState {
|
|||||||
...this.settings,
|
...this.settings,
|
||||||
...updates
|
...updates
|
||||||
};
|
};
|
||||||
this.notifyChange();
|
this.saveToStorage();
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update template variables
|
|
||||||
*/
|
|
||||||
updateTemplateVariables(updates: Record<string, any>): void {
|
|
||||||
this.settings.templateVariables = {
|
|
||||||
...this.settings.templateVariables,
|
|
||||||
...updates
|
|
||||||
};
|
|
||||||
this.notifyChange();
|
this.notifyChange();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,16 +132,74 @@ export class ModalState implements IModalState {
|
|||||||
* Reset state to defaults
|
* Reset state to defaults
|
||||||
*/
|
*/
|
||||||
reset(): void {
|
reset(): void {
|
||||||
this.settings.templateVariables = {};
|
// Reset to plugin defaults, not localStorage defaults
|
||||||
this.settings.progressPercent = 0;
|
this.settings = {
|
||||||
this.settings.currentOperation = '';
|
...this.settings,
|
||||||
this.settings.isExporting = false;
|
template: 'default.typ',
|
||||||
this.settings.canCancel = false;
|
format: ExportFormat.Standard,
|
||||||
this.typography = {
|
outputFolder: 'exports',
|
||||||
fontFamily: 'Concourse OT',
|
templateVariables: {},
|
||||||
fontSize: '11pt',
|
progressPercent: 0,
|
||||||
lineHeight: '1.5'
|
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();
|
this.notifyChange();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save current state to localStorage
|
||||||
|
*/
|
||||||
|
private saveToStorage(): void {
|
||||||
|
const stateToSave = {
|
||||||
|
settings: {
|
||||||
|
template: this.settings.template,
|
||||||
|
format: this.settings.format,
|
||||||
|
outputFolder: this.settings.outputFolder,
|
||||||
|
openAfterExport: this.settings.openAfterExport,
|
||||||
|
preserveFolderStructure: this.settings.preserveFolderStructure
|
||||||
|
},
|
||||||
|
templateVariables: this.templateVariables
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
localStorage.setItem(ModalState.STORAGE_KEY, JSON.stringify(stateToSave));
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to save modal state to localStorage:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load state from localStorage
|
||||||
|
*/
|
||||||
|
private loadFromStorage(): { settings: Partial<ExportConfigModalSettings>, templateVariables: Record<string, any> } | null {
|
||||||
|
try {
|
||||||
|
const saved = localStorage.getItem(ModalState.STORAGE_KEY);
|
||||||
|
if (saved) {
|
||||||
|
return JSON.parse(saved);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to load modal state from localStorage:', error);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user