Bug Fixes

This commit is contained in:
2025-11-22 18:03:37 +01:00
parent 66652afc90
commit 9de2b00a2f

View File

@@ -551,7 +551,6 @@ export default class FocusTaskPlugin extends Plugin {
async logTaskToDailyNote(task: FocusTask) { async logTaskToDailyNote(task: FocusTask) {
try { try {
const dailyNotePath = this.getDailyNotePath();
const list = this.settings.lists.find(l => l.id === task.list); const list = this.settings.lists.find(l => l.id === task.list);
// Format the task entry // Format the task entry
@@ -573,83 +572,122 @@ export default class FocusTaskPlugin extends Plugin {
const taskEntry = `- [x] ${task.text} | ${list?.icon || '📋'} ${list?.name || 'Task'} | ⏱️ ${this.formatTimeHuman(task.actualMinutes)} / ${this.formatTimeHuman(task.estimatedMinutes)} (${timeComparison}) | ✅ ${completedTime}`; const taskEntry = `- [x] ${task.text} | ${list?.icon || '📋'} ${list?.name || 'Task'} | ⏱️ ${this.formatTimeHuman(task.actualMinutes)} / ${this.formatTimeHuman(task.estimatedMinutes)} (${timeComparison}) | ✅ ${completedTime}`;
await this.appendToDailyNote(dailyNotePath, taskEntry); await this.appendToDailyNote(taskEntry);
} catch (e) { } catch (e) {
console.error('Failed to log task to daily note:', e); console.error('Failed to log task to daily note:', e);
new Notice('Failed to log task to daily note'); new Notice('Failed to log task to daily note. Make sure Daily Notes core plugin is enabled.');
} }
} }
getDailyNotePath(): string { getDailyNoteSettings(): { folder: string; format: string; template: string } | null {
const now = new Date(); // Access the core Daily Notes plugin settings
const format = this.settings.dailyNoteFormat; const dailyNotesPlugin = (this.app as any).internalPlugins?.plugins?.['daily-notes'];
// Simple date formatting if (!dailyNotesPlugin?.enabled) {
return null;
}
const settings = dailyNotesPlugin.instance?.options;
return {
folder: settings?.folder || '',
format: settings?.format || 'YYYY-MM-DD',
template: settings?.template || '',
};
}
formatDailyNoteDate(format: string): string {
const now = new Date();
const year = now.getFullYear(); const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, '0'); const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0'); const day = now.getDate().toString().padStart(2, '0');
let filename = format // Handle common date format tokens
return format
.replace('YYYY', year.toString()) .replace('YYYY', year.toString())
.replace('YY', year.toString().slice(-2))
.replace('MM', month) .replace('MM', month)
.replace('DD', day); .replace('M', (now.getMonth() + 1).toString())
.replace('DD', day)
return `${filename}.md`; .replace('D', now.getDate().toString())
.replace('dddd', now.toLocaleDateString('en-US', { weekday: 'long' }))
.replace('ddd', now.toLocaleDateString('en-US', { weekday: 'short' }))
.replace('MMMM', now.toLocaleDateString('en-US', { month: 'long' }))
.replace('MMM', now.toLocaleDateString('en-US', { month: 'short' }));
} }
async appendToDailyNote(path: string, content: string) { async getOrCreateDailyNote(): Promise<TFile | null> {
const { vault } = this.app; const { vault } = this.app;
const heading = this.settings.dailyNoteHeading; const dailySettings = this.getDailyNoteSettings();
if (!dailySettings) {
new Notice('Daily Notes core plugin is not enabled. Please enable it in Settings → Core plugins.');
return null;
}
const filename = this.formatDailyNoteDate(dailySettings.format);
const folder = dailySettings.folder ? `${dailySettings.folder}/` : '';
const path = `${folder}${filename}.md`;
// Check if daily note exists
let file = vault.getAbstractFileByPath(path); let file = vault.getAbstractFileByPath(path);
if (!file) { if (file && file instanceof TFile) {
// Create the daily note if it doesn't exist return file;
await vault.create(path, `# ${new Date().toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}\n\n${heading}\n\n${content}\n`);
new Notice('📝 Task logged to new daily note');
return;
} }
if (!(file instanceof TFile)) { // Create the daily note
new Notice('Daily note path is not a file'); try {
return; // Ensure folder exists
} if (dailySettings.folder) {
const folderExists = vault.getAbstractFileByPath(dailySettings.folder);
// Read existing content if (!folderExists) {
let existingContent = await vault.read(file); await vault.createFolder(dailySettings.folder);
}
// Check if heading exists
if (existingContent.includes(heading)) {
// Find the heading and append after it
const headingIndex = existingContent.indexOf(heading);
const afterHeading = headingIndex + heading.length;
// Find the next heading or end of file
const nextHeadingMatch = existingContent.slice(afterHeading).match(/\n##? /);
let insertPosition: number;
if (nextHeadingMatch && nextHeadingMatch.index !== undefined) {
// Insert before the next heading
insertPosition = afterHeading + nextHeadingMatch.index;
} else {
// Append to end of file
insertPosition = existingContent.length;
} }
// Insert the new task entry // Check if template exists and use it
const before = existingContent.slice(0, insertPosition); let content = '';
const after = existingContent.slice(insertPosition); if (dailySettings.template) {
const templatePath = dailySettings.template.endsWith('.md')
? dailySettings.template
: `${dailySettings.template}.md`;
const templateFile = vault.getAbstractFileByPath(templatePath);
if (templateFile && templateFile instanceof TFile) {
content = await vault.read(templateFile);
// Replace template variables
content = content
.replace(/{{date}}/g, filename)
.replace(/{{time}}/g, new Date().toLocaleTimeString())
.replace(/{{title}}/g, filename);
}
}
// Make sure there's a newline before our content // Create the file
const newContent = before.trimEnd() + '\n' + content + '\n' + after.trimStart(); const newFile = await vault.create(path, content);
new Notice(`📝 Created daily note: ${filename}`);
await vault.modify(file, newContent); return newFile;
} else { } catch (e) {
// Add the heading and content at the end console.error('Failed to create daily note:', e);
const newContent = existingContent.trimEnd() + '\n\n' + heading + '\n\n' + content + '\n'; new Notice('Failed to create daily note');
await vault.modify(file, newContent); return null;
}
}
async appendToDailyNote(content: string) {
const file = await this.getOrCreateDailyNote();
if (!file) {
return;
} }
const { vault } = this.app;
// Read existing content and append to the end
const existingContent = await vault.read(file);
const newContent = existingContent.trimEnd() + '\n' + content + '\n';
await vault.modify(file, newContent);
new Notice('📝 Task logged to daily note'); new Notice('📝 Task logged to daily note');
} }
@@ -843,7 +881,7 @@ class FocusTaskSettingTab extends PluginSettingTab {
new Setting(containerEl) new Setting(containerEl)
.setName('Log completed tasks to daily note') .setName('Log completed tasks to daily note')
.setDesc('When you complete a task, add an entry to your daily note') .setDesc('When you complete a task, add an entry to your daily note. Uses the core Daily Notes plugin settings.')
.addToggle(toggle => toggle .addToggle(toggle => toggle
.setValue(this.plugin.settings.logToDaily) .setValue(this.plugin.settings.logToDaily)
.onChange(async value => { .onChange(async value => {
@@ -851,27 +889,17 @@ class FocusTaskSettingTab extends PluginSettingTab {
await this.plugin.saveAllData(); await this.plugin.saveAllData();
})); }));
new Setting(containerEl) // Show info about Daily Notes plugin
.setName('Daily note filename format') const infoEl = containerEl.createEl('div', { cls: 'setting-item-description' });
.setDesc('Format for daily note filename (YYYY = year, MM = month, DD = day)') infoEl.style.marginTop = '-10px';
.addText(text => text infoEl.style.marginBottom = '20px';
.setPlaceholder('YYYY-MM-DD') infoEl.innerHTML = `
.setValue(this.plugin.settings.dailyNoteFormat) <small>
.onChange(async value => { This feature uses the <strong>Daily Notes</strong> core plugin.
this.plugin.settings.dailyNoteFormat = value || 'YYYY-MM-DD'; Configure your daily note folder, date format, and template in
await this.plugin.saveAllData(); <em>Settings → Core plugins → Daily notes</em>.
})); </small>
`;
new Setting(containerEl)
.setName('Section heading')
.setDesc('Heading under which completed tasks will be logged')
.addText(text => text
.setPlaceholder('## ⚡ Completed Tasks')
.setValue(this.plugin.settings.dailyNoteHeading)
.onChange(async value => {
this.plugin.settings.dailyNoteHeading = value || '## ⚡ Completed Tasks';
await this.plugin.saveAllData();
}));
// Lists Management // Lists Management
containerEl.createEl('h2', { text: '📋 Lists' }); containerEl.createEl('h2', { text: '📋 Lists' });