3 Commits

Author SHA1 Message Date
aeb1d62895 Bug fixes 2025-11-22 18:05:01 +01:00
9de2b00a2f Bug Fixes 2025-11-22 18:03:37 +01:00
66652afc90 Bug Fixes 2025-11-22 17:53:41 +01:00
3 changed files with 176 additions and 131 deletions

123
main.js
View File

@@ -46,9 +46,7 @@ var DEFAULT_SETTINGS = {
autoStartBreak: false,
tickSoundEnabled: false,
// Daily note logging
logToDaily: false,
dailyNoteFormat: "YYYY-MM-DD",
dailyNoteHeading: "## \u26A1 Completed Tasks"
logToDaily: false
};
var DEFAULT_DATA = {
tasks: [],
@@ -888,7 +886,6 @@ var FocusTaskPlugin = class extends import_obsidian3.Plugin {
// ============ Daily Note Logging ============
async logTaskToDailyNote(task) {
try {
const dailyNotePath = this.getDailyNotePath();
const list = this.settings.lists.find((l) => l.id === task.list);
const timeDiff = task.actualMinutes - task.estimatedMinutes;
let timeComparison = "";
@@ -905,58 +902,80 @@ var FocusTaskPlugin = class extends import_obsidian3.Plugin {
hour12: false
});
const taskEntry = `- [x] ${task.text} | ${(list == null ? void 0 : list.icon) || "\u{1F4CB}"} ${(list == null ? void 0 : list.name) || "Task"} | \u23F1\uFE0F ${this.formatTimeHuman(task.actualMinutes)} / ${this.formatTimeHuman(task.estimatedMinutes)} (${timeComparison}) | \u2705 ${completedTime}`;
await this.appendToDailyNote(dailyNotePath, taskEntry);
await this.appendToDailyNote(taskEntry);
} catch (e) {
console.error("Failed to log task to daily note:", e);
new import_obsidian3.Notice("Failed to log task to daily note");
new import_obsidian3.Notice("Failed to log task to daily note. Make sure Daily Notes core plugin is enabled.");
}
}
getDailyNotePath() {
getDailyNoteSettings() {
var _a, _b, _c;
const dailyNotesPlugin = (_b = (_a = this.app.internalPlugins) == null ? void 0 : _a.plugins) == null ? void 0 : _b["daily-notes"];
if (!(dailyNotesPlugin == null ? void 0 : dailyNotesPlugin.enabled)) {
return null;
}
const settings = (_c = dailyNotesPlugin.instance) == null ? void 0 : _c.options;
return {
folder: (settings == null ? void 0 : settings.folder) || "",
format: (settings == null ? void 0 : settings.format) || "YYYY-MM-DD",
template: (settings == null ? void 0 : settings.template) || ""
};
}
formatDailyNoteDate(format) {
const now = new Date();
const format = this.settings.dailyNoteFormat;
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, "0");
const day = now.getDate().toString().padStart(2, "0");
let filename = format.replace("YYYY", year.toString()).replace("MM", month).replace("DD", day);
return `${filename}.md`;
return format.replace("YYYY", year.toString()).replace("YY", year.toString().slice(-2)).replace("MM", month).replace("M", (now.getMonth() + 1).toString()).replace("DD", day).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, content) {
async getOrCreateDailyNote() {
const { vault } = this.app;
const heading = this.settings.dailyNoteHeading;
const dailySettings = this.getDailyNoteSettings();
if (!dailySettings) {
new import_obsidian3.Notice("Daily Notes core plugin is not enabled. Please enable it in Settings \u2192 Core plugins.");
return null;
}
const filename = this.formatDailyNoteDate(dailySettings.format);
const folder = dailySettings.folder ? `${dailySettings.folder}/` : "";
const path = `${folder}${filename}.md`;
let file = vault.getAbstractFileByPath(path);
if (!file) {
await vault.create(path, `# ${new Date().toLocaleDateString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric" })}
${heading}
${content}
`);
new import_obsidian3.Notice("\u{1F4DD} Task logged to new daily note");
return;
if (file && file instanceof import_obsidian3.TFile) {
return file;
}
if (!(file instanceof import_obsidian3.TFile)) {
new import_obsidian3.Notice("Daily note path is not a file");
return;
}
let existingContent = await vault.read(file);
if (existingContent.includes(heading)) {
const headingIndex = existingContent.indexOf(heading);
const afterHeading = headingIndex + heading.length;
const nextHeadingMatch = existingContent.slice(afterHeading).match(/\n##? /);
let insertPosition;
if (nextHeadingMatch && nextHeadingMatch.index !== void 0) {
insertPosition = afterHeading + nextHeadingMatch.index;
} else {
insertPosition = existingContent.length;
try {
if (dailySettings.folder) {
const folderExists = vault.getAbstractFileByPath(dailySettings.folder);
if (!folderExists) {
await vault.createFolder(dailySettings.folder);
}
}
const before = existingContent.slice(0, insertPosition);
const after = existingContent.slice(insertPosition);
const newContent = before.trimEnd() + "\n" + content + "\n" + after.trimStart();
await vault.modify(file, newContent);
} else {
const newContent = existingContent.trimEnd() + "\n\n" + heading + "\n\n" + content + "\n";
await vault.modify(file, newContent);
let content = "";
if (dailySettings.template) {
const templatePath = dailySettings.template.endsWith(".md") ? dailySettings.template : `${dailySettings.template}.md`;
const templateFile = vault.getAbstractFileByPath(templatePath);
if (templateFile && templateFile instanceof import_obsidian3.TFile) {
content = await vault.read(templateFile);
content = content.replace(/{{date}}/g, filename).replace(/{{time}}/g, new Date().toLocaleTimeString()).replace(/{{title}}/g, filename);
}
}
const newFile = await vault.create(path, content);
new import_obsidian3.Notice(`\u{1F4DD} Created daily note: ${filename}`);
return newFile;
} catch (e) {
console.error("Failed to create daily note:", e);
new import_obsidian3.Notice("Failed to create daily note");
return null;
}
}
async appendToDailyNote(content) {
const file = await this.getOrCreateDailyNote();
if (!file) {
return;
}
const { vault } = this.app;
const existingContent = await vault.read(file);
const newContent = existingContent.trimEnd() + "\n" + content + "\n";
await vault.modify(file, newContent);
new import_obsidian3.Notice("\u{1F4DD} Task logged to daily note");
}
// ============ Utilities ============
@@ -1067,18 +1086,20 @@ var FocusTaskSettingTab = class extends import_obsidian3.PluginSettingTab {
await this.plugin.saveAllData();
}));
containerEl.createEl("h2", { text: "\u{1F4DD} Daily Note Integration" });
new import_obsidian3.Setting(containerEl).setName("Log completed tasks to daily note").setDesc("When you complete a task, add an entry to your daily note").addToggle((toggle) => toggle.setValue(this.plugin.settings.logToDaily).onChange(async (value) => {
new import_obsidian3.Setting(containerEl).setName("Log completed tasks to 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.setValue(this.plugin.settings.logToDaily).onChange(async (value) => {
this.plugin.settings.logToDaily = value;
await this.plugin.saveAllData();
}));
new import_obsidian3.Setting(containerEl).setName("Daily note filename format").setDesc("Format for daily note filename (YYYY = year, MM = month, DD = day)").addText((text) => text.setPlaceholder("YYYY-MM-DD").setValue(this.plugin.settings.dailyNoteFormat).onChange(async (value) => {
this.plugin.settings.dailyNoteFormat = value || "YYYY-MM-DD";
await this.plugin.saveAllData();
}));
new import_obsidian3.Setting(containerEl).setName("Section heading").setDesc("Heading under which completed tasks will be logged").addText((text) => text.setPlaceholder("## \u26A1 Completed Tasks").setValue(this.plugin.settings.dailyNoteHeading).onChange(async (value) => {
this.plugin.settings.dailyNoteHeading = value || "## \u26A1 Completed Tasks";
await this.plugin.saveAllData();
}));
const infoEl = containerEl.createEl("div", { cls: "setting-item-description" });
infoEl.style.marginTop = "-10px";
infoEl.style.marginBottom = "20px";
infoEl.innerHTML = `
<small>
This feature uses the <strong>Daily Notes</strong> core plugin.
Configure your daily note folder, date format, and template in
<em>Settings \u2192 Core plugins \u2192 Daily notes</em>.
</small>
`;
containerEl.createEl("h2", { text: "\u{1F4CB} Lists" });
this.plugin.settings.lists.forEach((list, index) => {
new import_obsidian3.Setting(containerEl).setName(`${list.icon} ${list.name}`).addText((text) => text.setValue(list.name).setPlaceholder("List name").onChange(async (value) => {

View File

@@ -551,7 +551,6 @@ export default class FocusTaskPlugin extends Plugin {
async logTaskToDailyNote(task: FocusTask) {
try {
const dailyNotePath = this.getDailyNotePath();
const list = this.settings.lists.find(l => l.id === task.list);
// 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}`;
await this.appendToDailyNote(dailyNotePath, taskEntry);
await this.appendToDailyNote(taskEntry);
} catch (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 {
const now = new Date();
const format = this.settings.dailyNoteFormat;
getDailyNoteSettings(): { folder: string; format: string; template: string } | null {
// Access the core Daily Notes plugin settings
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 month = (now.getMonth() + 1).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('YY', year.toString().slice(-2))
.replace('MM', month)
.replace('DD', day);
return `${filename}.md`;
.replace('M', (now.getMonth() + 1).toString())
.replace('DD', day)
.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 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);
if (!file) {
// Create the daily note if it doesn't exist
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 && file instanceof TFile) {
return file;
}
if (!(file instanceof TFile)) {
new Notice('Daily note path is not a file');
return;
}
// Read existing content
let existingContent = await vault.read(file);
// 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;
// Create the daily note
try {
// Ensure folder exists
if (dailySettings.folder) {
const folderExists = vault.getAbstractFileByPath(dailySettings.folder);
if (!folderExists) {
await vault.createFolder(dailySettings.folder);
}
}
// Insert the new task entry
const before = existingContent.slice(0, insertPosition);
const after = existingContent.slice(insertPosition);
// Check if template exists and use it
let content = '';
if (dailySettings.template) {
const templatePath = dailySettings.template.endsWith('.md')
? dailySettings.template
: `${dailySettings.template}.md`;
const templateFile = vault.getAbstractFileByPath(templatePath);
// Make sure there's a newline before our content
const newContent = before.trimEnd() + '\n' + content + '\n' + after.trimStart();
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);
}
}
await vault.modify(file, newContent);
} else {
// Add the heading and content at the end
const newContent = existingContent.trimEnd() + '\n\n' + heading + '\n\n' + content + '\n';
await vault.modify(file, newContent);
// Create the file
const newFile = await vault.create(path, content);
new Notice(`📝 Created daily note: ${filename}`);
return newFile;
} catch (e) {
console.error('Failed to create daily note:', e);
new Notice('Failed to create daily note');
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');
}
@@ -843,7 +881,7 @@ class FocusTaskSettingTab extends PluginSettingTab {
new Setting(containerEl)
.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
.setValue(this.plugin.settings.logToDaily)
.onChange(async value => {
@@ -851,27 +889,17 @@ class FocusTaskSettingTab extends PluginSettingTab {
await this.plugin.saveAllData();
}));
new Setting(containerEl)
.setName('Daily note filename format')
.setDesc('Format for daily note filename (YYYY = year, MM = month, DD = day)')
.addText(text => text
.setPlaceholder('YYYY-MM-DD')
.setValue(this.plugin.settings.dailyNoteFormat)
.onChange(async value => {
this.plugin.settings.dailyNoteFormat = value || 'YYYY-MM-DD';
await this.plugin.saveAllData();
}));
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();
}));
// Show info about Daily Notes plugin
const infoEl = containerEl.createEl('div', { cls: 'setting-item-description' });
infoEl.style.marginTop = '-10px';
infoEl.style.marginBottom = '20px';
infoEl.innerHTML = `
<small>
This feature uses the <strong>Daily Notes</strong> core plugin.
Configure your daily note folder, date format, and template in
<em>Settings → Core plugins → Daily notes</em>.
</small>
`;
// Lists Management
containerEl.createEl('h2', { text: '📋 Lists' });

View File

@@ -34,8 +34,6 @@ export interface FocusTaskSettings {
tickSoundEnabled: boolean;
// Daily note logging
logToDaily: boolean;
dailyNoteFormat: string;
dailyNoteHeading: string;
}
export interface FocusTaskData {
@@ -64,8 +62,6 @@ export const DEFAULT_SETTINGS: FocusTaskSettings = {
tickSoundEnabled: false,
// Daily note logging
logToDaily: false,
dailyNoteFormat: 'YYYY-MM-DD',
dailyNoteHeading: '## ⚡ Completed Tasks',
};
export const DEFAULT_DATA: FocusTaskData = {