refactor: extract FontManager from main.ts
Extract all font management functionality from main.ts into a focused FontManager module to improve maintainability and reduce complexity. - Create FontManager.ts with font discovery and caching logic - Extract cacheAvailableFonts() and getCachedFonts() methods - Add getAvailableFonts() wrapper method for consistent API - Delegate font operations from main.ts to FontManager - Fix initialization order: FontManager before PluginLifecycle - Make resolveExecutablePath() public for FontManager access - Reduce main.ts by ~115 lines while maintaining all functionality 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2 files changed
+157
-116
No files matched your search
@@ -39,6 +39,7 @@ import { PluginLifecycle } from './src/plugin/PluginLifecycle';
|
|||||||
import { CommandRegistry } from './src/plugin/CommandRegistry';
|
import { CommandRegistry } from './src/plugin/CommandRegistry';
|
||||||
import { EventHandlers } from './src/plugin/EventHandlers';
|
import { EventHandlers } from './src/plugin/EventHandlers';
|
||||||
import { ExportOrchestrator } from './src/plugin/ExportOrchestrator';
|
import { ExportOrchestrator } from './src/plugin/ExportOrchestrator';
|
||||||
|
import { FontManager } from './src/plugin/FontManager';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
|
|
||||||
@@ -52,6 +53,7 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
private commandRegistry: CommandRegistry;
|
private commandRegistry: CommandRegistry;
|
||||||
private eventHandlers: EventHandlers;
|
private eventHandlers: EventHandlers;
|
||||||
private exportOrchestrator: ExportOrchestrator;
|
private exportOrchestrator: ExportOrchestrator;
|
||||||
|
fontManager: FontManager;
|
||||||
|
|
||||||
// Type predicate to filter for markdown TFiles
|
// Type predicate to filter for markdown TFiles
|
||||||
isMarkdownFile(file: TAbstractFile): file is TFile {
|
isMarkdownFile(file: TAbstractFile): file is TFile {
|
||||||
@@ -62,6 +64,9 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
// Initialize lifecycle manager
|
// Initialize lifecycle manager
|
||||||
this.lifecycle = new PluginLifecycle(this);
|
this.lifecycle = new PluginLifecycle(this);
|
||||||
|
|
||||||
|
// Initialize font manager first (needed by PluginLifecycle)
|
||||||
|
this.fontManager = new FontManager(this);
|
||||||
|
|
||||||
// Initialize core plugin functionality
|
// Initialize core plugin functionality
|
||||||
await this.lifecycle.initialize();
|
await this.lifecycle.initialize();
|
||||||
|
|
||||||
@@ -98,7 +103,7 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
/**
|
/**
|
||||||
* Resolve an executable path, handling empty settings by falling back to system search
|
* Resolve an executable path, handling empty settings by falling back to system search
|
||||||
*/
|
*/
|
||||||
private resolveExecutablePath(userPath: string | undefined, defaultName: string): string {
|
resolveExecutablePath(userPath: string | undefined, defaultName: string): string {
|
||||||
// If user provided a path and it's not empty, use it
|
// If user provided a path and it's not empty, use it
|
||||||
if (userPath && userPath.trim() !== '') {
|
if (userPath && userPath.trim() !== '') {
|
||||||
return userPath;
|
return userPath;
|
||||||
@@ -131,121 +136,7 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
return defaultName;
|
return defaultName;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Cache available fonts from typst to a file for quick access
|
|
||||||
*/
|
|
||||||
async cacheAvailableFonts(): Promise<void> {
|
|
||||||
try {
|
|
||||||
const { spawn } = require('child_process');
|
|
||||||
|
|
||||||
const typstPath = this.resolveExecutablePath(this.settings.typstPath, 'typst');
|
|
||||||
|
|
||||||
// Use spawn instead of exec for security - arguments passed separately
|
|
||||||
const stdout = await new Promise<string>((resolve, reject) => {
|
|
||||||
const typstProcess = spawn(typstPath, ['fonts'], {
|
|
||||||
stdio: ['pipe', 'pipe', 'pipe'],
|
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let output = '';
|
|
||||||
let error = '';
|
|
||||||
|
|
||||||
typstProcess.stdout?.on('data', (data: Buffer) => {
|
|
||||||
output += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
typstProcess.stderr?.on('data', (data: Buffer) => {
|
|
||||||
error += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
typstProcess.on('close', (code: number | null) => {
|
|
||||||
if (code === 0) {
|
|
||||||
resolve(output);
|
|
||||||
} else {
|
|
||||||
reject(new Error(`typst fonts command failed with code ${code}: ${error}`));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
typstProcess.on('error', (err: Error) => {
|
|
||||||
reject(new Error(`Failed to spawn typst process: ${err.message}`));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const fonts = stdout
|
|
||||||
.split('\n')
|
|
||||||
.map((line: string) => line.trim())
|
|
||||||
.filter((line: string) => line.length > 0)
|
|
||||||
.sort();
|
|
||||||
|
|
||||||
// Write fonts to cache file in plugin data directory
|
|
||||||
const cacheData = {
|
|
||||||
fonts: fonts,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
typstPath: typstPath
|
|
||||||
};
|
|
||||||
|
|
||||||
const fontsCachePath = path.join(this.manifest.dir!, 'fonts-cache.json');
|
|
||||||
await this.app.vault.adapter.write(fontsCachePath,
|
|
||||||
JSON.stringify(cacheData, null, 2));
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to cache fonts from typst:', error);
|
|
||||||
|
|
||||||
// Notify user of font caching failure (only if debug mode is enabled or if it's a critical error)
|
|
||||||
if (this.settings.behavior.debugMode) {
|
|
||||||
new Notice(`Font caching failed: ${error.message}. Using fallback fonts.`, 5000);
|
|
||||||
} else {
|
|
||||||
// For non-debug mode, show a more gentle notice
|
|
||||||
new Notice('Font list may be incomplete. Check debug mode for details.', 3000);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create fallback cache file
|
|
||||||
const fallbackFonts = FALLBACK_FONTS;
|
|
||||||
|
|
||||||
const cacheData = {
|
|
||||||
fonts: fallbackFonts,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
typstPath: 'fallback',
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
|
|
||||||
const fontsCachePath = path.join(this.manifest.dir!, 'fonts-cache.json');
|
|
||||||
await this.app.vault.adapter.write(fontsCachePath,
|
|
||||||
JSON.stringify(cacheData, null, 2));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get cached fonts list
|
|
||||||
*/
|
|
||||||
async getCachedFonts(): Promise<string[]> {
|
|
||||||
try {
|
|
||||||
const fontsCachePath = path.join(this.manifest.dir!, 'fonts-cache.json');
|
|
||||||
const cacheContent = await this.app.vault.adapter.read(fontsCachePath);
|
|
||||||
const cacheData = JSON.parse(cacheContent);
|
|
||||||
|
|
||||||
// Check if cache is older than 24 hours or typst path changed
|
|
||||||
const isStale = Date.now() - cacheData.timestamp > 24 * 60 * 60 * 1000;
|
|
||||||
const resolvedTypstPath = this.resolveExecutablePath(this.settings.typstPath, 'typst');
|
|
||||||
const pathChanged = cacheData.typstPath !== resolvedTypstPath;
|
|
||||||
|
|
||||||
if (isStale || pathChanged) {
|
|
||||||
// Refresh cache in background
|
|
||||||
this.cacheAvailableFonts();
|
|
||||||
}
|
|
||||||
|
|
||||||
return cacheData.fonts || [];
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to read fonts cache:', error);
|
|
||||||
// Try to recreate cache
|
|
||||||
await this.cacheAvailableFonts();
|
|
||||||
|
|
||||||
// Return fallback fonts
|
|
||||||
return [...FALLBACK_FONTS];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Export the current note with default settings
|
* Export the current note with default settings
|
||||||
@@ -345,6 +236,20 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
return this.exportOrchestrator.exportFiles(files);
|
return this.exportOrchestrator.exportFiles(files);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache available fonts (delegated to FontManager)
|
||||||
|
*/
|
||||||
|
async cacheAvailableFonts(): Promise<void> {
|
||||||
|
return this.fontManager.cacheAvailableFonts();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get cached fonts list (delegated to FontManager)
|
||||||
|
*/
|
||||||
|
async getCachedFonts(): Promise<string[]> {
|
||||||
|
return this.fontManager.getCachedFonts();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Show dependency status modal
|
* Show dependency status modal
|
||||||
@@ -1376,7 +1281,7 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
|||||||
|
|
||||||
// Helper methods for fonts
|
// Helper methods for fonts
|
||||||
private async getAvailableFonts(): Promise<string[]> {
|
private async getAvailableFonts(): Promise<string[]> {
|
||||||
return await this.plugin.getCachedFonts();
|
return await this.plugin.fontManager.getCachedFonts();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper methods for margin conversion
|
// Helper methods for margin conversion
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
/**
|
||||||
|
* Font Management
|
||||||
|
* Handles font discovery, caching, and retrieval for the plugin
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Notice } from 'obsidian';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../main';
|
||||||
|
import { FALLBACK_FONTS } from '../core/constants';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
|
export class FontManager {
|
||||||
|
constructor(private plugin: obsidianTypstPDFExport) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache available fonts from typst to a file for quick access
|
||||||
|
*/
|
||||||
|
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
|
||||||
|
const stdout = await new Promise<string>((resolve, reject) => {
|
||||||
|
const typstProcess = spawn(typstPath, ['fonts'], {
|
||||||
|
stdio: ['pipe', 'pipe', 'pipe'],
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = '';
|
||||||
|
let error = '';
|
||||||
|
|
||||||
|
typstProcess.stdout?.on('data', (data: Buffer) => {
|
||||||
|
output += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
typstProcess.stderr?.on('data', (data: Buffer) => {
|
||||||
|
error += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
typstProcess.on('close', (code: number | null) => {
|
||||||
|
if (code === 0) {
|
||||||
|
resolve(output);
|
||||||
|
} else {
|
||||||
|
reject(new Error(`typst fonts command failed with code ${code}: ${error}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
typstProcess.on('error', (err: Error) => {
|
||||||
|
reject(new Error(`Failed to spawn typst process: ${err.message}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const fonts = stdout
|
||||||
|
.split('\n')
|
||||||
|
.map((line: string) => line.trim())
|
||||||
|
.filter((line: string) => line.length > 0)
|
||||||
|
.sort();
|
||||||
|
|
||||||
|
// Write fonts to cache file in plugin data directory
|
||||||
|
const cacheData = {
|
||||||
|
fonts: fonts,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
typstPath: typstPath
|
||||||
|
};
|
||||||
|
|
||||||
|
const fontsCachePath = path.join(this.plugin.manifest.dir!, 'fonts-cache.json');
|
||||||
|
await this.plugin.app.vault.adapter.write(fontsCachePath,
|
||||||
|
JSON.stringify(cacheData, null, 2));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to cache fonts from typst:', error);
|
||||||
|
|
||||||
|
// Notify user of font caching failure (only if debug mode is enabled or if it's a critical error)
|
||||||
|
if (this.plugin.settings.behavior.debugMode) {
|
||||||
|
new Notice(`Font caching failed: ${error.message}. Using fallback fonts.`, 5000);
|
||||||
|
} else {
|
||||||
|
// For non-debug mode, show a more gentle notice
|
||||||
|
new Notice('Font list may be incomplete. Check debug mode for details.', 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create fallback cache file
|
||||||
|
const fallbackFonts = FALLBACK_FONTS;
|
||||||
|
|
||||||
|
const cacheData = {
|
||||||
|
fonts: fallbackFonts,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
typstPath: 'fallback',
|
||||||
|
error: error.message
|
||||||
|
};
|
||||||
|
|
||||||
|
const fontsCachePath = path.join(this.plugin.manifest.dir!, 'fonts-cache.json');
|
||||||
|
await this.plugin.app.vault.adapter.write(fontsCachePath,
|
||||||
|
JSON.stringify(cacheData, null, 2));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get cached fonts list
|
||||||
|
*/
|
||||||
|
async getCachedFonts(): Promise<string[]> {
|
||||||
|
try {
|
||||||
|
const fontsCachePath = path.join(this.plugin.manifest.dir!, 'fonts-cache.json');
|
||||||
|
const cacheContent = await this.plugin.app.vault.adapter.read(fontsCachePath);
|
||||||
|
const cacheData = JSON.parse(cacheContent);
|
||||||
|
|
||||||
|
// Check if cache is older than 24 hours or typst path changed
|
||||||
|
const isStale = Date.now() - cacheData.timestamp > 24 * 60 * 60 * 1000;
|
||||||
|
const resolvedTypstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst');
|
||||||
|
const pathChanged = cacheData.typstPath !== resolvedTypstPath;
|
||||||
|
|
||||||
|
if (isStale || pathChanged) {
|
||||||
|
// Refresh cache in background
|
||||||
|
this.cacheAvailableFonts();
|
||||||
|
}
|
||||||
|
|
||||||
|
return cacheData.fonts || [];
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to read fonts cache:', error);
|
||||||
|
// Try to recreate cache
|
||||||
|
await this.cacheAvailableFonts();
|
||||||
|
|
||||||
|
// Return fallback fonts
|
||||||
|
return [...FALLBACK_FONTS];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get available fonts (wrapper for cached fonts)
|
||||||
|
*/
|
||||||
|
async getAvailableFonts(): Promise<string[]> {
|
||||||
|
return await this.getCachedFonts();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user