Merge branch 'release/1.2.1'

This commit is contained in:
AlexKucera committed 2025-09-10 23:00:56 +02:00
commit 75d6f3d002
25 files changed
+383 -237

No files matched your search

+2 -2
View File
@@ -125,7 +125,7 @@ jobs:
## Installation
### Automatic Installation (Community Plugins)
### Automatic Installation (Community Plugins) - Plugin still waiting for approval
Search for "Typst PDF Export" in Obsidian's Community Plugins tab.
### Manual Installation
@@ -138,7 +138,7 @@ jobs:
### Requirements
- [Pandoc](https://pandoc.org/installing.html)
- [Typst](https://typst.app/docs/installation/)
- ImageMagick (optional, for enhanced image processing)
- [ImageMagick](https://imagemagick.org) (for enhanced image processing)
## Files in this release
- `main.js` - Plugin code with embedded templates
+17
View File
@@ -5,6 +5,23 @@ All notable changes to the Obsidian Typst PDF Export plugin will be documented i
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.2.1] - 2025-01-10
### Fixed
- **Horizontal Rule Processing**: Resolved YAML parsing conflicts when documents contain horizontal rules (`---`)
- Added HorizontalRuleProcessor to transform horizontal rules to asterisks (`***`) before Pandoc processing
- Preserved YAML frontmatter by detecting and skipping frontmatter sections during transformation
- Added horizontalrule definition to all Typst templates for Pandoc compatibility
- **TypeScript Build Errors**: Fixed 23 TypeScript errors in 8 files
- Resolved DataAdapter casting issues with proper type assertions
- Fixed template variable type issues by adding undefined to union types
- Ensured type safety while maintaining full functionality
### Changed
- **Code Quality**: Replaced explicit any types for Obsidian plugin review compliance
- Improved type safety throughout the codebase
- Enhanced code maintainability with proper type assertions
## [1.2.0] - 2025-01-10
### Changed
+1 -1
View File
@@ -48,7 +48,7 @@ Typst offers several advantages over standard PDF export:
## Installation
### Method 1: Community Plugin Store (Recommended)
### Method 1: Community Plugin Store (Recommended) - Still waiting on plugin approval
1. Open **Settings** → **Community Plugins**
2. **Disable Safe Mode** if needed
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "typst-pdf-export",
"name": "Typst PDF Export",
"version": "1.2.0",
"version": "1.2.1",
"minAppVersion": "1.9.12",
"description": "Exports a note or collection of notes to a pretty Typst PDF.",
"author": "Alexander Kucera",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "obsidian-typst-pdf-export",
"version": "1.2.0",
"version": "1.2.1",
"description": "Exports a note or collection of notes to a pretty Typst PDF.",
"main": "main.js",
"scripts": {
+13 -6
View File
@@ -8,6 +8,7 @@ import { WikilinkProcessor, WikilinkConfig, WikilinkProcessorConfig } from './pr
import { EmbedProcessor, EmbedProcessorConfig } from './preprocessors/EmbedProcessor';
import { CalloutProcessor } from './preprocessors/CalloutProcessor';
import { MetadataExtractor } from './preprocessors/MetadataExtractor';
import { HorizontalRuleProcessor } from './preprocessors/HorizontalRuleProcessor';
export interface PreprocessorOptions {
/** Preserve existing frontmatter */
@@ -75,6 +76,7 @@ export class MarkdownPreprocessor {
private options: PreprocessorOptions;
private wikilinkConfig: WikilinkConfig;
private noteTitle?: string;
private horizontalRuleProcessor: HorizontalRuleProcessor;
private frontmatterProcessor: FrontmatterProcessor;
private wikilinkProcessor: WikilinkProcessor;
private embedProcessor: EmbedProcessor;
@@ -86,6 +88,8 @@ export class MarkdownPreprocessor {
this.wikilinkConfig = config.wikilinkConfig;
this.noteTitle = config.noteTitle;
this.horizontalRuleProcessor = new HorizontalRuleProcessor();
const frontmatterConfig: FrontmatterProcessorConfig = {
noteTitle: this.noteTitle,
preserveFrontmatter: this.options.preserveFrontmatter,
@@ -123,22 +127,25 @@ export class MarkdownPreprocessor {
};
try {
// Step 1: Extract and process frontmatter first (always process for metadata extraction)
// Step 1: Process horizontal rules to avoid YAML delimiter conflicts
result.content = this.horizontalRuleProcessor.process(result.content);
// Step 2: Extract and process frontmatter (always process for metadata extraction)
result.content = this.frontmatterProcessor.processFrontmatter(result.content, result);
// Step 2: Convert email blocks to Typst format
// Step 3: Convert email blocks to Typst format
result.content = this.calloutProcessor.processEmailBlocks(result.content, result);
// Step 3: Filter out unnecessary links (Open: links and Mail.app links)
// Step 4: Filter out unnecessary links (Open: links and Mail.app links)
result.content = this.calloutProcessor.filterUnnecessaryLinks(result.content, result);
// Step 4: Convert embeds FIRST (before wikilinks to avoid .md extension being added)
// Step 5: Convert embeds FIRST (before wikilinks to avoid .md extension being added)
result.content = this.embedProcessor.processEmbeds(result.content, result);
// Step 5: Convert wikilinks (after embeds are processed)
// Step 6: Convert wikilinks (after embeds are processed)
result.content = this.wikilinkProcessor.processWikilinks(result.content, result);
// Step 6: Convert callouts
// Step 7: Convert callouts
result.content = this.calloutProcessor.processCallouts(result.content, result);
// Extract title from content if not available from frontmatter
+32 -32
View File
@@ -94,42 +94,42 @@ export class PandocTypstConverter {
* Convert markdown content to PDF
*/
async convertMarkdownToPDF(
content: string,
outputPath: string,
options: Partial<PandocOptions> = {},
progressCallback?: ProgressCallback
): Promise<ConversionResult> {
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 {
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;
await fsPromises.unlink(tempInputPath);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
success: false,
error: `Conversion failed: ${errorMessage}`
};
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
+1 -1
View File
@@ -83,7 +83,7 @@ export class BinaryLocator {
// Strategy 2: Assuming we're running from vault root
path.join(configDir, 'plugins', pluginDirName),
// Strategy 3: From vault base path if plugin is available
...(plugin ? [path.join((plugin.app.vault.adapter as { basePath: string }).basePath, plugin.manifest.dir!)] : [])
...(plugin ? [path.join((plugin.app.vault.adapter as unknown as { basePath: string }).basePath, plugin.manifest.dir!)] : [])
];
}
@@ -27,188 +27,220 @@ export class FrontmatterProcessor {
* Process frontmatter using the gray-matter library approach
*/
public processFrontmatter(content: string, result: PreprocessingResult): string {
try {
// Use gray-matter for robust frontmatter parsing
const matter = require('gray-matter');
const parsed = matter(content);
if (parsed.data && Object.keys(parsed.data).length > 0) {
// 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) {
let frontmatterTags: string[] = [];
if (Array.isArray(parsed.data.tags)) {
// Handle array of tags
frontmatterTags = parsed.data.tags
.map((tag: unknown) => typeof tag === 'string' ? tag : String(tag))
.filter((tag: string) => tag.trim() !== '');
} else if (typeof parsed.data.tags === 'string') {
// Handle comma-separated string or single tag
frontmatterTags = parsed.data.tags
.split(/[,\s]+/)
.map((tag: string) => tag.trim())
.filter((tag: string) => tag !== '');
}
// Merge with existing tags (avoid duplicates)
for (const tag of frontmatterTags) {
if (!result.metadata.tags.includes(tag)) {
result.metadata.tags.push(tag);
}
}
}
// 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();
}
// Handle frontmatter preservation and display options
const finalFrontmatter = this.noteTitle ?
{ ...parsed.data, title: this.noteTitle } :
parsed.data;
if (this.preserveFrontmatter) {
// Keep the frontmatter in the content, but reconstruct it with the modified title
const yaml = require('js-yaml');
const newFrontmatter = yaml.dump(finalFrontmatter);
let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`;
// Add printed frontmatter if requested
if (this.printFrontmatter) {
const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter);
processedContent = `---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n${parsed.content}`;
}
return processedContent;
} else {
// Return content without frontmatter, but add title as frontmatter for Pandoc
let processedContent: string;
if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`;
} else {
processedContent = parsed.content;
}
// Add printed frontmatter if requested
if (this.printFrontmatter) {
const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter);
// Insert after the title frontmatter but before content
const lines = processedContent.split('\n');
if (lines[0] === '---' && lines.findIndex(line => line === '---') > 0) {
const endIndex = lines.findIndex((line, i) => i > 0 && line === '---');
lines.splice(endIndex + 1, 0, '', frontmatterDisplay, '');
processedContent = lines.join('\n');
} else {
processedContent = `${frontmatterDisplay}\n\n${processedContent}`;
}
}
return processedContent;
}
try {
// Check if content actually has frontmatter before trying to parse
if (!this.FRONTMATTER_PATTERN.test(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 });
result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle };
return `---\n${titleFrontmatter}---\n${content}`;
} else {
// No frontmatter found - add title frontmatter if we have a noteTitle
return content;
}
}
// Use gray-matter for robust frontmatter parsing
const matter = require('gray-matter');
// Add debugging to see what's being parsed
console.log('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected');
console.log('First 200 chars:', content.substring(0, 200));
const parsed = matter(content);
if (parsed.data && Object.keys(parsed.data).length > 0) {
// 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) {
let frontmatterTags: string[] = [];
if (Array.isArray(parsed.data.tags)) {
// Handle array of tags
frontmatterTags = parsed.data.tags
.map((tag: unknown) => typeof tag === 'string' ? tag : String(tag))
.filter((tag: string) => tag.trim() !== '');
} else if (typeof parsed.data.tags === 'string') {
// Handle comma-separated string or single tag
frontmatterTags = parsed.data.tags
.split(/[,\s]+/)
.map((tag: string) => tag.trim())
.filter((tag: string) => tag !== '');
}
// Merge with existing tags (avoid duplicates)
for (const tag of frontmatterTags) {
if (!result.metadata.tags.includes(tag)) {
result.metadata.tags.push(tag);
}
}
}
// 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();
}
// Handle frontmatter preservation and display options
const finalFrontmatter = this.noteTitle ?
{ ...parsed.data, title: this.noteTitle } :
parsed.data;
if (this.preserveFrontmatter) {
// Keep the frontmatter in the content, but reconstruct it with the modified title
const yaml = require('js-yaml');
const newFrontmatter = yaml.dump(finalFrontmatter);
let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`;
// Add printed frontmatter if requested
if (this.printFrontmatter) {
const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter);
processedContent = `---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n${parsed.content}`;
}
return processedContent;
} else {
// Return content without frontmatter, but add title as frontmatter for Pandoc
let processedContent: string;
if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
return `---\n${titleFrontmatter}---\n${content}`;
processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`;
} else {
return content;
processedContent = parsed.content;
}
}
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`);
// Fallback to simple regex-based parsing
const frontmatterMatch = content.match(this.FRONTMATTER_PATTERN);
if (frontmatterMatch) {
try {
const yamlContent = frontmatterMatch[1];
const frontmatter: Record<string, unknown> = {};
const lines = yamlContent.split('\n');
for (const line of lines) {
const colonIndex = line.indexOf(':');
if (colonIndex > 0) {
const key = line.substring(0, colonIndex).trim();
const value = line.substring(colonIndex + 1).trim();
const cleanValue = value.replace(/^["']|["']$/g, '');
frontmatter[key] = cleanValue;
}
}
// Replace title with noteTitle if provided
if (this.noteTitle) {
frontmatter.title = this.noteTitle;
}
result.metadata.frontmatter = frontmatter;
if (this.preserveFrontmatter) {
// Reconstruct frontmatter with modified title
if (this.noteTitle) {
const yaml = require('js-yaml');
const newFrontmatter = yaml.dump(frontmatter);
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`);
// Add printed frontmatter if requested
if (this.printFrontmatter) {
const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter);
processedContent = processedContent.replace(
this.FRONTMATTER_PATTERN,
`---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n`
);
}
return processedContent;
} else {
return content;
}
// Add printed frontmatter if requested
if (this.printFrontmatter) {
const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter);
// Insert after the title frontmatter but before content
const lines = processedContent.split('\n');
if (lines[0] === '---' && lines.findIndex(line => line === '---') > 0) {
const endIndex = lines.findIndex((line, i) => i > 0 && line === '---');
lines.splice(endIndex + 1, 0, '', frontmatterDisplay, '');
processedContent = lines.join('\n');
} else {
// 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 });
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`);
// Add printed frontmatter if requested
if (this.printFrontmatter) {
const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter);
processedContent = processedContent.replace(
this.FRONTMATTER_PATTERN,
`---\n${titleFrontmatter}---\n\n${frontmatterDisplay}\n\n`
);
}
return processedContent;
} else {
return content.replace(this.FRONTMATTER_PATTERN, '');
}
processedContent = `${frontmatterDisplay}\n\n${processedContent}`;
}
} catch (fallbackError: unknown) {
const fallbackErrorMessage = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);
result.warnings.push(`Fallback frontmatter parsing also failed: ${fallbackErrorMessage}`);
}
return processedContent;
}
} else {
// 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 });
result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle };
return `---\n${titleFrontmatter}---\n${content}`;
} else {
return content;
}
return content;
}
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.log('FrontmatterProcessor: gray-matter failed with error:', errorMessage);
console.log('Content being parsed (first 500 chars):', content.substring(0, 500));
result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`);
// Fallback to simple regex-based parsing
const frontmatterMatch = content.match(this.FRONTMATTER_PATTERN);
if (frontmatterMatch) {
try {
const yamlContent = frontmatterMatch[1];
const frontmatter: Record<string, unknown> = {};
const lines = yamlContent.split('\n');
for (const line of lines) {
const colonIndex = line.indexOf(':');
if (colonIndex > 0) {
const key = line.substring(0, colonIndex).trim();
const value = line.substring(colonIndex + 1).trim();
const cleanValue = value.replace(/^["']|["']$/g, '');
frontmatter[key] = cleanValue;
}
}
// Replace title with noteTitle if provided
if (this.noteTitle) {
frontmatter.title = this.noteTitle;
}
result.metadata.frontmatter = frontmatter;
if (this.preserveFrontmatter) {
// Reconstruct frontmatter with modified title
if (this.noteTitle) {
const yaml = require('js-yaml');
const newFrontmatter = yaml.dump(frontmatter);
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`);
// Add printed frontmatter if requested
if (this.printFrontmatter) {
const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter);
processedContent = processedContent.replace(
this.FRONTMATTER_PATTERN,
`---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n`
);
}
return processedContent;
} else {
return content;
}
} else {
// 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 });
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`);
// Add printed frontmatter if requested
if (this.printFrontmatter) {
const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter);
processedContent = processedContent.replace(
this.FRONTMATTER_PATTERN,
`---\n${titleFrontmatter}---\n\n${frontmatterDisplay}\n\n`
);
}
return processedContent;
} else {
return content.replace(this.FRONTMATTER_PATTERN, '');
}
}
} catch (fallbackError: unknown) {
const fallbackErrorMessage = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);
result.warnings.push(`Fallback frontmatter parsing also failed: ${fallbackErrorMessage}`);
}
} else {
// No frontmatter pattern found, but gray-matter failed - treat as file without frontmatter
if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle };
return `---\n${titleFrontmatter}---\n${content}`;
}
}
return content;
}
}
/**
* Format frontmatter as a readable display block
@@ -0,0 +1,77 @@
/**
* Processes horizontal rules to avoid conflicts with YAML frontmatter delimiters
*
* Transforms markdown horizontal rules that could be mistaken for YAML delimiters
* into alternative formats that Pandoc will still recognize as horizontal rules
* but won't interpret as YAML frontmatter boundaries.
*
* Preserves YAML frontmatter sections by detecting and skipping them.
*/
export class HorizontalRuleProcessor {
private readonly FRONTMATTER_PATTERN = /^---\s*\n([\s\S]*?)\n---\s*\n/;
constructor() {
// No initialization needed
}
/**
* Process horizontal rules to avoid YAML conflicts
*
* Transforms:
* - `---` (3 dashes) -> `***` (3 asterisks)
* - `----` (4+ dashes) -> `****` (4+ asterisks)
*
* Both formats are valid markdown horizontal rules but `***` won't be
* mistaken for YAML delimiters by Pandoc.
*
* Skips YAML frontmatter sections to preserve them.
*/
process(content: string): string {
// Check if content has frontmatter at the beginning
const frontmatterMatch = content.match(this.FRONTMATTER_PATTERN);
if (frontmatterMatch) {
// Content has frontmatter - separate it from the main content
const frontmatter = frontmatterMatch[0];
const mainContent = content.slice(frontmatter.length);
// Process only the main content (after frontmatter)
const processedMainContent = this.processContentLines(mainContent);
// Recombine frontmatter with processed main content
return frontmatter + processedMainContent;
} else {
// No frontmatter - process the entire content
return this.processContentLines(content);
}
}
/**
* Process lines for horizontal rule transformation
*/
private processContentLines(content: string): string {
// Split content into lines for processing
const lines = content.split('\n');
const processedLines: string[] = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Check if line is a horizontal rule made of dashes
// Must be at least 3 dashes, optionally with spaces
const dashRuleMatch = line.match(/^(\s*)(---+)(\s*)$/);
if (dashRuleMatch) {
// Transform dash horizontal rule to asterisk horizontal rule
const [, leadingSpaces, dashes, trailingSpaces] = dashRuleMatch;
const asterisks = '*'.repeat(dashes.length);
processedLines.push(`${leadingSpaces}${asterisks}${trailingSpaces}`);
} else {
// Keep line unchanged
processedLines.push(line);
}
}
return processedLines.join('\n');
}
}
+1 -1
View File
@@ -52,7 +52,7 @@ export class ModalSettingsHelper {
/**
* Build template variables object from plugin settings
*/
private static buildTemplateVariables(settings: obsidianTypstPDFExportSettings): Record<string, string | number | boolean> {
private static buildTemplateVariables(settings: obsidianTypstPDFExportSettings): Record<string, string | number | boolean | undefined> {
const baseVariables = {
pageSize: settings.pageSetup.size,
orientation: settings.pageSetup.orientation,
+1 -1
View File
@@ -132,7 +132,7 @@ export class ExportOrchestrator {
* Export a file with specific configuration
*/
async exportFileWithConfig(file: TFile, config: ExportConfig): Promise<void> {
const vaultPath = (this.plugin.app.vault.adapter as { basePath: string }).basePath;
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath;
const pluginDir = path.join(vaultPath, this.plugin.manifest.dir!);
// Create controller for this export (allows cancellation)
+1 -1
View File
@@ -57,7 +57,7 @@ export class PathResolver {
throw new Error(`Invalid output folder path: ${outputFolder}. Path contains invalid characters or traversal attempts.`);
}
const vaultPath = (this.plugin.app.vault.adapter as { basePath: string }).basePath;
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath;
const outputDir = path.join(vaultPath, outputFolder);
// Create output directory if it doesn't exist
+3 -3
View File
@@ -22,7 +22,7 @@ export class PluginLifecycle {
await this.plugin.loadSettings();
// Initialize embedded template manager
const vaultPath = (this.plugin.app.vault.adapter as { basePath: string }).basePath;
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath;
const pluginDir = path.join(vaultPath, this.plugin.manifest.dir!);
this.plugin.embeddedTemplateManager = new EmbeddedTemplateManager(pluginDir);
@@ -66,7 +66,7 @@ export class PluginLifecycle {
// Clean up temp directories on plugin unload
try {
const vaultPath = (this.plugin.app.vault.adapter as { basePath: string }).basePath;
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath;
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir);
cleanupManager.cleanupAllTempDirs();
} catch (error) {
@@ -79,7 +79,7 @@ export class PluginLifecycle {
*/
private cleanupStartupTempDirectories(): void {
try {
const vaultPath = (this.plugin.app.vault.adapter as { basePath: string }).basePath;
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath;
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir);
const _result = cleanupManager.cleanupAllTempDirs();
+1 -1
View File
@@ -15,7 +15,7 @@ export class TemplateManager {
this.plugin = plugin;
// Templates are stored in the plugin directory
this.templatesPath = path.join(
(this.plugin.app.vault.adapter as { basePath: string }).basePath,
(this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath,
this.plugin.manifest.dir!,
'templates'
);
+3 -3
View File
@@ -13,7 +13,7 @@ export interface ExportConfig {
/** Override output folder */
outputFolder?: string;
/** Template variables for this export */
templateVariables?: Record<string, string | number | boolean>;
templateVariables?: Record<string, string | number | boolean | undefined>;
/** Open PDF after export */
openAfterExport?: boolean;
/** Preserve folder structure when exporting */
@@ -59,9 +59,9 @@ export interface ValidationResult {
export interface ModalState {
settings: ExportConfigModalSettings;
templateVariables: Record<string, string | number | boolean>;
templateVariables: Record<string, string | number | boolean | undefined>;
updateSettings(updates: Partial<ExportConfigModalSettings>): void;
updateTemplateVariables(updates: Record<string, string | number | boolean>): void;
updateTemplateVariables(updates: Record<string, string | number | boolean | undefined>): void;
buildExportConfig(): ExportConfig;
notifyChange(): void;
setProgress(percent: number, operation: string): void;
+3 -3
View File
@@ -33,7 +33,7 @@ export class PageSetupSection implements ModalSection {
});
dropdown
.setValue(state.templateVariables.pageSize || 'a4')
.setValue(String(state.templateVariables.pageSize || 'a4'))
.onChange(value => {
state.updateTemplateVariables({ pageSize: value });
});
@@ -50,7 +50,7 @@ export class PageSetupSection implements ModalSection {
dropdown
.addOption('portrait', 'Portrait')
.addOption('landscape', 'Landscape')
.setValue(state.templateVariables.orientation || 'portrait')
.setValue(String(state.templateVariables.orientation || 'portrait'))
.onChange(value => {
const isLandscape = value === 'landscape';
state.updateTemplateVariables({
@@ -90,7 +90,7 @@ export class PageSetupSection implements ModalSection {
.addText(text => {
const input = text
.setPlaceholder(marginDefaults[side as keyof typeof marginDefaults])
.setValue(state.templateVariables[`margin${side.charAt(0).toUpperCase() + side.slice(1)}`] || marginDefaults[side as keyof typeof marginDefaults])
.setValue(String(state.templateVariables[`margin${side.charAt(0).toUpperCase() + side.slice(1)}`] || marginDefaults[side as keyof typeof marginDefaults]))
.onChange(value => {
const marginKey = `margin${side.charAt(0).toUpperCase() + side.slice(1)}`;
state.updateTemplateVariables({ [marginKey]: value });
+6 -6
View File
@@ -31,7 +31,7 @@ export class TypographySection implements ModalSection {
.setName('Body font')
.setDesc('Primary font for document text')
.addDropdown(dropdown => {
const currentFont = state.templateVariables.bodyFont || 'Times New Roman';
const currentFont = String(state.templateVariables.bodyFont || 'Times New Roman');
// Add all available fonts
availableFonts.forEach(font => {
@@ -56,7 +56,7 @@ export class TypographySection implements ModalSection {
.setName('Heading font')
.setDesc('Font for headings and titles')
.addDropdown(dropdown => {
const currentFont = state.templateVariables.headingFont || 'Times New Roman';
const currentFont = String(state.templateVariables.headingFont || 'Times New Roman');
// Add all available fonts
availableFonts.forEach(font => {
@@ -81,7 +81,7 @@ export class TypographySection implements ModalSection {
.setName('Monospace font')
.setDesc('Font for code blocks and inline code')
.addDropdown(dropdown => {
const currentFont = state.templateVariables.monospaceFont || 'Courier New';
const currentFont = String(state.templateVariables.monospaceFont || 'Courier New');
// Add all available fonts
availableFonts.forEach(font => {
@@ -111,7 +111,7 @@ export class TypographySection implements ModalSection {
.setDesc('Base font size for document text (in points)')
.addSlider(slider => slider
.setLimits(8, 16, 0.5)
.setValue(state.templateVariables.bodyFontSize || 11)
.setValue(Number(state.templateVariables.bodyFontSize || 11))
.setDynamicTooltip()
.onChange(value => {
state.updateTemplateVariables({ bodyFontSize: value });
@@ -179,7 +179,7 @@ export class TypographySection implements ModalSection {
: state.templateVariables.headingFont;
dropdown
.setValue(currentValue || 'Concourse OT')
.setValue(String(currentValue || 'Concourse OT'))
.onChange((value: string) => {
if (fontType === 'body') {
state.updateTemplateVariables({ bodyFont: value });
@@ -199,7 +199,7 @@ export class TypographySection implements ModalSection {
.addOption('DejaVu Sans Mono', 'DejaVu Sans Mono')
.addOption('Liberation Mono', 'Liberation Mono')
.addOption('Ubuntu Mono', 'Ubuntu Mono')
.setValue(state.templateVariables.monospaceFont || 'Source Code Pro')
.setValue(String(state.templateVariables.monospaceFont || 'Source Code Pro'))
.onChange((value: string) => {
state.updateTemplateVariables({ monospaceFont: value });
});
+2 -2
View File
@@ -8,7 +8,7 @@ import { ExportFormat, obsidianTypstPDFExportSettings } from '../../../core/sett
export class ModalState implements IModalState {
settings: ExportConfigModalSettings;
templateVariables: Record<string, string | number | boolean>;
templateVariables: Record<string, string | number | boolean | undefined>;
private changeListeners: Set<() => void> = new Set();
private static readonly STORAGE_KEY = 'typst-export-modal-state';
@@ -64,7 +64,7 @@ export class ModalState implements IModalState {
/**
* Update template variables
*/
updateTemplateVariables(updates: Record<string, string | number | boolean>): void {
updateTemplateVariables(updates: Record<string, string | number | boolean | undefined>): void {
this.templateVariables = {
...this.templateVariables,
...updates
+3
View File
@@ -1,3 +1,6 @@
// Horizontal rule definition for Pandoc compatibility
#let horizontalrule = line(start: (25%,0%), end: (75%,0%))
// Email block styling function
#let email-block(from: none, to: none, subject: none, date: none, body) = {
block(
+3
View File
@@ -1,3 +1,6 @@
// Horizontal rule definition for Pandoc compatibility
#let horizontalrule = pad(y: 11pt, (line(stroke: 2pt + gray, length: 75%)))
// Email block styling function
#let email-block(from: none, to: none, subject: none, date: none, body) = {
block(
+3
View File
@@ -1,3 +1,6 @@
// Horizontal rule definition for Pandoc compatibility
#let horizontalrule = line(start: (25%,0%), end: (75%,0%))
// Email block styling function - compact for single page
#let email-block(from: none, to: none, subject: none, date: none, body) = {
block(
+3
View File
@@ -1,3 +1,6 @@
// Horizontal rule definition for Pandoc compatibility
#let horizontalrule = line(start: (25%,0%), end: (75%,0%))
// Email block styling function
#let email-block(from: none, to: none, subject: none, date: none, body) = {
block(
+1 -1
View File
@@ -1,7 +1,7 @@
// Universal Pandoc wrapper for all Typst templates
// This wrapper handles Pandoc's variable substitution and passes them to the actual Typst template
#import "$template_path$": conf, email-block
#import "$template_path$": conf, email-block, horizontalrule
#show: doc => conf(
$if(title)$title: [$title$],$else$title: none,$endif$
+2 -1
View File
@@ -2,5 +2,6 @@
"1.0.0": "1.9.12",
"1.0.1": "1.9.12",
"1.1.0": "1.9.12",
"1.2.0": "1.9.12"
"1.2.0": "1.9.12",
"1.2.1": "1.9.12"
}