refactor: extract ExportOrchestrator from main.ts
Extract all export orchestration methods from main.ts into a focused ExportOrchestrator module to improve maintainability and reduce complexity. - Create ExportOrchestrator.ts with export workflow coordination - Extract exportFile(), exportFiles(), exportFileWithConfig() methods - Extract processBatchExport(), cancelExport(), handleFolderExport() methods - Delegate export operations from main.ts to ExportOrchestrator - Make processing methods public for ExportOrchestrator access - Reduce main.ts by ~205 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
+283
-248
No files matched your search
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* Export Orchestration
|
||||
* Handles the coordination and execution of all export workflows
|
||||
*/
|
||||
|
||||
import { TFile, TFolder, Notice } from 'obsidian';
|
||||
import type { obsidianTypstPDFExport } from '../../main';
|
||||
import { ExportConfig } from '../ui/modal/modalTypes';
|
||||
import { MarkdownPreprocessor } from '../converters/MarkdownPreprocessor';
|
||||
import { TempDirectoryManager } from '../core/TempDirectoryManager';
|
||||
import { ExportErrorHandler } from '../core/ExportErrorHandler';
|
||||
import * as path from 'path';
|
||||
|
||||
export class ExportOrchestrator {
|
||||
constructor(private plugin: obsidianTypstPDFExport) {}
|
||||
|
||||
/**
|
||||
* Export a file with default configuration
|
||||
*/
|
||||
async exportFile(file: TFile): Promise<void> {
|
||||
const config: ExportConfig = {
|
||||
template: this.plugin.settings.exportDefaults.template,
|
||||
format: this.plugin.settings.exportDefaults.format,
|
||||
outputFolder: this.plugin.settings.outputFolder,
|
||||
templateVariables: {
|
||||
// Page setup - use NEW settings structure (same as modal)
|
||||
pageSize: this.plugin.settings.pageSetup.size,
|
||||
orientation: this.plugin.settings.pageSetup.orientation,
|
||||
flipped: this.plugin.settings.pageSetup.orientation === 'landscape',
|
||||
marginTop: this.plugin.settings.pageSetup.margins.top.toString(),
|
||||
marginBottom: this.plugin.settings.pageSetup.margins.bottom.toString(),
|
||||
marginLeft: this.plugin.settings.pageSetup.margins.left.toString(),
|
||||
marginRight: this.plugin.settings.pageSetup.margins.right.toString(),
|
||||
// Typography - use NEW settings structure (same as modal)
|
||||
bodyFont: this.plugin.settings.typography.fonts.body,
|
||||
headingFont: this.plugin.settings.typography.fonts.heading,
|
||||
monospaceFont: this.plugin.settings.typography.fonts.monospace,
|
||||
bodyFontSize: this.plugin.settings.typography.fontSizes.body
|
||||
},
|
||||
openAfterExport: this.plugin.settings.behavior.openAfterExport,
|
||||
preserveFolderStructure: this.plugin.settings.behavior.preserveFolderStructure
|
||||
};
|
||||
|
||||
await this.exportFileWithConfig(file, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export multiple files with default configuration
|
||||
*/
|
||||
async exportFiles(files: TFile[]): Promise<void> {
|
||||
await this.processBatchExport(
|
||||
files,
|
||||
`Exporting ${files.length} files to PDF...`,
|
||||
(file: TFile) => this.exportFile(file)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a file with specific configuration
|
||||
*/
|
||||
async exportFileWithConfig(file: TFile, config: ExportConfig): Promise<void> {
|
||||
const vaultPath = (this.plugin.app.vault.adapter as any).basePath;
|
||||
const pluginDir = path.join(vaultPath, this.plugin.manifest.dir!);
|
||||
|
||||
// Create controller for this export (allows cancellation)
|
||||
this.plugin.currentExportController = new AbortController();
|
||||
|
||||
try {
|
||||
// Create temp directory for conversion
|
||||
const tempManager = new TempDirectoryManager({ vaultPath: vaultPath, configDir: this.plugin.app.vault.configDir });
|
||||
const tempDir = tempManager.ensureTempDir('pandoc');
|
||||
|
||||
// Load file content
|
||||
const content = await this.plugin.app.vault.read(file);
|
||||
|
||||
// Create progress notice with cancel button
|
||||
const progressNotice = new Notice('', 0);
|
||||
const cancelButton = progressNotice.noticeEl.createEl('button', {
|
||||
text: 'Cancel',
|
||||
cls: 'mod-warning'
|
||||
});
|
||||
cancelButton.addEventListener('click', () => this.cancelExport());
|
||||
progressNotice.setMessage('Preprocessing markdown content...');
|
||||
|
||||
// Preprocess markdown
|
||||
const preprocessor = new MarkdownPreprocessor({
|
||||
vaultPath: vaultPath,
|
||||
options: {
|
||||
includeMetadata: true,
|
||||
preserveFrontmatter: config.printFrontmatter ?? this.plugin.settings.behavior.printFrontmatter,
|
||||
baseUrl: undefined,
|
||||
printFrontmatter: config.printFrontmatter ?? this.plugin.settings.behavior.printFrontmatter
|
||||
},
|
||||
wikilinkConfig: {
|
||||
format: 'md',
|
||||
extension: '.md'
|
||||
},
|
||||
noteTitle: file.basename
|
||||
});
|
||||
|
||||
const processedResult = await preprocessor.process(content);
|
||||
|
||||
if (processedResult.errors.length > 0) {
|
||||
console.warn('Preprocessing errors:', processedResult.errors);
|
||||
}
|
||||
if (processedResult.warnings.length > 0) {
|
||||
console.warn('Preprocessing warnings:', processedResult.warnings);
|
||||
}
|
||||
|
||||
// Process PDF embeds if any were found
|
||||
if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) {
|
||||
const embedPdfFiles = config.embedPdfFiles ?? this.plugin.settings.behavior.embedPdfFiles;
|
||||
await this.plugin.processPdfEmbeds(processedResult, vaultPath, tempDir, file, embedPdfFiles);
|
||||
}
|
||||
|
||||
// Process image embeds if any were found
|
||||
if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) {
|
||||
await this.plugin.processImageEmbeds(processedResult, vaultPath, tempDir, file);
|
||||
}
|
||||
|
||||
// Process file embeds if any were found
|
||||
if (processedResult.metadata.fileEmbeds && processedResult.metadata.fileEmbeds.length > 0) {
|
||||
const embedAllFiles = config.embedAllFiles ?? this.plugin.settings.behavior.embedAllFiles;
|
||||
await this.plugin.processFileEmbeds(processedResult, vaultPath, tempDir, file, embedAllFiles);
|
||||
}
|
||||
|
||||
// Prepare output path
|
||||
const outputPath = await this.plugin.prepareOutputPath(file, config.outputFolder || this.plugin.settings.outputFolder);
|
||||
|
||||
// Get full template path
|
||||
const templatePath = config.template ?
|
||||
this.plugin.templateManager.getTemplatePath(config.template) :
|
||||
this.plugin.templateManager.getTemplatePath('default.typ');
|
||||
|
||||
// Convert to PDF using the preprocessed content
|
||||
const templateVariables = {
|
||||
...(config.templateVariables || {}),
|
||||
// Add format from config if specified (takes priority over settings default)
|
||||
...(config.format && { export_format: config.format })
|
||||
};
|
||||
|
||||
const result = await this.plugin.converter.convertMarkdownToPDF(
|
||||
processedResult.content, // Use preprocessed content instead of raw content
|
||||
outputPath,
|
||||
{
|
||||
template: templatePath,
|
||||
variables: templateVariables,
|
||||
pluginDir: pluginDir,
|
||||
vaultBasePath: vaultPath
|
||||
},
|
||||
(message: string, progress?: number) => {
|
||||
progressNotice.setMessage(`${message}${progress ? ` (${Math.round(progress)}%)` : ''}`);
|
||||
}
|
||||
);
|
||||
|
||||
// Hide progress notice
|
||||
progressNotice.hide();
|
||||
|
||||
if (result.success) {
|
||||
new Notice(`PDF exported successfully to ${result.outputPath}`);
|
||||
|
||||
// Open PDF if configured
|
||||
if (this.plugin.settings.behavior.openAfterExport) {
|
||||
this.plugin.openPDF(result.outputPath!);
|
||||
}
|
||||
} else {
|
||||
new Notice(`Export failed: ${result.error}`);
|
||||
}
|
||||
} catch (error) {
|
||||
ExportErrorHandler.handleSingleExportError(error);
|
||||
} finally {
|
||||
this.plugin.currentExportController = null;
|
||||
|
||||
// Clean up temporary directories
|
||||
try {
|
||||
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir);
|
||||
cleanupManager.cleanupAllTempDirs();
|
||||
} catch (cleanupError) {
|
||||
console.warn('Export: Failed to clean up temporary directories:', cleanupError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Export multiple files with specific configuration
|
||||
*/
|
||||
async exportFilesWithConfig(files: TFile[], config: ExportConfig): Promise<void> {
|
||||
await this.processBatchExport(
|
||||
files,
|
||||
`Exporting ${files.length} files with custom configuration...`,
|
||||
(file: TFile) => this.exportFileWithConfig(file, config)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Common batch processing logic for exporting multiple files
|
||||
*/
|
||||
async processBatchExport(
|
||||
files: TFile[],
|
||||
progressMessage: string,
|
||||
exportFunction: (file: TFile) => Promise<void>
|
||||
): Promise<void> {
|
||||
if (files.length === 0) {
|
||||
new Notice('No files to export');
|
||||
return;
|
||||
}
|
||||
|
||||
ExportErrorHandler.showProgressNotice(progressMessage);
|
||||
|
||||
const { recordSuccess, recordError, getResult } = ExportErrorHandler.createBatchTracker();
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
await exportFunction(file);
|
||||
recordSuccess();
|
||||
} catch (error) {
|
||||
recordError(file.name, error);
|
||||
}
|
||||
}
|
||||
|
||||
// Show final result
|
||||
ExportErrorHandler.handleBatchResult(getResult());
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel the current export
|
||||
*/
|
||||
cancelExport(): void {
|
||||
if (this.plugin.currentExportController) {
|
||||
this.plugin.currentExportController.abort();
|
||||
this.plugin.currentExportController = null;
|
||||
ExportErrorHandler.showCancellationNotice();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Export an entire folder to PDF
|
||||
*/
|
||||
async handleFolderExport(folder: TFolder): Promise<void> {
|
||||
// Get all markdown files in the folder
|
||||
const markdownFiles = folder.children.filter(this.plugin.isMarkdownFile);
|
||||
|
||||
if (markdownFiles.length === 0) {
|
||||
new Notice('No markdown files found in this folder');
|
||||
return;
|
||||
}
|
||||
|
||||
ExportErrorHandler.showProgressNotice(`Exporting ${markdownFiles.length} files from ${folder.name}...`);
|
||||
|
||||
const { recordSuccess, recordError, getResult } = ExportErrorHandler.createBatchTracker();
|
||||
|
||||
for (const file of markdownFiles) {
|
||||
try {
|
||||
await this.exportFile(file);
|
||||
recordSuccess();
|
||||
} catch (error) {
|
||||
recordError(file.name, error);
|
||||
}
|
||||
}
|
||||
|
||||
ExportErrorHandler.handleBatchResult(getResult());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user