feat: refactor export system and improve PDF/email handling

Major improvements to PDF export functionality and code organization:

- BREAKING: Refactor main.ts from 4224 to 994 lines by extracting modular components
- Replace broken PDF links with proper Typst pdf.embed() attachments
- Filter out unnecessary "Open:" links and Mail.app links from exports
- Fix duplicate title issue by replacing frontmatter title with filename
- Move temp file processing from system temp to plugin folder
- Clean up temp-images and temp-pandoc directories after export
- Remove timestamp from export filenames to match note names exactly
- Handle Unicode line separators (0x2028, 0x2029) in email content
- Improve markdown preprocessing with better frontmatter handling

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Jarvis committed 2025-09-02 17:16:55 +02:00
1 parent 175fad5b4e
commit 172a69161d
20 files changed
+7166 -3936

No files matched your search

+642 -3872
View File
File diff suppressed because it is too large. Load diff
+4224
View File
File diff suppressed because it is too large. Load diff
+142 -22
View File
@@ -58,12 +58,15 @@ export interface MarkdownPreprocessorConfig {
options: PreprocessorOptions;
/** Wikilink conversion configuration */
wikilinkConfig: WikilinkConfig;
/** Note title to add as H1 heading at top (optional) */
noteTitle?: string;
}
export class MarkdownPreprocessor {
private vaultPath: string;
private options: PreprocessorOptions;
private wikilinkConfig: WikilinkConfig;
private noteTitle?: string;
// Regex patterns for Obsidian syntax
private readonly WIKILINK_PATTERN = /\[\[([^\|\]]+)(?:\|([^\]]+))?\]\]/g;
@@ -80,6 +83,7 @@ export class MarkdownPreprocessor {
this.vaultPath = config.vaultPath;
this.options = config.options;
this.wikilinkConfig = config.wikilinkConfig;
this.noteTitle = config.noteTitle;
}
/**
@@ -117,16 +121,19 @@ export class MarkdownPreprocessor {
// Step 3: Convert email blocks to Typst format
result.content = this.parseEmailBlocks(result.content, result);
// Step 4: Convert embeds FIRST (before wikilinks to avoid .md extension being added)
// Step 4: Filter out unnecessary links (Open: links and Mail.app links)
result.content = this.filterUnnecessaryLinks(result.content, result);
// Step 5: Convert embeds FIRST (before wikilinks to avoid .md extension being added)
result.content = this.parseEmbeds(result.content, result);
// Step 5: Convert wikilinks (after embeds are processed)
// Step 6: Convert wikilinks (after embeds are processed)
result.content = this.parseWikilinks(result.content, result);
// Step 6: Convert callouts
// Step 7: Convert callouts
result.content = this.parseCallouts(result.content, result);
// Step 7: Calculate final metadata
// Step 8: Calculate final metadata
result.metadata.wordCount = this.calculateWordCount(result.content);
// Use title from frontmatter if available, otherwise extract from content
@@ -151,7 +158,14 @@ export class MarkdownPreprocessor {
const parsed = matter(content);
if (parsed.data && Object.keys(parsed.data).length > 0) {
result.metadata.frontmatter = parsed.data;
// Replace frontmatter title with filename if noteTitle is provided
if (this.noteTitle) {
const frontmatterCopy = { ...parsed.data };
frontmatterCopy.title = this.noteTitle;
result.metadata.frontmatter = frontmatterCopy;
} else {
result.metadata.frontmatter = parsed.data;
}
// Extract tags from frontmatter if they exist
if (parsed.data.tags) {
@@ -178,21 +192,45 @@ export class MarkdownPreprocessor {
}
}
// Extract title from frontmatter if available
if (parsed.data.title && typeof parsed.data.title === 'string') {
// Extract title - use noteTitle if available, otherwise frontmatter title
if (this.noteTitle) {
result.metadata.title = this.noteTitle;
} else if (parsed.data.title && typeof parsed.data.title === 'string') {
result.metadata.title = parsed.data.title.trim();
}
if (this.options.preserveFrontmatter) {
// Keep the frontmatter in the content
return content;
// Keep the frontmatter in the content, but reconstruct it with the modified title
if (this.noteTitle) {
const yaml = require('js-yaml');
const frontmatterCopy = { ...parsed.data };
frontmatterCopy.title = this.noteTitle;
const newFrontmatter = yaml.dump(frontmatterCopy);
return `---\n${newFrontmatter}---\n${parsed.content}`;
} else {
return content;
}
} else {
// Return content without frontmatter
return parsed.content;
// Return content without frontmatter, but add title as frontmatter for Pandoc
if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
console.log('Replacing frontmatter with title:', titleFrontmatter);
return `---\n${titleFrontmatter}---\n${parsed.content}`;
} else {
return parsed.content;
}
}
} else {
// No frontmatter found, return original content
return content;
// No frontmatter found - add title frontmatter if we have a noteTitle
if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
console.log('Adding title frontmatter:', titleFrontmatter);
return `---\n${titleFrontmatter}---\n${content}`;
} else {
return content;
}
}
} catch (error: any) {
result.warnings.push(`Failed to parse frontmatter with gray-matter: ${error.message}`);
@@ -216,12 +254,31 @@ export class MarkdownPreprocessor {
}
}
// Replace title with noteTitle if provided
if (this.noteTitle) {
frontmatter.title = this.noteTitle;
}
result.metadata.frontmatter = frontmatter;
if (this.options.preserveFrontmatter) {
return content;
// Reconstruct frontmatter with modified title
if (this.noteTitle) {
const yaml = require('js-yaml');
const newFrontmatter = yaml.dump(frontmatter);
return content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`);
} else {
return content;
}
} else {
return content.replace(this.FRONTMATTER_PATTERN, '');
// Add title as frontmatter for Pandoc even when not preserving original
if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
return content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`);
} else {
return content.replace(this.FRONTMATTER_PATTERN, '');
}
}
} catch (fallbackError: any) {
result.warnings.push(`Fallback frontmatter parsing also failed: ${fallbackError.message}`);
@@ -517,7 +574,7 @@ export class MarkdownPreprocessor {
}
/**
* Process PDF embeds - Convert to image preview with PDF attachment
* Process PDF embeds - Convert to image preview with PDF attachment using Typst's pdf.embed
*/
private processPdfEmbed(pdfPath: string, options: string | undefined, result: PreprocessingResult): string {
const sanitizedPath = this.sanitizeFilePath(pdfPath);
@@ -527,8 +584,8 @@ export class MarkdownPreprocessor {
const fileName = pdfPath.substring(pdfPath.lastIndexOf('/') + 1);
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
// Create a marker that the export process can detect and replace
const marker = `PDF_EMBED_MARKER:${pdfPath}:${baseName}:${options || ''}`;
// Create a marker that the export process can detect and replace with Typst code
const marker = `TYPST_PDF_EMBED_MARKER:${pdfPath}:${baseName}:${options || ''}`;
// Add to processing queue for later conversion
if (!result.metadata.pdfEmbeds) {
@@ -543,7 +600,7 @@ export class MarkdownPreprocessor {
marker: marker
});
result.warnings.push(`PDF embed queued for image conversion: ${pdfPath}`);
result.warnings.push(`PDF embed queued for processing with Typst pdf.embed: ${pdfPath}`);
return marker;
}
@@ -570,6 +627,25 @@ export class MarkdownPreprocessor {
}
});
}
/**
* Filter out unnecessary links from the markdown content
* This includes [[filename|Open: filename]] links and [Open in Mail.app](message://) links
*/
private filterUnnecessaryLinks(content: string, result: PreprocessingResult): string {
// Remove [[filename|Open: filename]] links from general content
let filtered = content.replace(/\[\[.*?\|Open:.*?\]\]/g, '');
// Remove [Open in Mail.app](message://) links from general content
filtered = filtered.replace(/\[Open in Mail\.app\]\(message:\/\/[^)]+\)/g, '');
// Clean up any resulting excessive newlines
filtered = filtered.replace(/\n{3,}/g, '\n\n');
result.warnings.push('Filtered out unnecessary Open: and Mail.app links from content');
return filtered;
}
/**
* Process individual email block content and convert to Typst format
@@ -579,7 +655,15 @@ export class MarkdownPreprocessor {
// Split at --- to separate header from body
const parts = blockContent.split('---');
const yamlHeader = parts[0].trim();
const body = parts.length > 1 ? parts.slice(1).join('---').trim() : '';
let body = parts.length > 1 ? parts.slice(1).join('---').trim() : '';
// Filter out unnecessary links from the body
// Remove [[filename|Open: filename]] links
body = body.replace(/\[\[.*?\|Open:.*?\]\]/g, '');
// Remove [Open in Mail.app](message://) links
body = body.replace(/\[Open in Mail\.app\]\(message:\/\/[^)]+\)/g, '');
// Clean up any resulting double newlines
body = body.replace(/\n{3,}/g, '\n\n').trim();
// Parse YAML header
const params = this.parseEmailYaml(yamlHeader);
@@ -602,8 +686,8 @@ export class MarkdownPreprocessor {
}
// Add body as string parameter (always present, even if empty)
// Use the formatBodyForTypst method to preserve paragraphs but keep as string
const bodyParam = `"${this.escapeQuotes(body)}"`;
// Use the escapeQuotes method to preserve paragraphs but keep as string
const bodyParam = `"${this.escapeBodyForTypst(body)}"`;
// Construct the Typst email-block function call with proper line breaks
// Wrap in Pandoc raw blocks so it's treated as Typst code, not markdown text
@@ -710,6 +794,42 @@ export class MarkdownPreprocessor {
.replace(/\r/g, '\\r'); // Convert carriage returns
}
/**
* Escape text for Typst string parameters while preserving actual newlines
* Used specifically for email body content where we want to keep paragraph breaks
* Also cleans up problematic Unicode characters that cause formatting issues
*/
private escapeBodyForTypst(text: string): string {
if (!text) return '';
// First, clean up problematic Unicode characters
let cleaned = text
// Replace various Unicode spaces with regular spaces
.replace(/[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000\uFEFF]/g, ' ')
// Replace Unicode line separators with regular newlines
.replace(/[\u2028\u2029]/g, '\n') // Line Separator and Paragraph Separator
// Replace Unicode hyphens/dashes with regular hyphen
.replace(/[\u2010-\u2015\u2212]/g, '-')
// Remove or replace problematic symbols that can cause layout issues
.replace(/[\u2020\u2021]/g, '') // Remove dagger symbols
.replace(/[\u2022\u2023\u2043]/g, '• ') // Replace various bullets with standard bullet
// Remove zero-width characters
.replace(/[\u200B-\u200D\uFEFF]/g, '')
// Remove other problematic Unicode characters that can cause spacing issues
.replace(/[\u00AD\u061C\u180E\u2066-\u2069]/g, '')
// Normalize multiple spaces to single space (but preserve newlines)
.replace(/[ \t]+/g, ' ')
// Preserve paragraph breaks but clean up excessive newlines
.replace(/\n{3,}/g, '\n\n');
// Then escape for Typst string safety
return cleaned
.replace(/\\/g, '\\\\') // Escape backslashes first
.replace(/"/g, '\\"') // Escape double quotes
.replace(/'/g, "\\'"); // Escape single quotes
// Note: DO NOT replace newlines - they should be preserved for proper formatting
}
/**
* Process multi-line callouts with comprehensive support
*/
+628
View File
@@ -0,0 +1,628 @@
/**
* Pandoc to Typst PDF Converter
* Handles the conversion of Markdown to PDF using Pandoc with Typst engine
*/
import { spawn, ChildProcess } from 'child_process';
import * as fs from 'fs';
import { promises as fsPromises } from 'fs';
import * as path from 'path';
import * as os from 'os';
import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './types';
import type { obsidianTypstPDFExportSettings } from '../core/settings';
export class PandocTypstConverter {
private tempDir: string | null = null;
private cleanupHandlers: (() => void)[] = [];
private plugin: any; // Will be properly typed when we refactor the main plugin class
/**
* Create a new PandocTypstConverter instance
* @param plugin The main plugin instance for accessing settings
* @param pandocOptions Configuration options for Pandoc
* @param typstSettings Settings specific to Typst engine
*/
constructor(
plugin: any,
private pandocOptions: PandocOptions = {},
private typstSettings: TypstSettings = {}
) {
this.plugin = plugin;
// Set up cleanup handlers for process termination
this.setupCleanup();
}
/**
* Convert a markdown file to PDF using Pandoc with Typst engine
* @param inputPath Path to the input markdown file
* @param outputPath Path where the PDF should be saved
* @param progressCallback Optional callback for progress updates
* @returns Promise resolving to conversion result
*/
async convertToPDF(
inputPath: string,
outputPath: string,
progressCallback?: ProgressCallback
): Promise<ConversionResult> {
try {
progressCallback?.('Starting PDF conversion...', 0);
// Create temporary directory if needed
await this.ensureTempDirectory();
// Build pandoc arguments
const args = await this.buildPandocArgs(inputPath, outputPath);
progressCallback?.('Executing Pandoc with Typst engine...', 30);
// Execute pandoc process
const result = await this.executePandoc(args, progressCallback);
// Add the output path to the result if successful
if (result.success) {
result.outputPath = outputPath;
}
progressCallback?.('Conversion complete!', 100);
return result;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
success: false,
error: `Conversion failed: ${errorMessage}`
};
}
}
/**
* Convert markdown content to PDF
*/
async convertMarkdownToPDF(
content: string,
outputPath: string,
options: Partial<PandocOptions> = {},
progressCallback?: ProgressCallback
): Promise<ConversionResult> {
try {
progressCallback?.('Preparing markdown content...', 10);
// Create temporary markdown file
await this.ensureTempDirectory();
const tempInputPath = path.join(this.tempDir!, `temp-${Date.now()}.md`);
await fsPromises.writeFile(tempInputPath, content, 'utf-8');
// Merge options
this.pandocOptions = { ...this.pandocOptions, ...options };
// Convert using the file-based method
const result = await this.convertToPDF(tempInputPath, outputPath, progressCallback);
// Cleanup temp file
try {
await fsPromises.unlink(tempInputPath);
} catch (error) {
console.warn('Failed to cleanup temp file:', error);
}
return result;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
success: false,
error: `Conversion failed: ${errorMessage}`
};
}
}
/**
* Set up cleanup handlers for temporary files
*/
private setupCleanup(): void {
const cleanup = () => {
this.cleanup();
};
process.on('exit', cleanup);
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
process.on('uncaughtException', cleanup);
}
/**
* Process PDF embeds by converting them to images and creating combined output
*/
async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string): Promise<void> {
const { PdfToImageConverter } = require('../PdfToImageConverter');
const converter = PdfToImageConverter.getInstance(this.plugin);
for (const pdfEmbed of processedResult.metadata.pdfEmbeds) {
try {
console.log(`Export: Processing PDF embed: ${pdfEmbed.originalPath}`);
// Resolve full path to the PDF
const fullPdfPath = path.resolve(vaultBasePath, pdfEmbed.sanitizedPath);
// Check if PDF file exists
const fs = require('fs');
if (!fs.existsSync(fullPdfPath)) {
console.warn(`Export: PDF file not found: ${fullPdfPath}`);
// Replace marker with error message
processedResult.content = processedResult.content.replace(
pdfEmbed.marker,
`[⚠️ PDF not found: ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})`
);
continue;
}
// Convert PDF to image
const conversionResult = await converter.convertFirstPageToImage(
fullPdfPath,
tempDir,
{
scale: 1.5,
maxWidth: 600,
maxHeight: 400,
format: 'png'
}
);
if (conversionResult.success) {
// Get relative path for the generated image
const relativeImagePath = path.relative(vaultBasePath, conversionResult.imagePath);
// Create combined output: image preview + PDF attachment link
const combinedOutput = [
`![${pdfEmbed.fileName} - Page 1](${relativeImagePath})`,
`[📎 **Download PDF:** ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})`
].join('\n\n');
// Replace marker with combined output
processedResult.content = processedResult.content.replace(pdfEmbed.marker, combinedOutput);
console.log(`Export: Successfully converted PDF: ${pdfEmbed.fileName} -> ${path.basename(conversionResult.imagePath)}`);
} else {
console.error(`Export: PDF conversion failed: ${conversionResult.error}`);
// Replace marker with fallback link
processedResult.content = processedResult.content.replace(
pdfEmbed.marker,
`[📖 ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Note: PDF preview could not be generated*`
);
}
} catch (error: any) {
console.error(`Export: Error processing PDF embed: ${error.message}`);
// Replace marker with error fallback
processedResult.content = processedResult.content.replace(
pdfEmbed.marker,
`[⚠️ ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Error: Could not process PDF embed*`
);
}
}
}
/**
* Clean up temporary files and directories
*/
private async cleanup(): Promise<void> {
try {
// Execute registered cleanup handlers
this.cleanupHandlers.forEach(handler => {
try {
handler();
} catch (error) {
console.warn('Cleanup handler failed:', error);
}
});
// Remove temporary directory
if (this.tempDir) {
await fsPromises.rmdir(this.tempDir, { recursive: true });
this.tempDir = null;
}
} catch (error) {
console.warn('Cleanup failed:', error);
}
}
/**
* Ensure temporary directory exists
*/
private async ensureTempDirectory(): Promise<string> {
if (!this.tempDir) {
// Create temp directory in plugin folder instead of system temp
const pluginTempDir = this.pandocOptions.vaultBasePath
? path.join(this.pandocOptions.vaultBasePath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-pandoc')
: path.join(os.tmpdir(), 'obsidian-typst-');
// Ensure the temp directory exists
if (pluginTempDir.includes('temp-pandoc')) {
await fsPromises.mkdir(pluginTempDir, { recursive: true });
this.tempDir = pluginTempDir;
} else {
// Fallback to system temp if plugin folder not available
this.tempDir = await fsPromises.mkdtemp(pluginTempDir);
}
}
return this.tempDir;
}
/**
* Build pandoc command-line arguments
*/
private async buildPandocArgs(inputPath: string, outputPath: string): Promise<string[]> {
const args: string[] = [];
// Input file
args.push(inputPath);
// Output file
args.push('-o', outputPath);
// Specify input format as markdown with smart extension disabled
args.push('--from', 'markdown-smart');
// Set PDF engine to Typst (use configured path if available)
if (this.pandocOptions.typstPath) {
args.push(`--pdf-engine=${this.pandocOptions.typstPath}`);
} else {
args.push('--pdf-engine=typst');
}
// Enable standalone mode (required for PDF output)
args.push('--standalone');
// Embed resources (images, etc.) directly into the output
args.push('--embed-resources');
// Add resource paths for attachment resolution
if (this.pandocOptions.vaultBasePath) {
const fs = require('fs');
// Add vault root as primary resource path
args.push('--resource-path', this.pandocOptions.vaultBasePath);
// Add common attachment directories as additional resource paths
const commonAttachmentPaths = [
path.join(this.pandocOptions.vaultBasePath, 'attachments'),
path.join(this.pandocOptions.vaultBasePath, 'assets'),
path.join(this.pandocOptions.vaultBasePath, 'files'),
path.join(this.pandocOptions.vaultBasePath, 'images'),
path.join(this.pandocOptions.vaultBasePath, '.attachments')
];
// Check if these directories exist and add them
for (const attachPath of commonAttachmentPaths) {
if (fs.existsSync(attachPath)) {
args.push('--resource-path', attachPath);
console.log('Added resource path:', attachPath);
}
}
// Also scan for note-specific attachment folders (Obsidian often creates these)
try {
const vaultContents = fs.readdirSync(this.pandocOptions.vaultBasePath);
for (const item of vaultContents) {
const itemPath = path.join(this.pandocOptions.vaultBasePath, item);
const stat = fs.statSync(itemPath);
if (stat.isDirectory() && !item.startsWith('.') && !item.startsWith('_')) {
// Check if this directory contains images
try {
const dirContents = fs.readdirSync(itemPath);
const hasImages = dirContents.some((file: string) =>
/\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file)
);
if (hasImages) {
args.push('--resource-path', itemPath);
console.log('Added note-specific resource path:', itemPath);
}
} catch (e) {
// Ignore directories we can't read
}
}
}
} catch (e) {
console.warn('Could not scan vault for attachment directories:', e);
}
}
// Use universal wrapper with --template and pass actual template as template_path variable
if (this.pandocOptions.template) {
// Get absolute path to universal wrapper using plugin directory from pandocOptions
const fs = require('fs');
const absolutePluginDir = this.pandocOptions.pluginDir || '';
const wrapperPath = path.resolve(absolutePluginDir, 'templates', 'universal-wrapper.pandoc.typ');
console.log('Universal wrapper path:', wrapperPath);
// Verify wrapper exists
if (!fs.existsSync(wrapperPath)) {
throw new Error(`Universal wrapper template not found at: ${wrapperPath}`);
}
args.push('--template', wrapperPath);
// Pass the actual template path as a variable
// Make the path relative to the vault (working directory) for Typst
let templatePathForTypst = this.pandocOptions.template;
if (this.pandocOptions.vaultBasePath && path.isAbsolute(templatePathForTypst)) {
// If template path is absolute and inside vault, make it relative
if (templatePathForTypst.startsWith(this.pandocOptions.vaultBasePath)) {
templatePathForTypst = path.relative(this.pandocOptions.vaultBasePath, templatePathForTypst);
}
}
args.push('-V', `template_path=${templatePathForTypst}`);
}
// Add variables for document metadata
// These variables come from the ExportConfig and include font settings from the modal
if (this.pandocOptions.variables) {
for (const [key, value] of Object.entries(this.pandocOptions.variables)) {
if (value && value.toString().trim() !== '') {
// Don't add quotes around the value - pandoc handles this
args.push('-V', `${key}=${value}`);
}
}
}
// Only add typography settings from plugin settings if they're not already in variables
// This prevents duplicate font variables
if (this.plugin && this.plugin.settings) {
const settings: obsidianTypstPDFExportSettings = this.plugin.settings;
const existingVars = this.pandocOptions.variables || {};
// Add typography variables only if not already present in variables
if (settings.typography) {
if (settings.typography.fonts) {
// Only add if not already in variables from ExportConfig
if (!existingVars.font && settings.typography.fonts.body) {
args.push('-V', `font=${settings.typography.fonts.body}`);
}
if (!existingVars.heading_font && settings.typography.fonts.heading) {
args.push('-V', `heading_font=${settings.typography.fonts.heading}`);
}
if (!existingVars.monospace_font && settings.typography.fonts.monospace) {
args.push('-V', `monospace_font=${settings.typography.fonts.monospace}`);
}
}
if (settings.typography.fontSizes) {
if (!existingVars.fontsize && settings.typography.fontSizes.body) {
args.push('-V', `fontsize=${settings.typography.fontSizes.body}pt`);
}
if (!existingVars.heading_fontsize && settings.typography.fontSizes.heading) {
args.push('-V', `heading_fontsize=${settings.typography.fontSizes.heading}pt`);
}
if (!existingVars.small_fontsize && settings.typography.fontSizes.small) {
args.push('-V', `small_fontsize=${settings.typography.fontSizes.small}pt`);
}
}
}
// Add page setup variables
if (settings.pageSetup) {
if (settings.pageSetup.size) {
args.push('-V', `paper=${settings.pageSetup.size}`);
}
if (settings.pageSetup.orientation) {
args.push('-V', `orientation=${settings.pageSetup.orientation}`);
}
// Convert margin points to cm for Typst (1 point = 0.0352778 cm)
if (settings.pageSetup.margins) {
const margins = settings.pageSetup.margins;
if (margins.top !== undefined) {
const topCm = (margins.top * 0.0352778).toFixed(2);
args.push('-V', `margin_top=${topCm}cm`);
}
if (margins.right !== undefined) {
const rightCm = (margins.right * 0.0352778).toFixed(2);
args.push('-V', `margin_right=${rightCm}cm`);
}
if (margins.bottom !== undefined) {
const bottomCm = (margins.bottom * 0.0352778).toFixed(2);
args.push('-V', `margin_bottom=${bottomCm}cm`);
}
if (margins.left !== undefined) {
const leftCm = (margins.left * 0.0352778).toFixed(2);
args.push('-V', `margin_left=${leftCm}cm`);
}
}
}
// Add export format variable
if (settings.exportDefaults) {
if (settings.exportDefaults.format) {
args.push('-V', `export_format=${settings.exportDefaults.format}`);
}
}
}
// Add Typst engine options
if (this.typstSettings.engineOptions) {
for (const option of this.typstSettings.engineOptions) {
args.push('--pdf-engine-opt', option);
}
}
// Generate intermediate Typst file if requested
if (this.pandocOptions.generateIntermediateTypst) {
const tempDir = await this.ensureTempDirectory();
const typstPath = path.join(tempDir, 'intermediate.typ');
args.push('--output', typstPath);
}
// Add additional arguments
if (this.pandocOptions.additionalArgs) {
args.push(...this.pandocOptions.additionalArgs);
}
return args;
}
/**
* Execute pandoc process with the given arguments
*/
private async executePandoc(args: string[], progressCallback?: ProgressCallback): Promise<ConversionResult> {
return new Promise((resolve) => {
const pandocPath = this.pandocOptions.pandocPath || 'pandoc';
const timeout = this.pandocOptions.timeout || 60000;
// Log the exact command being executed for debugging
console.log('Executing Pandoc command:', pandocPath, args.join(' '));
progressCallback?.('Starting Pandoc process...', 40);
// Determine working directory - use vault base path if available, fallback to plugin directory
let workingDir: string;
if (this.pandocOptions.vaultBasePath) {
workingDir = this.pandocOptions.vaultBasePath;
console.log('Pandoc working directory (vault):', workingDir);
} else {
// Fallback to plugin directory
const pluginDir = this.pandocOptions.pluginDir || process.cwd();
workingDir = pluginDir;
console.log('Pandoc working directory (plugin fallback):', workingDir);
}
// Augment PATH to include common binary locations
const augmentedEnv = {
...process.env,
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
};
// Spawn pandoc process with vault as working directory for attachment resolution
const pandocProcess: ChildProcess = spawn(pandocPath, args, {
stdio: ['pipe', 'pipe', 'pipe'],
cwd: workingDir,
env: augmentedEnv, // Use augmented environment
});
let stdout = '';
let stderr = '';
let hasTimedOut = false;
// Set up timeout
const timeoutHandle = setTimeout(() => {
hasTimedOut = true;
pandocProcess.kill('SIGTERM');
resolve({
success: false,
error: `Pandoc process timed out after ${timeout}ms`,
exitCode: -1
});
}, timeout);
// Collect stdout
pandocProcess.stdout?.on('data', (data: Buffer) => {
stdout += data.toString();
progressCallback?.('Processing document...', 60);
});
// Collect stderr and monitor for progress
pandocProcess.stderr?.on('data', (data: Buffer) => {
const output = data.toString();
stderr += output;
console.log('Pandoc stderr:', output);
// Parse progress information from stderr if available
this.parseProgressFromOutput(output, progressCallback);
});
// Handle process completion
pandocProcess.on('close', (code: number | null) => {
clearTimeout(timeoutHandle);
if (hasTimedOut) {
return; // Already resolved with timeout error
}
const success = code === 0;
const result: ConversionResult = {
success,
stdout,
stderr,
exitCode: code || -1
};
if (!success) {
result.error = this.extractErrorMessage(stderr, stdout);
} else {
progressCallback?.('PDF generation complete!', 90);
}
resolve(result);
});
// Handle process errors
pandocProcess.on('error', (error: Error) => {
clearTimeout(timeoutHandle);
console.log('Pandoc process error:', error);
resolve({
success: false,
error: `Failed to start Pandoc process: ${error.message}`,
exitCode: -1
});
});
});
}
/**
* Parse progress information from pandoc output
*/
private parseProgressFromOutput(output: string, progressCallback?: ProgressCallback): void {
// Look for common progress indicators in pandoc/typst output
if (output.includes('reading')) {
progressCallback?.('Reading input file...', 50);
} else if (output.includes('parsing')) {
progressCallback?.('Parsing document...', 55);
} else if (output.includes('typst')) {
progressCallback?.('Generating PDF with Typst...', 70);
} else if (output.includes('writing')) {
progressCallback?.('Writing output file...', 80);
}
}
/**
* Extract meaningful error messages from pandoc output
*/
private extractErrorMessage(stderr: string, stdout: string): string {
// Look for common error patterns
const errorPatterns = [
/error:/i,
/Error:/,
/failed/i,
/Fatal/i,
/pandoc:/i
];
const allOutput = (stderr + '\n' + stdout).split('\n');
for (const line of allOutput) {
for (const pattern of errorPatterns) {
if (pattern.test(line)) {
return line.trim();
}
}
}
// If no specific error found, return first non-empty line from stderr
const stderrLines = stderr.split('\n').filter(line => line.trim().length > 0);
if (stderrLines.length > 0) {
return stderrLines[0];
}
return 'Unknown error occurred during conversion';
}
/**
* Dispose of the converter and clean up resources
*/
async dispose(): Promise<void> {
await this.cleanup();
}
}
+48
View File
@@ -0,0 +1,48 @@
/**
* Type definitions for Pandoc and Typst conversion
*/
export interface PandocOptions {
/** Path to pandoc executable (optional, uses PATH if not specified) */
pandocPath?: string;
/** Path to typst executable (optional, uses PATH if not specified) */
typstPath?: string;
/** Template file path */
template?: string;
/** Template variables to pass to pandoc */
variables?: Record<string, string | number | boolean>;
/** Additional pandoc arguments */
additionalArgs?: string[];
/** Timeout for pandoc process in milliseconds (default: 60000) */
timeout?: number;
/** Generate intermediate .typ file for debugging */
generateIntermediateTypst?: boolean;
/** Vault base path for resolving attachment paths */
vaultBasePath?: string;
/** Plugin directory path for resolving plugin-relative paths */
pluginDir?: string;
}
export interface TypstSettings {
/** Additional options to pass to Typst engine */
engineOptions?: string[];
}
export interface ConversionResult {
/** Whether the conversion was successful */
success: boolean;
/** Path to the output PDF file */
outputPath?: string;
/** Path to intermediate .typ file (if generated) */
intermediateTypstPath?: string;
/** Error message if conversion failed */
error?: string;
/** Pandoc stdout output */
stdout?: string;
/** Pandoc stderr output */
stderr?: string;
/** Process exit code */
exitCode?: number;
}
export type ProgressCallback = (message: string, progress?: number) => void;
+125
View File
@@ -0,0 +1,125 @@
/**
* Core settings and configuration for Obsidian Typst PDF Export plugin
*/
export enum ExportFormat {
/** Standard multi-page PDF format */
Standard = 'standard',
/** Single-page continuous PDF format */
SinglePage = 'single-page'
}
export interface obsidianTypstPDFExportSettings {
/** Path to the Pandoc executable */
pandocPath: string;
/** Path to the Typst executable */
typstPath: string;
/** Default output folder for exported PDFs */
outputFolder: string;
/** Executable paths configuration */
executablePaths: {
/** Path to ImageMagick convert command (optional, uses PATH if not specified) */
imagemagickPath: string;
/** Additional paths to append to PATH environment variable */
additionalPaths: string[];
};
/** Export defaults */
exportDefaults: {
/** Default template to use for exports */
template: string;
/** Default export format */
format: ExportFormat;
};
/** Typography settings */
typography: {
/** Font families for different text types */
fonts: {
body: string;
heading: string;
monospace: string;
};
/** Font sizes */
fontSizes: {
body: number;
heading: number;
small: number;
};
};
/** Page setup configuration */
pageSetup: {
/** Page size (e.g., "a4", "letter", "custom") */
size: string;
/** Page orientation */
orientation: "portrait" | "landscape";
/** Page margins in points */
margins: {
top: number;
right: number;
bottom: number;
left: number;
};
};
/** Behavior flags */
behavior: {
/** Open PDF after export */
openAfterExport: boolean;
/** Preserve folder structure in output */
preserveFolderStructure: boolean;
/** Number of concurrent exports to run (default: 3) */
exportConcurrency: number;
/** Enable debug mode for verbose logging */
debugMode: boolean;
};
}
export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = {
pandocPath: '',
typstPath: '',
outputFolder: 'exports',
executablePaths: {
imagemagickPath: '', // Empty means use system PATH
additionalPaths: ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin']
},
exportDefaults: {
template: 'default',
format: ExportFormat.Standard
},
typography: {
fonts: {
body: 'Concourse OT',
heading: 'SF Pro Text',
monospace: 'UbuntuMono Nerd Font Mono'
},
fontSizes: {
body: 11,
heading: 16,
small: 9
}
},
pageSetup: {
size: 'a4',
orientation: 'portrait',
margins: {
top: 72,
right: 72,
bottom: 72,
left: 72
}
},
behavior: {
openAfterExport: true,
preserveFolderStructure: true,
exportConcurrency: 3,
debugMode: false
}
};
+511
View File
@@ -0,0 +1,511 @@
/**
* Export Configuration Modal
* Refactored modular version that uses section components
*/
import { Modal, App, Notice } from 'obsidian';
import { obsidianTypstPDFExport } from '../../main';
import { ExportConfig, ExportConfigModalSettings, ModalSection } from './types';
import { ModalState } from './state/ModalState';
import { GeneralSection } from './sections/GeneralSection';
import { TypographySection } from './sections/TypographySection';
import { LayoutSection } from './sections/LayoutSection';
import { TemplateManager } from '../templates/TemplateManager';
export class ExportConfigModal extends Modal {
plugin: obsidianTypstPDFExport;
private state: ModalState;
private sections: Map<string, ModalSection> = new Map();
private onSubmit: (config: ExportConfig) => void;
private onCancel?: () => void;
// UI elements
private contentContainer: HTMLElement;
private formContainer: HTMLElement;
private progressContainer: HTMLElement;
private progressBar: HTMLElement;
private progressText: HTMLElement;
private submitButton: HTMLButtonElement;
private cancelButton: HTMLButtonElement;
constructor(
app: App,
plugin: obsidianTypstPDFExport,
settings: Partial<ExportConfigModalSettings>,
onSubmit: (config: ExportConfig) => void,
onCancel?: () => void
) {
super(app);
this.plugin = plugin;
this.onSubmit = onSubmit;
this.onCancel = onCancel;
// Initialize state
this.state = new ModalState(settings);
// Register sections
this.registerSections();
// Listen for state changes
this.state.onChange(() => this.handleStateChange());
}
private registerSections(): void {
// Register all modal sections
const sections = [
new GeneralSection(),
new TypographySection(),
new LayoutSection()
];
sections.forEach(section => {
this.sections.set(section.getId(), section);
});
}
onOpen(): void {
const { contentEl } = this;
contentEl.addClass('export-config-modal');
// Add styles
this.addModalStyles();
// Create main container
this.contentContainer = contentEl.createDiv('export-config-container');
// Create header
this.createHeader();
// Create form container
this.formContainer = this.contentContainer.createDiv('export-config-form');
// Render sections
this.renderSections();
// Create progress container (initially hidden)
this.createProgressContainer();
// Create action buttons
this.createActionButtons();
// Load available templates
this.loadAvailableTemplates();
}
private createHeader(): void {
const header = this.contentContainer.createDiv('export-config-header');
header.createEl('h2', { text: 'Export to PDF' });
if (this.state.settings.noteTitle) {
header.createEl('p', {
text: `Exporting: ${this.state.settings.noteTitle}`,
cls: 'export-note-title'
});
}
}
private renderSections(): void {
// Clear existing content
this.formContainer.empty();
// Render each section
this.sections.forEach(section => {
section.render(this.formContainer, this.state);
});
// Add preview section
this.createPreviewSection();
}
private createPreviewSection(): void {
const previewSection = this.formContainer.createDiv('export-section preview-section');
previewSection.createEl('h3', { text: 'Preview' });
const previewContainer = previewSection.createDiv('export-preview');
// Output path preview
const outputPreview = previewContainer.createDiv('preview-item');
outputPreview.createEl('span', { text: 'Output: ', cls: 'preview-label' });
const outputPath = outputPreview.createEl('code', { cls: 'preview-value' });
// Template preview
const templatePreview = previewContainer.createDiv('preview-item');
templatePreview.createEl('span', { text: 'Template: ', cls: 'preview-label' });
const templateName = templatePreview.createEl('code', { cls: 'preview-value' });
// Update preview on state change
const updatePreview = () => {
const config = this.state.buildExportConfig();
outputPath.textContent = `${config.outputFolder}/${this.getOutputFilename()}`;
templateName.textContent = config.template || 'default.typ';
};
// Initial update
updatePreview();
// Listen for changes
this.state.onChange(updatePreview);
}
private createProgressContainer(): void {
this.progressContainer = this.contentContainer.createDiv('export-progress-container');
this.progressContainer.style.display = 'none';
// Progress text
this.progressText = this.progressContainer.createEl('div', {
cls: 'export-progress-text',
text: 'Preparing export...'
});
// Progress bar container
const progressBarContainer = this.progressContainer.createDiv('export-progress-bar-container');
this.progressBar = progressBarContainer.createDiv('export-progress-bar');
// Progress percentage
const progressPercent = this.progressContainer.createEl('div', {
cls: 'export-progress-percent',
text: '0%'
});
}
private createActionButtons(): void {
const buttonContainer = this.contentContainer.createDiv('export-config-buttons');
// Cancel button
this.cancelButton = buttonContainer.createEl('button', {
text: 'Cancel',
cls: 'mod-cancel'
});
this.cancelButton.addEventListener('click', () => this.handleCancel());
// Export button
this.submitButton = buttonContainer.createEl('button', {
text: 'Export',
cls: 'mod-cta'
});
this.submitButton.addEventListener('click', () => this.handleSubmit());
}
private async loadAvailableTemplates(): Promise<void> {
try {
const templateManager = new TemplateManager(this.plugin);
const templates = await templateManager.getAvailableTemplates();
this.state.updateSettings({
availableTemplates: templates
});
// Update the general section's template dropdown
const generalSection = this.sections.get('general') as GeneralSection;
if (generalSection && generalSection.updateAvailableTemplates) {
generalSection.updateAvailableTemplates(templates);
}
} catch (error) {
console.error('Failed to load templates:', error);
new Notice('Failed to load available templates');
}
}
private handleStateChange(): void {
// State change handler for any UI updates needed
// This is called whenever the state is updated
}
private async handleSubmit(): Promise<void> {
// Validate all sections
const validationResults = this.validateAllSections();
if (!validationResults.isValid) {
this.showValidationErrors(validationResults.errors);
return;
}
// Show any warnings
if (validationResults.warnings.length > 0) {
this.showValidationWarnings(validationResults.warnings);
}
// Build export configuration
const config = this.state.buildExportConfig();
// Show progress
this.showProgress('Starting export...', 0);
// Disable buttons
this.submitButton.disabled = true;
this.cancelButton.textContent = 'Close';
try {
// Call the submit handler
await this.onSubmit(config);
// Show success
this.showProgress('Export completed successfully!', 100);
// Auto-close after delay
setTimeout(() => this.close(), 2000);
} catch (error) {
console.error('Export failed:', error);
this.showProgress(`Export failed: ${error.message}`, -1);
this.submitButton.disabled = false;
}
}
private handleCancel(): void {
if (this.state.settings.isExporting && this.state.settings.canCancel) {
// Cancel ongoing export
if (this.onCancel) {
this.onCancel();
}
this.showProgress('Export cancelled', -1);
} else {
// Close modal
this.close();
}
}
private validateAllSections(): { isValid: boolean; errors: string[]; warnings: string[] } {
const errors: string[] = [];
const warnings: string[] = [];
this.sections.forEach(section => {
if (section.validate) {
const result = section.validate();
errors.push(...result.errors);
if (result.warnings) {
warnings.push(...result.warnings);
}
}
});
return {
isValid: errors.length === 0,
errors,
warnings
};
}
private showValidationErrors(errors: string[]): void {
const errorContainer = this.formContainer.createDiv('validation-errors');
errorContainer.createEl('h4', { text: 'Validation Errors', cls: 'error-title' });
const errorList = errorContainer.createEl('ul');
errors.forEach(error => {
errorList.createEl('li', { text: error });
});
// Remove after 5 seconds
setTimeout(() => errorContainer.remove(), 5000);
}
private showValidationWarnings(warnings: string[]): void {
warnings.forEach(warning => {
new Notice(`Warning: ${warning}`, 3000);
});
}
private showProgress(message: string, percent: number): void {
this.progressContainer.style.display = 'block';
this.formContainer.style.display = 'none';
this.progressText.textContent = message;
if (percent >= 0) {
this.progressBar.style.width = `${percent}%`;
const percentEl = this.progressContainer.querySelector('.export-progress-percent');
if (percentEl) {
percentEl.textContent = `${Math.round(percent)}%`;
}
}
// Update state
this.state.setProgress(percent, message);
}
updateProgress(message: string, percent: number): void {
this.showProgress(message, percent);
}
private getOutputFilename(): string {
const noteName = this.state.settings.noteTitle || 'document';
return `${noteName}.pdf`;
}
private addModalStyles(): void {
// Add custom styles for the modal
const style = document.createElement('style');
style.textContent = `
.export-config-modal {
width: 90vw;
max-width: 520px;
height: 80vh;
max-height: 600px;
}
.export-config-container {
display: flex;
flex-direction: column;
height: 100%;
}
.export-config-header {
padding: 20px;
border-bottom: 1px solid var(--background-modifier-border);
}
.export-config-header h2 {
margin: 0;
}
.export-note-title {
margin: 10px 0 0 0;
color: var(--text-muted);
font-size: 0.9em;
}
.export-config-form {
flex: 1;
overflow-y: auto;
padding: 20px;
}
.export-section {
margin-bottom: 30px;
}
.export-section h3 {
margin-bottom: 15px;
font-size: 1.1em;
font-weight: 600;
}
.export-section h4 {
margin: 15px 0 10px 0;
font-size: 0.95em;
font-weight: 500;
color: var(--text-muted);
}
.export-preview {
background: var(--background-secondary);
padding: 15px;
border-radius: 5px;
}
.preview-item {
margin-bottom: 10px;
}
.preview-label {
font-weight: 500;
margin-right: 10px;
}
.preview-value {
background: var(--background-primary);
padding: 2px 6px;
border-radius: 3px;
font-family: var(--font-monospace);
font-size: 0.9em;
}
.export-progress-container {
padding: 40px;
text-align: center;
}
.export-progress-text {
margin-bottom: 20px;
font-size: 1.1em;
}
.export-progress-bar-container {
width: 100%;
height: 20px;
background: var(--background-secondary);
border-radius: 10px;
overflow: hidden;
}
.export-progress-bar {
height: 100%;
background: var(--interactive-accent);
transition: width 0.3s ease;
}
.export-progress-percent {
margin-top: 10px;
color: var(--text-muted);
}
.export-config-buttons {
padding: 20px;
border-top: 1px solid var(--background-modifier-border);
display: flex;
justify-content: flex-end;
gap: 10px;
}
.validation-errors {
background: var(--background-modifier-error);
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.error-title {
color: var(--text-error);
margin: 0 0 10px 0;
}
.validation-errors ul {
margin: 0;
padding-left: 20px;
}
.margin-preset-button {
margin: 0 5px;
padding: 2px 10px;
font-size: 0.85em;
}
.margins-container {
background: var(--background-secondary-alt);
padding: 15px;
border-radius: 5px;
margin-top: 15px;
}
.margin-presets {
margin-top: 15px;
padding-top: 15px;
border-top: 1px solid var(--background-modifier-border);
}
.font-sizes {
background: var(--background-secondary-alt);
padding: 15px;
border-radius: 5px;
margin-top: 15px;
}
`;
document.head.appendChild(style);
}
onClose(): void {
// Clean up state listeners
this.state.onChange(() => {}); // Remove listener
// Clear sections
this.sections.clear();
// Remove added styles
const style = document.querySelector('style');
if (style && style.textContent?.includes('export-config-modal')) {
style.remove();
}
const { contentEl } = this;
contentEl.empty();
}
}
+134
View File
@@ -0,0 +1,134 @@
/**
* General Section for Export Configuration Modal
* Handles template selection, format options, and output settings
*/
import { Setting } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../types';
import { ExportFormat } from '../../core/settings';
export class GeneralSection implements ModalSection {
private container: HTMLElement | null = null;
private templateDropdown: any = null;
private outputFolderInput: HTMLInputElement | null = null;
render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'General Settings' });
this.createTemplateSelection(state);
this.createFormatSelection(state);
this.createOutputSettings(state);
}
private createTemplateSelection(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('Typst template')
.setDesc('Select template for document styling')
.addDropdown(dropdown => {
// Populate with available templates
state.settings.availableTemplates.forEach(template => {
dropdown.addOption(template, this.getTemplateDisplayName(template));
});
dropdown
.setValue(state.settings.template || 'default.typ')
.onChange(value => {
state.updateSettings({ template: value });
});
this.templateDropdown = dropdown;
});
}
private createFormatSelection(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('PDF format')
.setDesc('Choose document layout format')
.addDropdown(dropdown => {
dropdown
.addOption(ExportFormat.Standard, 'Standard (multi-page PDF)')
.addOption(ExportFormat.SinglePage, 'Single-page (continuous layout)')
.setValue(state.settings.format || ExportFormat.Standard)
.onChange(value => {
state.updateSettings({ format: value as ExportFormat });
});
});
}
private createOutputSettings(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('Output folder')
.setDesc('Folder where PDFs will be saved (relative to vault root)')
.addText(text => {
const input = text
.setPlaceholder('exports')
.setValue(state.settings.outputFolder || 'exports')
.onChange(value => {
state.updateSettings({ outputFolder: value });
});
this.outputFolderInput = input.inputEl;
});
}
private getTemplateDisplayName(template: string): string {
// Remove extension and capitalize
const name = template.replace(/\.(typ|pandoc\.typ)$/, '');
return name.charAt(0).toUpperCase() + name.slice(1).replace(/-/g, ' ');
}
validate(): ValidationResult {
const errors: string[] = [];
const warnings: string[] = [];
// Validate output folder
if (this.outputFolderInput) {
const value = this.outputFolderInput.value.trim();
if (!value) {
errors.push('Output folder is required');
} else if (value.startsWith('/') || value.startsWith('\\')) {
warnings.push('Output folder should be relative to vault root');
}
}
// Check template selection
if (!this.templateDropdown || !this.templateDropdown.getValue()) {
errors.push('Template selection is required');
}
return {
isValid: errors.length === 0,
errors,
warnings
};
}
updateAvailableTemplates(templates: string[]): void {
if (!this.templateDropdown) return;
const currentValue = this.templateDropdown.getValue();
// Clear and repopulate dropdown
this.templateDropdown.selectEl.empty();
templates.forEach(template => {
this.templateDropdown.addOption(template, this.getTemplateDisplayName(template));
});
// Restore selection if still available
if (templates.includes(currentValue)) {
this.templateDropdown.setValue(currentValue);
} else if (templates.length > 0) {
this.templateDropdown.setValue(templates[0]);
}
}
getId(): string {
return 'general';
}
}
+158
View File
@@ -0,0 +1,158 @@
/**
* Layout Section for Export Configuration Modal
* Handles page setup, orientation, and margins
*/
import { Setting } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../types';
export class LayoutSection implements ModalSection {
private container: HTMLElement | null = null;
private marginInputs: Map<string, number> = new Map();
render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Page Layout' });
this.createPageSizeSettings(state);
this.createOrientationSettings(state);
this.createMarginSettings(state);
}
private createPageSizeSettings(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('Page size')
.setDesc('Standard page sizes for the PDF document')
.addDropdown(dropdown => {
dropdown
.addOption('a4', 'A4 (210 × 297 mm)')
.addOption('letter', 'Letter (8.5 × 11 in)')
.addOption('legal', 'Legal (8.5 × 14 in)')
.addOption('a3', 'A3 (297 × 420 mm)')
.addOption('a5', 'A5 (148 × 210 mm)')
.setValue('a4') // Default to A4
.onChange(value => {
state.updateTemplateVariables({ pageSize: value });
});
});
}
private createOrientationSettings(state: ModalState): void {
if (!this.container) return;
new Setting(this.container)
.setName('Orientation')
.setDesc('Page orientation for the document')
.addDropdown(dropdown => {
dropdown
.addOption('portrait', 'Portrait')
.addOption('landscape', 'Landscape')
.setValue('portrait')
.onChange(value => {
state.updateTemplateVariables({ orientation: value });
});
});
}
private createMarginSettings(state: ModalState): void {
if (!this.container) return;
const marginsContainer = this.container.createDiv('margins-container');
marginsContainer.createEl('h4', { text: 'Margins' });
const marginDefaults = {
top: 72,
bottom: 57,
left: 72,
right: 43
};
// Create margin sliders
['top', 'bottom', 'left', 'right'].forEach(side => {
new Setting(marginsContainer)
.setName(side.charAt(0).toUpperCase() + side.slice(1))
.setDesc(`${side} margin in points`)
.addSlider(slider => {
slider
.setLimits(36, 144, 6) // 0.5" to 2" in 6pt increments
.setValue(marginDefaults[side as keyof typeof marginDefaults])
.setDynamicTooltip()
.onChange(value => {
this.marginInputs.set(side, value);
this.updateMargins(state);
});
// Set initial value
this.marginInputs.set(side, marginDefaults[side as keyof typeof marginDefaults]);
});
});
// Add preset buttons
const presetContainer = marginsContainer.createDiv('margin-presets');
presetContainer.createEl('span', { text: 'Presets: ' });
const presets = [
{ name: 'Narrow', values: { top: 36, bottom: 36, left: 36, right: 36 } },
{ name: 'Normal', values: { top: 72, bottom: 72, left: 72, right: 72 } },
{ name: 'Wide', values: { top: 108, bottom: 108, left: 108, right: 108 } }
];
presets.forEach(preset => {
const button = presetContainer.createEl('button', {
text: preset.name,
cls: 'margin-preset-button'
});
button.addEventListener('click', () => {
Object.entries(preset.values).forEach(([side, value]) => {
this.marginInputs.set(side, value);
});
this.updateMargins(state);
// Would need to update slider UI here in real implementation
state.notifyChange(); // Trigger UI refresh
});
});
}
private updateMargins(state: ModalState): void {
const margins = {
top: this.marginInputs.get('top') || 72,
bottom: this.marginInputs.get('bottom') || 72,
left: this.marginInputs.get('left') || 72,
right: this.marginInputs.get('right') || 72
};
// Convert points to Typst measurements
const typstMargins = {
marginTop: `${margins.top}pt`,
marginBottom: `${margins.bottom}pt`,
marginLeft: `${margins.left}pt`,
marginRight: `${margins.right}pt`
};
state.updateTemplateVariables(typstMargins);
}
validate(): ValidationResult {
const errors: string[] = [];
const warnings: string[] = [];
// Check for extremely small margins
this.marginInputs.forEach((value, side) => {
if (value < 36) {
warnings.push(`${side} margin is very small and may cause content to be cut off`);
}
});
return {
isValid: errors.length === 0,
errors,
warnings
};
}
getId(): string {
return 'layout';
}
}
+129
View File
@@ -0,0 +1,129 @@
/**
* Typography Section for Export Configuration Modal
* Handles font selection and size configuration
*/
import { Setting } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../types';
export class TypographySection implements ModalSection {
private container: HTMLElement | null = null;
private fontInputs: Map<string, HTMLInputElement> = new Map();
private sizeSliders: Map<string, any> = new Map();
render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Typography' });
this.createFontSettings(state);
this.createFontSizeSettings(state);
}
private createFontSettings(state: ModalState): void {
if (!this.container) return;
// Body font
const bodyFontSetting = new Setting(this.container)
.setName('Body font')
.setDesc('Primary font for document text')
.addText(text => {
const input = text
.setPlaceholder('Concourse OT')
.setValue(state.typography.fontFamily)
.onChange(value => {
state.updateTypography({ fontFamily: value });
});
this.fontInputs.set('body', input.inputEl);
return text;
});
// Heading font (future enhancement)
// For now, we'll use the same font for all text types
// but this can be expanded later
// Monospace font (future enhancement)
// Similar to heading font, can be expanded later
}
private createFontSizeSettings(state: ModalState): void {
if (!this.container) return;
const sizesContainer = this.container.createDiv('font-sizes');
sizesContainer.createEl('h4', { text: 'Text Formatting' });
// Font size
new Setting(sizesContainer)
.setName('Font size')
.setDesc('Base font size for document text')
.addDropdown(dropdown => {
dropdown
.addOptions({
'9pt': '9pt - Small',
'10pt': '10pt - Compact',
'11pt': '11pt - Standard',
'12pt': '12pt - Large',
'14pt': '14pt - Extra Large'
})
.setValue(state.typography.fontSize)
.onChange(value => {
state.updateTypography({ fontSize: value });
});
});
// Line height
new Setting(sizesContainer)
.setName('Line height')
.setDesc('Spacing between lines of text')
.addDropdown(dropdown => {
dropdown
.addOptions({
'1.0': 'Single',
'1.15': 'Slightly Loose',
'1.5': 'One and a Half',
'1.8': 'Relaxed',
'2.0': 'Double'
})
.setValue(state.typography.lineHeight)
.onChange(value => {
state.updateTypography({ lineHeight: value });
});
});
}
validate(): ValidationResult {
const errors: string[] = [];
const warnings: string[] = [];
// Check if fonts are likely available
this.fontInputs.forEach((input, type) => {
const value = input.value.trim();
if (value && this.isUncommonFont(value)) {
warnings.push(`Font "${value}" may not be available on the system. The template will use fallback fonts if needed.`);
}
});
return {
isValid: errors.length === 0,
errors,
warnings
};
}
private isUncommonFont(fontName: string): boolean {
// List of commonly available fonts
const commonFonts = [
'arial', 'helvetica', 'times new roman', 'georgia',
'verdana', 'tahoma', 'trebuchet ms', 'palatino',
'courier', 'courier new', 'monaco', 'consolas',
'sf pro', 'roboto', 'open sans', 'lato',
'concourse ot', 'ubuntu', 'source code pro'
];
const normalized = fontName.toLowerCase().trim();
return !commonFonts.some(font => normalized.includes(font));
}
getId(): string {
return 'typography';
}
}
+149
View File
@@ -0,0 +1,149 @@
/**
* Modal State Management
* Centralized state management for the Export Configuration Modal
*/
import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../types';
import { ExportFormat } from '../../core/settings';
export class ModalState implements IModalState {
settings: ExportConfigModalSettings;
typography: {
fontFamily: string;
fontSize: string;
lineHeight: string;
};
private changeListeners: Set<() => void> = new Set();
constructor(initialSettings: Partial<ExportConfigModalSettings>) {
// Initialize with defaults
this.settings = {
notePath: '',
noteTitle: '',
template: 'default.typ',
format: ExportFormat.Standard,
outputFolder: 'exports',
templateVariables: {},
availableTemplates: [],
isExporting: false,
progressPercent: 0,
currentOperation: '',
canCancel: false,
...initialSettings
};
// Initialize typography with defaults that will be passed to template
this.typography = {
fontFamily: 'Concourse OT',
fontSize: '11pt',
lineHeight: '1.5'
};
}
/**
* Update typography settings
*/
updateTypography(updates: Partial<ModalState['typography']>): void {
this.typography = {
...this.typography,
...updates
};
this.notifyChange();
}
/**
* Build export configuration from current state
*/
buildExportConfig(): ExportConfig {
const config: ExportConfig = {
template: this.settings.template,
format: this.settings.format,
outputFolder: this.settings.outputFolder,
templateVariables: {
...this.settings.templateVariables,
// Add typography settings to template variables
font: this.typography.fontFamily,
fontsize: this.typography.fontSize,
lineheight: this.typography.lineHeight
},
// Include typography in the export config
typography: {
fontFamily: this.typography.fontFamily,
fontSize: this.typography.fontSize,
lineHeight: this.typography.lineHeight
}
};
return config;
}
/**
* Register a change listener
*/
onChange(listener: () => void): void {
this.changeListeners.add(listener);
}
/**
* Unregister a change listener
*/
offChange(listener: () => void): void {
this.changeListeners.delete(listener);
}
/**
* Notify all listeners of state change
*/
notifyChange(): void {
this.changeListeners.forEach(listener => listener());
}
/**
* Update settings
*/
updateSettings(updates: Partial<ExportConfigModalSettings>): void {
this.settings = {
...this.settings,
...updates
};
this.notifyChange();
}
/**
* Update template variables
*/
updateTemplateVariables(updates: Record<string, any>): void {
this.settings.templateVariables = {
...this.settings.templateVariables,
...updates
};
this.notifyChange();
}
/**
* Set export progress
*/
setProgress(percent: number, operation: string): void {
this.settings.progressPercent = percent;
this.settings.currentOperation = operation;
this.notifyChange();
}
/**
* Reset state to defaults
*/
reset(): void {
this.settings.templateVariables = {};
this.settings.progressPercent = 0;
this.settings.currentOperation = '';
this.settings.isExporting = false;
this.settings.canCancel = false;
this.typography = {
fontFamily: 'Concourse OT',
fontSize: '11pt',
lineHeight: '1.5'
};
this.notifyChange();
}
}
+65
View File
@@ -0,0 +1,65 @@
/**
* Type definitions for the Export Configuration Modal
*/
import { ExportFormat } from '../core/settings';
export interface ExportConfig {
/** Override default template */
template?: string;
/** Override default format */
format?: ExportFormat;
/** Override output folder */
outputFolder?: string;
/** Template variables for this export */
templateVariables?: Record<string, any>;
/** Typography settings for this export */
typography?: {
fontFamily?: string;
fontSize?: string;
lineHeight?: string;
};
}
export interface ExportConfigModalSettings extends ExportConfig {
/** Note being exported */
notePath: string;
/** Note title for display */
noteTitle: string;
/** Available templates from TemplateManager */
availableTemplates: string[];
/** Current export in progress */
isExporting: boolean;
/** Progress percentage (0-100) */
progressPercent: number;
/** Current operation description */
currentOperation: string;
/** Whether export can be cancelled */
canCancel: boolean;
}
export interface ModalSection {
render(containerEl: HTMLElement, state: ModalState): void;
validate?(): ValidationResult;
getId(): string;
}
export interface ValidationResult {
isValid: boolean;
errors: string[];
warnings?: string[];
}
export interface ModalState {
settings: ExportConfigModalSettings;
typography: {
fontFamily: string;
fontSize: string;
lineHeight: string;
};
updateTypography(updates: Partial<ModalState['typography']>): void;
updateSettings(updates: Partial<ExportConfigModalSettings>): void;
updateTemplateVariables(updates: Record<string, any>): void;
buildExportConfig(): ExportConfig;
notifyChange(): void;
}
+142
View File
@@ -0,0 +1,142 @@
/**
* Template Manager
* Handles template discovery, loading, and validation
*/
import { obsidianTypstPDFExport } from '../../main';
import * as path from 'path';
import * as fs from 'fs';
export class TemplateManager {
private plugin: obsidianTypstPDFExport;
private templatesPath: string;
constructor(plugin: obsidianTypstPDFExport) {
this.plugin = plugin;
// Templates are stored in the plugin directory
this.templatesPath = path.join(
(this.plugin.app.vault.adapter as any).basePath,
'.obsidian/plugins/obsidian-typst-pdf-export/templates'
);
}
/**
* Get list of available template files
*/
async getAvailableTemplates(): Promise<string[]> {
try {
// Check if templates directory exists
if (!fs.existsSync(this.templatesPath)) {
console.warn('Templates directory does not exist:', this.templatesPath);
return ['default.typ'];
}
// Read directory contents
const files = fs.readdirSync(this.templatesPath);
// Filter for .typ and .pandoc.typ files
const templates = files.filter(file => {
return file.endsWith('.typ') || file.endsWith('.pandoc.typ');
});
// Always include default if not present
if (!templates.includes('default.typ')) {
templates.unshift('default.typ');
}
return templates;
} catch (error) {
console.error('Error loading templates:', error);
return ['default.typ'];
}
}
/**
* Get the full path to a template file
*/
getTemplatePath(templateName: string): string {
return path.join(this.templatesPath, templateName);
}
/**
* Check if a template exists
*/
async templateExists(templateName: string): Promise<boolean> {
const templatePath = this.getTemplatePath(templateName);
try {
return fs.existsSync(templatePath);
} catch {
return false;
}
}
/**
* Load template content
*/
async loadTemplate(templateName: string): Promise<string | null> {
const templatePath = this.getTemplatePath(templateName);
try {
if (fs.existsSync(templatePath)) {
return fs.readFileSync(templatePath, 'utf-8');
}
} catch (error) {
console.error('Error loading template:', error);
}
return null;
}
/**
* Get template metadata (if available in template comments)
*/
async getTemplateMetadata(templateName: string): Promise<TemplateMetadata | null> {
const content = await this.loadTemplate(templateName);
if (!content) return null;
// Parse template header comments for metadata
const metadataRegex = /^\/\/\s*@(\w+):\s*(.+)$/gm;
const metadata: TemplateMetadata = {
name: templateName,
description: '',
author: '',
version: '',
variables: []
};
let match;
while ((match = metadataRegex.exec(content)) !== null) {
const [, key, value] = match;
switch (key) {
case 'description':
metadata.description = value;
break;
case 'author':
metadata.author = value;
break;
case 'version':
metadata.version = value;
break;
case 'variable':
// Parse variable definition (e.g., @variable: font:string:Body font family)
const [name, type, description] = value.split(':');
metadata.variables.push({ name, type, description });
break;
}
}
return metadata;
}
}
export interface TemplateMetadata {
name: string;
description: string;
author: string;
version: string;
variables: TemplateVariable[];
}
export interface TemplateVariable {
name: string;
type: string;
description: string;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 403 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 260 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 472 KiB

+10 -1
View File
@@ -99,6 +99,7 @@
// Set page layout with conditional height based on export format
set page(
paper: paper,
orientation: orientation,
margin: page-margin,
..if export_format == "single-page" { (height: auto,) } else { (:) },
numbering: pagenumbering,
@@ -136,7 +137,7 @@
)
// Magazine-style paragraphs
set par(justify: true, leading: 0.7em, first-line-indent: 0.8em)
set par(justify: false, leading: 0.7em, first-line-indent: 0.8em)
// No heading numbering for magazine style
if sectionnumbering != none {
@@ -182,6 +183,14 @@
#it.body #h(0.5em) #line(length: 3cm, stroke: 1pt + rgb("#93c5fd"))
]
// Apply monospace font to code blocks and inline code
let code-font = if monospace_font != none and type(monospace_font) == str {
(monospace_font, "Courier New", "Monaco")
} else {
("Courier New", "Monaco")
}
show raw: set text(font: code-font)
// Decorative title block with background
if title != none and title != "" [
+26 -17
View File
@@ -2,38 +2,38 @@
#let email-block(from: none, to: none, subject: none, date: none, body) = {
block(
width: 100%,
inset: 6pt,
stroke: 1pt + gray,
inset: 16pt,
stroke: 0.5pt + blue,
radius: 5pt,
breakable: true
)[
#grid(
columns: (auto, 1fr),
row-gutter: 3pt,
row-gutter: 13pt,
column-gutter: 8pt,
if from != none [
#text(style: "italic", size: 0.9em)[From:]
#text(style: "italic", size: 1em)[From:]
] else [],
if from != none [
#text(size: 0.9em)[#from]
#text(size: 1em)[#from]
] else [],
if to != none [
#text(style: "italic", size: 0.9em)[To:]
#text(style: "italic", size: 1em)[To:]
] else [],
if to != none [
#text(size: 0.9em)[#to]
#text(size: 1em)[#to]
] else [],
if subject != none [
#text(style: "italic", size: 0.9em)[Subject:]
#text(style: "italic", size: 1em)[Subject:]
] else [],
if subject != none [
#text(size: 0.9em)[#subject]
#text(size: 1em)[#subject]
] else [],
if date != none [
#text(style: "italic", size: 0.9em)[Date:]
#text(style: "italic", size: 1em)[Date:]
] else [],
if date != none [
#text(size: 0.9em)[#date]
#text(size: 1em)[#date]
] else [],
)
#if body != none [
@@ -55,7 +55,7 @@
lang: "en",
region: "US",
paper: "a4",
margin: (x: 1.5cm, y: 1.5cm),
margin: (x: 1.5cm, y: 1cm),
cols: 1,
font: ("Concourse OT 3", "Helvetica Neue", "Arial"),
fontsize: 11pt,
@@ -66,7 +66,7 @@
monospace_font: none,
heading_fontsize: none,
small_fontsize: none,
margin_top: none,
margin_top: 9cm,
margin_right: none,
margin_bottom: none,
margin_left: none,
@@ -84,7 +84,7 @@
// Use UI-configured margins if available, otherwise fall back to template defaults
let page-margin = if margin_top != none {
(
top: if margin_top != none { margin_top } else { 1.5cm },
top: if margin_top != none { margin_top } else { 9cm },
right: if margin_right != none { margin_right } else { 1.5cm },
bottom: if margin_bottom != none { margin_bottom } else { 1.5cm },
left: if margin_left != none { margin_left } else { 1.5cm },
@@ -97,7 +97,8 @@
// Set page layout with conditional height based on export format
set page(
paper: paper,
margin: page-margin,
flipped: false,
margin: (top: 2.5cm, right: 1.5cm, bottom: 2cm, left: 2.5cm),
..if export_format == "single-page" { (height: auto,) } else { (:) },
numbering: pagenumbering,
header: context {
@@ -125,7 +126,7 @@
)
// Set paragraph properties - Clean spacing
set par(justify: true, leading: 0.6em)
set par(justify: false, leading: 0.6em)
// Set heading numbering
if sectionnumbering != none {
@@ -162,10 +163,18 @@
#it
]
// Apply monospace font to code blocks and inline code
let code-font = if monospace_font != none and type(monospace_font) == str {
(monospace_font, "Courier New", "Monaco")
} else {
("Courier New", "Monaco")
}
show raw: set text(font: code-font)
// Title block - Clean and minimal
if title != none and title != "" [
#align(center, text(16pt, weight: "bold")[#title])
#align(left, text(16pt, weight: "bold")[#title])
#v(0.8em)
]
+17 -18
View File
@@ -90,25 +90,16 @@
} else {
margin
}
// Set page layout with conditional height based on export format
if export_format == "single-page" {
set page(
paper: paper,
margin: page-margin,
height: auto, // Auto height for continuous single page
numbering: pagenumbering,
fill: rgb("#fafafa")
)
} else {
set page(
paper: paper,
margin: page-margin,
// No height specified = uses default paper size height
numbering: pagenumbering,
fill: rgb("#fafafa")
)
}
set page(
paper: paper,
orientation: orientation,
margin: (top: 2.5cm, right: 1.5cm, bottom: 2cm, left: 2.5cm),
..if export_format == "single-page" { (height: auto,) } else { (:) },
numbering: pagenumbering,
fill: rgb("#fafafa")
)
// Modern sans-serif fonts
// Use UI-configured font if available, otherwise use template default
@@ -179,6 +170,14 @@
#it.body
]
// Apply monospace font to code blocks and inline code
let code-font = if monospace_font != none and type(monospace_font) == str {
(monospace_font, "Courier New", "Monaco")
} else {
("Courier New", "Monaco")
}
show raw: set text(font: code-font)
// Modern title header with sidebar design
if title != none and title != "" [
+16 -6
View File
@@ -67,7 +67,7 @@
paper: "a4",
margin: (x: 3cm, y: 2.5cm),
cols: 1,
font: ("Concourse OT", "Helvetica Neue", "Arial", "sans-serif"),
font: ("Concourse OT 3", "Helvetica Neue", "Arial"),
fontsize: 11pt,
sectionnumbering: "1.",
pagenumbering: "1",
@@ -105,6 +105,7 @@
// Set page layout with conditional height based on export format
set page(
paper: paper,
orientation: orientation,
margin: page-margin,
..if export_format == "single-page" { (height: auto,) } else { (:) },
numbering: pagenumbering,
@@ -139,7 +140,7 @@
// Business document font
// Use UI-configured font if available, otherwise use template default
let body-font = if font != none and type(font) == str {
(font, "Concourse OT", "Helvetica Neue", "Arial", "sans-serif")
(font, "Concourse OT 3", "Helvetica Neue", "Arial")
} else {
font
}
@@ -153,8 +154,9 @@
region: region
)
// Professional paragraph formatting
set par(justify: true, leading: 0.7em, first-line-indent: 0pt)
// Professional paragraph formatting - use left alignment instead of full justification
// Full justification can create ugly gaps in short lines and attachment text
set par(justify: false, leading: 0.7em, first-line-indent: 0pt)
// Chapter-style numbering
if sectionnumbering != none {
@@ -172,7 +174,7 @@
inset: 12pt,
stroke: (left: 4pt + rgb("#1f2937")),
)[
#set text(font: ("SF Pro Text", "Helvetica Neue", "Arial", "sans-serif"), size: 18pt, weight: "bold", fill: rgb("#1f2937"))
#set text(font: ("SF Pro Text", "Helvetica Neue", "Arial"), size: 18pt, weight: "bold", fill: rgb("#1f2937"))
#grid(
columns: (auto, 1fr),
column-gutter: 12pt,
@@ -189,7 +191,7 @@
inset: (bottom: 6pt),
stroke: (bottom: 1pt + rgb("#e5e7eb")),
)[
#set text(font: ("SF Pro Text", "Helvetica Neue", "Arial", "sans-serif"), size: 14pt, weight: "semibold", fill: rgb("#374151"))
#set text(font: ("SF Pro Text", "Helvetica Neue", "Arial"), size: 14pt, weight: "semibold", fill: rgb("#374151"))
#counter(heading).display()
#h(0.8em)
#it.body
@@ -206,6 +208,14 @@
#it.body
]
// Apply monospace font to code blocks and inline code
let code-font = if monospace_font != none and type(monospace_font) == str {
(monospace_font, "Courier New", "Monaco")
} else {
("Courier New", "Monaco")
}
show raw: set text(font: code-font)
// Professional title page
if title != none and title != "" [