import { Notice, MarkdownView, Modal, App, Setting, TFile } from "obsidian"; import { AIService } from "../AIService"; import { resolveChatProvider } from "../ProviderResolver"; import NibbleAI from "main"; class PropertyPromptModal extends Modal { private plugin: NibbleAI; private onSubmit: (propertyName: string) => void; private propertyName: string; constructor(app: App, plugin: NibbleAI, onSubmit: (name: string) => void) { super(app); this.plugin = plugin; this.onSubmit = onSubmit; this.propertyName = ""; this.setTitle("Fill property with AI"); } onOpen() { const { contentEl } = this; contentEl.createEl("p", { text: "Enter the name of the property to fill (e.g., summary, tags, status):", }); new Setting(contentEl) .setName("Property name") .addText((text) => { text.setPlaceholder("e.g., summary") .setValue(this.propertyName) .onChange((value) => { this.propertyName = value.trim(); }); text.inputEl.focus(); text.inputEl.addEventListener("keydown", (e) => { if (e.key === "Enter") this.submit(); }); }); const buttonContainer = contentEl.createDiv({ cls: "modal-button-container" }); buttonContainer.style.display = "flex"; buttonContainer.style.gap = "8px"; buttonContainer.style.justifyContent = "flex-end"; buttonContainer.style.marginTop = "16px"; const cancelBtn = buttonContainer.createEl("button", { text: "Cancel", cls: "mod-cta", }); cancelBtn.style.backgroundColor = "var(--interactive-normal)"; cancelBtn.style.color = "var(--text-normal)"; cancelBtn.addEventListener("click", () => this.close()); const submitBtn = buttonContainer.createEl("button", { text: "Fill", cls: "mod-cta", }); submitBtn.addEventListener("click", () => this.submit()); } private submit() { if (!this.propertyName) { new Notice("Please enter a property name."); return; } this.onSubmit(this.propertyName); this.close(); } onClose() { const { contentEl } = this; contentEl.empty(); } } export class PropertyFiller { private plugin: NibbleAI; constructor(plugin: NibbleAI) { this.plugin = plugin; } async fillProperty(): Promise { new PropertyPromptModal( this.plugin.app, this.plugin, async (propertyName: string) => { await this.fillPropertyWithName(propertyName); } ).open(); } async fillSpecificProperty(propertyName: string): Promise { await this.fillPropertyWithName(propertyName); } private async fillPropertyWithName(propertyName: string): Promise { const activeView = this.plugin.app.workspace.getActiveViewOfType(MarkdownView); if (!activeView) { new Notice("No active note open."); return; } const file = activeView.file; if (!file) { new Notice("No file associated with the active view."); return; } const content = await this.plugin.app.vault.read(file); if (!content || content.trim().length === 0) { new Notice("Note is empty."); return; } const config = resolveChatProvider( this.plugin.app, this.plugin.settings, this.plugin.settings.propertyGenProvider || "openrouter" ); if (!config) { new Notice( "⚠️ No API key for selected provider. Check Settings \u2192 NibbleAI \u2192 API Keys." ); return; } const frontmatter = this.plugin.app.metadataCache.getFileCache( file )?.frontmatter; const propertyExists = frontmatter && frontmatter[propertyName] !== undefined; if (propertyExists && !this.plugin.settings.propertyOverwrite) { new Notice( `Property "${propertyName}" already exists. Enable "Overwrite existing properties" in settings to replace it.` ); return; } new Notice(`🤖 Generating value for "${propertyName}"...`); try { const promptTemplate = this.plugin.settings.propertyGenPrompt || "Based on the following note content, generate a value for the property '{property}'. Return only the value, nothing else."; const prompt = promptTemplate.replace(/\{property\}/g, propertyName); const { text: generated } = await AIService.callChatCompletion( content, prompt, { apiKey: config.apiKey, model: this.plugin.settings.propertyGenModel, endpoint: config.endpoint, provider: config.provider, temperature: 0.3, maxTokens: 200, } ); if (!generated || generated.trim().length === 0) { new Notice("⚠️ AI returned empty result. No changes made."); return; } const value = generated.trim(); await this.insertProperty(file, content, propertyName, value); new Notice(`✅ "${propertyName}" filled: ${value.slice(0, 60)}${value.length > 60 ? "..." : ""}`); } catch (error) { console.error("Property filling error:", error); new Notice( `❌ Property fill failed: ${error instanceof Error ? error.message : String(error)}` ); } } private async insertProperty( file: TFile, content: string, propertyName: string, value: string ): Promise { const frontmatterData = this.plugin.app.metadataCache.getFileCache( file )?.frontmatter; let newContent: string; const escapedValue = value.includes(":") || value.includes("#") || value.includes("[") ? `"${value.replace(/"/g, '\\"')}"` : value; if (frontmatterData && frontmatterData.position) { const lines = content.split("\n"); const fmEnd = frontmatterData.position.end.line; let propertyFound = false; for (let i = 1; i < fmEnd; i++) { if (lines[i].startsWith(`${propertyName}:`)) { lines[i] = `${propertyName}: ${escapedValue}`; propertyFound = true; break; } } if (!propertyFound) { let insertPos = fmEnd; for (let i = fmEnd - 1; i > 0; i--) { if (lines[i].trim() && lines[i] !== "---") { insertPos = i + 1; break; } } lines.splice(insertPos, 0, `${propertyName}: ${escapedValue}`); } newContent = lines.join("\n"); } else { newContent = `---\n${propertyName}: ${escapedValue}\n---\n\n${content}`; } await this.plugin.app.vault.modify(file, newContent); } }