Applies Obsidian linter and fixes code issues
Applies linting rules to the codebase and resolves identified issues. Addresses: - Renamed headings in settings tabs to improve UI consistency and style. - Resolved require() style imports - Added void operator to ensure correct promise handling. - Replaced deprecated Obsidian API calls. - Enforces sentence case to enhance UI text consistency.
This commit is contained in:
37 files changed
+4314
-872
No files matched your search
@@ -202,7 +202,7 @@ export interface MarkdownPreprocessorConfig {
|
||||
*
|
||||
* // Process markdown
|
||||
* const obsidianMarkdown = '# My Note\n\n[[internal-link]]\n\n![[image.png]]';
|
||||
* const result = await preprocessor.process(obsidianMarkdown);
|
||||
* const result = preprocessor.process(obsidianMarkdown);
|
||||
*
|
||||
* console.log(result.content); // Standard markdown
|
||||
* console.log(result.metadata.imageEmbeds); // Image processing info
|
||||
@@ -218,7 +218,7 @@ export interface MarkdownPreprocessorConfig {
|
||||
* });
|
||||
*
|
||||
* // Process with new configuration
|
||||
* const newResult = await preprocessor.process(markdown);
|
||||
* const newResult = preprocessor.process(markdown);
|
||||
* ```
|
||||
*/
|
||||
export class MarkdownPreprocessor {
|
||||
@@ -268,7 +268,6 @@ export class MarkdownPreprocessor {
|
||||
* in the correct order, aggregates metadata from each stage, and returns a complete
|
||||
* result with processed content and comprehensive metadata.
|
||||
*
|
||||
* The method is async to support future extensions (though current processors are sync).
|
||||
* Processing is stateless - each call operates independently on the provided content.
|
||||
*
|
||||
* Processing Order (critical for avoiding conflicts):
|
||||
@@ -300,7 +299,7 @@ export class MarkdownPreprocessor {
|
||||
* Callout: > [!note] This is important
|
||||
* `;
|
||||
*
|
||||
* const result = await preprocessor.process(markdown);
|
||||
* const result = preprocessor.process(markdown);
|
||||
*
|
||||
* // Check for errors
|
||||
* if (result.errors.length > 0) {
|
||||
@@ -320,7 +319,7 @@ export class MarkdownPreprocessor {
|
||||
* ```typescript
|
||||
* // Handle remote images
|
||||
* const markdown = '';
|
||||
* const result = await preprocessor.process(markdown);
|
||||
* const result = preprocessor.process(markdown);
|
||||
*
|
||||
* // Remote images are queued for download
|
||||
* result.metadata.imageEmbeds.forEach(embed => {
|
||||
@@ -329,7 +328,7 @@ export class MarkdownPreprocessor {
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
public async process(content: string): Promise<PreprocessingResult> {
|
||||
public process(content: string): PreprocessingResult {
|
||||
const result: PreprocessingResult = {
|
||||
content: content,
|
||||
metadata: {
|
||||
@@ -506,7 +505,7 @@ export class MarkdownPreprocessor {
|
||||
* });
|
||||
*
|
||||
* // Process note with web-friendly links
|
||||
* const result = await preprocessor.process(markdown);
|
||||
* const result = preprocessor.process(markdown);
|
||||
* // Links will use the new base URL
|
||||
* ```
|
||||
*
|
||||
@@ -521,7 +520,7 @@ export class MarkdownPreprocessor {
|
||||
* });
|
||||
*
|
||||
* // Process with HTML-style links
|
||||
* const result = await preprocessor.process(markdown);
|
||||
* const result = preprocessor.process(markdown);
|
||||
* // [[note]] becomes [note](note.html)
|
||||
* ```
|
||||
*
|
||||
|
||||
@@ -299,7 +299,7 @@ export class PandocTypstConverter {
|
||||
this.processCleanupHandler = () => {
|
||||
// Only cleanup if not already disposed to avoid double-cleanup
|
||||
if (!this.isDisposed) {
|
||||
this.cleanup();
|
||||
void this.cleanup();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -364,14 +364,14 @@ export class PandocTypstConverter {
|
||||
if (!this.tempDir) {
|
||||
if (this.pandocOptions.vaultBasePath) {
|
||||
// Use TempDirectoryManager for plugin temp directories
|
||||
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian';
|
||||
const configDir = this.plugin?.app?.vault?.configDir;
|
||||
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
|
||||
this.tempDir = await tempManager.ensureTempDir('pandoc');
|
||||
} else {
|
||||
// Fallback to system temp if plugin folder not available - use TempDirectoryManager fallback
|
||||
const pathUtils = new PathUtils(this.plugin.app);
|
||||
const vaultPath = pathUtils.getVaultPath();
|
||||
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian';
|
||||
const configDir = this.plugin?.app?.vault?.configDir;
|
||||
const tempManager = new TempDirectoryManager({ vaultPath, configDir, app: this.plugin.app });
|
||||
this.tempDir = await tempManager.ensureTempDir('pandoc');
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* Handles discovery of pdf2img and other CLI tools in the Obsidian environment.
|
||||
*/
|
||||
|
||||
import { promises as fs } from 'fs';
|
||||
import * as path from 'path';
|
||||
import type { obsidianTypstPDFExport } from '../../../main';
|
||||
import { PathUtils } from '../../core/PathUtils';
|
||||
@@ -30,7 +31,10 @@ export class BinaryLocator {
|
||||
// In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path
|
||||
// Try multiple strategies to find the plugin directory
|
||||
const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export';
|
||||
const configDir = plugin?.app.vault.configDir || '.obsidian';
|
||||
const configDir = plugin?.app.vault.configDir;
|
||||
if (!configDir) {
|
||||
throw new Error('Unable to determine Obsidian configuration directory');
|
||||
}
|
||||
const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir);
|
||||
|
||||
// Find the first directory that exists and has node_modules
|
||||
@@ -154,7 +158,6 @@ export class BinaryLocator {
|
||||
try {
|
||||
if (!plugin?.app) {
|
||||
// This should not happen in normal plugin operation, but provide fallback
|
||||
const fs = require('fs').promises;
|
||||
await fs.access(binaryPath);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* Handles filename pattern matching when pdf2img generates files with different names.
|
||||
*/
|
||||
|
||||
import { promises as fs } from 'fs';
|
||||
import * as path from 'path';
|
||||
import { PathUtils } from '../../core/PathUtils';
|
||||
import type { obsidianTypstPDFExport } from '../../../main';
|
||||
@@ -35,7 +36,6 @@ export class FileDiscovery {
|
||||
if (!plugin?.app) {
|
||||
// Fallback to path for external tool output directories
|
||||
const expectedOutputPath = path.join(outputDir, expectedFileName);
|
||||
const fs = require('fs').promises;
|
||||
try {
|
||||
await fs.access(expectedOutputPath);
|
||||
return {
|
||||
@@ -112,8 +112,7 @@ export class FileDiscovery {
|
||||
files = dirList.files.map(f => path.basename(f));
|
||||
} else {
|
||||
// Use filesystem fallback for absolute/external paths
|
||||
const fs = require('fs').promises;
|
||||
files = await fs.readdir(outputDir);
|
||||
files = await fs.readdir(outputDir);
|
||||
}
|
||||
|
||||
// Look for any image files that might match
|
||||
@@ -180,7 +179,6 @@ export class FileDiscovery {
|
||||
expectedOutputPath: string
|
||||
): Promise<FileDiscoveryResult> {
|
||||
try {
|
||||
const fs = require('fs').promises;
|
||||
// Debug: List what files are actually in the output directory
|
||||
const files = await fs.readdir(outputDir);
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
* Handles format conversion, quality management, and dimension detection.
|
||||
*/
|
||||
|
||||
import { spawn } from 'child_process';
|
||||
import { promises as fs } from 'fs';
|
||||
import * as path from 'path';
|
||||
import { PathUtils } from '../../core/PathUtils';
|
||||
import type { obsidianTypstPDFExport } from '../../../main';
|
||||
@@ -58,7 +60,6 @@ export class ImageOptimizer {
|
||||
quality: number = 90
|
||||
): Promise<{success: boolean; error?: string}> {
|
||||
try {
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
// Use ImageMagick to convert PNG to JPEG
|
||||
const convertProcess = spawn('magick', [
|
||||
@@ -108,7 +109,6 @@ export class ImageOptimizer {
|
||||
fallbackDimensions: ImageDimensions = { width: 800, height: 600 }
|
||||
): Promise<{dimensions: ImageDimensions; success: boolean; error?: string}> {
|
||||
try {
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
// Use ImageMagick identify to get image dimensions
|
||||
const identifyProcess = spawn('magick', [
|
||||
@@ -233,7 +233,6 @@ export class ImageOptimizer {
|
||||
|
||||
await plugin.app.vault.adapter.remove(relativePath);
|
||||
} else {
|
||||
const fs = require('fs').promises;
|
||||
await fs.unlink(inputImagePath);
|
||||
}
|
||||
} catch (unlinkError) {
|
||||
@@ -249,7 +248,6 @@ export class ImageOptimizer {
|
||||
await plugin.app.vault.adapter.writeBinary(pngFinalPath, content);
|
||||
await plugin.app.vault.adapter.remove(inputImagePath);
|
||||
} else {
|
||||
const fs = require('fs').promises;
|
||||
await fs.rename(inputImagePath, pngFinalPath);
|
||||
}
|
||||
actualImagePath = pngFinalPath;
|
||||
@@ -261,7 +259,6 @@ export class ImageOptimizer {
|
||||
await plugin.app.vault.adapter.writeBinary(finalOutputPath, content);
|
||||
await plugin.app.vault.adapter.remove(inputImagePath);
|
||||
} else {
|
||||
const fs = require('fs').promises;
|
||||
await fs.rename(inputImagePath, finalOutputPath);
|
||||
}
|
||||
actualImagePath = finalOutputPath;
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
* Executes external pdf2img binary to convert PDF pages to images.
|
||||
*/
|
||||
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import * as path from 'path';
|
||||
import { BinaryLocator } from './BinaryLocator';
|
||||
import { EnvironmentUtils } from './EnvironmentUtils';
|
||||
@@ -111,8 +113,6 @@ export class PdfCliExecutor {
|
||||
plugin?: obsidianTypstPDFExport
|
||||
): Promise<PdfCliResult> {
|
||||
try {
|
||||
const { exec } = require('child_process');
|
||||
const { promisify } = require('util');
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
// Get augmented environment for CLI execution
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
* Extracted from MarkdownPreprocessor for better code organization
|
||||
*/
|
||||
|
||||
import * as yaml from 'js-yaml';
|
||||
import matter from 'gray-matter';
|
||||
import { PreprocessingResult } from '../MarkdownPreprocessor';
|
||||
|
||||
export interface FrontmatterProcessorConfig {
|
||||
@@ -32,7 +34,6 @@ export class FrontmatterProcessor {
|
||||
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 };
|
||||
@@ -43,11 +44,10 @@ export class FrontmatterProcessor {
|
||||
}
|
||||
|
||||
// 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));
|
||||
console.debug('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected');
|
||||
console.debug('First 200 chars:', content.substring(0, 200));
|
||||
|
||||
const parsed = matter(content);
|
||||
|
||||
@@ -100,7 +100,6 @@ export class FrontmatterProcessor {
|
||||
|
||||
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}`;
|
||||
|
||||
@@ -115,8 +114,7 @@ export class FrontmatterProcessor {
|
||||
// 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 });
|
||||
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
||||
processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`;
|
||||
} else {
|
||||
processedContent = parsed.content;
|
||||
@@ -141,7 +139,6 @@ export class FrontmatterProcessor {
|
||||
} 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 };
|
||||
@@ -152,8 +149,8 @@ export class FrontmatterProcessor {
|
||||
}
|
||||
} 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));
|
||||
console.error('FrontmatterProcessor: gray-matter failed with error:', errorMessage);
|
||||
console.error('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
|
||||
@@ -185,8 +182,7 @@ export class FrontmatterProcessor {
|
||||
if (this.preserveFrontmatter) {
|
||||
// Reconstruct frontmatter with modified title
|
||||
if (this.noteTitle) {
|
||||
const yaml = require('js-yaml');
|
||||
const newFrontmatter = yaml.dump(frontmatter);
|
||||
const newFrontmatter = yaml.dump(frontmatter);
|
||||
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`);
|
||||
|
||||
// Add printed frontmatter if requested
|
||||
@@ -205,8 +201,7 @@ export class FrontmatterProcessor {
|
||||
} 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 });
|
||||
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
||||
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`);
|
||||
|
||||
// Add printed frontmatter if requested
|
||||
@@ -230,7 +225,6 @@ export class FrontmatterProcessor {
|
||||
} 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 };
|
||||
@@ -265,13 +259,18 @@ export class FrontmatterProcessor {
|
||||
if (Array.isArray(value)) {
|
||||
// For arrays, put each item on its own line if there are many items
|
||||
if (value.length > 3) {
|
||||
formattedValue = '\n\n' + value.map(item => `- ${item}`).join('\n') + '\n';
|
||||
formattedValue = '\n\n' + value.map(item =>
|
||||
typeof item === 'object' ? JSON.stringify(item) : String(item)
|
||||
).join('\n').split('\n').map(line => `- ${line}`).join('\n') + '\n';
|
||||
} else {
|
||||
formattedValue = value.join(', ');
|
||||
formattedValue = value.map(item =>
|
||||
typeof item === 'object' ? JSON.stringify(item) : String(item)
|
||||
).join(', ');
|
||||
}
|
||||
} else if (typeof value === 'object') {
|
||||
} else if (typeof value === 'object' && value !== null) {
|
||||
formattedValue = JSON.stringify(value);
|
||||
} else {
|
||||
} else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
||||
// Handle primitive values
|
||||
const valueStr = String(value);
|
||||
// If the value is very long (like email lists), break it up
|
||||
if (valueStr.length > 80 && valueStr.includes(',')) {
|
||||
@@ -308,8 +307,11 @@ export class FrontmatterProcessor {
|
||||
} else {
|
||||
formattedValue = valueStr;
|
||||
}
|
||||
} else {
|
||||
// Handle null, undefined, or any other unexpected types
|
||||
formattedValue = '';
|
||||
}
|
||||
|
||||
|
||||
// Add line break after the property label, then the value
|
||||
if (formattedValue.startsWith('\n')) {
|
||||
// Value already starts with newline (like lists), so just add the label
|
||||
|
||||
@@ -348,12 +348,12 @@ ${dependencyResult.allAvailable
|
||||
* // Run 'Check Dependencies' command for details."
|
||||
* ```
|
||||
*/
|
||||
public static async checkDependenciesAsync(
|
||||
public static checkDependenciesAsync(
|
||||
pandocPath?: string,
|
||||
typstPath?: string,
|
||||
imagemagickPath?: string,
|
||||
additionalPaths: string[] = []
|
||||
): Promise<void> {
|
||||
): void {
|
||||
// Check dependencies silently on startup
|
||||
try {
|
||||
const missingDeps = this.checkDependenciesSync(
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
* - Cross-platform path handling (Unix and Windows)
|
||||
*/
|
||||
|
||||
import { spawn, spawnSync } from 'child_process';
|
||||
import { DEPENDENCY_CONSTANTS } from './constants';
|
||||
import * as path from 'path';
|
||||
|
||||
@@ -140,8 +141,6 @@ export class ExecutableChecker {
|
||||
* ```
|
||||
*/
|
||||
private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> {
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
try {
|
||||
const stdout = await new Promise<string>((resolve, reject) => {
|
||||
const env = this.getAugmentedEnv(additionalPaths);
|
||||
@@ -259,8 +258,6 @@ export class ExecutableChecker {
|
||||
const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName;
|
||||
|
||||
// Try to find the executable using which command synchronously
|
||||
const { spawnSync } = require('child_process');
|
||||
|
||||
// Use platform-specific command: 'where' on Windows, 'which' on Unix
|
||||
const whichCommand = process.platform === 'win32' ? 'where' : 'which';
|
||||
|
||||
@@ -323,8 +320,6 @@ export class ExecutableChecker {
|
||||
versionCommand: string,
|
||||
versionRegex: RegExp
|
||||
): Promise<DependencyInfo> {
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
try {
|
||||
// Use spawn instead of exec for security - arguments passed separately
|
||||
const stdout = await new Promise<string>((resolve, reject) => {
|
||||
@@ -396,8 +391,6 @@ export class ExecutableChecker {
|
||||
* ```
|
||||
*/
|
||||
public static checkDependencySync(executablePath: string, versionCommand: string): boolean {
|
||||
const { spawnSync } = require('child_process');
|
||||
|
||||
try {
|
||||
const result = spawnSync(executablePath, versionCommand.split(' '), {
|
||||
encoding: 'utf8',
|
||||
|
||||
@@ -181,7 +181,7 @@ export class ExportErrorHandler {
|
||||
console.warn(`${operation}:`, error);
|
||||
break;
|
||||
case 'info':
|
||||
console.info(`${operation}:`, error);
|
||||
console.debug(`${operation}:`, error);
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
*/
|
||||
|
||||
import { TFile } from 'obsidian';
|
||||
import { obsidianTypstPDFExportSettings } from './settings';
|
||||
import { obsidianTypstPDFExportSettings, ExportFormat } from './settings';
|
||||
import { ExportConfigModalSettings } from '../ui/modal/modalTypes';
|
||||
|
||||
/**
|
||||
@@ -179,8 +179,8 @@ export class ModalSettingsHelper {
|
||||
};
|
||||
|
||||
// Auto-adjust width for single-page landscape mode
|
||||
const landscapeAdjustment = settings.pageSetup.orientation === 'landscape'
|
||||
&& settings.exportDefaults.format === 'single-page'
|
||||
const landscapeAdjustment = settings.pageSetup.orientation === 'landscape'
|
||||
&& settings.exportDefaults.format === ExportFormat.SinglePage
|
||||
? { width: 'auto' }
|
||||
: {};
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// ABOUTME: Centralized path utilities for safe Obsidian API operations
|
||||
// ABOUTME: Handles vault paths, plugin directories, and file operations
|
||||
|
||||
import { promises as fs } from 'fs';
|
||||
import { FileSystemAdapter, normalizePath, Notice } from 'obsidian';
|
||||
import type { App, PluginManifest } from 'obsidian';
|
||||
import * as path from 'path';
|
||||
@@ -238,7 +239,6 @@ export class PathUtils {
|
||||
|
||||
if (isAbsolutePath) {
|
||||
try {
|
||||
const fs = require('fs').promises;
|
||||
await fs.access(path);
|
||||
return true;
|
||||
} catch {
|
||||
|
||||
@@ -218,7 +218,7 @@ export class SecurityUtils {
|
||||
// Check for command injection attempts
|
||||
const dangerousPatterns = [
|
||||
/[;&|`$<>]/, // Shell metacharacters that can't appear in safe paths
|
||||
// eslint-disable-next-line no-control-regex
|
||||
// eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
|
||||
/\x00/, // Null bytes
|
||||
/\n|\r/, // Newlines
|
||||
/\s*[;&|]\s*/, // Command separators with whitespace
|
||||
@@ -374,7 +374,8 @@ export class SecurityUtils {
|
||||
if (/[;&|`$<>]/.test(normalizedPath)) {
|
||||
return 'Shell metacharacters are not allowed in executable paths';
|
||||
}
|
||||
if (/\x00/.test(normalizedPath)) { // eslint-disable-line no-control-regex
|
||||
// eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
|
||||
if (/\x00/.test(normalizedPath)) {
|
||||
return 'Null bytes are not allowed in paths';
|
||||
}
|
||||
if (/\n|\r/.test(normalizedPath)) {
|
||||
|
||||
@@ -18,7 +18,9 @@ export class CommandRegistry {
|
||||
id: 'export-current-note',
|
||||
name: 'Export current note(s)',
|
||||
editorCallback: (editor: Editor, view: MarkdownView) => {
|
||||
this.plugin.exportCurrentNote(view);
|
||||
this.plugin.exportCurrentNote(view).catch(error => {
|
||||
console.error('Failed to export current note:', error);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -27,7 +29,9 @@ export class CommandRegistry {
|
||||
id: 'export-with-config',
|
||||
name: 'Export with configuration…',
|
||||
editorCallback: (editor: Editor, view: MarkdownView) => {
|
||||
this.plugin.showExportModal(view);
|
||||
this.plugin.showExportModal(view).catch(error => {
|
||||
console.error('Failed to show export modal:', error);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -36,7 +40,9 @@ export class CommandRegistry {
|
||||
id: 'check-dependencies',
|
||||
name: 'Check Pandoc and Typst dependencies',
|
||||
callback: () => {
|
||||
this.plugin.showDependencyStatus();
|
||||
this.plugin.showDependencyStatus().catch(error => {
|
||||
console.error('Failed to show dependency status:', error);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
* Handles processing of PDF, image, and file embeds for PDF export
|
||||
*/
|
||||
|
||||
import { exec } from 'child_process';
|
||||
import * as util from 'util';
|
||||
import { TFile } from 'obsidian';
|
||||
import type { obsidianTypstPDFExport } from '../../main';
|
||||
import type { PreprocessingResult } from '../converters/MarkdownPreprocessor';
|
||||
@@ -108,7 +110,7 @@ export class EmbedProcessor {
|
||||
// Select appropriate protocol based on parsed URL (handles case-insensitive schemes)
|
||||
const protocol = urlObj.protocol === 'https:' ? https : http;
|
||||
|
||||
console.log(`Export: Downloading remote image: ${imageUrl}`);
|
||||
console.debug(`Export:Downloading remote image: ${imageUrl}`);
|
||||
|
||||
// Use parsed URL object for the request to ensure correct protocol handling
|
||||
const request = protocol.get(urlObj, (response) => {
|
||||
@@ -120,7 +122,7 @@ export class EmbedProcessor {
|
||||
// This handles both absolute URLs (e.g., "https://example.com/img.png")
|
||||
// and relative URLs (e.g., "/assets/img.png" or "../img.png")
|
||||
const absoluteRedirectUrl = new URL(redirectUrl, imageUrl).href;
|
||||
console.log(`Export: Following redirect to: ${absoluteRedirectUrl}`);
|
||||
console.debug(`Export:Following redirect to: ${absoluteRedirectUrl}`);
|
||||
// Recursively follow redirect with resolved absolute URL
|
||||
this.downloadRemoteImage(absoluteRedirectUrl, tempDir).then(resolve);
|
||||
return;
|
||||
@@ -157,7 +159,7 @@ export class EmbedProcessor {
|
||||
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
|
||||
await this.plugin.app.vault.adapter.writeBinary(outputPath, arrayBuffer);
|
||||
|
||||
console.log(`Export: Successfully downloaded image to: ${outputPath}`);
|
||||
console.debug(`Export:Successfully downloaded image to: ${outputPath}`);
|
||||
resolve(outputPath);
|
||||
} catch (err) {
|
||||
console.error(`Export: Error writing image file: ${err.message}`);
|
||||
@@ -295,13 +297,13 @@ export class EmbedProcessor {
|
||||
|
||||
if (isRemoteUrl) {
|
||||
// Try to download the remote image
|
||||
console.log(`Export: Attempting to download remote image: ${decodedPath}`);
|
||||
console.debug(`Export:Attempting to download remote image: ${decodedPath}`);
|
||||
const downloadedPath = await this.downloadRemoteImage(decodedPath, tempDir);
|
||||
|
||||
if (downloadedPath) {
|
||||
// Successfully downloaded, use it as a local image
|
||||
fullImagePath = downloadedPath;
|
||||
console.log(`Export: Successfully downloaded and will embed remote image`);
|
||||
console.debug(`Export:Successfully downloaded and will embed remote image`);
|
||||
} else {
|
||||
// Download failed, use placeholder
|
||||
console.warn(`Export: Failed to download remote image: ${decodedPath}`);
|
||||
@@ -342,11 +344,9 @@ export class EmbedProcessor {
|
||||
await this.pathUtils.ensureDir(vaultTempImagesDir);
|
||||
|
||||
const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName);
|
||||
|
||||
const { exec } = require('child_process');
|
||||
const util = require('util');
|
||||
|
||||
const execAsync = util.promisify(exec);
|
||||
|
||||
|
||||
try {
|
||||
// Use PathResolver to get the correct ImageMagick path
|
||||
const { PathResolver } = await import('./PathResolver');
|
||||
|
||||
@@ -23,7 +23,9 @@ export class EventHandlers {
|
||||
.setTitle('Export to PDF (Typst)')
|
||||
.setIcon('file-output')
|
||||
.onClick(() => {
|
||||
this.plugin.exportFile(file);
|
||||
this.plugin.exportFile(file).catch(error => {
|
||||
console.error('Failed to export file:', error);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -38,7 +40,9 @@ export class EventHandlers {
|
||||
.setTitle('Export to PDF (Typst)')
|
||||
.setIcon('file-output')
|
||||
.onClick(() => {
|
||||
this.plugin.exportCurrentNote(view);
|
||||
this.plugin.exportCurrentNote(view).catch(error => {
|
||||
console.error('Failed to export current note:', error);
|
||||
});
|
||||
});
|
||||
});
|
||||
})
|
||||
@@ -48,7 +52,7 @@ export class EventHandlers {
|
||||
this.plugin.registerEvent(
|
||||
this.plugin.app.workspace.on('files-menu', (menu: Menu, files: TAbstractFile[]) => {
|
||||
// Filter for markdown files only
|
||||
const markdownFiles = files.filter(this.plugin.isMarkdownFile);
|
||||
const markdownFiles = files.filter((file) => this.plugin.isMarkdownFile(file));
|
||||
|
||||
if (markdownFiles.length > 0) {
|
||||
menu.addItem((item) => {
|
||||
@@ -56,7 +60,9 @@ export class EventHandlers {
|
||||
.setTitle(`Export to PDF (Typst)`)
|
||||
.setIcon('file-output')
|
||||
.onClick(() => {
|
||||
this.plugin.exportFiles(markdownFiles);
|
||||
this.plugin.exportFiles(markdownFiles).catch(error => {
|
||||
console.error('Failed to export files:', error);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -65,7 +71,9 @@ export class EventHandlers {
|
||||
.setTitle(`Export with configuration...`)
|
||||
.setIcon('settings')
|
||||
.onClick(() => {
|
||||
this.plugin.showExportModalForFiles(markdownFiles);
|
||||
this.plugin.showExportModalForFiles(markdownFiles).catch(error => {
|
||||
console.error('Failed to show export modal for files:', error);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -92,7 +100,9 @@ export class EventHandlers {
|
||||
.setTitle('Export current note(s)')
|
||||
.setIcon('file-output')
|
||||
.onClick(() => {
|
||||
this.plugin.exportFile(activeView.file!);
|
||||
this.plugin.exportFile(activeView.file!).catch(error => {
|
||||
console.error('Failed to export file:', error);
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
@@ -101,7 +111,9 @@ export class EventHandlers {
|
||||
.setTitle('Export with configuration…')
|
||||
.setIcon('settings')
|
||||
.onClick(() => {
|
||||
this.plugin.showExportModal(activeView);
|
||||
this.plugin.showExportModal(activeView).catch(error => {
|
||||
console.error('Failed to show export modal:', error);
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ export class ExportOrchestrator {
|
||||
|
||||
// Create progress notice with cancel button
|
||||
const progressNotice = new Notice('', 0);
|
||||
const cancelButton = progressNotice.noticeEl.createEl('button', {
|
||||
const cancelButton = progressNotice.messageEl.createEl('button', {
|
||||
text: 'Cancel',
|
||||
cls: 'mod-warning'
|
||||
});
|
||||
@@ -179,7 +179,7 @@ export class ExportOrchestrator {
|
||||
noteTitle: file.basename
|
||||
});
|
||||
|
||||
const processedResult = await preprocessor.process(content);
|
||||
const processedResult = preprocessor.process(content);
|
||||
|
||||
if (processedResult.errors.length > 0) {
|
||||
console.warn('Preprocessing errors:', processedResult.errors);
|
||||
@@ -319,7 +319,7 @@ export class ExportOrchestrator {
|
||||
*/
|
||||
async handleFolderExport(folder: TFolder): Promise<void> {
|
||||
// Get all markdown files in the folder
|
||||
const markdownFiles = folder.children.filter(this.plugin.isMarkdownFile);
|
||||
const markdownFiles = folder.children.filter((file) => this.plugin.isMarkdownFile(file));
|
||||
|
||||
if (markdownFiles.length === 0) {
|
||||
new Notice('No markdown files found in this folder');
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* Handles font discovery, caching, and retrieval for the plugin
|
||||
*/
|
||||
|
||||
import { spawn } from 'child_process';
|
||||
import type { obsidianTypstPDFExport } from '../../main';
|
||||
import { ExportErrorHandler } from '../core/ExportErrorHandler';
|
||||
import { FALLBACK_FONTS } from '../core/constants';
|
||||
@@ -16,8 +17,6 @@ export class FontManager {
|
||||
*/
|
||||
async cacheAvailableFonts(): Promise<void> {
|
||||
try {
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
const typstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst');
|
||||
|
||||
// Use spawn instead of exec for security - arguments passed separately
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* Handles executable path resolution and output path preparation
|
||||
*/
|
||||
|
||||
import { spawnSync } from 'child_process';
|
||||
import { TFile } from 'obsidian';
|
||||
import type { obsidianTypstPDFExport } from '../../main';
|
||||
import { SecurityUtils } from '../core/SecurityUtils';
|
||||
@@ -26,8 +27,6 @@ export class PathResolver {
|
||||
}
|
||||
|
||||
// Try to find the executable using which command
|
||||
const { spawnSync } = require('child_process');
|
||||
|
||||
// Use platform-specific command: 'where' on Windows, 'which' on Unix
|
||||
const whichCommand = process.platform === 'win32' ? 'where' : 'which';
|
||||
|
||||
|
||||
@@ -51,12 +51,12 @@ export class PluginLifecycle {
|
||||
|
||||
// Clean up any leftover temp directories from previous sessions
|
||||
this.cleanupStartupTempDirectories();
|
||||
|
||||
// Check dependencies on startup (async, don't await)
|
||||
|
||||
// Check dependencies on startup
|
||||
this.plugin.checkDependenciesAsync();
|
||||
|
||||
|
||||
// Cache available fonts (async, don't await)
|
||||
this.plugin.cacheAvailableFonts();
|
||||
void this.plugin.cacheAvailableFonts();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,7 +69,7 @@ export class PluginLifecycle {
|
||||
}
|
||||
|
||||
// Clean up temp directories on plugin unload (fire-and-forget async)
|
||||
(async () => {
|
||||
void (async () => {
|
||||
try {
|
||||
const vaultPath = this.pathUtils.getVaultPath();
|
||||
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
|
||||
@@ -85,11 +85,11 @@ export class PluginLifecycle {
|
||||
*/
|
||||
private cleanupStartupTempDirectories(): void {
|
||||
// Clean up temp directories (fire-and-forget async)
|
||||
(async () => {
|
||||
void (async () => {
|
||||
try {
|
||||
const vaultPath = this.pathUtils.getVaultPath();
|
||||
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
|
||||
const _result = await cleanupManager.cleanupAllTempDirs();
|
||||
await cleanupManager.cleanupAllTempDirs();
|
||||
|
||||
if (this.plugin.settings.behavior.debugMode) {
|
||||
// Debug logging was here but empty in original
|
||||
|
||||
@@ -27,8 +27,10 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
display(): void {
|
||||
const { containerEl } = this;
|
||||
containerEl.empty();
|
||||
|
||||
containerEl.createEl('h2', { text: 'Typst PDF Export Settings' });
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName('Typst PDF Export Settings')
|
||||
.setHeading();
|
||||
|
||||
// Executable paths section
|
||||
this.createExecutablePathsSection(containerEl);
|
||||
@@ -47,14 +49,16 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
}
|
||||
|
||||
private createExecutablePathsSection(containerEl: HTMLElement): void {
|
||||
containerEl.createEl('h3', { text: 'Executable Paths' });
|
||||
new Setting(containerEl)
|
||||
.setName('Executable paths')
|
||||
.setHeading();
|
||||
|
||||
// Add dependency check button
|
||||
new Setting(containerEl)
|
||||
.setName('Dependencies')
|
||||
.setDesc('Check the status of external dependencies')
|
||||
.addButton(button => button
|
||||
.setButtonText('Check Dependencies')
|
||||
.setButtonText('Check dependencies')
|
||||
.setCta()
|
||||
.onClick(async () => {
|
||||
await this.plugin.showDependencyStatus();
|
||||
@@ -131,7 +135,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
}
|
||||
|
||||
private createExportDefaultsSection(containerEl: HTMLElement): void {
|
||||
containerEl.createEl('h3', { text: 'Export Defaults' });
|
||||
new Setting(containerEl)
|
||||
.setName('Export defaults')
|
||||
.setHeading();
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName('Default template')
|
||||
@@ -229,7 +235,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
}
|
||||
|
||||
private createTypographyDefaultsSection(containerEl: HTMLElement): void {
|
||||
containerEl.createEl('h3', { text: 'Typography Defaults' });
|
||||
new Setting(containerEl)
|
||||
.setName('Typography defaults')
|
||||
.setHeading();
|
||||
|
||||
// Use helper method for all three font dropdowns
|
||||
this.createFontDropdown(
|
||||
@@ -293,7 +301,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
}
|
||||
|
||||
private createPageSetupSection(containerEl: HTMLElement): void {
|
||||
containerEl.createEl('h3', { text: 'Page Setup' });
|
||||
new Setting(containerEl)
|
||||
.setName('Page setup')
|
||||
.setHeading();
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName('Page size')
|
||||
@@ -363,7 +373,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
}
|
||||
|
||||
private createBehaviorSection(containerEl: HTMLElement): void {
|
||||
containerEl.createEl('h3', { text: 'Behavior' });
|
||||
new Setting(containerEl)
|
||||
.setName('Behavior')
|
||||
.setHeading();
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName('Open after export')
|
||||
|
||||
@@ -127,11 +127,12 @@ export class TemplateManager {
|
||||
case 'version':
|
||||
metadata.version = value;
|
||||
break;
|
||||
case 'variable':
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ export class ExportConfigModal extends Modal {
|
||||
plugin: obsidianTypstPDFExport;
|
||||
private state: ModalState;
|
||||
private sections: Map<string, ModalSection> = new Map();
|
||||
private onSubmit: (config: ExportConfig) => void;
|
||||
private onSubmit: (config: ExportConfig) => void | Promise<void>;
|
||||
private onCancel?: () => void;
|
||||
private renderer: ModalRenderer;
|
||||
private validator: ModalValidator;
|
||||
@@ -29,7 +29,7 @@ export class ExportConfigModal extends Modal {
|
||||
app: App,
|
||||
plugin: obsidianTypstPDFExport,
|
||||
settings: Partial<ExportConfigModalSettings>,
|
||||
onSubmit: (config: ExportConfig) => void,
|
||||
onSubmit: (config: ExportConfig) => void | Promise<void>,
|
||||
onCancel?: () => void
|
||||
) {
|
||||
super(app);
|
||||
@@ -38,7 +38,7 @@ export class ExportConfigModal extends Modal {
|
||||
this.onCancel = onCancel;
|
||||
|
||||
// Initialize state
|
||||
this.state = new ModalState(settings);
|
||||
this.state = new ModalState(settings, app);
|
||||
|
||||
// Register sections
|
||||
this.registerSections();
|
||||
@@ -81,9 +81,9 @@ export class ExportConfigModal extends Modal {
|
||||
|
||||
// Initialize renderer with content container
|
||||
this.renderer.initialize(contentContainer);
|
||||
|
||||
|
||||
// Load available templates
|
||||
this.loadAvailableTemplates();
|
||||
void this.loadAvailableTemplates();
|
||||
}
|
||||
|
||||
private async loadAvailableTemplates(): Promise<void> {
|
||||
@@ -117,10 +117,10 @@ export class ExportConfigModal extends Modal {
|
||||
|
||||
// Re-render sections to update UI
|
||||
this.renderer.refreshSections();
|
||||
|
||||
|
||||
// Reload templates to update the dropdown
|
||||
this.loadAvailableTemplates();
|
||||
|
||||
void this.loadAvailableTemplates();
|
||||
|
||||
ExportErrorHandler.showSettingsReset();
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import { ModalSection } from './modalTypes';
|
||||
export interface ModalRendererCallbacks {
|
||||
onReset: () => void;
|
||||
onCancel: () => void;
|
||||
onSubmit: () => void;
|
||||
onSubmit: () => void | Promise<void>;
|
||||
}
|
||||
|
||||
export class ModalRenderer {
|
||||
@@ -47,7 +47,6 @@ export class ModalRenderer {
|
||||
initialize(contentContainer: HTMLElement): void {
|
||||
this.contentContainer = contentContainer;
|
||||
this.setupInitialLayout();
|
||||
this.addModalStyles();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -119,9 +118,9 @@ export class ModalRenderer {
|
||||
// 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', {
|
||||
this.progressContainer.createEl('div', {
|
||||
cls: 'export-progress-percent',
|
||||
text: '0%'
|
||||
});
|
||||
@@ -135,7 +134,7 @@ export class ModalRenderer {
|
||||
|
||||
// Reset button (left side)
|
||||
this.resetButton = buttonContainer.createEl('button', {
|
||||
text: 'Reset to Defaults',
|
||||
text: 'Reset to defaults',
|
||||
cls: 'mod-muted'
|
||||
});
|
||||
this.resetButton.addEventListener('click', () => this.callbacks.onReset());
|
||||
@@ -219,7 +218,7 @@ export class ModalRenderer {
|
||||
}
|
||||
|
||||
const errorContainer = this.formContainer.createDiv('validation-errors');
|
||||
errorContainer.createEl('h4', { text: 'Validation Errors', cls: 'error-title' });
|
||||
errorContainer.createEl('h4', { text: 'Validation errors', cls: 'error-title' });
|
||||
|
||||
const errorList = errorContainer.createEl('ul');
|
||||
errors.forEach(error => {
|
||||
@@ -251,241 +250,4 @@ export class ModalRenderer {
|
||||
// Remove after 5 seconds
|
||||
setTimeout(() => warningContainer.remove(), 5000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add custom CSS styles for the modal
|
||||
*/
|
||||
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: 16px 24px 8px 24px;
|
||||
border-bottom: 1px solid var(--background-modifier-border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.export-config-header h2 {
|
||||
margin: 0 0 8px 0;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.export-note-title {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
color: var(--text-muted);
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.export-config-form {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 16px 24px;
|
||||
}
|
||||
|
||||
.export-config-section {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.export-config-section:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.export-config-section-title {
|
||||
font-weight: 600;
|
||||
margin-bottom: 12px;
|
||||
padding-bottom: 4px;
|
||||
border-bottom: 1px solid var(--background-modifier-border-hover);
|
||||
}
|
||||
|
||||
.export-config-buttons {
|
||||
padding: 16px 24px;
|
||||
border-top: 1px solid var(--background-modifier-border);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.export-config-buttons .right-buttons {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* Progress styles */
|
||||
.export-progress-container {
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.export-progress-container.export-hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.export-progress-container.export-progress-visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.export-form-hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.export-progress-text {
|
||||
margin-bottom: 16px;
|
||||
font-size: 14px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.export-progress-bar-container {
|
||||
width: 100%;
|
||||
height: 8px;
|
||||
background-color: var(--background-modifier-border);
|
||||
border-radius: 4px;
|
||||
margin-bottom: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.export-progress-bar {
|
||||
height: 100%;
|
||||
background-color: var(--interactive-accent);
|
||||
border-radius: 4px;
|
||||
width: var(--progress-width, 0%);
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.export-progress-percent {
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
/* Form field styles */
|
||||
.export-setting-item {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.export-setting-item-info {
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.export-setting-item-name {
|
||||
font-weight: 500;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.export-setting-item-description {
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.export-setting-item-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.export-setting-item-control input,
|
||||
.export-setting-item-control select {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Folder suggest styles */
|
||||
.export-folder-suggest-container {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.export-folder-suggest-input {
|
||||
width: 100%;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--background-modifier-border);
|
||||
border-radius: 4px;
|
||||
background: var(--background-primary);
|
||||
color: var(--text-normal);
|
||||
}
|
||||
|
||||
.export-folder-suggest-input:focus {
|
||||
border-color: var(--interactive-accent);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* Validation styles */
|
||||
.validation-errors, .validation-warnings {
|
||||
background: var(--background-modifier-error);
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.validation-warnings {
|
||||
background: var(--background-modifier-warning);
|
||||
}
|
||||
|
||||
.error-title {
|
||||
color: var(--text-error);
|
||||
margin: 0 0 10px 0;
|
||||
}
|
||||
|
||||
.warning-title {
|
||||
color: var(--text-warning);
|
||||
margin: 0 0 10px 0;
|
||||
}
|
||||
|
||||
.validation-errors ul, .validation-warnings ul {
|
||||
margin: 0;
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.export-validation-error {
|
||||
color: var(--text-error);
|
||||
font-size: 12px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.export-validation-warning {
|
||||
color: var(--text-warning);
|
||||
font-size: 12px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* Template variable styles */
|
||||
.export-template-variables {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.export-template-variable {
|
||||
margin-bottom: 8px;
|
||||
padding: 8px;
|
||||
background: var(--background-secondary);
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.export-template-variable-name {
|
||||
font-weight: 500;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.export-template-variable-description {
|
||||
color: var(--text-muted);
|
||||
font-style: italic;
|
||||
}
|
||||
`;
|
||||
|
||||
if (!document.head.querySelector('style[data-export-config-modal]')) {
|
||||
style.setAttribute('data-export-config-modal', 'true');
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,9 @@ export class BehaviorSection implements ModalSection {
|
||||
|
||||
render(containerEl: HTMLElement, state: ModalState): void {
|
||||
this.container = containerEl.createDiv('export-section');
|
||||
this.container.createEl('h3', { text: 'Export Behavior' });
|
||||
new Setting(this.container)
|
||||
.setName('Export behavior')
|
||||
.setHeading();
|
||||
|
||||
this.createBehaviorToggles(state);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,9 @@ export class GeneralSection implements ModalSection {
|
||||
render(containerEl: HTMLElement, state: ModalState, app?: App): void {
|
||||
if (app) this.app = app;
|
||||
this.container = containerEl.createDiv('export-section');
|
||||
this.container.createEl('h3', { text: 'General Settings' });
|
||||
new Setting(this.container)
|
||||
.setName('General settings')
|
||||
.setHeading();
|
||||
|
||||
this.createTemplateSelection(state);
|
||||
this.createFormatSelection(state);
|
||||
|
||||
@@ -13,7 +13,9 @@ export class LayoutSection implements ModalSection {
|
||||
|
||||
render(containerEl: HTMLElement, state: ModalState): void {
|
||||
this.container = containerEl.createDiv('export-section');
|
||||
this.container.createEl('h3', { text: 'Page Layout' });
|
||||
new Setting(this.container)
|
||||
.setName('Page layout')
|
||||
.setHeading();
|
||||
|
||||
this.createPageSizeSettings(state);
|
||||
this.createOrientationSettings(state);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { Setting } from 'obsidian';
|
||||
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
|
||||
import { SUPPORTED_PAPER_SIZES } from '../../../utils/paperSizeMapper';
|
||||
import { ExportFormat } from '../../../core/settings';
|
||||
|
||||
export class PageSetupSection implements ModalSection {
|
||||
private container: HTMLElement | null = null;
|
||||
@@ -13,7 +14,9 @@ export class PageSetupSection implements ModalSection {
|
||||
|
||||
render(containerEl: HTMLElement, state: ModalState): void {
|
||||
this.container = containerEl.createDiv('export-section');
|
||||
this.container.createEl('h3', { text: 'Page Setup' });
|
||||
new Setting(this.container)
|
||||
.setName('Page setup')
|
||||
.setHeading();
|
||||
|
||||
this.createPageSizeSettings(state);
|
||||
this.createOrientationSettings(state);
|
||||
@@ -53,12 +56,12 @@ export class PageSetupSection implements ModalSection {
|
||||
.setValue(String(state.templateVariables.orientation || 'portrait'))
|
||||
.onChange(value => {
|
||||
const isLandscape = value === 'landscape';
|
||||
state.updateTemplateVariables({
|
||||
state.updateTemplateVariables({
|
||||
orientation: value,
|
||||
flipped: isLandscape,
|
||||
// Auto-adjust width for single-page mode when flipped
|
||||
...(isLandscape && state.settings.format === 'single-page'
|
||||
? { width: 'auto' }
|
||||
...(isLandscape && state.settings.format === ExportFormat.SinglePage
|
||||
? { width: 'auto' }
|
||||
: {})
|
||||
});
|
||||
});
|
||||
@@ -69,7 +72,7 @@ export class PageSetupSection implements ModalSection {
|
||||
if (!this.container) return;
|
||||
|
||||
const marginsContainer = this.container.createDiv('margins-container');
|
||||
marginsContainer.createEl('h4', { text: 'Text Margins' });
|
||||
marginsContainer.createEl('h4', { text: 'Text margins' });
|
||||
marginsContainer.createEl('p', {
|
||||
text: 'Enter margins in centimeters (e.g., "2.5", "1.8", "3.0")',
|
||||
cls: 'setting-item-description'
|
||||
|
||||
@@ -13,10 +13,12 @@ export class TypographySection implements ModalSection {
|
||||
render(containerEl: HTMLElement, state: ModalState, app?: App): void {
|
||||
if (app) this.app = app;
|
||||
this.container = containerEl.createDiv('export-section');
|
||||
this.container.createEl('h3', { text: 'Typography' });
|
||||
new Setting(this.container)
|
||||
.setName('Typography')
|
||||
.setHeading();
|
||||
|
||||
// Create font settings asynchronously
|
||||
this.createFontSettings(state);
|
||||
void this.createFontSettings(state);
|
||||
this.createFontSizeSettings(state);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* Centralized state management for the Export Configuration Modal
|
||||
*/
|
||||
|
||||
import { App } from 'obsidian';
|
||||
import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../modalTypes';
|
||||
import { ExportFormat, obsidianTypstPDFExportSettings } from '../../../core/settings';
|
||||
|
||||
@@ -13,7 +14,7 @@ export class ModalState implements IModalState {
|
||||
private changeListeners: Set<() => void> = new Set();
|
||||
private static readonly STORAGE_KEY = 'typst-export-modal-state';
|
||||
|
||||
constructor(initialSettings: Partial<ExportConfigModalSettings>) {
|
||||
constructor(initialSettings: Partial<ExportConfigModalSettings>, private app: App) {
|
||||
// Load from localStorage if available
|
||||
const savedState = this.loadFromStorage();
|
||||
|
||||
@@ -174,7 +175,7 @@ export class ModalState implements IModalState {
|
||||
}
|
||||
|
||||
/**
|
||||
* Save current state to localStorage
|
||||
* Save current state to vault-specific storage
|
||||
*/
|
||||
private saveToStorage(): void {
|
||||
const stateToSave = {
|
||||
@@ -187,25 +188,25 @@ export class ModalState implements IModalState {
|
||||
},
|
||||
templateVariables: this.templateVariables
|
||||
};
|
||||
|
||||
|
||||
try {
|
||||
localStorage.setItem(ModalState.STORAGE_KEY, JSON.stringify(stateToSave));
|
||||
this.app.saveLocalStorage(ModalState.STORAGE_KEY, JSON.stringify(stateToSave));
|
||||
} catch (error) {
|
||||
console.warn('Failed to save modal state to localStorage:', error);
|
||||
console.warn('Failed to save modal state to vault storage:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load state from localStorage
|
||||
* Load state from vault-specific storage
|
||||
*/
|
||||
private loadFromStorage(): { settings: Partial<ExportConfigModalSettings>, templateVariables: Record<string, string | number | boolean> } | null {
|
||||
try {
|
||||
const saved = localStorage.getItem(ModalState.STORAGE_KEY);
|
||||
const saved = this.app.loadLocalStorage(ModalState.STORAGE_KEY);
|
||||
if (saved) {
|
||||
return JSON.parse(saved);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load modal state from localStorage:', error);
|
||||
console.warn('Failed to load modal state from vault storage:', error);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user