// ── Main plugin entry ── import { Plugin, WorkspaceLeaf, Notice, TFile, TFolder, TAbstractFile, getAllTags, moment, } from 'obsidian'; import { WaypointSettings, DEFAULT_SETTINGS, DateSystemSettings, DEFAULT_DATE_SYSTEM } from 'src/settings'; import { WaypointSettingTab } from 'src/settings-tab'; import { WaypointView, WAYPOINT_VIEW_TYPE } from 'src/views/waypoint-view'; import { BookmarkItem, RecentFileEntry, WaypointData } from 'src/models/bookmark'; import { DatePickerModal } from 'src/modals/date-picker-modal'; import { remapRenamedPath } from 'src/utils/path-utils'; import { recentFilesFor, trimRecentFiles } from 'src/utils/recent-files'; import { splitNameFormat, isInFolder, matchesSystemName, titleFromBasename, sanitizeTitle, formatHasDateToken, } from 'src/utils/date-systems'; export type PeriodKey = 'day' | 'week' | 'month' | 'quarter' | 'year'; /** One existing note of a date system, with the label the menu should show. */ export interface DateSystemNote { file: TFile; /** Free-text title for many-per-date systems, else the system name. */ label: string; } /** A day-scoped system and the notes it already holds for one date. */ export interface DateSystemNotes { system: DateSystemSettings; /** Sorted by basename. Empty when the date has no note in this system. */ notes: DateSystemNote[]; /** True when nameFormat carries {title}, i.e. many notes per date. */ multiple: boolean; } /** One coloured calendar marker for a date system that has a note on a day. */ export interface DateSystemIndicator { id: string; name: string; color: string; } export default class WaypointPlugin extends Plugin { public settings: WaypointSettings; public waypointData: WaypointData; public recentFiles: RecentFileEntry[] = []; private recentFilesSaveTimer: number | undefined; /** Serializes writes to data.json so overlapping saves cannot lose updates. */ private savePromise: Promise = Promise.resolve(); /** Basenames of every markdown file in the vault, for O(1) calendar lookups. */ private markdownBasenames: Set = new Set(); /** Results for the displayed month; invalidated by markdown-file changes. */ private dateSystemIndicators: Map | null = null; private dateSystemIndicatorKey = ''; /** * True once `data.json` carries the post-migration schema. Set on every * load and included in every save, so a single migration run is durable * even if this session never triggers another settings write. */ private indicatorModeMigrated = false; /** * The file that was active just before the current one. Its editor may * still flush a pending save after the switch, which is the user's own * edit and must not be flagged as a background change. */ private previouslyActive: { path: string; until: number } | null = null; private activePath: string | null = null; async onload(): Promise { console.debug('Waypoint: loading plugin v' + this.manifest.version); // Load persisted data — data.json is read exactly once here. const saved = await this.loadData() as Record | null; const migrated = this.applySettings(saved); this.applyWaypointData(saved); if (migrated) { // Persist immediately: an install that only ever reads data.json // (never changes a setting or bookmark this session) must still // keep the migrated value instead of re-migrating every load. void this.persistAll(); } // Register the sidebar view this.registerView( WAYPOINT_VIEW_TYPE, (leaf: WorkspaceLeaf) => new WaypointView(leaf, this), ); // Register settings tab this.addSettingTab(new WaypointSettingTab( this.app, this, this.settings, () => { this.enforceRecentFilesLimit(); this.invalidateDateSystemIndicators(); this.redrawAll(); }, )); // ── Commands ── this.addCommand({ id: 'waypoint-open-view', name: 'Open Waypoint sidebar', callback: async () => { const leaves = this.app.workspace.getLeavesOfType(WAYPOINT_VIEW_TYPE); if (leaves.length > 0) { await this.app.workspace.revealLeaf(leaves[0]); } else { const leaf = this.app.workspace.getLeftLeaf(false); if (leaf) { await leaf.setViewState({ type: WAYPOINT_VIEW_TYPE }); await this.app.workspace.revealLeaf(leaf); } } }, }); this.addCommand({ id: 'waypoint-add-bookmark', name: 'Add current file as Waypoint bookmark', callback: async () => { const file = this.app.workspace.getActiveFile(); if (!file) { new Notice('No active file'); return; } this.addBookmark(file.path, file.basename, 'file'); new Notice(`Bookmarked: ${file.basename}`); }, }); this.addCommand({ id: 'waypoint-go-to-daily', name: 'Go to daily note', hotkeys: [{ modifiers: ['Mod', 'Shift', 'Alt'], key: 'd' }], callback: async () => { await this.openPeriodNote('day', moment()); }, }); this.addCommand({ id: 'waypoint-go-to-weekly', name: 'Go to weekly note', hotkeys: [{ modifiers: ['Mod', 'Shift', 'Alt'], key: 'w' }], callback: async () => { await this.openPeriodNote('week', moment()); }, }); this.addCommand({ id: 'waypoint-go-to-monthly', name: 'Go to monthly note', hotkeys: [{ modifiers: ['Mod', 'Shift', 'Alt'], key: 'm' }], callback: async () => { await this.openPeriodNote('month', moment()); }, }); this.addCommand({ id: 'waypoint-go-to-quarterly', name: 'Go to quarterly note', hotkeys: [{ modifiers: ['Mod', 'Shift', 'Alt'], key: 'q' }], callback: async () => { await this.openPeriodNote('quarter', moment()); }, }); this.addCommand({ id: 'waypoint-go-to-yearly', name: 'Go to yearly note', hotkeys: [{ modifiers: ['Mod', 'Shift', 'Alt'], key: 'y' }], callback: async () => { await this.openPeriodNote('year', moment()); }, }); this.addCommand({ id: 'waypoint-open-date', name: 'Open daily note for a date…', callback: () => { new DatePickerModal(this.app, moment(), (date) => { this.showDateInViews(date); void this.openPeriodNote('day', date); }).open(); }, }); // ── Period navigation commands (no hotkeys) ── const directions = ['next', 'prev'] as const; const periodLabels = ['daily', 'weekly', 'monthly', 'quarterly', 'yearly'] as const; const directionLabels: Record = { next: 'Next', prev: 'Previous' }; for (const period of periodLabels) { for (const dir of directions) { const id = `waypoint-go-to-${dir}-${period}`; const name = `${directionLabels[dir]} ${period} note`; this.addCommand({ id, name, callback: async () => { await this.navigatePeriodNote(dir); }, }); } } // ── Events ── this.registerEvent( this.app.workspace.on('file-open', (file: TFile | null) => { if (file) this.onFileOpen(file); }), ); this.registerEvent( this.app.vault.on('create', (file: TAbstractFile) => this.onVaultCreate(file)), ); this.registerEvent( this.app.vault.on('delete', (file: TAbstractFile) => this.onVaultDelete(file)), ); this.registerEvent( this.app.vault.on('rename', (file, oldPath) => this.onRename(file, oldPath)), ); this.registerEvent( this.app.vault.on('modify', (file: TAbstractFile) => this.onFileChange(file)), ); // Auto-open view on first load this.app.workspace.onLayoutReady(() => { this.buildMarkdownIndex(); const leaves = this.app.workspace.getLeavesOfType(WAYPOINT_VIEW_TYPE); if (leaves.length === 0) { const leaf = this.app.workspace.getLeftLeaf(false); if (leaf) { leaf.setViewState({ type: WAYPOINT_VIEW_TYPE }); } } else { // A restored view may have rendered before the index existed. this.broadcastRedraw(); } }); // Midnight refresh (check every 10 min) let lastDate = new Date().toDateString(); this.registerInterval( window.setInterval(() => { const currentDate = new Date().toDateString(); if (currentDate !== lastDate) { lastDate = currentDate; this.redrawAll(); } }, 600000), // 10 min ); } async onunload(): Promise { this.app.workspace.detachLeavesOfType(WAYPOINT_VIEW_TYPE); } // ── Settings & persistence ── /** * Merge persisted settings over the defaults. Nested objects are merged * individually so existing configs keep their values while picking up * fields added in newer versions. Returns true the one time a one-off * migration (see `indicatorModeMigrated` below) actually changes a value, * so the caller can persist that change immediately. */ private applySettings(saved: Record | null): boolean { const s = (saved?.settings || {}) as Partial; this.settings = Object.assign({}, DEFAULT_SETTINGS, s); this.settings.recentFiles = Object.assign({}, DEFAULT_SETTINGS.recentFiles, s.recentFiles || {}); // Drop keys of removed features: the old type filter (`filterTags`, // then `showTypeFilter`) and the single `updateOn` mode, now the header // filter `show`. const legacyRecent = this.settings.recentFiles as Partial<{ filterTags: string[]; showTypeFilter: boolean; updateOn: string }>; this.settings.recentFiles.types = Array.isArray(s.recentFiles?.types) ? s.recentFiles.types.map(t => ({ ...t })) : []; delete legacyRecent.filterTags; delete legacyRecent.showTypeFilter; delete legacyRecent.updateOn; this.settings.calendar = Object.assign({}, DEFAULT_SETTINGS.calendar, s.calendar || {}); this.settings.display = Object.assign({}, DEFAULT_SETTINGS.display, s.display || {}); for (const key of PERIOD_SETTING_KEYS) { this.settings[key] = Object.assign({}, DEFAULT_SETTINGS[key], s[key] || {}); } // Cloned, not Object.assign'd in: the defaults array would otherwise be // aliased into the live settings and the settings UI would edit // DEFAULT_DATE_SYSTEM so older configs pick up fields added since. Known // built-ins use their own defaults too, preserving Journal/Meeting colours // when this field is first introduced. this.settings.dateSystems = Array.isArray(s.dateSystems) ? s.dateSystems.map(sys => { const builtIn = DEFAULT_SETTINGS.dateSystems.find(defaultSystem => defaultSystem.id === sys.id); return Object.assign({}, builtIn || DEFAULT_DATE_SYSTEM, sys); }) : DEFAULT_SETTINGS.dateSystems.map(sys => Object.assign({}, sys)); // `indicatorMode` shipped with a default of 'any' before per-system // colours existed, so every install that loaded before that default // changed silently persisted 'any' to disk as if it were a deliberate // choice — changing DEFAULT_SETTINGS alone can never reach an install // that already has an explicit value on disk. Promote that one-time // default to the current default exactly once; any choice made after // this flag is set is real and must never be touched again. const alreadyMigrated = saved?.indicatorModeMigrated === true; let didMigrateValue = false; if (!alreadyMigrated && s.calendar?.indicatorMode === 'any') { this.settings.calendar.indicatorMode = 'systems'; didMigrateValue = true; } this.indicatorModeMigrated = true; return didMigrateValue; } private applyWaypointData(saved: Record | null): void { const d = (saved?.waypointData || {}) as Partial; this.waypointData = { bookmarks: Array.isArray(d.bookmarks) ? d.bookmarks : [], recentFiles: Array.isArray(d.recentFiles) ? d.recentFiles : [], }; // Entries saved before per-kind timestamps carry only their order and // the old single tracking mode. Small descending stamps keep that order // and sort them after anything recorded from now on. const legacy = (saved?.settings as { recentFiles?: { updateOn?: string } } | undefined)?.recentFiles?.updateOn; const legacyKind = legacy === 'file-edit' ? 'changedAt' : 'openedAt'; const count = this.waypointData.recentFiles.length; this.recentFiles = trimRecentFiles( this.waypointData.recentFiles.map((entry, i) => entry.openedAt === undefined && entry.changedAt === undefined ? { ...entry, [legacyKind]: count - i } : entry), this.settings.recentFiles.maxItems, ); this.waypointData.recentFiles = this.recentFiles; } /** * Write both top-level keys of data.json from memory. * * Saves never re-read from disk: `settings` and `waypointData` are the only * keys and both are held in memory, so a read-modify-write would only give * two concurrent saves a stale snapshot of the other's key. Writes are * chained onto `savePromise` so they cannot interleave. */ private persistAll(): Promise { const write = this.savePromise.then(() => { // Sync recentFiles into waypointData before writing this.waypointData.recentFiles = this.recentFiles; return this.saveData({ settings: this.settings, waypointData: this.waypointData, indicatorModeMigrated: this.indicatorModeMigrated, }); }); // Keep the queue usable after a failed write without leaving an // unhandled rejection behind; callers still see `write` reject. this.savePromise = write.catch(() => undefined); return write; } async saveSettings(): Promise { await this.persistAll(); } async saveWaypointData(): Promise { await this.persistAll(); } /** * Trim recent files to the current maxItems limit and persist. * Called when the maxItems setting changes. */ enforceRecentFilesLimit(): void { const trimmed = trimRecentFiles(this.recentFiles, this.settings.recentFiles.maxItems); if (trimmed.length !== this.recentFiles.length) { this.recentFiles = trimmed; this.persistRecentFiles(); } } /** * Persist recent files to disk (debounced to avoid excessive writes on rapid opens). */ persistRecentFiles(): void { this.waypointData.recentFiles = this.recentFiles; window.clearTimeout(this.recentFilesSaveTimer); this.recentFilesSaveTimer = window.setTimeout(() => { this.saveWaypointData(); }, 300); } // ── Recent Files ── private onFileOpen(file: TFile): void { if (this.activePath && this.activePath !== file.path) { this.previouslyActive = { path: this.activePath, until: Date.now() + PENDING_SAVE_GRACE_MS }; } this.activePath = file.path; this.recordRecentFile(file, 'opened'); } /** Vault `modify`, and `create` once the layout is ready (sync, other plugins). */ private onFileChange(file: TAbstractFile): void { if (!(file instanceof TFile)) return; this.recordRecentFile(file, 'changed', this.isBackgroundChange(file)); } /** A change the user did not make in the editor: the file is neither active nor just left. */ private isBackgroundChange(file: TFile): boolean { if (this.app.workspace.getActiveFile()?.path === file.path) return false; const prev = this.previouslyActive; return !(prev && prev.path === file.path && Date.now() < prev.until); } /** Stamp `file` as just opened or just changed. Opening clears the background dot. */ private recordRecentFile(file: TFile, kind: 'opened' | 'changed', background = false): void { if (this.isOmittedFromRecentFiles(file)) return; let entry = this.recentFiles.find(f => f.path === file.path); // The editor saves every couple of seconds while you type. When this // file already leads both orderings and the dot is unchanged, only the // timestamp moves, so the sidebar does not need a rebuild. const quiet = kind === 'changed' && entry !== undefined && this.recentFiles[0] === entry && recentFilesFor(this.recentFiles, 'changed')[0] === entry && !(background && !entry.changedInBackground); if (!entry) { entry = { path: file.path, basename: file.basename }; this.recentFiles.push(entry); } if (kind === 'opened') { entry.openedAt = Date.now(); delete entry.changedInBackground; } else { entry.changedAt = Date.now(); if (background) entry.changedInBackground = true; } this.recentFiles = trimRecentFiles(this.recentFiles, this.settings.recentFiles.maxItems); this.persistRecentFiles(); if (!quiet) this.broadcastRedraw(); } /** * Apply the omittedPaths / omittedTags filters. Each entry is treated as a * regex; an invalid pattern is skipped rather than throwing. */ private isOmittedFromRecentFiles(file: TFile): boolean { for (const pattern of this.settings.recentFiles.omittedPaths) { try { if (new RegExp(pattern).test(file.path)) return true; } catch { // Invalid regex, skip } } const omittedTags = this.settings.recentFiles.omittedTags; if (omittedTags.length === 0) return false; const cache = this.app.metadataCache.getFileCache(file); const tags = (cache ? getAllTags(cache) : null) || []; if (tags.length === 0) return false; const bareTags = tags.map(tag => tag.replace(/^#/, '')); for (const pattern of omittedTags) { try { const regex = new RegExp(pattern); if (bareTags.some(tag => regex.test(tag))) return true; } catch { // Invalid regex, skip } } return false; } /** * Obsidian fires `rename` for folders too, so a stored path may need * remapping either because it is the renamed item or because it sits * inside a renamed folder. */ private onRename(file: TAbstractFile, oldPath: string): void { this.invalidateDateSystemIndicators(); const indexChanged = this.syncIndexForRename(file, oldPath); let dataChanged = false; for (const entry of this.recentFiles) { const remapped = remapRenamedPath(entry.path, oldPath, file.path); if (remapped === null) continue; entry.path = remapped; entry.basename = basenameFromPath(remapped); dataChanged = true; } const remapBookmarks = (items: BookmarkItem[]): void => { for (const item of items) { if (item.filePath) { const remapped = remapRenamedPath(item.filePath, oldPath, file.path); if (remapped !== null) { item.filePath = remapped; dataChanged = true; } } if (item.children) remapBookmarks(item.children); } }; remapBookmarks(this.waypointData.bookmarks); if (dataChanged) { this.waypointData.recentFiles = this.recentFiles; this.persistAll(); } if (dataChanged || indexChanged) this.broadcastRedraw(); } private onVaultCreate(file: TAbstractFile): void { if (file instanceof TFile && file.extension === 'md') { this.markdownBasenames.add(file.basename); this.invalidateDateSystemIndicators(); } // The initial vault scan fires `create` for every file before layout-ready. if (this.app.workspace.layoutReady) this.onFileChange(file); this.broadcastRedraw(); } private onVaultDelete(file: TAbstractFile): void { if (file instanceof TFile && file.extension === 'md') { this.removeFromMarkdownIndex(file.basename, file.path); this.invalidateDateSystemIndicators(); } this.broadcastRedraw(); } // ── Markdown basename index (calendar note indicators) ── private buildMarkdownIndex(): void { this.markdownBasenames.clear(); for (const file of this.app.vault.getMarkdownFiles()) { this.markdownBasenames.add(file.basename); } } /** Forget a month result when markdown paths or date-system settings change. */ private invalidateDateSystemIndicators(): void { this.dateSystemIndicators = null; this.dateSystemIndicatorKey = ''; } /** * Drop a basename from the index, unless another markdown file still * carries it. `path` is excluded from that check because the vault may not * have dropped the file yet when the event fires. */ private removeFromMarkdownIndex(basename: string, path: string): boolean { if (!this.markdownBasenames.has(basename)) return false; const stillExists = this.app.vault.getMarkdownFiles() .some(f => f.basename === basename && f.path !== path); if (stillExists) return false; this.markdownBasenames.delete(basename); return true; } /** Returns true when the index changed. Folder renames never change basenames. */ private syncIndexForRename(file: TAbstractFile, oldPath: string): boolean { if (!(file instanceof TFile)) return false; let changed = false; const oldBasename = basenameFromPath(oldPath); if (oldPath.toLowerCase().endsWith('.md') && (oldBasename !== file.basename || file.extension !== 'md')) { changed = this.removeFromMarkdownIndex(oldBasename, oldPath); } if (file.extension === 'md' && !this.markdownBasenames.has(file.basename)) { this.markdownBasenames.add(file.basename); changed = true; } return changed; } /** * Whether any markdown file in the vault is named exactly `dateStr`. * Synchronous and O(1) — the calendar calls this once per day cell. */ hasNoteForDate(dateStr: string): boolean { return this.markdownBasenames.has(dateStr); } // ── Bookmarks ── addBookmark(filePath: string, label: string, type: 'file' | 'group' | 'separator' | 'spacer' = 'file', icon = ''): BookmarkItem { const id = `bm-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`; const item: BookmarkItem = { id, type, label, filePath: type === 'file' ? filePath : '', icon, children: [], collapsed: false, indent: 0, }; this.waypointData.bookmarks.push(item); this.saveWaypointData(); this.broadcastRedraw(); return item; } removeBookmark(id: string): void { const removeRecursive = (items: BookmarkItem[]): boolean => { const idx = items.findIndex(i => i.id === id); if (idx >= 0) { items.splice(idx, 1); return true; } for (const item of items) { if (item.children && removeRecursive(item.children)) return true; } return false; }; removeRecursive(this.waypointData.bookmarks); this.saveWaypointData(); this.broadcastRedraw(); } updateBookmark(id: string, updates: Partial): void { const findRecursive = (items: BookmarkItem[]): BookmarkItem | null => { for (const item of items) { if (item.id === id) return item; if (item.children) { const found = findRecursive(item.children); if (found) return found; } } return null; }; const item = findRecursive(this.waypointData.bookmarks); if (item) { Object.assign(item, updates); this.saveWaypointData(); this.broadcastRedraw(); } } // ── Date systems: discovery, creation, opening ── /** Periodic notes are date systems with a fixed one-note-per-period format. */ private periodAsDateSystem(period: PeriodKey): DateSystemSettings { const config = PERIOD_CONFIGS[period]; const periodSettings = this.settings[config.key]; return { id: config.key, name: config.label, folder: periodSettings.folder, nameFormat: periodSettings.nameFormat, templateFile: periodSettings.templateFile, typeProperty: periodSettings.typeProperty, icon: 'calendar', indicatorColor: this.settings.calendar.dailyIndicatorColor, }; } /** All day-scoped systems: the daily periodic note first, then settings.dateSystems. */ dateSystems(): DateSystemSettings[] { return [this.periodAsDateSystem('day'), ...this.settings.dateSystems]; } /** * Bucket the notes every day-scoped system already holds for `date`. * * One vault scan serves all systems at once. That is affordable because * this runs once per right-click, not once per calendar cell, and it keeps * arbitrary user-defined name formats out of the incremental index. */ findDateSystemNotes(date: moment.Moment): DateSystemNotes[] { const buckets = this.dateSystems().map(system => { const parts = splitNameFormat(system.nameFormat); return { result: { system, notes: [] as DateSystemNote[], multiple: parts.hasTitle }, // Each half is formatted on its own: the raw format may still // hold {title}, whose letters are live moment tokens. before: formatDatePart(date, parts.before), after: formatDatePart(date, parts.after), hasTitle: parts.hasTitle, // Empty/date-less formats have no date-specific filename. They stay // editable in Settings but must not contribute a menu action. skip: !formatHasDateToken(system.nameFormat), }; }); for (const file of this.app.vault.getMarkdownFiles()) { for (const bucket of buckets) { if (bucket.skip) continue; const system = bucket.result.system; if (!isInFolder(file.path, system.folder)) continue; if (!matchesSystemName(file.basename, bucket.before, bucket.after, bucket.hasTitle)) continue; bucket.result.notes.push({ file, label: bucket.hasTitle ? titleFromBasename(file.basename, bucket.before, bucket.after) : system.name, }); } } for (const bucket of buckets) { bucket.result.notes.sort((a, b) => a.file.basename.localeCompare(b.file.basename)); } return buckets .filter(bucket => !bucket.skip) .map(bucket => bucket.result); } /** * Return one coloured indicator per system with a note on each requested day. * * The day grid calls this once per render. Its result is cached by the * displayed dates and system settings, then invalidated by file changes, so * a 42-cell calendar never repeats the vault scan per cell or per redraw. */ getDateSystemIndicators(dates: moment.Moment[]): Map { const dateStrings = dates.map(date => date.format('YYYY-MM-DD')); const systems = this.dateSystems() .filter(system => formatHasDateToken(system.nameFormat)) .map(system => { const parts = splitNameFormat(system.nameFormat); return { system, hasTitle: parts.hasTitle, dates: dates.map((date, index) => ({ dateStr: dateStrings[index], before: formatDatePart(date, parts.before), after: formatDatePart(date, parts.after), })), }; }); const key = JSON.stringify({ dates: dateStrings, systems: systems.map(({ system }) => [ system.id, system.name, system.folder, system.nameFormat, system.indicatorColor, ]), }); if (this.dateSystemIndicators && this.dateSystemIndicatorKey === key) { return this.dateSystemIndicators; } const matchingIds = new Map>(); for (const dateStr of dateStrings) matchingIds.set(dateStr, new Set()); // The only vault traversal: filter a file by system folder first, then // test it against the month's at-most-42 formatted day patterns. for (const file of this.app.vault.getMarkdownFiles()) { for (const entry of systems) { if (!isInFolder(file.path, entry.system.folder)) continue; for (const match of entry.dates) { if (matchesSystemName(file.basename, match.before, match.after, entry.hasTitle)) { matchingIds.get(match.dateStr)?.add(entry.system.id); } } } } const result = new Map(); for (const dateStr of dateStrings) { const ids = matchingIds.get(dateStr); result.set(dateStr, systems .filter(({ system }) => ids?.has(system.id)) .map(({ system }) => ({ id: system.id, name: system.name, color: system.indicatorColor, }))); } this.dateSystemIndicatorKey = key; this.dateSystemIndicators = result; return result; } /** * Open (creating if needed) the note `system` holds for `date`. * * `opts.title` fills the `{title}` token of a many-per-date system and is * ignored by systems without one. An explicit `opts.leaf` takes precedence; * otherwise `opts.reuseExistingLeaf` reveals an open Markdown tab for the * exact file path, falling back to the active leaf when none is open. */ async openDateSystemNote( system: DateSystemSettings, date: moment.Moment, opts?: { title?: string; leaf?: WorkspaceLeaf; reuseExistingLeaf?: boolean }, ): Promise { if (!formatHasDateToken(system.nameFormat)) { new Notice(`Waypoint: ${system.name || 'This'} name format needs a date placeholder.`); return; } const parts = splitNameFormat(system.nameFormat); const before = formatDatePart(date, parts.before); const after = formatDatePart(date, parts.after); let basename: string; if (parts.hasTitle) { const title = sanitizeTitle(opts?.title || ''); // Public method, so a caller can legitimately hand us nothing; // creating "2026-09-07 - .md" would be worse than refusing. if (!title) { new Notice(`Waypoint: a ${system.name.toLowerCase()} note needs a title.`); return; } basename = before + title + after; } else { basename = before + after; } const fullPath = system.folder ? `${system.folder}/${basename}.md` : `${basename}.md`; let file = this.app.vault.getFileByPath(fullPath); if (!file) { file = await this.createDatedNote(fullPath, system, date); if (!file) return; } if (opts?.reuseExistingLeaf && !opts.leaf) { // View state also identifies deferred tabs whose view is not loaded yet. const existing = this.app.workspace.getLeavesOfType('markdown') .find(leaf => leaf.getViewState().state?.file === file.path); if (existing) { await this.app.workspace.revealLeaf(existing); this.app.workspace.setActiveLeaf(existing, { focus: true }); return; } } const target = opts?.leaf || this.app.workspace.getLeaf(false); await target.openFile(file); } /** * Open (creating if needed) the period note for `date`. * An explicit `leaf` wins; otherwise reuse an open tab when enabled. */ async openPeriodNote(period: PeriodKey, date: moment.Moment, leaf?: WorkspaceLeaf): Promise { await this.openDateSystemNote(this.periodAsDateSystem(period), date, { leaf, reuseExistingLeaf: this.settings.reusePeriodicNoteTabs, }); } /** * Create a date system's note from its template, or from minimal frontmatter. * * Every failure path names the offending path and the reason: the usual * cause is a configured folder that does not exist yet, which `vault.create` * refuses outright rather than creating. */ private async createDatedNote( fullPath: string, system: DateSystemSettings, date: moment.Moment, ): Promise { const noun = system.name.toLowerCase(); const slash = fullPath.lastIndexOf('/'); const folder = slash < 0 ? '' : fullPath.slice(0, slash); try { await this.ensureFolderExists(folder); } catch (err: unknown) { new Notice( `Waypoint: could not create the folder "${folder}" for the ${noun} note.\n` + `${describeError(err)}\n` + 'Check Settings → Waypoint Sidebar → Periodic Notes.', DIAGNOSTIC_NOTICE_MS, ); return null; } const configuredTemplate = system.templateFile; const templateFile = this.resolveTemplateFile(configuredTemplate); let content: string; if (templateFile) { try { content = await this.app.vault.read(templateFile); } catch (err: unknown) { new Notice( `Waypoint: could not read the template "${templateFile.path}" for the ${noun} note.\n` + describeError(err), DIAGNOSTIC_NOTICE_MS, ); return null; } } else { content = `---\ntype: ${system.typeProperty}\ndate: ${date.format('YYYY-MM-DD')}\n---\n\n`; } let file: TFile; try { file = await this.app.vault.create(fullPath, content); } catch (err: unknown) { new Notice( `Waypoint: could not create the ${noun} note at "${fullPath}".\n${describeError(err)}`, DIAGNOSTIC_NOTICE_MS, ); return null; } // A configured-but-missing template otherwise fails silently: the note // just appears with the fallback frontmatter and no explanation. if (configuredTemplate && !templateFile) { new Notice( `Created ${noun} note: ${file.basename}\n` + `Template "${configuredTemplate}" was not found, so a basic note was created instead.`, DIAGNOSTIC_NOTICE_MS, ); } else { new Notice(`Created ${noun} note: ${file.basename}`); } return file; } /** * Create `folder` and any missing ancestors. * `vault.create` throws when the parent folder is absent, so this runs first. */ private async ensureFolderExists(folder: string): Promise { if (!folder) return; if (this.app.vault.getAbstractFileByPath(folder) instanceof TFolder) return; let path = ''; for (const segment of folder.split('/')) { if (!segment) continue; path = path ? `${path}/${segment}` : segment; if (this.app.vault.getAbstractFileByPath(path) instanceof TFolder) continue; try { await this.app.vault.createFolder(path); } catch (err: unknown) { // Someone else may have created it between the check and the call. if (!(this.app.vault.getAbstractFileByPath(path) instanceof TFolder)) throw err; } } } /** The setting may or may not already carry the .md extension. */ private resolveTemplateFile(templateFile: string): TFile | null { if (!templateFile) return null; const path = templateFile.toLowerCase().endsWith('.md') ? templateFile : `${templateFile}.md`; return this.app.vault.getFileByPath(path); } // ── Period note navigation (next/prev from current file) ── /** * Detect the period type from a filename's basename using the configured * name formats, so custom formats keep working. Parsing is strict, which * stops a loose format (e.g. YYYY) from swallowing a longer basename. * Returns the period key and the parsed moment, or null if not a period note. */ private detectPeriodType(basename: string): { period: PeriodKey; date: moment.Moment } | null { for (const period of PERIOD_DETECTION_ORDER) { const format = this.settings[PERIOD_CONFIGS[period].key].nameFormat; if (!format) continue; const date = moment(basename, format, true); if (date.isValid()) return { period, date }; } return null; } /** * Navigate to the next or previous period note based on the currently active file. */ async navigatePeriodNote(direction: 'next' | 'prev'): Promise { const file = this.app.workspace.getActiveFile(); if (!file) { new Notice('No active file'); return; } const detected = this.detectPeriodType(file.basename); if (!detected) { const formats = PERIOD_DETECTION_ORDER .map(p => `${PERIOD_CONFIGS[p].label.toLowerCase()} "${this.settings[PERIOD_CONFIGS[p].key].nameFormat}"`) .join(', '); new Notice( `Waypoint: "${file.basename}" does not match any configured periodic note format.\n` + `Expected one of: ${formats}.`, DIAGNOSTIC_NOTICE_MS, ); return; } const { period, date } = detected; const amount = direction === 'next' ? 1 : -1; // Map period to moment duration unit const newDate = period === 'quarter' ? date.clone().add(amount * 3, 'months') : date.clone().add(amount, `${period}s` as moment.unitOfTime.DurationConstructor); await this.openPeriodNote(period, newDate); } // ── Redraw ── private redrawAll(): void { this.broadcastRedraw(); } private broadcastRedraw(): void { const leaves = this.app.workspace.getLeavesOfType(WAYPOINT_VIEW_TYPE); for (const leaf of leaves) { if (leaf.view instanceof WaypointView) { leaf.view.redraw(); } } } /** Point every Waypoint calendar at `date`'s month and mark that day. */ showDateInViews(date: moment.Moment): void { for (const leaf of this.app.workspace.getLeavesOfType(WAYPOINT_VIEW_TYPE)) { if (leaf.view instanceof WaypointView) { leaf.view.showDate(date); } } } } // ── Module helpers ── type PeriodSettingKey = 'daily' | 'weekly' | 'monthly' | 'quarterly' | 'yearly'; const PERIOD_SETTING_KEYS: PeriodSettingKey[] = ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']; const PERIOD_CONFIGS: Record = { day: { key: 'daily', label: 'Daily' }, week: { key: 'weekly', label: 'Weekly' }, month: { key: 'monthly', label: 'Monthly' }, quarter: { key: 'quarterly', label: 'Quarterly' }, year: { key: 'yearly', label: 'Yearly' }, }; /** Checked day → year so a loose format (YYYY) cannot claim a longer basename. */ const PERIOD_DETECTION_ORDER: PeriodKey[] = ['day', 'week', 'month', 'quarter', 'year']; function basenameFromPath(path: string): string { const name = path.slice(path.lastIndexOf('/') + 1); return name.replace(/\.[^/.]+$/, ''); } /** Notices that carry a diagnosis need longer on screen than the default. */ const DIAGNOSTIC_NOTICE_MS = 10000; /** How long after leaving a file its editor's last save still counts as the user's edit. */ const PENDING_SAVE_GRACE_MS = 5000; function describeError(err: unknown): string { return err instanceof Error ? err.message : String(err); } /** * Format one half of a split name format. Moment falls back to its default * ISO output when handed an empty format string, so an empty half must never * reach it. */ function formatDatePart(date: moment.Moment, part: string): string { return part ? date.format(part) : ''; }