Files
freewriting-cleanup/main.ts
T
AlexKucera c3d4888c98 Optimizes settings and model cache loading
Refactors loadSettings method to avoid redundant data loading
Reduces duplicate loadData() calls by reusing loaded data
Improves efficiency of plugin initialization process
2025-10-24 10:57:47 +02:00

86 lines
2.9 KiB
TypeScript

// ABOUTME: Main plugin file for Freewriting Cleanup - cleans up freewriting text using AI
// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle
import { Editor, MarkdownView, Plugin } from 'obsidian';
import { FreewritingCleanupSettings, FreewritingCleanupData } from './types';
import { DEFAULT_SETTINGS, FreewritingCleanupSettingTab } from './settings';
import { CleanupService } from './services/cleanupService';
import { ModelService } from './services/modelService';
import { CleanupCommand } from './commands/cleanupCommand';
export default class FreewritingCleanupPlugin extends Plugin {
settings: FreewritingCleanupSettings;
cleanupService: CleanupService;
modelService: ModelService;
cleanupCommand: CleanupCommand;
async onload() {
// Load settings and reuse the data to avoid double loadData() call
const data = await this.loadSettings();
// Initialize services
this.cleanupService = new CleanupService(this.settings.apiKey);
this.modelService = new ModelService(this.cleanupService.anthropicClient);
this.cleanupCommand = new CleanupCommand(this.cleanupService);
// Load model cache from already-loaded data
if (data?.modelCache) {
this.modelService.loadCache(data.modelCache);
}
// Register command
this.registerCommand();
// Add settings tab
this.addSettingTab(new FreewritingCleanupSettingTab(this.app, this));
}
onunload() {
// Cleanup if needed
}
// MARK: - Settings Management
async loadSettings(): Promise<FreewritingCleanupData | null> {
const data = await this.loadData() as FreewritingCleanupData | null;
this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
return data;
}
async saveSettings() {
// Save settings with model cache
const data: FreewritingCleanupData = {
...this.settings,
modelCache: this.modelService?.getCache() || undefined
};
await this.saveData(data);
// Update the cleanup service with new settings
if (this.cleanupService) {
this.cleanupService.updateApiKey(this.settings.apiKey);
}
}
// MARK: - Command Registration
private registerCommand() {
this.addCommand({
id: 'cleanup-text',
name: 'Clean up text',
editorCallback: async (editor: Editor, view: MarkdownView) => {
await this.executeCleanupCommand(editor, view);
}
});
}
// MARK: - Command Implementation
private async executeCleanupCommand(editor: Editor, view: MarkdownView): Promise<void> {
try {
await this.cleanupCommand.execute(editor, view, this.settings);
} catch (error) {
console.error('Error executing cleanup command:', error);
}
}
}