27 Commits
Author SHA1 Message Date
olivier ff15470a06 release v1.9.0: date picker and open-date command, recent files opened/changed with background dot and type icons, mobile layout 2026-10-28 14:02:41 -04:00
olivier 984a0ab44f release v1.8.0: reuse open tabs for periodic notes 2026-10-08 16:36:47 -04:00
olivier 695141383f release v1.7.1: native template autocomplete, durable indicator migration 2026-09-08 10:49:01 -04:00
olivier a0a3b50d94 docs: add QA coverage for indicator migration and native autocomplete 2026-09-08 10:33:10 -04:00
olivier 621bef0d29 fix: native template autocomplete and durable indicator migration
Template file fields used an unstyled <datalist>, not Obsidian's native suggest popup. Replace it with TemplateFileSuggest, an AbstractInputSuggest<TFile> matching Templater's own FileSuggest/FolderSuggest pattern exactly. Requires Obsidian >=1.4.10; minAppVersion corrected.

The coloured-indicator default never reached existing installs: every install that loaded before that default changed had already persisted the prior default (indicatorMode: 'any') to data.json as if it were a deliberate choice, and Object.assign-based settings merging always prefers a value already on disk over a new code default. Hand-editing data.json directly does not fix this durably either -- Obsidian holds settings in memory while a vault is open and overwrites external edits on its own save cycle.

Add a one-time, code-level migration: on load, an install with a persisted indicatorMode of 'any' and no indicatorModeMigrated flag is promoted to 'systems' and the flag is persisted immediately, so it survives even a session with no further settings changes. Any indicatorMode chosen after the flag exists, any (deliberately) included, is never touched again.
2026-09-08 10:32:54 -04:00
olivier e8ba4cd2ad release v1.7.0: redesigned calendar with coloured system indicators 2026-09-08 10:18:43 -04:00
olivier 5a9b7bfff8 docs: describe calendar indicator defaults and autocomplete 2026-09-07 21:53:03 -04:00
olivier 72a61e49ee fix: default calendar to system indicators
Use coloured system markers by default, preserve configured colours through settings migration, expose all template fields through native vault-path autocomplete, and remove the redundant Calendar heading.
2026-09-07 21:52:34 -04:00
olivier 069456799e feat: add coloured calendar system indicators
Add a selectable single-dot or per-system indicator mode. Date systems now carry configurable colours; results are cached per displayed month and invalidated when paths/settings change. Refine calendar hierarchy, spacing, hover, and today states.
2026-09-07 21:43:21 -04:00
olivier 12209155dc release v1.6.0: add calendar date systems 2026-09-07 21:34:32 -04:00
olivier e027ac4a9e fix: let Templater own date-system templates
Leave the default Journal and Meeting systems without a raw Waypoint template so Templater folder triggers own interactive rendering. Their fallback frontmatter now matches the journal and meeting types. Document the required folder-trigger setup and selected-date filename contract.
2026-09-07 21:33:03 -04:00
olivier 26a1a481ac feat: add date systems menu to calendar days
Right-clicking a calendar day now lists every configured date-prefixed note system. Journal notes are singletons; {title} formats support multiple notes per date, such as meetings.\n\nAdds default Journal and Meeting systems, configurable settings UI, safe filename/title handling, one shared dated-note creation path, and a compiled menu smoke test fixture in the test vault.
2026-09-07 21:07:18 -04:00
olivier b617c275eb release v1.5.2: crash, data-loss, and race-condition fixes 2026-09-07 20:30:05 -04:00
olivier bb842b55b4 chore: sync stale lockfile version (1.0.0 -> 1.5.1)
Written by a clean npm install; no dependency changes.
2026-09-07 20:22:43 -04:00
olivier 0eb529e604 chore: rebuild bundle 2026-09-07 20:22:33 -04:00
olivier ece066caf8 fix: pointer cursor on clickables, 'No icon' is a real button
styles.css used cursor: var(--cursor) in 10 places and the icon modal in 2
more. Obsidian defines --cursor as 'default', so nothing in the plugin ever
showed a pointer — the old 'correct cursor on hover' todo never actually
worked. Use var(--cursor-link, pointer): themeable, pointer by default.
cursor: grab on separators/spacers is left alone.

'No icon' was a bare accent-coloured span in the status row. It commits a
value and closes, exactly like Save, so it is now a real button in the
modal button container, left-aligned via margin-right: auto to read as a
secondary action. Also adds the missing trailing newline to styles.css.
2026-09-07 20:22:29 -04:00
olivier b064a64142 fix: create missing period folders and explain failures
Clicking a week/month/quarter/year in a vault whose configured folder does
not exist yet failed with a generic 'Failed to create X note: <raw error>',
because vault.create refuses to create parent folders. Create the folder
(and any missing ancestors) first, then report what actually went wrong.

- Every failure path now names the offending path and the reason, and points
  at the relevant settings section; diagnostic notices stay up for 10s.
- A configured-but-missing template used to fall back to basic frontmatter
  silently; the creation notice now says the template was not found.
- The unreachable !date.isValid() branch after detectPeriodType is gone; the
  'not a periodic note' notice now lists the configured formats it expected.
2026-09-07 20:22:29 -04:00
olivier ec3ad7d384 style: transparent nav buttons, tighter calendar breadcrumb
Drops the default button background/shadow from the header 'more', calendar
nav and Today buttons, and tightens breadcrumb spacing so Q/month/year read
as inline links rather than buttons.
2026-09-07 20:18:30 -04:00
olivier d22b53253e chore: rebuild bundle
Regenerated main.js from the fixed sources (this is what BRAT and manual
installs ship). The bare 'monday' global reference is gone from the bundle.
2026-09-07 20:04:01 -04:00
olivier 61c191505e docs: correct claims contradicted by the source, extend QA checklist
DOCUMENTATION.md said recent files were in-memory only and lost on vault
close, while the code persists them under waypointData.recentFiles; the
WaypointData/RecentFilesSettings/WaypointSettings snippets were also missing
real fields. Fix those, describe the new behaviour (single-writer saves,
settings-driven period detection, O(1) basename lookups, folder-aware rename
remapping, unified openPeriodNote, typechecked build), and trim Known
Limitations to the two still true (full-DOM redraw, CDN icon dependency).

QA.md: restate the 'No icon' case and add coverage for week-number
middle-click and for moving a folder that contains bookmarked files.
2026-09-07 20:04:01 -04:00
olivier c5282dbdef build: gate builds on tsc, fix lib floor, correct minAppVersion
The build only ran esbuild, which strips types without checking them — that
is how the week-number ReferenceError shipped. Add a typecheck script and run
it before bundling. It is invoked as 'node node_modules/typescript/bin/tsc'
rather than a bare 'tsc' because this repo's node_modules/.bin entries are
Linux-style symlinks with no Windows .cmd shims, matching how the existing
scripts already call 'node esbuild.config.mjs' directly.

- tsconfig lib gains ES2017 so Object.entries resolves (was TS2550 plus
  cascading TS7031 implicit-any errors); strictness untouched.
- manifest minAppVersion 0.16.3 -> 1.4.4: the plugin calls setTooltip(), added
  in API 1.4.4, so every declared-supported version below that threw
  TypeError on render.
- settings-tab: type plugin as WaypointPlugin via a type-only import (no
  runtime cycle) to drop the (this.plugin as any).saveSettings() cast, and
  make the slider helper generic instead of obj: any. No UI change.
- Add the MIT LICENSE file that package.json and the About tab already claim.
2026-09-07 20:03:53 -04:00
olivier dc9e4c3200 fix: week-number middle-click crash and 'No icon' never clearing
- Middle-clicking a calendar week number threw ReferenceError: monday is not
  defined (shipped in v1.5.1) — the variable was declared inside the click
  closure and read from the sibling mousedown handler. Hoist it to weekStart.
- promptIcon guarded on if (iconName), so the picker's 'No icon' link
  submitting '' was silently dropped and the old icon stayed. '' is a valid
  value; always apply it.
- renderCalendar scanned vault.getFiles() per day cell (up to 42 full vault
  scans per render); use the O(1) plugin.hasNoteForDate().
- Collapse ~180 lines of triplicated drag listeners into one
  attachBookmarkDragHandlers(); replace (el as any).__dropAbove/__dropInto
  stashing with a typed WeakMap; drop the getLeaf(x as any) casts.
- dragManager.dragFile was called twice per dragstart; call it once behind a
  single narrowly-typed accessor.
- Cache the Lucide catalog per session instead of refetching the CDN on every
  picker open; normalize IconSuggestModal to the file's const/arrow style.
2026-09-07 20:03:45 -04:00
olivier 6a1a044566 fix: folder renames no longer destroy bookmarks, plus data.json save race
- onRename remapped paths by exact equality only, so files inside a moved
  folder kept stale paths and the view then permanently deleted their
  bookmarks on next click. Add pure remapRenamedPath() (path-utils.ts,
  obsidian-free so it is unit-testable) and remap recentFiles + the whole
  bookmark tree, folder moves included.
- saveSettings/saveWaypointData each did loadData -> mutate one key ->
  saveData, so two concurrent saves carried a stale snapshot of the other
  key and one silently reverted the other. Both now delegate to persistAll(),
  which writes both keys from memory through a promise-chain mutex.
- data.json is read once in onload instead of twice; period sub-objects are
  deep-merged so old configs pick up new fields.
- detectPeriodType now derives from the configured nameFormat with strict
  moment parsing instead of hardcoded regexes, so custom formats work.
- Merge openPeriodNoteInLeaf into openPeriodNote(period, date, leaf?); stop
  double-appending .md to templateFile; type the caught error as unknown.
- hasNoteForDate is synchronous and O(1) over a maintained basename Set;
  delete dead getNotesForDate.
- Implement the previously dead omittedTags filter and the no-op
  updateOn: 'file-edit' mode (vault modify event).
2026-09-07 20:03:36 -04:00
olivier 3c7b6741f5 fix: calendar disappeared for existing users
Shallow Object.assign on settings meant filterTags (new in 1.5.0) was
undefined for anyone with prior saved settings. Accessing .length on
undefined threw, killing the entire redraw before calendar could render.

- Defensive fallback: filterTags || []
- Deep merge on loadSettings for recentFiles, calendar, display
2026-06-22 10:18:37 -04:00
olivier abf4d6ccf7 feat: configurable filter tags for recent files
New 'Filter tags' setting in Recent Files tab. Enter tag names one per line
to pin specific tags as filter pills. Leave empty to auto-detect from
frontmatter 'type' property (existing behavior).
2026-06-22 10:15:54 -04:00
olivier 141121878f feat: add About tab to settings with version and plugin description 2026-06-22 10:07:22 -04:00
olivier 6a89660cf4 release v1.4.1 2026-06-22 10:01:47 -04:00
19 changed files with 2417 additions and 632 deletions

No files matched your search

+233 -78
View File
@@ -9,19 +9,21 @@
``` ```
src/ src/
├── main.ts Plugin entry — lifecycle, commands, events, data persistence ├── main.ts Plugin entry — lifecycle, commands, events, data persistence
├── settings.ts Interface definitions + DEFAULT_SETTINGS constant ├── settings.ts Interface definitions + DEFAULT_SETTINGS / DEFAULT_DATE_SYSTEM constants
├── settings-tab.ts PluginSettingTab UI (calendar, periodic paths, recent files) ├── settings-tab.ts PluginSettingTab UI — calendar, periodic, date systems, recent, display, about
├── models/ ├── models/
│ └── bookmark.ts BookmarkItem + WaypointData interfaces │ └── bookmark.ts BookmarkItem + WaypointData interfaces
├── utils/ ├── utils/
│ └── date-utils.ts Moment.js helpers: period formatting, month grid, navigation │ ├── date-utils.ts Moment.js helpers: period formatting, month grid, navigation
│ ├── date-systems.ts Pure date-system filename helpers (no `obsidian` import, unit-testable)
│ └── path-utils.ts Pure path helper: rename remapping (no `obsidian` import, unit-testable)
└── views/ └── views/
└── waypoint-view.ts ItemView subclass — full sidebar rendering + interaction └── waypoint-view.ts ItemView subclass — full sidebar rendering + interaction
``` ```
**Build:** esbuild bundles `src/main.ts` → `main.js`. TypeScript strict, ESNext target. **Build:** `npm run build` runs `tsc --noEmit` first, then esbuild bundles `src/main.ts` → `main.js`. The typecheck is a real gate — esbuild strips types without checking them, so without it type errors would ship. `npm run typecheck` runs the check alone; `npm run dev` (watch) stays ungated for speed. TypeScript strict-null + `noImplicitAny`, ESNext modules, ES6 target, `lib` floor at ES2017.
**Data persistence:** Single `data.json` via Obsidian `Plugin.loadData()/saveData()`. Top-level keys: `settings` (merged with `DEFAULT_SETTINGS`), `waypointData` (bookmark tree). Recent files are in-memory only (lost on vault close). **Data persistence:** Single `data.json` via Obsidian `Plugin.loadData()/saveData()`. Top-level keys: `settings` (merged with `DEFAULT_SETTINGS`), `waypointData` (bookmark tree **and** recent files). Recent files are persisted under `waypointData.recentFiles` and reloaded on startup; writes are debounced 300ms so rapid file opens collapse into one save.
--- ---
@@ -29,11 +31,11 @@ src/
### `onload()` ### `onload()`
1. **Load data** — `loadSettings()` then `loadWaypointData()`, both merge saved partials over defaults via `Object.assign({}, DEFAULT, partial)`. 1. **Load data** — reads `data.json` exactly once, then `applySettings(saved)` and `applyWaypointData(saved)` merge its partial data over defaults.
2. **Register view** — `WAYPOINT_VIEW_TYPE = "waypoint-view"` maps to `WaypointView` factory `(leaf) => new WaypointView(leaf, this)`. 2. **Register view** — `WAYPOINT_VIEW_TYPE = "waypoint-view"` maps to `WaypointView` factory `(leaf) => new WaypointView(leaf, this)`.
3. **Settings tab** — `WaypointSettingTab` receives the live `settings` object + `() => this.redrawAll()` callback for live preview. 3. **Settings tab** — `WaypointSettingTab` receives the live `settings` object + `() => this.redrawAll()` callback for live preview.
4. **Register commands** (see Commands section below). 4. **Register commands** (see Commands section below).
5. **Register events** — `file-open`, `vault:create`, `vault:delete`, `vault:rename`. 5. **Register events** — `file-open`, `vault:create`, `vault:delete`, `vault:rename`, `vault:modify`.
6. **Auto-open** — On `onLayoutReady`, if no existing leaves of the view type, opens one in the left sidebar. 6. **Auto-open** — On `onLayoutReady`, if no existing leaves of the view type, opens one in the left sidebar.
7. **Midnight refresh** — 10-minute `setInterval` checks if `new Date().toDateString()` changed; if so, calls `redrawAll()` (calendar day indicators refresh). 7. **Midnight refresh** — 10-minute `setInterval` checks if `new Date().toDateString()` changed; if so, calls `redrawAll()` (calendar day indicators refresh).
@@ -49,13 +51,16 @@ Detaches all leaves of `WAYPOINT_VIEW_TYPE`.
```typescript ```typescript
interface WaypointSettings { interface WaypointSettings {
calendar: CalendarSettings; // firstDayOfWeek (0=Sun,1=Mon), showNoteIndicators calendar: CalendarSettings; // week start, indicator visibility/style, daily indicator colour
daily: PeriodNoteSettings; daily: PeriodNoteSettings;
reusePeriodicNoteTabs: boolean; // defaults to false; all periodic-note openers reuse an open tab
weekly: PeriodNoteSettings; weekly: PeriodNoteSettings;
monthly: PeriodNoteSettings; monthly: PeriodNoteSettings;
quarterly: PeriodNoteSettings; quarterly: PeriodNoteSettings;
yearly: PeriodNoteSettings; yearly: PeriodNoteSettings;
recentFiles: RecentFilesSettings; // maxItems, updateOn, omittedPaths[], omittedTags[] dateSystems: DateSystemSettings[]; // day-scoped systems beyond the daily note, in menu order
recentFiles: RecentFilesSettings; // maxItems, show, omittedPaths[], omittedTags[], showTypeFilter, types[]
display: DisplaySettings; // px sizing for bookmark rows, fonts, icons, calendar cells
} }
interface PeriodNoteSettings { interface PeriodNoteSettings {
@@ -67,17 +72,36 @@ interface PeriodNoteSettings {
interface CalendarSettings { interface CalendarSettings {
firstDayOfWeek: number; // 0 = Sunday, 1 = Monday firstDayOfWeek: number; // 0 = Sunday, 1 = Monday
showNoteIndicators: boolean; // dot on days with existing .md files showNoteIndicators: boolean; // show or hide all calendar markers
indicatorMode: 'any' | 'systems'; // defaults to systems; one neutral dot or one per date system
dailyIndicatorColor: string; // daily's colour in systems mode
} }
interface RecentFilesSettings { interface RecentFilesSettings {
maxItems: number; // default 50 maxItems: number; // default 50, per kind (opened / changed)
updateOn: 'file-open' | 'file-edit'; // trigger mode show: 'all' | 'opened' | 'changed'; // header switch, default 'all'
omittedPaths: string[]; // regex patterns (one per line) omittedPaths: string[]; // regex patterns (one per line)
omittedTags: string[]; // regex patterns for frontmatter tags omittedTags: string[]; // regex patterns for frontmatter/inline tags
showTypeFilter: boolean; // type pills above the list, default true
types: { type: string; icon: string }[]; // frontmatter types: row icon + pill order (empty = pills auto-detected)
} }
``` ```
Migration in `applySettings`: a saved `filterTags: string[]` becomes `types` with empty icons; the saved `updateOn` is dropped (both kinds are always tracked).
```typescript
interface DisplaySettings {
rowSize: number; // px, base height of bookmark items (18–40)
rowSpacing: number; // px, gap between items (0–12)
indentSize: number; // px, indent per depth level (8–32)
fontSize: number; // px, font size for bookmark labels (10–18)
iconSize: number; // px, icon size (12–24)
calendarCellSize: number; // px, calendar day cell height (20–48)
}
```
`dateSystems` holds the user's configured date systems in menu order — see the Date Systems section for the `DateSystemSettings` shape and the two systems shipped by default.
### BookmarkItem (recursive tree) ### BookmarkItem (recursive tree)
```typescript ```typescript
@@ -94,10 +118,11 @@ interface BookmarkItem {
interface WaypointData { interface WaypointData {
bookmarks: BookmarkItem[]; bookmarks: BookmarkItem[];
recentFiles: { path: string; basename: string }[];
} }
``` ```
The bookmark tree is stored flat in `data.json` under `waypointData.bookmarks` but rendered recursively. Groups contain children; files/separators/spacers are leaf nodes. The bookmark tree is stored under `waypointData.bookmarks` and rendered recursively. Groups contain children; files/separators/spacers are leaf nodes. `waypointData.recentFiles` holds the persisted recent-files list (mirrored into the live `plugin.recentFiles` array on load).
--- ---
@@ -113,7 +138,7 @@ The bookmark tree is stored flat in `data.json` under `waypointData.bookmarks` b
| `waypoint-go-to-quarterly` | Go to quarterly note | `Mod+Shift+Alt+Q` | | `waypoint-go-to-quarterly` | Go to quarterly note | `Mod+Shift+Alt+Q` |
| `waypoint-go-to-yearly` | Go to yearly note | `Mod+Shift+Alt+Y` | | `waypoint-go-to-yearly` | Go to yearly note | `Mod+Shift+Alt+Y` |
All call `openPeriodNote(period, moment())` — opens or creates the current period's note. All five commands call `openPeriodNote(period, moment())` — opening or creating the current period's note. **Periodic Notes → Use existing tabs** defaults to off. When enabled, the shared opener focuses a Markdown tab for the exact configured file path, including in another pane or window, without reopening the file or resetting its editor position. This also applies to next/previous navigation and regular calendar clicks. With no matching tab, normal note creation/opening is unchanged. Explicit open-in-new-tab actions still win; existing duplicate tabs are not closed.
### Next/Previous period (no default hotkeys) ### Next/Previous period (no default hotkeys)
@@ -121,15 +146,9 @@ All call `openPeriodNote(period, moment())` — opens or creates the current per
These call `navigatePeriodNote(direction)` which: These call `navigatePeriodNote(direction)` which:
1. Gets the active file's basename. 1. Gets the active file's basename.
2. Calls `detectPeriodType(basename)` — regex matching: 2. Calls `detectPeriodType(basename)` — **settings-driven**, not hardcoded regexes. It reads `settings.{daily,weekly,monthly,quarterly,yearly}.nameFormat` and tries `moment(basename, nameFormat, true).isValid()` (strict parsing) in order day → week → month → quarter → year, returning the first match as `{ period, date }`. Periods with an empty `nameFormat` are skipped; returns `null` if nothing matches. Changing a name format in settings therefore keeps next/prev navigation working.
- `^\d{4}-\d{2}-\d{2}$` → daily 3. Adds ±1 period (quarters add ±3 months).
- `^\d{4}-W\d{2}$` → weekly 4. Calls `openPeriodNote` for the new date.
- `^\d{4}-\d{2}$` → monthly
- `^\d{4}-Q[1-4]$` → quarterly
- `^\d{4}$` → yearly
3. Parses date via `moment(basename, format)`.
4. Adds ±1 period (quarters add ±3 months).
5. Calls `openPeriodNote` for the new date.
### Other commands ### Other commands
@@ -137,21 +156,135 @@ These call `navigatePeriodNote(direction)` which:
|---|---| |---|---|
| `waypoint-open-view` | Open Waypoint sidebar | | `waypoint-open-view` | Open Waypoint sidebar |
| `waypoint-add-bookmark` | Add current file as Waypoint bookmark | | `waypoint-add-bookmark` | Add current file as Waypoint bookmark |
| `waypoint-open-date` | Open daily note for a date… — `DatePickerModal` (`src/modals/date-picker-modal.ts`, native `<input type="date">`), then `showDateInViews(date)` and `openPeriodNote('day', date)` |
---
## Date Systems
A **date system** is a folder of notes whose filenames begin with a date. Daily notes, a journal and meeting notes are all the same shape, so they share one settings model, one discovery pass and one creation path.
### `DateSystemSettings`
interface DateSystemSettings {
id: string; // stable across edits + reordering, so settings rows can key on it
name: string; // menu label, e.g. "Journal"
folder: string; // e.g. "periodic/journal"
nameFormat: string; // moment format string; may contain "{title}"
templateFile: string; // may omit the .md extension
typeProperty: string; // fallback frontmatter `type:` value
icon: string; // Lucide icon name for the menu item
indicatorColor: string; // calendar dot colour in systems mode
}
```
Configured systems live in `settings.dateSystems`, where array order is menu order. `DEFAULT_DATE_SYSTEM` (in `settings.ts`, typed `Omit<DateSystemSettings, 'id'>`) supplies the field defaults for a newly added row **and** the merge base for saved ones, so a system persisted before a field existed still loads with that field defined. `DEFAULT_SETTINGS.dateSystems` ships two:
| `id` | `name` | Folder | `nameFormat` | Indicator colour | Notes per date |
|---|---|---|---|---|---|
| `journal` | Journal | `periodic/journal` | `YYYY-MM-DD - [Journal]` | green (`#22c55e`) | one |
| `meetings` | Meeting | `periodic/meetings` | `YYYY-MM-DD - {title}` | violet (`#a855f7`) | many |
The default calendar mode is `systems`, while `any` preserves the older one-neutral-dot behaviour. Existing installs that silently persisted the pre-`systems` default of `any` are promoted to `systems` exactly once, on load, via a `data.json`-level `indicatorModeMigrated` flag; a value chosen after that flag is set (including `any`) is never touched again. Template file fields in both Periodic Notes and Date systems use `TemplateFileSuggest`, an `AbstractInputSuggest<TFile>` (the same base class Templater's own template pickers use — Obsidian's native fuzzy-suggest popup, not an unstyled `<datalist>`), searching every Markdown path in the vault. `AbstractInputSuggest` requires Obsidian ≥1.4.10, hence `manifest.json`'s `minAppVersion`.
### Templater folder triggers
Waypoint deliberately does not evaluate Templater syntax. For an interactive Templater template, configure Templater's **Trigger Templater on new file creation** mode for the relevant folder, then leave that date system's `templateFile` blank in Waypoint. Waypoint creates a safe fallback note from `typeProperty` and the selected `YYYY-MM-DD` date; Templater's folder trigger owns the rendered content, prompts, scripts, and cursor placement.
The target filename is the contract between them. A calendar-created journal note is already named `YYYY-MM-DD - Journal`; a meeting is already `YYYY-MM-DD - {title}`. Templates must extract the date from `tp.file.title`, not `tp.date` or `tp.file.creation_date()`, because those refer to when Templater runs rather than the date selected in the calendar.
The journal template may retain a manual fallback: only prompt for a date and rename when `tp.file.title` does **not** match the date-system filename. That preserves manual note creation without a prompt or rename race on calendar creation.
### The `{title}` convention
`nameFormat` is a moment format string, so literal text needs bracket escaping — `YYYY-MM-DD - [Journal]` — the same convention the periodic formats `GGGG-[W]WW` and `YYYY-[Q]Q` already use.
When the format contains `{title}`, the system holds **many** notes per date: the text before the token is the date prefix used to discover them, and the token marks where a typed free-text title goes on creation. Without the token, a date maps to **exactly one** filename.
**Why the token is split out before moment sees the string:** `t`, `i`, `l` and `e` are all live moment format tokens — `l` on its own expands to an entire localized date. Passing `{title}` through `date.format()` would expand those letters and destroy the placeholder, with no way to recover it afterwards. `splitNameFormat()` therefore cuts the format at the token *first*, and callers format `before` and `after` separately, then join the two results around the title. It is also why discovery matches on formatted affixes instead of on a regex derived from the raw format.
### Helpers (`src/utils/date-systems.ts`)
Imports nothing from `'obsidian'` — callers make every moment call and pass the resulting strings in, which keeps the module unit-testable in plain node (same rationale as `path-utils.ts`).
| Export | Signature | Purpose |
|---|---|---|
| `TITLE_TOKEN` | `'{title}'` | The literal placeholder. |
| `splitNameFormat(nameFormat)` | `string → NameFormatParts` | `{ before, after, hasTitle }` — the format cut around the token. |
| `isInFolder(path, folder)` | `string, string → boolean` | Path sits in `folder` or any subfolder. An empty folder means the vault root, so everything matches. |
| `matchesSystemName(basename, before, after, hasTitle)` | `string, string, string, boolean → boolean` | One-per-date: the basename must equal `before + after`. Many-per-date: prefix/suffix match, since the middle is free text. |
| `titleFromBasename(basename, before, after)` | `string, string, string → string` | Strips the affixes to recover the menu label; falls back to the whole basename when they do not line up. |
| `sanitizeTitle(title)` | `string → string` | Collapses filename-illegal and link-syntax characters (`\ / : * ? " < > \| # ^ [ ]`) to `-`, squeezes runs of whitespace, trims — so a typed "Meeting w/ Mark" still yields a creatable filename. |
| `formatHasDateToken(nameFormat)` | `string → boolean` | Strips bracket-escaped literals out of `before`, then looks for any moment date token. Drives the settings warning. |
`matchesSystemName` deliberately returns `false` for a many-per-date format whose `before` is empty (a format of just `{title}`): an empty date prefix would otherwise claim every file in the folder for every date. The settings tab flags formats with no date token, and `findDateSystemNotes()` excludes them from the menu; `openDateSystemNote()` also refuses them. An unfinished or invalid row therefore cannot create `.md` or a static filename.
### Plugin API (`main.ts`)
```typescript
interface DateSystemNote {
file: TFile;
label: string; // free-text title for many-per-date systems, else the system name
}
interface DateSystemNotes {
system: DateSystemSettings;
notes: DateSystemNote[];
multiple: boolean; // nameFormat carries {title}
}
interface DateSystemIndicator {
id: string;
name: string;
color: string;
}
dateSystems(): DateSystemSettings[]
findDateSystemNotes(date: moment.Moment): DateSystemNotes[]
getDateSystemIndicators(dates: moment.Moment[]): Map<string, DateSystemIndicator[]>
openDateSystemNote(
system: DateSystemSettings,
date: moment.Moment,
opts?: { title?: string; leaf?: WorkspaceLeaf; reuseExistingLeaf?: boolean },
): Promise<void>
```
**`getDateSystemIndicators(dates)`** — returns one `{ id, name, color }` marker per configured system with one or more notes on a requested day. The calendar calls it once for the visible month only in `indicatorMode: 'systems'`. It makes one vault pass, caches the result by displayed dates and date-system settings, and invalidates it on markdown create/delete/rename or any Settings change. It does not run on ordinary markdown edits: content edits cannot change a filename-derived indicator.
**`dateSystems()`** — every day-scoped system in menu order: the daily periodic note, synthesized into a `DateSystemSettings` from `settings.daily`, followed by `settings.dateSystems`. The daily note is therefore not a special case in any consumer.
**`findDateSystemNotes(date)`** — **one** vault scan per call, not one per system. It formats each usable system's `before`/`after` affixes for `date` once, then walks the markdown file list a single time, bucketing each file into the system that claims it (`isInFolder` + `matchesSystemName`). Systems whose formats have no date token are omitted rather than offering an unsafe create action. It returns the remaining `DateSystemNotes` in `dateSystems()` order, each bucket sorted by basename. The calendar's day context menu is built from exactly one of these calls per right-click.
**`openDateSystemNote(system, date, opts)`** — the single opener for every dated note:
1. **Filename** — `splitNameFormat(system.nameFormat)`, format `before` and `after` against `date`, and for a many-per-date system join `sanitizeTitle(opts.title)` between them. Append `.md`; prepend `system.folder` when it is set.
2. **Existing note** — a `vault.getFileByPath()` hit is opened as-is, never overwritten. A date that already has notes can still gain another in a many-per-date system, because the title makes the filename unique.
3. **Missing note** — created via `createDatedNote`, then opened.
4. **Leaf** — an explicit `opts.leaf` always wins (middle-click and Ctrl/Cmd-click pass a tab leaf). Otherwise, when `opts.reuseExistingLeaf` is true, scan Markdown leaves by `getViewState().state.file` so deferred tabs also match; compare the complete file path, not the basename. Await `workspace.revealLeaf(existing)` to reveal/load the tab, then call `workspace.setActiveLeaf(existing, { focus: true })` to activate it and focus its editor. Return without calling `openFile`, preserving editor position. With no matching tab, or when reuse is disabled, open in `workspace.getLeaf(false)` as before.
### Note creation (`createDatedNote`)
A single creation path shared by periodic notes and date systems; it replaced the period-only `createPeriodNote`.
1. With a non-empty `system.templateFile`, reads it (appending `.md` when omitted) and creates the note with its raw contents. This is for plain, non-Templater templates.
2. With no template, the note is created with minimal frontmatter instead: `type: {system.typeProperty}` + `date: YYYY-MM-DD`. Use this mode with a Templater folder trigger, which replaces that fallback content with its rendered template.
--- ---
## Period Note Creation (`openPeriodNote`) ## Period Note Creation (`openPeriodNote`)
For a given period + moment date: ```typescript
openPeriodNote(
period: 'day' | 'week' | 'month' | 'quarter' | 'year',
date: moment.Moment,
leaf?: WorkspaceLeaf,
): Promise<void>
```
1. **Build filename:** `date.format(periodSettings.nameFormat) + ".md"`. Single unified opener — there is no separate `openPeriodNoteInLeaf`, and since the date-systems refactor there is no separate creation path either. `openPeriodNote` synthesizes the period's `PeriodNoteSettings` into a `DateSystemSettings` (`folder`, `nameFormat`, `templateFile` and `typeProperty` carry over verbatim; a period format never contains `{title}`, so a period maps to exactly one filename) and delegates to `openDateSystemNote(system, date, { leaf, reuseExistingLeaf: settings.reusePeriodicNoteTabs })`. All five periodic-note types therefore share the same tab-reuse policy, with an explicit `leaf` taking precedence.
2. **Build full path:** If `periodSettings.folder` is set, prepend it; otherwise root.
3. **Check existence:** `vault.getFileByPath(fullPath)`. Filename building, the existence check, template-or-frontmatter creation and leaf selection are therefore documented once, under Date Systems above.
4. **If not found, create:**
- Try to read template at `periodSettings.templateFile + ".md"`. Middle-click handlers in the view pass an explicit tab leaf: `openPeriodNote(period, date, this.app.workspace.getLeaf('tab'))`.
- If template exists → `vault.create(fullPath, templateContent)`.
- If no template → `vault.create(fullPath, minimalFrontmatter)` where frontmatter is `type: {typeProperty}` + `date: YYYY-MM-DD`.
5. **Open in new leaf:** `workspace.getLeaf(false).openFile(file)`.
--- ---
@@ -159,32 +292,44 @@ For a given period + moment date:
### `file-open` ### `file-open`
If `settings.recentFiles.updateOn === 'file-open'` → calls `addToRecentFiles(file)`. Records the previously active path in `previouslyActive` (valid for `PENDING_SAVE_GRACE_MS` = 5 s) and the new one in `activePath`, then `recordRecentFile(file, 'opened')`: sets `openedAt` and clears `changedInBackground`.
If `updateOn === 'file-edit'` → currently skipped (placeholder for future edit-detection). ### `vault:modify`
`onFileChange(file)` (guarded to `TFile`) calls `recordRecentFile(file, 'changed', isBackgroundChange(file))`: sets `changedAt`, and `changedInBackground` when the file is neither `getActiveFile()` nor left less than 5 s ago (its editor flushing a pending save after a tab switch). When the file already leads both the `all` and `changed` orderings and the dot does not change — the editor saving while you type — only the timestamp moves and no redraw happens.
### `vault:create` / `vault:delete` ### `vault:create` / `vault:delete`
Both trigger `broadcastRedraw()` — tells all WaypointView instances to re-render (needed for calendar note indicators and stale recent file references). Both update the markdown-basename set used for calendar note indicators, then trigger `broadcastRedraw()` — telling all WaypointView instances to re-render (needed for the indicators and for stale recent file references). After layout-ready, `create` also goes through `onFileChange` (synced or plugin-created notes); the initial vault scan fires `create` for every file before layout-ready and is skipped.
### `vault:rename` ### `vault:rename`
1. Updates `recentFiles` entry if path matches `oldPath`. 1. Updates the markdown-basename set (old basename out, new basename in).
2. Calls `updateBookmarkPath(oldPath, newPath)` — recursively scans `waypointData.bookmarks` and updates any `filePath` matching `oldPath`. 2. Remaps the `recentFiles` entry through `remapRenamedPath(entry.path, oldPath, newPath)`.
3. Remaps every bookmark `filePath` through the same helper.
`remapRenamedPath(path, oldPath, newPath)` (in `src/utils/path-utils.ts`) returns the updated path when `path` **is** `oldPath` (a plain file rename) *or* is nested under it (`path.startsWith(oldPath + '/')`, i.e. a folder rename/move), and `null` when the path is unaffected. This is why moving a folder no longer orphans the bookmarks inside it. The helper deliberately imports nothing from `'obsidian'` so it stays pure and unit-testable in plain node.
--- ---
## Recent Files (in-memory) ## Recent Files (persisted)
```typescript ```typescript
recentFiles: { path: string; basename: string }[] recentFiles: { path: string; basename: string; changedInBackground?: boolean }[] // RecentFileEntry
``` ```
**Update flow:** Backed by `waypointData.recentFiles` in `data.json`, so the list survives vault reload. `applyWaypointData(saved)` restores it; entries saved before per-kind timestamps get small descending `openedAt` values (or `changedAt` if the old `updateOn` was `'file-edit'`), keeping their order and sorting after anything new.
1. `addToRecentFiles(file)` — dedupes (removes existing entry), prepends to front, truncates to `maxItems`.
2. Calls `broadcastRedraw()`.
**Omitted paths/tags:** Settings store regex patterns but the current `addToRecentFiles` does **not** filter by them — these are only exposed in the settings UI. The filtering is not yet wired up in the add logic. **Ordering and trimming** (`src/utils/recent-files.ts`, pure): `recentFilesFor(entries, show)` lists entries with an `openedAt` (`opened`), a `changedAt` (`changed`), or either (`all`, by the later of the two), most recent first. `trimRecentFiles(entries, max)` keeps an entry while it is among the `max` most recently opened **or** the `max` most recently changed, so a burst of synced changes cannot evict opened files. `this.recentFiles` is stored in `all` order.
**Update flow:**
1. `recordRecentFile(file, kind, background)` — omission check, stamp (creating the entry if needed), `trimRecentFiles`.
2. `persistRecentFiles()` — mirrors the array into `waypointData.recentFiles` and schedules a debounced (300ms) `saveWaypointData()`.
3. Calls `broadcastRedraw()` unless the change was quiet (see `vault:modify`).
**Omitted paths/tags:** Both filters are applied in `recordRecentFile`. `omittedPaths` entries are treated as regexes tested against `file.path`; `omittedTags` entries are regexes tested against the file's tags, read via `getAllTags(metadataCache.getFileCache(file))` with the leading `#` stripped. An invalid regex is skipped rather than throwing.
**`enforceRecentFilesLimit()`:** Called from the settings-change callback — re-trims when `maxItems` is lowered and persists the result.
**On file not found:** When clicking a recent file that no longer exists, `focusFile()` shows a Notice and removes the stale entry from `recentFiles`. **On file not found:** When clicking a recent file that no longer exists, `focusFile()` shows a Notice and removes the stale entry from `recentFiles`.
@@ -196,17 +341,17 @@ Extends `ItemView`. View type: `"waypoint-view"`, icon: `compass`.
### Rendering (`redraw`) ### Rendering (`redraw`)
Called on every change. Full DOM rebuild — `contentEl.empty()` then three sections in order: Called on every change. Full DOM rebuild — `contentEl.empty()`, then Favorites and Recent Files inside a `.waypoint-lists` wrapper, then the Calendar:
1. **Favorites** (`renderFavorites`) — bookmark tree 1. **Favorites** (`renderFavorites(lists)`) — bookmark tree
2. **Recent Files** (`renderRecentFiles`) — flat list 2. **Recent Files** (`renderRecentFiles(lists)`) — flat list
3. **Calendar** (`renderCalendar`) — month grid 3. **Calendar** (`renderCalendar`) — month grid, `.waypoint-calendar-section`
The last section (`waypoint-section:last-child`) gets `margin-top: auto`, pushing it to the bottom of the sidebar. `.waypoint-calendar-section` gets `margin-top: auto`, pushing it to the bottom of the sidebar. On desktop `.waypoint-lists` is `display: contents`, so the whole view scrolls as before. On mobile (`.is-mobile`) the wrapper becomes the only scroller and the view itself stops scrolling, so the full calendar is always on screen when the drawer opens.
### Calendar Panel ### Calendar Panel
**State:** `currentDisplayMonth` (0-indexed), `currentDisplayYear` — allows navigating months independently of today. **State:** `currentDisplayMonth` (0-indexed), `currentDisplayYear` — allows navigating months independently of today. `selectedDate` — day reached through the date picker or the "Open date" command (`showDate(date)`), drawn as `.is-selected`; Today and ◀/▶ clear it.
**Layout:** **Layout:**
@@ -221,18 +366,32 @@ The last section (`waypoint-section:last-child`) gets `margin-top: auto`, pushin
``` ```
- **Breadcrumb:** Q-label, month name, year — each clickable to open that period note. - **Breadcrumb:** Q-label, month name, year — each clickable to open that period note.
- **Nav buttons:** ◀/▶ shift month ±1. "Today" resets to current month. - **Nav buttons:** ◀/▶ shift month ±1. "Today" resets to current month. The `calendar-search` button calls `showPicker()` on a hidden native `<input type="date">` (`.waypoint-calendar-pick-input`); picking a date calls `showDate()` — the calendar jumps to that month and marks the day without opening or creating a note.
- **Week number column:** Clicking a week number opens the weekly note for that week's Monday. - **Week number column:** Clicking a week number opens the weekly note for that week's Monday; middle-clicking opens it in a new tab.
- **Day cells:** Click opens daily note. `.other-month` dimmed. `.today` has accent border. `.has-note` gets a dot indicator (checked via `vault.getFiles().some(f => f.basename === dateStr)`). - **Day cells:** Left-click opens the daily note, middle-click opens it in a new tab, right-click opens the day context menu (below). `.other-month` is muted; `.today` has an inset accent ring; hover receives a quiet fill. With `indicatorMode: 'any'`, `.has-note` shows the existing single neutral dot through the O(1) `plugin.hasNoteForDate(dateStr)` lookup. With `indicatorMode: 'systems'`, the view calls `getDateSystemIndicators()` once for the month and renders one tooltip-labelled coloured dot per matching daily/journal/meeting/custom system.
- **Grid generation:** `getMonthGrid(year, month, firstDayOfWeek)` in `date-utils.ts` produces up to 6 weeks, each with 7 `CalendarDay` objects containing `moment`, `dayOfMonth`, `isToday`, `isCurrentMonth`, `isoWeekNumber`. - **Grid generation:** `getMonthGrid(year, month, firstDayOfWeek)` in `date-utils.ts` produces up to 6 weeks, each with 7 `CalendarDay` objects containing `moment`, `dayOfMonth`, `isToday`, `isCurrentMonth`, `isoWeekNumber`.
**Day context menu (right-click):** Built from a single `plugin.findDateSystemNotes(day.date)` call. The first entry is a non-clickable header showing the full date. Then, per system in `dateSystems()` order:
- Each existing note, labelled with its `DateSystemNote.label` and the system's `icon`. Click opens it in the current leaf; Ctrl/Cmd-click opens it in a new tab.
- A create entry (icon `plus`) labelled `New {lowercased system name} note`. Many-per-date systems always show one, with a trailing ellipsis because it first opens a `PromptModal` for the title (`New meeting note…`). A one-per-date system shows one without the ellipsis only while its note is missing (`New journal note`); once the note exists, the existing-note entry is all it gets.
Every label is derived from `system.name`, so a renamed or newly added system needs no view changes. Left-click and middle-click on the cell are untouched.
### Recent Files Panel ### Recent Files Panel
Renders `plugin.recentFiles` as Obsidian-native `nav-file` elements using the file explorer's CSS classes (`tree-item`, `nav-file-title`, `nav-file-title-content`). Renders `recentFilesFor(plugin.recentFiles, settings.show)` as Obsidian-native `nav-file` elements using the file explorer's CSS classes (`tree-item`, `nav-file-title`, `nav-file-title-content`).
**Header switch** (`.waypoint-recent-show`): `all` / `opened` / `changed`, saved to `settings.recentFiles.show`.
**Type pills** (only when `showTypeFilter`): with `types` configured, one pill per type in that order (count may be 0); otherwise one per frontmatter `type` present, most frequent first. The pill filter is view state (`recentFilesFilter`) and resets when pills are turned off. Types with an empty name (rows being typed in settings) are ignored.
**Type icons** (`.waypoint-recent-icon`): a file whose frontmatter `type` matches a configured type with an icon shows that Lucide icon before its name. Once any type has an icon, every row reserves the slot so names stay aligned.
**Per-file features:** **Per-file features:**
- **Active indicator:** `.is-active` class if path matches `workspace.getActiveFile()`. - **Active indicator:** `.is-active` class if path matches `workspace.getActiveFile()`.
- **Remove button:** × icon, appears on hover (`.waypoint-recent-remove`), removes entry from array + saves settings + redraws. - **Remove button:** × icon, appears on hover (`.waypoint-recent-remove`), drops the entry from `plugin.recentFiles`, calls `persistRecentFiles()`, then redraws.
- **Background-change dot:** `.waypoint-recent-changed` after the name when `changedInBackground` is set, with tooltip "Changed in the background". Cleared when the file is opened.
- **Drag:** Uses `app.dragManager.dragFile()` for native Obsidian drag. - **Drag:** Uses `app.dragManager.dragFile()` for native Obsidian drag.
- **Hover preview:** Triggers `hover-link` event for Obsidian's page preview popup. - **Hover preview:** Triggers `hover-link` event for Obsidian's page preview popup.
- **Context menu:** "Open in new tab" + Obsidian's native `file-menu` event. - **Context menu:** "Open in new tab" + Obsidian's native `file-menu` event.
@@ -265,7 +424,7 @@ Renders `plugin.recentFiles` as Obsidian-native `nav-file` elements using the fi
**Context menu (right-click):** **Context menu (right-click):**
- File items: "Open in new tab" - File items: "Open in new tab"
- File/Group items: "Rename" (opens `RenameModal`), "Change icon" (opens `IconSuggestModal`) - File/Group items: "Rename" (opens `PromptModal`), "Change icon" (opens `IconSuggestModal`)
- "Move to group" submenu: Lists all available groups (excluding self + descendants) + "(Root)" for ungrouping - "Move to group" submenu: Lists all available groups (excluding self + descendants) + "(Root)" for ungrouping
- Group items: "Expand/Collapse", "Add bookmark here", "New sub-group" - Group items: "Expand/Collapse", "Add bookmark here", "New sub-group"
- All items: "Insert separator above/below", "Insert spacer above/below", "Remove" - All items: "Insert separator above/below", "Insert spacer above/below", "Remove"
@@ -275,13 +434,13 @@ Renders `plugin.recentFiles` as Obsidian-native `nav-file` elements using the fi
2. If targetGroupId: find group, set `item.indent = group.indent + 1`, push to group's children. 2. If targetGroupId: find group, set `item.indent = group.indent + 1`, push to group's children.
3. If null (root): set `item.indent = 0`, push to `waypointData.bookmarks`. 3. If null (root): set `item.indent = 0`, push to `waypointData.bookmarks`.
**Rename modal (`RenameModal`):** Simple Modal with text input + Cancel/Save buttons. Enter key submits. **Prompt modal (`PromptModal`):** Simple Modal with a text input plus Cancel and CTA buttons. Enter key submits. Constructed as `new PromptModal(app, options, onSubmit)`, where `options` is `{ title, placeholder?, initialValue?, cta? }` and `cta` (the submit button label) defaults to `Save`. Generalized from the old rename-only `RenameModal` so the calendar's day context menu can reuse it to prompt for a note title.
**Icon picker (`IconSuggestModal`):** Modal with: **Icon picker (`IconSuggestModal`):** Modal with:
- Live preview of selected icon. - Live preview of selected icon.
- Search input with 60ms debounce. - Search input with 60ms debounce.
- Grid of matching icons (max 80 shown), loaded from `https://cdn.jsdelivr.net/npm/lucide-static@0.517.0/tags.json` with fallback to `https://lucide.dev/api/tags` and a hardcoded `FALLBACK_ICONS` object (~300 icons). - Grid of matching icons (max 80 shown), loaded from `https://cdn.jsdelivr.net/npm/lucide-static@0.517.0/tags.json` with fallback to `https://lucide.dev/api/tags` and a hardcoded `FALLBACK_ICONS` object (~300 icons). The fetch result is cached for the session, so at most one network round-trip happens no matter how often the picker is opened.
- Click to select, "No icon" link to clear, Save/Cancel buttons. - Click to select, **No icon** button to clear, Save/Cancel buttons.
--- ---
@@ -290,18 +449,20 @@ Renders `plugin.recentFiles` as Obsidian-native `nav-file` elements using the fi
All classes prefixed with `waypoint-`. Uses Obsidian CSS variables throughout: All classes prefixed with `waypoint-`. Uses Obsidian CSS variables throughout:
- `--font-ui-small`, `--font-ui-medium`, `--font-semibold`, `--font-medium`, `--font-light` - `--font-ui-small`, `--font-ui-medium`, `--font-semibold`, `--font-medium`, `--font-light`
- `--text-muted`, `--text-faint`, `--text-accent`, `--text-on-accent` - `--text-muted`, `--text-faint`, `--text-accent`, `--text-on-accent`, `--text-error`
- `--background-modifier-border`, `--background-modifier-active-hover`, `--background-primary`, `--background-secondary` - `--background-modifier-border`, `--background-modifier-active-hover`, `--background-modifier-hover`, `--background-primary`, `--background-primary-alt`, `--background-secondary`
- `--interactive-accent` - `--interactive-accent`
- `--cursor` (for custom cursor support) - `--cursor-link` (pointer cursor, with a `pointer` fallback)
Key layout: Key layout:
- `.waypoint-view` — flex column, `overflow-y: auto`, 8px padding. - `.waypoint-view` — flex column, `overflow-y: auto` (hidden on mobile, where `.waypoint-lists` scrolls instead), 8px padding.
- `.waypoint-section` — `flex-shrink: 0`, 16px bottom margin. Last section gets `margin-top: auto` (pins calendar to bottom). - `.waypoint-section` — `flex-shrink: 0`, 16px bottom margin. `.waypoint-calendar-section` gets `margin-top: auto` (pins calendar to bottom).
- `.waypoint-section-header` — uppercase, muted, with bottom border. - `.waypoint-settings-tabs` — wraps onto several rows; on mobile the tabs become rounded pills without the underline overlap.
- Calendar table — `table-layout: fixed`, `border-collapse: collapse`. - `.waypoint-calendar` — padded, bordered surface with separated day cells for clear scan lines.
- `.waypoint-day.today` — accent color text + 1px accent border. - Calendar table — `table-layout: fixed`, `border-collapse: separate`, 2px horizontal / 3px vertical cell spacing.
- `.waypoint-day.has-note::after` — 4px dot indicator. - `.waypoint-day.today` — accent text with an inset accent ring, avoiding layout shifts.
- `.waypoint-day.has-note::after` — neutral single-dot indicator.
- `.waypoint-day-indicators` / `.waypoint-day-indicator` — compact ordered dot row; `--waypoint-indicator-color` carries each configured system colour.
- `.waypoint-bm-chevron` — `rotate(-90deg)` on collapsed groups. - `.waypoint-bm-chevron` — `rotate(-90deg)` on collapsed groups.
- `.waypoint-bm-drop-line` / `.waypoint-bm-drop-below` — 3px accent border for drag indicators. - `.waypoint-bm-drop-line` / `.waypoint-bm-drop-below` — 3px accent border for drag indicators.
@@ -345,7 +506,7 @@ Settings and waypoint data share a single `data.json` via Obsidian's `Plugin.loa
} }
``` ```
Both `loadSettings()` and `loadWaypointData()` read from the same file, merging partials over defaults. `saveSettings()` and `saveWaypointData()` each re-read the full data, update their key, and write back. This means they must not run concurrently (no locking — relies on Obsidian's synchronous save behavior). `onload()` reads `data.json` once, then `applySettings(saved)` and `applyWaypointData(saved)` merge partial persisted values over defaults. `persistAll()` writes both in-memory keys through one promise chain; it never re-reads stale disk state. Recent-file writes additionally go through the 300ms debounce in `persistRecentFiles()`.
--- ---
@@ -353,7 +514,7 @@ Both `loadSettings()` and `loadWaypointData()` read from the same file, merging
`broadcastRedraw()` iterates all leaves of `WAYPOINT_VIEW_TYPE` and calls `view.redraw()` on each. `redraw()` is a full DOM rebuild (no virtual DOM, no diffing). This is triggered by: `broadcastRedraw()` iterates all leaves of `WAYPOINT_VIEW_TYPE` and calls `view.redraw()` on each. `redraw()` is a full DOM rebuild (no virtual DOM, no diffing). This is triggered by:
- File open/create/delete/rename events - File open/create/delete/rename/modify events
- Bookmark add/remove/update - Bookmark add/remove/update
- Period navigation - Period navigation
- Settings changes (via `onSettingsChange` callback) - Settings changes (via `onSettingsChange` callback)
@@ -365,11 +526,5 @@ The sidebar is re-rendered from scratch on every change. For a small sidebar thi
## Known Limitations / Gaps ## Known Limitations / Gaps
1. **Recent files omittedPaths/omittedTags** — Settings UI exposes these regex filters, but `addToRecentFiles()` does not apply them. Files are never filtered out. 1. **No virtual DOM** — Full rebuild on every redraw. Bookmark drag/drop, rename, and any change tears down and rebuilds the entire sidebar. For a small sidebar this is acceptable; for larger bookmark lists it may cause flicker.
2. **`updateOn: 'file-edit'`** — The `file-open` handler returns early for this mode, but no edit-detection event is registered. Recent files never update in edit mode. 2. **IconSuggestModal fetches from CDN** — Network dependency for the Lucide tag list. The fetch happens at most once per session (the result is cached) and falls back to the hardcoded `FALLBACK_ICONS` list on failure, but a first-open with no network still degrades to that reduced list.
3. **No virtual DOM** — Full rebuild on every redraw. Bookmark drag/drop, rename, and any change tears down and rebuilds the entire sidebar.
4. **Concurrent saves** — `saveSettings()` and `saveWaypointData()` both re-read then write `data.json`. Rapid sequential calls could race.
5. **Recent files not persisted** — Cleared on vault reload. Only bookmarks survive restarts.
6. **Note indicators scan all vault files** — `hasNoteForDate()` iterates `vault.getFiles()` on every calendar render (called per day cell). For large vaults, this is O(days × files). Not cached.
7. **`detectPeriodType` uses hardcoded formats** — The regex patterns in `main.ts` don't read from `settings.*.nameFormat`. If a user changes the name format to something non-standard, next/prev navigation breaks.
8. **IconSuggestModal fetches from CDN** — Network dependency on first icon picker open. Falls back to hardcoded list on failure.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Olivier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+75 -1
View File
@@ -40,7 +40,7 @@
- [ ] Type "arrow" → should find all arrow icons - [ ] Type "arrow" → should find all arrow icons
- [ ] Type a tag keyword like "fitness" → should find `activity`, `dumbbell`, etc. - [ ] Type a tag keyword like "fitness" → should find `activity`, `dumbbell`, etc.
- [ ] Clear search (empty input) → shows first 80 icons - [ ] Clear search (empty input) → shows first 80 icons
- [ ] Click "No icon" link → clears the icon - [ ] Set an icon on a bookmark, reopen the picker, click "No icon" → the previously-set icon is cleared
- [ ] Click an icon → preview updates, grid highlights selection - [ ] Click an icon → preview updates, grid highlights selection
- [ ] Click Save → icon applied, click Cancel → no change - [ ] Click Save → icon applied, click Cancel → no change
- [ ] Test with **network offline** → falls back to FALLBACK_ICONS list - [ ] Test with **network offline** → falls back to FALLBACK_ICONS list
@@ -56,18 +56,62 @@
- [ ] Hover preview (page preview popup) still works on file bookmarks - [ ] Hover preview (page preview popup) still works on file bookmarks
- [ ] Right-click context menu on a file bookmark still shows native Obsidian file-menu items - [ ] Right-click context menu on a file bookmark still shows native Obsidian file-menu items
- [ ] Bookmarks persist across vault reload - [ ] Bookmarks persist across vault reload
- [ ] Move a folder containing bookmarked files to a new location → those bookmarks survive and still open the moved files
## Periodic Notes: Reuse Existing Tabs
- [ ] An existing configuration without `reusePeriodicNoteTabs` loads with the toggle off
- [ ] Enable **Periodic Notes → Use existing tabs**, reload the plugin, and verify it stays enabled
- [ ] For each of daily, weekly, monthly, quarterly, and yearly: open the current note in another pane, run its **Go to…** command repeatedly → that tab becomes active, its editor position is preserved, and no duplicate opens
- [ ] For each type, a note with the same basename in another folder is not reused; the configured path opens or is created normally
- [ ] Regular calendar clicks and next/previous navigation focus existing periodic-note tabs when enabled
- [ ] With the toggle off, all five commands retain their original active-leaf opening behaviour
- [ ] With the toggle on, an explicit open-in-new-tab action still creates a new tab
- [ ] A deferred periodic-note tab or a periodic-note tab in a pop-out window is revealed and focused instead of duplicated
## Calendar (Regression) ## Calendar (Regression)
- [ ] Calendar renders with correct month grid - [ ] Calendar renders with correct month grid
- [ ] Click on a day → opens/creates daily note - [ ] Click on a day → opens/creates daily note
- [ ] Click on week number → opens/creates weekly note - [ ] Click on week number → opens/creates weekly note
- [ ] Middle-click on a week number → opens/creates the weekly note in a new tab, with no console error
- [ ] Click Q/M/Y breadcrumb → opens respective period note - [ ] Click Q/M/Y breadcrumb → opens respective period note
- [ ] ◀/▶ navigation shifts month - [ ] ◀/▶ navigation shifts month
- [ ] "Today" button returns to current month - [ ] "Today" button returns to current month
- [ ] Note indicator dots show on days with existing .md files - [ ] Note indicator dots show on days with existing .md files
- [ ] Today is highlighted with accent border - [ ] Today is highlighted with accent border
## Calendar: System-coloured indicators
- [ ] Calendar → Indicator style → **Single dot** keeps one neutral dot for an existing date-named note
- [ ] Calendar → Indicator style → **Colour by note system** shows a blue dot for Daily, green for Journal, and violet for Meeting by default
- [ ] A day holding multiple meeting notes still shows exactly one Meeting dot
- [ ] A day holding Daily, Journal, and Meeting notes shows three compact dots in that order
- [ ] Hover each coloured dot → its date-system name is identified by a tooltip
- [ ] Change Daily/Journal/Meeting indicator colours in Settings → the visible calendar refreshes immediately
- [ ] Add a custom date system with its own colour and a matching note → its dot appears in system order
- [ ] Create, delete, or rename a date-system note → coloured dots refresh without changing months
- [ ] An install that previously had **Single dot** as its silently-defaulted, never-touched setting shows **Colour by note system** after upgrading and reloading the plugin
- [ ] After that one-time change, manually selecting **Single dot** and reloading again keeps **Single dot** — the migration never re-fires
- [ ] Typing in any Template file field opens Obsidian's native fuzzy-suggest popup (matching the look of Templater's own template pickers), not a plain browser dropdown
## Calendar: Date systems
- [ ] Right-click a date with a daily note, journal note, and meeting note → full-date header, then all three systems appear in the menu
- [ ] Right-click a date with no date-system notes → each single-note system offers a create action and the many-note system offers “New …”
- [ ] Right-click a date with one meeting → the existing meeting and “New meeting note…” both appear
- [ ] Create a second meeting for the same date → it is created with that date prefix and both meetings appear on the next right-click
- [ ] Ctrl/Cmd-click an existing date-system menu entry → it opens in a new tab
- [ ] Submit an empty title for a new many-note system → a clear notice appears and no malformed file is created
- [ ] Add a date system in Settings → Date systems → it appears in the day menu
- [ ] Reorder and delete date systems → the day menu immediately follows the configured order and removes the deleted system
- [ ] Enter a non-empty name format with no date token → Settings shows the inline warning
- [ ] Left-click a day still opens/creates its daily note; middle-click still opens it in a new tab
- [ ] With Templater folder mappings for journal and meetings, create a date-system note → Templater expands `<% … %>` syntax rather than leaving it literal
- [ ] Create a journal from the calendar → no duplicate date prompt and no rename; its frontmatter `date` equals the selected calendar day
- [ ] Create a meeting from the calendar for a non-today date → its frontmatter `date` equals the selected calendar day
## Recent Files (Regression) ## Recent Files (Regression)
- [ ] Opening a file adds it to recent files - [ ] Opening a file adds it to recent files
@@ -77,3 +121,33 @@
- [ ] Left-click opens file, middle-click opens in new tab - [ ] Left-click opens file, middle-click opens in new tab
- [ ] Right-click shows "Open in new tab" + native file menu - [ ] Right-click shows "Open in new tab" + native file menu
- [ ] Hover preview popup works - [ ] Hover preview popup works
## Calendar: Date picker and "Open date" command
- [ ] The calendar-search button right of ▶ opens the native date picker (desktop popup, mobile sheet)
- [ ] Picking a date jumps the calendar to that month and fills that day with the accent colour; no note is opened or created
- [ ] "Today" or ◀/▶ clears the picked-day highlight
- [ ] Command "Open daily note for a date…" opens a modal prefilled with today; Enter or Open opens/creates that day's daily note and the calendar shows its month with the day marked
- [ ] Cancel or Escape closes the modal without opening anything
## Recent Files: Opened / changed, background dot, type icons
- [ ] The header switch beside "Recent Files" shows all / opened / changed; the choice survives a reload
- [ ] "opened" lists only files you opened; "changed" lists files that changed (yours and background); "all" orders by the later of the two
- [ ] A file changed while another note is active (sync, another plugin) moves to the top of all/changed with a dot; tooltip "Changed in the background"
- [ ] Opening that file clears the dot
- [ ] Editing the active note never shows a dot; neither does switching tabs right after typing (late save of the note you just left)
- [ ] Typing in the active note does not rebuild the sidebar on every save
- [ ] A note created in the background (e.g. synced) appears with a dot; a note you create and open yourself does not keep one
- [ ] Vault startup does not flood the list with every file
- [ ] With Max items = N, many background changes do not push out the N most recently opened files
- [ ] An existing list from before this version keeps its order (all entries appear under "opened")
- [ ] Settings → Recent Files → Type filter off hides the pills; on shows them again
- [ ] File types: add a type, pick an icon in the picker, matching recent files show the icon; names stay aligned; trash removes the type
- [ ] An old "Filter tags" list appears as File types without icons
## Mobile
- [ ] Opening the left drawer shows the whole calendar at the bottom; bookmarks and recent files scroll above it
- [ ] The date button fits inside the calendar header next to ◀ Today ▶
- [ ] Settings tabs wrap onto several rows instead of overflowing
+37 -2
View File
@@ -4,8 +4,10 @@ Calendar, recent files, and custom bookmarks sidebar for Obsidian.
## Features ## Features
- **Calendar panel** — month grid with clickable days, week numbers, period indicators (day/week/month/quarter/year) - **Calendar panel** — refined month grid; left-click a day opens its daily note, middle-click opens it in a tab, and right-click reveals every configured note system for that date. The date button beside **Today** jumps to any date.
- **Recent files** — track recently opened/edited files - **Calendar indicators** — retain a single neutral note dot or show a coloured dot per daily, journal, meeting, or custom date system
- **Recent files** — files you opened and files that changed. The switch beside the title shows all, only opened, or only changed files. A dot marks a file changed in the background (sync, another plugin) until you open it. Give frontmatter types (meeting, daily-note…) an icon under **Settings → Recent Files → File types**; the type filter pills can be turned off.
- **Mobile** — the whole calendar stays on screen when the sidebar opens; the lists above it scroll on their own.
- **Favorites** — custom bookmarks with groups, icons, and rename - **Favorites** — custom bookmarks with groups, icons, and rename
## Commands ## Commands
@@ -18,6 +20,39 @@ Calendar, recent files, and custom bookmarks sidebar for Obsidian.
| Go to quarterly note | `Ctrl+Shift+Alt+Q` | | Go to quarterly note | `Ctrl+Shift+Alt+Q` |
| Go to yearly note | `Ctrl+Shift+Alt+Y` | | Go to yearly note | `Ctrl+Shift+Alt+Y` |
| Next/Previous daily/weekly/monthly/quarterly/yearly note | — | | Next/Previous daily/weekly/monthly/quarterly/yearly note | — |
| Open daily note for a date… | — |
Under **Settings → Waypoint Sidebar → Periodic Notes**, turn on **Use existing tabs** to switch to a daily, weekly, monthly, quarterly, or yearly note's tab if it is already open. This works with the five **Go to…** commands, next/previous navigation, and regular calendar clicks. If the note is not open, it opens or is created as usual. The setting is off by default. It keeps your place in the note and leaves existing duplicate tabs alone. Choosing to open a new tab still opens a new tab.
## Date systems
Right-click any calendar day to open its **date systems** menu. The daily note always appears first; left-click behaviour is unchanged. The included defaults match this vault's common layouts:
| System | Folder | Name format | Behaviour |
|---|---|---|---|
| Journal | `periodic/journal` | `YYYY-MM-DD - [Journal]` | Opens or creates one journal note for the date |
| Meeting | `periodic/meetings` | `YYYY-MM-DD - {title}` | Lists every meeting for the date and can create another |
Configure systems in **Settings → Waypoint Sidebar → Date systems**. Each system has a folder, filename format, template, fallback frontmatter type, Lucide icon, and indicator colour. Template file fields autocomplete every Markdown path in the vault.
`Name format` uses moment.js tokens. Bracket-escape literal text: `YYYY-MM-DD - [Journal]`. Add `{title}` when a date can have multiple notes; it is replaced with the title requested when creating a note. Without `{title}`, the system has exactly one note per date.
Ctrl/Cmd-click a menu entry opens it in a new tab.
### Calendar indicators
Under **Settings → Waypoint Sidebar → Calendar**, choose either:
- **Colour by note system** — the default; one compact coloured dot per configured date system that has a note on that day. Hover a dot to identify its system.
- **Single dot** — a neutral marker for any note whose filename is exactly the date.
Daily uses the Calendar tab’s colour picker. Journal, Meeting, and every custom system have their own **Indicator colour** picker under **Date systems**. The defaults are blue for Daily, green for Journal, and violet for Meeting.
### Templater folder templates
If a date system uses a Templater folder mapping, leave its Waypoint **Template file** field blank. Waypoint then creates a safe fallback note while Templater owns prompts, scripts, cursors, and rendered content.
The selected calendar date is encoded in the filename. Templater templates should derive their `date` from `tp.file.title`, not from `tp.date` or `tp.file.creation_date()`. A journal template can retain a prompt-and-rename fallback for manual note creation, but it must skip that flow when the filename already follows `YYYY-MM-DD - Journal`.
## Installation ## Installation
+16 -14
View File
@@ -2,20 +2,22 @@
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
*/ */
var z=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var U=(b,u)=>{for(var t in u)z(b,t,{get:u[t],enumerable:!0})},X=(b,u,t,i)=>{if(u&&typeof u=="object"||typeof u=="function")for(let s of j(u))!H.call(b,s)&&s!==t&&z(b,s,{get:()=>u[s],enumerable:!(i=Q(u,s))||i.enumerable});return b};var K=b=>X(z({},"__esModule",{value:!0}),b);var ee={};U(ee,{default:()=>O});module.exports=K(ee);var y=require("obsidian");var W={calendar:{firstDayOfWeek:1,showNoteIndicators:!0},daily:{folder:"periodic/daily",templateFile:"Templates/Daily note",nameFormat:"YYYY-MM-DD",typeProperty:"daily-note"},weekly:{folder:"periodic/weekly",templateFile:"Templates/Weekly note",nameFormat:"GGGG-[W]WW",typeProperty:"weekly-note"},monthly:{folder:"periodic/monthly",templateFile:"Templates/Monthly note",nameFormat:"YYYY-MM",typeProperty:"monthly-note"},quarterly:{folder:"periodic/quarterly",templateFile:"Templates/Quarterly note",nameFormat:"YYYY-[Q]Q",typeProperty:"quarterly-note"},yearly:{folder:"periodic/yearly",templateFile:"Templates/Yearly note",nameFormat:"YYYY",typeProperty:"yearly-note"},recentFiles:{maxItems:50,updateOn:"file-open",omittedPaths:[],omittedTags:[]},display:{rowSize:26,rowSpacing:2,indentSize:16,fontSize:13,iconSize:16,calendarCellSize:32}};var w=require("obsidian");var $=class extends w.PluginSettingTab{constructor(t,i,s,a){super(t,i);this.activeTab="calendar";this.plugin=i,this.settings=s,this.onSettingsChange=a}display(){let{containerEl:t}=this;t.empty();let i=t.createDiv({cls:"waypoint-settings-tabs"}),s=[{key:"calendar",label:"Calendar"},{key:"periodic",label:"Periodic Notes"},{key:"recent",label:"Recent Files"},{key:"display",label:"Display"}];for(let e of s)i.createEl("button",{cls:`waypoint-settings-tab${this.activeTab===e.key?" is-active":""}`,text:e.label}).addEventListener("click",()=>{this.activeTab=e.key,this.display()});let a=t.createDiv({cls:"waypoint-settings-content"});switch(this.activeTab){case"calendar":this.renderCalendarTab(a);break;case"periodic":this.renderPeriodicTab(a);break;case"recent":this.renderRecentTab(a);break;case"display":this.renderDisplayTab(a);break}}renderCalendarTab(t){new w.Setting(t).setName("First day of week").setDesc("Which day the calendar week starts on.").addDropdown(i=>{i.addOption("0","Sunday").addOption("1","Monday").setValue(String(this.settings.calendar.firstDayOfWeek)).onChange(s=>{this.settings.calendar.firstDayOfWeek=parseInt(s,10),this.saveAndRefresh()})}),new w.Setting(t).setName("Show note indicators").setDesc("Show a dot on days that have existing notes.").addToggle(i=>{i.setValue(this.settings.calendar.showNoteIndicators).onChange(s=>{this.settings.calendar.showNoteIndicators=s,this.saveAndRefresh()})})}renderPeriodicTab(t){this.addPeriodNoteSettings(t,"Daily",this.settings.daily),this.addPeriodNoteSettings(t,"Weekly",this.settings.weekly),this.addPeriodNoteSettings(t,"Monthly",this.settings.monthly),this.addPeriodNoteSettings(t,"Quarterly",this.settings.quarterly),this.addPeriodNoteSettings(t,"Yearly",this.settings.yearly)}addPeriodNoteSettings(t,i,s){new w.Setting(t).setHeading().setName(i),new w.Setting(t).setName("Folder").setDesc(`Folder path for ${i.toLowerCase()} notes.`).addText(a=>{a.setPlaceholder("periodic/daily"),a.setValue(s.folder),a.onChange(e=>{s.folder=e,this.saveAndRefresh()})}),new w.Setting(t).setName("Name format").setDesc(`Date format for ${i.toLowerCase()} note filenames (moment.js format).`).addText(a=>{a.setPlaceholder("yyyy-MM-dd"),a.setValue(s.nameFormat),a.onChange(e=>{s.nameFormat=e,this.saveAndRefresh()})}),new w.Setting(t).setName("Template file").setDesc("Path to the template file (without .md extension).").addText(a=>{a.setPlaceholder("Templates/Daily note"),a.setValue(s.templateFile),a.onChange(e=>{s.templateFile=e,this.saveAndRefresh()})}),new w.Setting(t).setName("Type property").setDesc("Value for the 'type' frontmatter property.").addText(a=>{a.setPlaceholder("daily-note"),a.setValue(s.typeProperty),a.onChange(e=>{s.typeProperty=e,this.saveAndRefresh()})})}renderRecentTab(t){new w.Setting(t).setName("Max items").setDesc("Maximum number of recent files to track.").addText(a=>{a.inputEl.setAttr("type","number"),a.inputEl.setAttr("placeholder","50"),a.setValue(String(this.settings.recentFiles.maxItems)),a.inputEl.onblur=()=>{let e=parseInt(a.getValue(),10);!isNaN(e)&&e>0&&(this.settings.recentFiles.maxItems=e,this.saveAndRefresh())}}),new w.Setting(t).setName("Update on").setDesc("When to add a file to the recent list.").addDropdown(a=>{a.addOption("file-open","File opened").addOption("file-edit","File changed").setValue(this.settings.recentFiles.updateOn).onChange(e=>{this.settings.recentFiles.updateOn=e,this.saveAndRefresh()})});let i=new DocumentFragment;i.appendText("Regex patterns for paths to exclude. One per line."),new w.Setting(t).setName("Omitted paths").setDesc(i).addTextArea(a=>{a.inputEl.setAttr("rows",4),a.setPlaceholder(`^archiv Line truncated var ie=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var De=Object.prototype.hasOwnProperty;var Fe=(c,d)=>{for(var e in d)ie(c,e,{get:d[e],enumerable:!0})},Se=(c,d,e,n)=>{if(d&&typeof d=="object"||typeof d=="function")for(let i of be(d))!De.call(c,i)&&i!==e&&ie(c,i,{get:()=>d[i],enumerable:!(n=ke(d,i))||n.enumerable});return c};var xe=c=>Se(ie({},"__esModule",{value:!0}),c);var Ae={};Fe(Ae,{default:()=>ne});module.exports=xe(Ae);var f=require("obsidian");var _={name:"",folder:"",nameFormat:"YYYY-MM-DD - {title}",templateFile:"",typeProperty:"",icon:"file",indicatorColor:"#64748b"},P={calendar:{firstDayOfWeek:1,showNoteIndicators:!0,indicatorMode:"systems",dailyIndicatorColor:"#3b82f6"},daily:{folder:"periodic/daily",templateFile:"Templates/Daily note",nameFormat:"YYYY-MM-DD",typeProperty:"daily-note"},reusePeriodicNoteTabs:!1,weekly:{folder:"periodic/weekly",templateFile:"Templates/Weekly note",nameFormat:"GGGG-[W]WW",typeProperty:"weekly-note"},monthly:{folder:"periodic/monthly",templateFile:"Templates/Monthly note",nameFormat:"YYYY-MM",typeProperty:"monthly-note"},quarterly:{folder:"periodic/quarterly",templateFile:"Templates/Quarterly note",nameFormat:"YYYY-[Q]Q",typeProperty:"quarterly-note"},yearly:{folder:"periodic/yearly",templateFile:"Templates/Yearly note",nameFormat:"YYYY",typeProperty:"yearly-note"},dateSystems:[{id:"journal",name:"Journal",folder:"periodic/journal",nameFormat:"YYYY-MM-DD - [Journal]",templateFile:"",typeProperty:"journal",icon:"book-open",indicatorColor:"#22c55e"},{id:"meetings",name:"Meeting",folder:"periodic/meetings",nameFormat:"YYYY-MM-DD - {title}",templateFile:"",typeProperty:"meeting",icon:"users",indicatorColor:"#a855f7"}],recentFiles:{maxItems:50,show:"all",omittedPaths:[],omittedTags:[],showTypeFilter:!0,types:[]},display:{rowSize:26,rowSpacing:2,indentSize:16,fontSize:13,iconSize:16,calendarCellSize:32}};var y=require("obsidian");var me="{title}";function q(c){let d=c.indexOf(me);return d<0?{before:c,after:"",hasTitle:!1}:{before:c.slice(0,d),after:c.slice(d+me.length),hasTitle:!0}}function ae(c,d){if(!d)return!0;let e=d.endsWith("/")?d:`${d}/`;return c.startsWith(e)}function se(c,d,e,n){return n?!d||c.length<d.length+e.length?!1:c.startsWith(d)&&c.endsWith(e):c===d+e}function ue(c,d,e){let n=c.startsWith(d)?d.length:0,i=e&&c.endsWith(e)?c.length-e.length:c.length;return i<=n?c:c.slice(n,i).trim()||c}var Te=/[\\/:*?"<>|#^[\]]/g;function ge(c){return c.replace(Te,"-").replace(/\s+/g," ").trim()}function $(c){let{before:d}=q(c),e=d.replace(/\[[^\]]*\]/g,"");return/[YMDQGWEwdgeo]/.test(e)}var m=require("obsidian");var Y=require("obsidian");function ye(c,d,e){let n=(0,Y.moment)({year:c,month:d,day:1}),i=(0,Y.moment)(n).endOf("month"),t=(0,Y.moment)(n).subtract((n.day()-e+7)%7,"days"),a=(0,Y.moment)().startOf("day"),r=[],s=(0,Y.moment)(t);for(;s.isBefore(i)||s.month()===d;){let o=[];for(let l=0;l<7;l++)o.push({date:(0,Y.moment)(s),dayOfMonth:s.date(),isToday:s.isSame(a,"day"),isCurrentMonth:s.month()===d,isoWeekNumber:s.isoWeek()}),s.add(1,"day");if(r.push({weekNumber:o[0].isoWeekNumber,days:o}),r.length>=6)break}return r}function Ee(c,d){return d==="opened"?c.openedAt:d==="changed"||c.openedAt===void 0?c.changedAt:c.changedAt===void 0?c.openedAt:Math.max(c.openedAt,c.changedAt)}function W(c,d){let e=[];for(let n of c){let i=Ee(n,d);i!==void 0&&e.push({entry:n,key:i})}return e.sort((n,i)=>i.key-n.key),e.map(n=>n.entry)}function K(c,d){let e=new Set([...W(c,"opened").slice(0,d),...W(c,"changed").slice(0,d)]);return W(c,"all").filter(n=>e.has(n))}var E="waypoint-view";function Me(c){return c.dragManager}var z=class extends m.ItemView{constructor(e,n){super(e);this.redraw=()=>{this.contentEl.empty(),this.contentEl.addClass("waypoint-view");let e=this.plugin.settings.display;this.contentEl.style.setProperty("--wp-row-size",e.rowSize+"px"),this.contentEl.style.setProperty("--wp-row-spacing",e.rowSpacing+"px"),this.contentEl.style.setProperty("--wp-indent-size",e.indentSize+"px"),this.contentEl.style.setProperty("--wp-font-size",e.fontSize+"px"),this.contentEl.style.setProperty("--wp-icon-size",e.iconSize+"px"),this.contentEl.style.setProperty("--wp-cal-cell-size",e.calendarCellSize+"px");let n=this.contentEl.createDiv({cls:"waypoint-lists"});this.renderFavorites(n),this.renderRecentFiles(n),this.renderCalendar()};this.currentDisplayMonth=(0,m.moment)().month();this.currentDisplayYear=(0,m.moment)().year();this.dragId=null;this.dropZones=new WeakMap;this.recentFilesFilter=null;this.selectedDate=null;this.plugin=n}getViewType(){return E}getDisplayText(){return"Waypoint"}getIcon(){return"compass"}async onOpen(){this.redraw()}async onClose(){}showDate(e){this.currentDisplayMonth=e.month(),this.currentDisplayYear=e.year(),this.selectedDate=e.clone(),this.redraw()}renderCalendar(){var le;let n=this.contentEl.createDiv({cls:"waypoint-section waypoint-calendar-section"}).createDiv({cls:"waypoint-calendar"}),i=(0,m.moment)(),t=(0,m.momenLine truncated
\\.png$`),a.setValue(this.settings.recentFiles.omittedPaths.join(` \\.png$`),t.setValue(this.settings.recentFiles.omittedPaths.join(`
`)),a.inputEl.onblur=()=>{this.settings.recentFiles.omittedPaths=a.getValue().split(` `)),t.inputEl.onblur=()=>{this.settings.recentFiles.omittedPaths=t.getValue().split(`
`).filter(e=>e.trim()),this.saveAndRefresh()}});let s=new DocumentFragment;s.appendText("Regex patterns for frontmatter tags to exclude. One per line."),new w.Setting(t).setName("Omitted tags").setDesc(s).addTextArea(a=>{a.inputEl.setAttr("rows",4),a.setPlaceholder(`ignore `).filter(a=>a.trim()),this.saveAndRefresh()}});let i=new DocumentFragment;i.appendText("Regex patterns for frontmatter tags to exclude. One per line."),new y.Setting(e).setName("Omitted tags").setDesc(i).addTextArea(t=>{t.inputEl.setAttr("rows",4),t.setPlaceholder(`ignore
archive`),a.setValue(this.settings.recentFiles.omittedTags.join(` archive`),t.setValue(this.settings.recentFiles.omittedTags.join(`
`)),a.inputEl.onblur=()=>{this.settings.recentFiles.omittedTags=a.getValue().split(` `)),t.inputEl.onblur=()=>{this.settings.recentFiles.omittedTags=t.getValue().split(`
`).filter(e=>e.trim()),this.saveAndRefresh()}})}renderDisplayTab(t){new w.Setting(t).setHeading().setName("Bookmarks"),this.addSliderSetting(t,"Row size","Height of bookmark items.",this.settings.display,"rowSize",18,40,1,"px"),this.addSliderSetting(t,"Row spacing","Gap between bookmark items.",this.settings.display,"rowSpacing",0,12,1,"px"),this.addSliderSetting(t,"Indent size","Indent per nesting depth.",this.settings.display,"indentSize",8,32,2,"px"),this.addSliderSetting(t,"Font size","Label font size.",this.settings.display,"fontSize",10,18,1,"px"),this.addSliderSetting(t,"Icon size","Bookmark icon size.",this.settings.display,"iconSize",12,24,1,"px"),new w.Setting(t).setHeading().setName("Calendar"),this.addSliderSetting(t,"Cell size","Height of calendar day cells.",this.settings.display,"calendarCellSize",20,48,2,"px"),new w.Setting(t).addButton(i=>i.setButtonText("Reset to defaults").onClick(()=>{this.settings.display={...W.display},this.saveAndRefresh(),this.display()}))}addSliderSetting(t,i,s,a,e,r,o,d,n){let l=new w.Setting(t).setName(i).setDesc(`${s} (${a[e]}${n})`);l.addSlider(c=>{c.setLimits(r,o,d).setValue(a[e]).setDynamicTooltip().onChange(h=>{a[e]=h,l.setDesc(`${s} (${h}${n})`),this.saveAndRefresh()})})}async saveAndRefresh(){await this.plugin.saveSettings(),this.onSettingsChange()}};var p=require("obsidian");var L=require("obsidian");function _(b,u,t){let i=(0,L.moment)({year:b,month:u,day:1}),s=(0,L.moment)(i).endOf("month"),a=(0,L.moment)(i).subtract((i.day()-t+7)%7,"days"),e=(0,L.moment)().startOf("day"),r=[],o=(0,L.moment)(a);for(;o.isBefore(s)||o.month()===u;){let d=[];for(let n=0;n<7;n++)d.push({date:(0,L.moment)(o),dayOfMonth:o.date(),isToday:o.isSame(e,"day"),isCurrentMonth:o.month()===u,isoWeekNumber:o.isoWeek()}),o.add(1,"day");if(r.push({weekNumber:d[0].isoWeekNumber,days:d}),r.length>=6)break}return r}var P="waypoint-view",A=class extends p.ItemView{constructor(t,i){super(t);this.redraw=()=>{this.contentEl.empty(),this.contentEl.addClass("waypoint-view");let t=this.plugin.settings.display;this.contentEl.style.setProperty("--wp-row-size",t.rowSize+"px"),this.contentEl.style.setProperty("--wp-row-spacing",t.rowSpacing+"px"),this.contentEl.style.setProperty("--wp-indent-size",t.indentSize+"px"),this.contentEl.style.setProperty("--wp-font-size",t.fontSize+"px"),this.contentEl.style.setProperty("--wp-icon-size",t.iconSize+"px"),this.contentEl.style.setProperty("--wp-cal-cell-size",t.calendarCellSize+"px"),this.renderFavorites(),this.renderRecentFiles(),this.renderCalendar()};this.currentDisplayMonth=(0,p.moment)().month();this.currentDisplayYear=(0,p.moment)().year();this.dragId=null;this.recentFilesFilter=null;this.plugin=i}getViewType(){return P}getDisplayText(){return"Waypoint"}getIcon(){return"compass"}async onOpen(){this.redraw()}async onClose(){}renderCalendar(){let t=this.contentEl.createDiv({cls:"waypoint-section"});t.createDiv({cls:"waypoint-section-header",text:"Calendar"});let i=t.createDiv({cls:"waypoint-calendar"}),s=(0,p.moment)(),a=(0,p.moment)({year:this.currentDisplayYear,month:this.currentDisplayMonth,day:1}),e=i.createDiv({cls:"waypoint-calendar-top"}),r=e.createDiv({cls:"waypoint-calendar-breadcrumb"}),o=a.format("[Q]Q"),d=r.createSpan({cls:"waypoint-clickable",text:o});d.addEventListener("click",()=>{this.plugin.openPeriodNote("quarter",a)}),d.addEventListener("mousedown",f=>{f.button===1&&(f.preventDefault(),this.plugin.openPeriodNoteInLeaf("quarter",a,this.app.workspace.getLeaf("tab")))});let n=a.format("MMMM"),l=r.createSpan({cls:"waypoint-clickable",text:n});l.addEventListener("click",()=>{this.plugin.openPeriodNote("month",a)}),l.addEventListener("mousedown",f=>{f.button===1&&(f.preventDefault(),this.plugin.openPeriodNoteInLeaf("month",a,this.app.workspace.getLeaf("tab")))});let c=a.format("YYYY"),h=r.createSpan({cls:"waypoint-clickable",text:c});h.addEventListener("click",()=>{this.plugin.openPeriodNote("year",a)}),h.addEventListener("mousedown",f=>{f.button===1&&(f.preventDefault(),this.plugin.openPeriodNoteInLeaf("year",a,this.app.workspace.getLeaf("tab")))});let m=e.createDiv({cls:"waypoint-calendar-today-group"}),g=m.createEl("button",{cls:"waypoint-calendar-nav-btn"});(0,p.setIcon)(g,"chevron-left"),g.addEventListener("click",()=>this.navigateMonth(-1)),m.createEl("button",{cls:"waypoint-calendar-today-btn",text:"Today"}).addEventListener("click",()=>{this.currentDisplayMonth=(0,p.moment)().month(),this.currentDisplayYear=(0,p.moment)().year(),this.redraw()});let C=m.createEl("button",{cls:"waypoint-calendar-nav-btn"});(0,p.setIcon)(C,"chevron-right"),C.addEventListener("click",()=>this.navigateMonth(1));let x=i.createEl("table"),T=x.createEl("thead").createEl("tr");T.createEl("th",{text:""});let k=["sun","mon","tue","wed","thu","fri","sat"],R=this.plugin.settings.calendar.firstDayOfWeek;for(let f=0;f<7;f++){let M=(R+f)%7;T.createEl("th",{text:k[M]})}let D=x.createEl("tbody"),E=_(this.currentDisplayYear,this.currentDisplayMonth,this.plugin.settings.c Line truncated `).filter(a=>a.trim()),this.saveAndRefresh()}}),new y.Setting(e).setName("Type filter").setDesc("Show pills above the list to filter recent files by their frontmatter `type`.").addToggle(t=>{t.setValue(this.settings.recentFiles.showTypeFilter).onChange(a=>{this.settings.recentFiles.showTypeFilter=a,this.saveAndRefresh()})}),this.renderRecentTypes(e)}renderRecentTypes(e){let n=this.settings.recentFiles.types;new y.Setting(e).setHeading().setName("File types").setDesc("Frontmatter `type` values. A type's icon shows beside matching recent files. With the type filter on, these types are the pills, in this order; with no types listed, pills are detected automatically."),n.forEach((i,t)=>{new y.Setting(e).addText(a=>{a.setPlaceholder("meeting"),a.setValue(i.type),a.inputEl.onblur=()=>{let r=a.getValue().trim();r!==i.type&&(i.type=r,this.saveAndRefresh())}}).addExtraButton(a=>{a.setIcon(i.icon||"image-off").setTooltip(i.icon?`Icon: ${i.icon}`:"Choose icon").onClick(()=>{new G(this.app,i.icon,r=>{i.icon=r,this.saveAndRefresh(),this.display()}).open()})}).addExtraButton(a=>{a.setIcon("trash").setTooltip("Remove this type").onClick(()=>{n.splice(t,1),this.saveAndRefresh(),this.display()})})}),new y.Setting(e).addButton(i=>{i.setButtonText("Add type").onClick(()=>{n.push({type:"",icon:""}),this.display()})})}renderDisplayTab(e){new y.Setting(e).setHeading().setName("Bookmarks"),this.addSliderSetting(e,"Row size","Height of bookmark items.",this.settings.display,"rowSize",18,40,1,"px"),this.addSliderSetting(e,"Row spacing","Gap between bookmark items.",this.settings.display,"rowSpacing",0,12,1,"px"),this.addSliderSetting(e,"Indent size","Indent per nesting depth.",this.settings.display,"indentSize",8,32,2,"px"),this.addSliderSetting(e,"Font size","Label font size.",this.settings.display,"fontSize",10,18,1,"px"),this.addSliderSetting(e,"Icon size","Bookmark icon size.",this.settings.display,"iconSize",12,24,1,"px"),new y.Setting(e).setHeading().setName("Calendar"),this.addSliderSetting(e,"Cell size","Height of calendar day cells.",this.settings.display,"calendarCellSize",20,48,2,"px"),new y.Setting(e).addButton(n=>n.setButtonText("Reset to defaults").onClick(()=>{this.settings.display={...P.display},this.saveAndRefresh(),this.display()}))}addSliderSetting(e,n,i,t,a,r,s,o,l){let p=new y.Setting(e).setName(n).setDesc(`${i} (${t[a]}${l})`);p.addSlider(u=>{u.setLimits(r,s,o).setValue(t[a]).setDynamicTooltip().onChange(D=>{t[a]=D,p.setDesc(`${i} (${D}${l})`),this.saveAndRefresh()})})}async saveAndRefresh(){await this.plugin.saveSettings(),this.onSettingsChange()}renderAboutTab(e){let n=this.plugin.manifest.version,i=e.createDiv();i.style.display="flex",i.style.alignItems="center",i.style.gap="12px",i.style.marginBottom="16px";let t=i.createDiv();t.style.display="flex",t.style.alignItems="center",t.style.justifyContent="center",t.style.width="48px",t.style.height="48px",t.style.borderRadius="12px",t.style.background="var(--interactive-accent)",t.style.color="var(--text-on-accent)",t.style.fontSize="24px",(0,y.setIcon)(t,"compass");let a=i.createDiv(),r=a.createEl("h2",{text:"Waypoint Sidebar"});r.style.margin="0",r.style.lineHeight="1.2";let s=a.createDiv({text:`v${n}`});s.style.color="var(--text-muted)",s.style.fontSize="var(--font-ui-small)";let o=e.createDiv();o.style.marginBottom="20px",o.style.lineHeight="1.6",o.style.color="var(--text-normal)",o.innerHTML=["<p><strong>Waypoint</strong> is a sidebar plugin that brings three essential panels into one view:</p>",'<ul style="padding-left: 20px; margin: 8px 0;">',"<li><strong>Calendar</strong> \u2014 a monthly grid for your periodic notes (daily, weekly, monthly, quarterly, yearly). Click any day, week, or month to open or create the corresponding note.</li>","<li><strong>Recent Files</strong> \u2014 a list of recently opened files with type filtering, drag-and-drop, and right-click actions.</li>","<li><strong>Bookmarks</strong> \u2014 custom bookmarks with icons, groups, nesting, and drag-and-drop reordering. Separate from Obsidian's native bookmarks.</li>","</ul>",'<p style="color: var(--text-muted); font-size: var(--font-ui-small);">Made by Olivier. Licensed under MIT.</p>'].join(`
type: ${e.typeProperty} `)}};var ee=require("obsidian"),X=class extends ee.Modal{constructor(e,n,i){super(e);this.initialDate=n;this.onSubmit=i}onOpen(){this.titleEl.setText("Open date");let e=this.contentEl.createEl("input",{type:"date",value:this.initialDate.format("YYYY-MM-DD")});e.style.width="100%",e.style.marginBottom="12px",e.focus();let n=()=>{let t=(0,ee.moment)(e.value,"YYYY-MM-DD",!0);t.isValid()&&(this.close(),this.onSubmit(t))};e.addEventListener("keydown",t=>{t.key==="Enter"&&n()});let i=this.contentEl.createDiv({cls:"modal-button-container"});i.createEl("button",{text:"Cancel"}).addEventListener("click",()=>this.close()),i.createEl("button",{text:"Open",cls:"mod-cta"}).addEventListener("click",n)}onClose(){this.contentEl.empty()}};function oe(c,d,e){return!c||!d?null:c===d?e:c.startsWith(d+"/")?e+c.slice(d.length):null}var ne=class extends f.Plugin{constructor(){super(...arguments);this.recentFiles=[];this.savePromise=Promise.resolve();this.markdownBasenames=new Set;this.dateSystemIndicators=null;this.dateSystemIndicatorKey="";this.indicatorModeMigrated=!1;this.previouslyActive=null;this.activePath=null}async onload(){console.debug("Waypoint: loading plugin v"+this.manifest.version);let e=await this.loadData(),n=this.applySettings(e);this.applyWaypointData(e),n&&this.persistAll(),this.registerView(E,s=>new z(s,this)),this.addSettingTab(new J(this.app,this,this.settings,()=>{this.enforceRecentFilesLimit(),this.invalidateDateSystemIndicators(),this.redrawAll()})),this.addCommand({id:"waypoint-open-view",name:"Open Waypoint sidebar",callback:async()=>{let s=this.app.workspace.getLeavesOfType(E);if(s.length>0)await this.app.workspace.revealLeaf(s[0]);else{let o=this.app.workspace.getLeftLeaf(!1);o&&(await o.setViewState({type:E}),await this.app.workspace.revealLeaf(o))}}}),this.addCommand({id:"waypoint-add-bookmark",name:"Add current file as Waypoint bookmark",callback:async()=>{let s=this.app.workspace.getActiveFile();if(!s){new f.Notice("No active file");return}this.addBookmark(s.path,s.basename,"file"),new f.Notice(`Bookmarked: ${s.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",(0,f.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",(0,f.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",(0,f.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",(0,f.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",(0,f.moment)())}}),this.addCommand({id:"waypoint-open-date",name:"Open daily note for a date\u2026",callback:()=>{new X(this.app,(0,f.moment)(),s=>{this.showDateInViews(s),this.openPeriodNote("day",s)}).open()}});let i=["next","prev"],t=["daily","weekly","monthly","quarterly","yearly"],a={next:"Next",prev:"Previous"};for(let s of t)for(let o of i){let l=`waypoint-go-to-${o}-${s}`,p=`${a[o]} ${s} note`;this.addCommand({id:l,name:p,callback:async()=>{await this.navigatePeriodNote(o)}})}this.registerEvent(this.app.workspace.on("file-open",s=>{s&&this.onFileOpen(s)})),this.registerEvent(this.app.vault.on("create",s=>this.onVaultCreate(s))),this.registerEvent(this.app.vault.on("delete",s=>this.onVaultDelete(s))),this.registerEvent(this.app.vault.on("rename",(s,o)=>this.onRename(s,o))),this.registerEvent(this.app.vault.on("modify",s=>this.onFileChange(s))),this.app.workspace.onLayoutReady(()=>{if(this.buildMarkdownIndex(),this.app.workspace.getLeavesOfType(E).length===0){let o=this.app.workspace.getLeftLeaf(!1);o&&o.setViewState({type:E})}else this.broadcastRedraw()});let r=new Date().toDateString();this.registerInterval(window.setInterval(()=>{let s=new Date().toDateString();s!==r&&(r=s,this.redrawAll())},6e5))}async onunload(){this.app.workspace.detachLeavesOfType(E)}applySettings(e){var r,s,o;let n=(e==null?void 0:e.settings)||{};this.settings=Object.assign({},P,n),this.settings.recentFiles=Object.assign({},P.recentFiles,n.recentFiles||{});let i=this.settings.recentFiles;this.settings.recentFiles.types=Array.isArray((r=n.recentFiles)==null?void 0:r.types)?n.recentFiles.types.map(l=>({...l})):((s=i.filterTags)!=null?s:[]).map(l=>({type:l,icon:""})),delete i.filterTags,delete i.updateOn,this.settings.calendar=Object.assign({},P.calendar,n.calendar||{}),this.settings.display=Object.assign({},P.display,n.display||{});for(let l of Ce)this.settings[l]=Object.assign({},P[l],n[l]||{});this.settings.dateSystems=Array.isArray(n.dateSystems)?n.dateSystems. Line truncated
${re(u)}
Check Settings \u2192 Waypoint Sidebar \u2192 Periodic Notes.`,j),null}let s=n.templateFile,o=this.resolveTemplateFile(s),l;if(o)try{l=await this.app.vault.read(o)}catch(u){return new f.Notice(`Waypoint: could not read the template "${o.path}" for the ${t} note.
`+re(u),j),null}else l=`---
type: ${n.typeProperty}
date: ${i.format("YYYY-MM-DD")} date: ${i.format("YYYY-MM-DD")}
--- ---
`;d=await this.app.vault.create(o,c)}}catch(n){new y.Notice(`Failed to create ${a.label.toLowerCase()} note: ${n.message}`);return}new y.Notice(`Created ${a.label.toLowerCase()} note: ${r}`)}d&&await this.app.workspace.getLeaf(!1).openFile(d)}async openPeriodNoteInLeaf(t,i,s){let e={day:{settings:this.settings.daily,label:"Daily"},week:{settings:this.settings.weekly,label:"Weekly"},month:{settings:this.settings.monthly,label:"Monthly"},quarter:{settings:this.settings.quarterly,label:"Quarterly"},year:{settings:this.settings.yearly,label:"Yearly"}}[t];if(!e)return;let{settings:r}=e,o=i.format(r.nameFormat)+".md",d=r.folder?`${r.folder}/${o}`:o,n=this.app.vault.getFileByPath(d);if(!n)try{let l=r.templateFile+".md",c=this.app.vault.getFileByPath(l);if(c){let h=await this.app.vault.read(c);n=await this.app.vault.create(d,h)}else{let h=`--- `;let p;try{p=await this.app.vault.create(e,l)}catch(u){return new f.Notice(`Waypoint: could not create the ${t} note at "${e}".
type: ${r.typeProperty} ${re(u)}`,j),null}return s&&!o?new f.Notice(`Created ${t} note: ${p.basename}
date: ${i.format("YYYY-MM-DD")} Template "${s}" was not found, so a basic note was created instead.`,j):new f.Notice(`Created ${t} note: ${p.basename}`),p}async ensureFolderExists(e){if(!e||this.app.vault.getAbstractFileByPath(e)instanceof f.TFolder)return;let n="";for(let i of e.split("/"))if(i&&(n=n?`${n}/${i}`:i,!(this.app.vault.getAbstractFileByPath(n)instanceof f.TFolder)))try{await this.app.vault.createFolder(n)}catch(t){if(!(this.app.vault.getAbstractFileByPath(n)instanceof f.TFolder))throw t}}resolveTemplateFile(e){if(!e)return null;let n=e.toLowerCase().endsWith(".md")?e:`${e}.md`;return this.app.vault.getFileByPath(n)}detectPeriodType(e){for(let n of fe){let i=this.settings[te[n].key].nameFormat;if(!i)continue;let t=(0,f.moment)(e,i,!0);if(t.isValid())return{period:n,date:t}}return null}async navigatePeriodNote(e){let n=this.app.workspace.getActiveFile();if(!n){new f.Notice("No active file");return}let i=this.detectPeriodType(n.basename);if(!i){let o=fe.map(l=>`${te[l].label.toLowerCase()} "${this.settings[te[l].key].nameFormat}"`).join(", ");new f.Notice(`Waypoint: "${n.basename}" does not match any configured periodic note format.
--- Expected one of: ${o}.`,j);return}let{period:t,date:a}=i,r=e==="next"?1:-1,s=t==="quarter"?a.clone().add(r*3,"months"):a.clone().add(r,`${t}s`);await this.openPeriodNote(t,s)}redrawAll(){this.broadcastRedraw()}broadcastRedraw(){let e=this.app.workspace.getLeavesOfType(E);for(let n of e)n.view instanceof z&&n.view.redraw()}showDateInViews(e){for(let n of this.app.workspace.getLeavesOfType(E))n.view instanceof z&&n.view.showDate(e)}},Ce=["daily","weekly","monthly","quarterly","yearly"],te={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"}},fe=["day","week","month","quarter","year"];function ve(c){return c.slice(c.lastIndexOf("/")+1).replace(/\.[^/.]+$/,"")}var j=1e4,Le=5e3;function re(c){return c instanceof Error?c.message:String(c)}function V(c,d){return d?c.format(d):""}
`;n=await this.app.vault.create(d,h)}}catch(l){new y.Notice(`Failed to create ${e.label.toLowerCase()} note: ${l.message}`);return}n&&await s.openFile(n)}detectPeriodType(t){return/^\d{4}-\d{2}-\d{2}$/.test(t)?{period:"day",date:(0,y.moment)(t,"YYYY-MM-DD")}:/^\d{4}-W\d{2}$/.test(t)?{period:"week",date:(0,y.moment)(t,"GGGG-[W]WW")}:/^\d{4}-\d{2}$/.test(t)?{period:"month",date:(0,y.moment)(t,"YYYY-MM")}:/^\d{4}-Q[1-4]$/.test(t)?{period:"quarter",date:(0,y.moment)(t,"YYYY-[Q]Q")}:/^\d{4}$/.test(t)?{period:"year",date:(0,y.moment)(t,"YYYY")}:null}async navigatePeriodNote(t){let i=this.app.workspace.getActiveFile();if(!i){new y.Notice("No active file");return}let s=this.detectPeriodType(i.basename);if(!s){new y.Notice("Current file is not a periodic note (daily/weekly/monthly/quarterly/yearly)");return}let{period:a,date:e}=s;if(!e.isValid()){new y.Notice(`Could not parse date from filename: ${i.basename}`);return}let r=t==="next"?1:-1,o=a==="quarter"?e.clone().add(r*3,"months"):e.clone().add(r,`${a}s`);await this.openPeriodNote(a,o)}redrawAll(){this.broadcastRedraw()}broadcastRedraw(){let t=this.app.workspace.getLeavesOfType(P);for(let i of t)i.view instanceof A&&i.view.redraw()}async getNotesForDate(t){return this.app.vault.getFiles().filter(i=>i.extension==="md"&&i.basename===t)}async hasNoteForDate(t){return this.app.vault.getFiles().some(i=>i.extension==="md"&&i.basename===t)}};
+2 -2
View File
@@ -1,8 +1,8 @@
{ {
"id": "waypoint-sidebar", "id": "waypoint-sidebar",
"name": "Waypoint Sidebar", "name": "Waypoint Sidebar",
"version": "1.4.0", "version": "1.9.0",
"minAppVersion": "0.16.3", "minAppVersion": "1.4.10",
"description": "Calendar, recent files, and custom bookmarks sidebar.", "description": "Calendar, recent files, and custom bookmarks sidebar.",
"author": "Olivier", "author": "Olivier",
"isDesktopOnly": false "isDesktopOnly": false
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "waypoint", "name": "waypoint",
"version": "1.0.0", "version": "1.8.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "waypoint", "name": "waypoint",
"version": "1.0.0", "version": "1.8.0",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"builtin-modules": "4.0.0", "builtin-modules": "4.0.0",
+3 -2
View File
@@ -1,11 +1,12 @@
{ {
"name": "waypoint", "name": "waypoint",
"version": "1.4.0", "version": "1.9.0",
"description": "Calendar, recent files, and custom bookmarks sidebar.", "description": "Calendar, recent files, and custom bookmarks sidebar.",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {
"dev": "node esbuild.config.mjs", "dev": "node esbuild.config.mjs",
"build": "node esbuild.config.mjs production" "typecheck": "node node_modules/typescript/bin/tsc --noEmit",
"build": "npm run typecheck && node esbuild.config.mjs production"
}, },
"keywords": [], "keywords": [],
"author": "Olivier", "author": "Olivier",
+727 -201
View File
File diff suppressed because it is too large. Load diff
+48
View File
@@ -0,0 +1,48 @@
// ── Date picker modal ──
import { App, Modal, moment } from 'obsidian';
/** Native date input (the OS picker on mobile), confirmed with Enter or Open. */
export class DatePickerModal extends Modal {
constructor(
app: App,
private initialDate: moment.Moment,
private onSubmit: (date: moment.Moment) => void,
) {
super(app);
}
onOpen(): void {
this.titleEl.setText('Open date');
const input = this.contentEl.createEl('input', {
type: 'date',
value: this.initialDate.format('YYYY-MM-DD'),
});
input.style.width = '100%';
input.style.marginBottom = '12px';
input.focus();
const submit = (): void => {
// A date input's value is always ISO (YYYY-MM-DD), or empty when incomplete.
const date = moment(input.value, 'YYYY-MM-DD', true);
if (!date.isValid()) return;
this.close();
this.onSubmit(date);
};
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') submit();
});
const btnContainer = this.contentEl.createDiv({ cls: 'modal-button-container' });
btnContainer.createEl('button', { text: 'Cancel' })
.addEventListener('click', () => this.close());
btnContainer.createEl('button', { text: 'Open', cls: 'mod-cta' })
.addEventListener('click', submit);
}
onClose(): void {
this.contentEl.empty();
}
}
+12 -1
View File
@@ -11,7 +11,18 @@ export interface BookmarkItem {
indent: number; indent: number;
} }
export interface RecentFileEntry {
path: string;
basename: string;
/** Epoch ms of the last open; absent if never opened while tracked. */
openedAt?: number;
/** Epoch ms of the last change (yours or not); absent if never changed while tracked. */
changedAt?: number;
/** Changed while not the active file (sync, another plugin…); cleared once opened. */
changedInBackground?: boolean;
}
export interface WaypointData { export interface WaypointData {
bookmarks: BookmarkItem[]; bookmarks: BookmarkItem[];
recentFiles: { path: string; basename: string }[]; recentFiles: RecentFileEntry[];
} }
+352 -25
View File
@@ -1,13 +1,44 @@
import { Setting, PluginSettingTab, App, Plugin } from 'obsidian'; import { Setting, PluginSettingTab, App, setIcon, AbstractInputSuggest, TFile } from 'obsidian';
import { WaypointSettings, DEFAULT_SETTINGS, PeriodNoteSettings } from 'src/settings'; import type WaypointPlugin from 'src/main';
import { WaypointSettings, DEFAULT_SETTINGS, DEFAULT_DATE_SYSTEM, PeriodNoteSettings } from 'src/settings';
import { formatHasDateToken } from 'src/utils/date-systems';
import { IconSuggestModal } from 'src/views/waypoint-view';
/**
* Vault-wide Markdown-file suggester for template-path fields, matching
* Obsidian's native suggest popup (same base class Templater's own template
* pickers use) rather than the browser's unstyled `<datalist>` dropdown.
*/
class TemplateFileSuggest extends AbstractInputSuggest<TFile> {
constructor(app: App, private inputEl: HTMLInputElement) {
super(app, inputEl);
}
getSuggestions(query: string): TFile[] {
const q = query.toLowerCase();
return this.app.vault.getMarkdownFiles()
.filter(file => file.path.toLowerCase().includes(q))
.slice(0, 200);
}
renderSuggestion(file: TFile, el: HTMLElement): void {
el.setText(file.path.replace(/\.md$/, ''));
}
selectSuggestion(file: TFile): void {
this.setValue(file.path.replace(/\.md$/, ''));
this.inputEl.trigger('input');
this.close();
}
}
export class WaypointSettingTab extends PluginSettingTab { export class WaypointSettingTab extends PluginSettingTab {
private plugin: Plugin; private plugin: WaypointPlugin;
private settings: WaypointSettings; private settings: WaypointSettings;
private onSettingsChange: () => void; private onSettingsChange: () => void;
private activeTab: 'calendar' | 'periodic' | 'recent' | 'display' = 'calendar'; private activeTab: 'calendar' | 'periodic' | 'systems' | 'recent' | 'display' | 'about' = 'calendar';
constructor(app: App, plugin: Plugin, settings: WaypointSettings, onSettingsChange: () => void) { constructor(app: App, plugin: WaypointPlugin, settings: WaypointSettings, onSettingsChange: () => void) {
super(app, plugin); super(app, plugin);
this.plugin = plugin; this.plugin = plugin;
this.settings = settings; this.settings = settings;
@@ -23,8 +54,10 @@ export class WaypointSettingTab extends PluginSettingTab {
const tabs = [ const tabs = [
{ key: 'calendar' as const, label: 'Calendar' }, { key: 'calendar' as const, label: 'Calendar' },
{ key: 'periodic' as const, label: 'Periodic Notes' }, { key: 'periodic' as const, label: 'Periodic Notes' },
{ key: 'systems' as const, label: 'Date systems' },
{ key: 'recent' as const, label: 'Recent Files' }, { key: 'recent' as const, label: 'Recent Files' },
{ key: 'display' as const, label: 'Display' }, { key: 'display' as const, label: 'Display' },
{ key: 'about' as const, label: 'About' },
]; ];
for (const tab of tabs) { for (const tab of tabs) {
@@ -47,12 +80,18 @@ export class WaypointSettingTab extends PluginSettingTab {
case 'periodic': case 'periodic':
this.renderPeriodicTab(tabContent); this.renderPeriodicTab(tabContent);
break; break;
case 'systems':
this.renderSystemsTab(tabContent);
break;
case 'recent': case 'recent':
this.renderRecentTab(tabContent); this.renderRecentTab(tabContent);
break; break;
case 'display': case 'display':
this.renderDisplayTab(tabContent); this.renderDisplayTab(tabContent);
break; break;
case 'about':
this.renderAboutTab(tabContent);
break;
} }
} }
@@ -86,6 +125,32 @@ export class WaypointSettingTab extends PluginSettingTab {
this.saveAndRefresh(); this.saveAndRefresh();
}); });
}); });
new Setting(container)
.setName('Indicator style')
.setDesc('Show one neutral dot for any dated note, or one coloured dot for each configured date system.')
.addDropdown((dropdown) => {
dropdown
.addOption('any', 'Single dot')
.addOption('systems', 'Colour by note system')
.setValue(this.settings.calendar.indicatorMode)
.onChange((value: 'any' | 'systems') => {
this.settings.calendar.indicatorMode = value;
this.saveAndRefresh();
});
});
new Setting(container)
.setName('Daily indicator colour')
.setDesc('Colour for daily-note dots when using “Colour by note system”.')
.addColorPicker((color) => {
color
.setValue(this.settings.calendar.dailyIndicatorColor)
.onChange((value) => {
this.settings.calendar.dailyIndicatorColor = value;
this.saveAndRefresh();
});
});
} }
// ═══════════════════════════════ // ═══════════════════════════════
@@ -93,6 +158,17 @@ export class WaypointSettingTab extends PluginSettingTab {
// ═══════════════════════════════ // ═══════════════════════════════
private renderPeriodicTab(container: HTMLElement): void { private renderPeriodicTab(container: HTMLElement): void {
new Setting(container)
.setName('Use existing tabs')
.setDesc('If a periodic note is already open, switch to its tab instead of opening it again.')
.addToggle((toggle) => {
toggle
.setValue(this.settings.reusePeriodicNoteTabs)
.onChange((value) => {
this.settings.reusePeriodicNoteTabs = value;
this.saveAndRefresh();
});
});
this.addPeriodNoteSettings(container, 'Daily', this.settings.daily); this.addPeriodNoteSettings(container, 'Daily', this.settings.daily);
this.addPeriodNoteSettings(container, 'Weekly', this.settings.weekly); this.addPeriodNoteSettings(container, 'Weekly', this.settings.weekly);
this.addPeriodNoteSettings(container, 'Monthly', this.settings.monthly); this.addPeriodNoteSettings(container, 'Monthly', this.settings.monthly);
@@ -129,10 +205,11 @@ export class WaypointSettingTab extends PluginSettingTab {
new Setting(container) new Setting(container)
.setName('Template file') .setName('Template file')
.setDesc(`Path to the template file (without .md extension).`) .setDesc('Path to the template file. The .md extension is optional.')
.addText((text) => { .addText((text) => {
text.setPlaceholder('Templates/Daily note'); text.setPlaceholder('Templates/Daily note');
text.setValue(period.templateFile); text.setValue(period.templateFile);
new TemplateFileSuggest(this.app, text.inputEl);
text.onChange((value) => { text.onChange((value) => {
period.templateFile = value; period.templateFile = value;
this.saveAndRefresh(); this.saveAndRefresh();
@@ -152,6 +229,152 @@ export class WaypointSettingTab extends PluginSettingTab {
}); });
} }
// ═══════════════════════════════
// Date systems tab
// ═══════════════════════════════
private renderSystemsTab(container: HTMLElement): void {
const intro = new DocumentFragment();
intro.createDiv({ text: 'A date system is a folder of notes whose filenames start with a date. Each one appears in the calendar\'s right-click menu for that day.' });
intro.createDiv({ text: 'The daily note is configured under Periodic Notes and always comes first in that menu.' });
intro.createDiv({ text: 'Name format is a moment.js format. Literal words need bracket escaping, e.g. YYYY-MM-DD - [Journal].' });
intro.createDiv({ text: 'Include {title} for systems that hold many notes per date, such as meetings: the text before the token finds the existing notes, and the token marks where a typed title goes. Without it, a date has exactly one note.' });
new Setting(container)
.setHeading()
.setName('Date systems')
.setDesc(intro);
this.settings.dateSystems.forEach((system, i, arr) => {
new Setting(container)
.setHeading()
.setName(system.name || 'Untitled system')
.addExtraButton((btn) => {
btn
.setIcon('arrow-up')
.setTooltip('Move up')
.setDisabled(i === 0)
.onClick(async () => {
if (i === 0) return;
const above = arr[i - 1];
arr[i - 1] = arr[i];
arr[i] = above;
await this.saveAndRefresh();
this.display();
});
})
.addExtraButton((btn) => {
btn
.setIcon('arrow-down')
.setTooltip('Move down')
.setDisabled(i === arr.length - 1)
.onClick(async () => {
if (i === arr.length - 1) return;
const below = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = below;
await this.saveAndRefresh();
this.display();
});
})
.addExtraButton((btn) => {
btn
.setIcon('trash')
.setTooltip('Delete this date system')
.onClick(async () => {
arr.splice(i, 1);
await this.saveAndRefresh();
this.display();
});
});
this.addSystemTextSetting(container,
'Name', 'Label shown in the calendar right-click menu.',
system, 'name', 'Journal',
);
this.addSystemTextSetting(container,
'Folder', 'Folder these notes live in.',
system, 'folder', 'periodic/journal',
);
const formatSetting = this.addSystemTextSetting(container,
'Name format', 'Filename format (moment.js format). Include {title} for many notes per date.',
system, 'nameFormat', 'YYYY-MM-DD - {title}',
);
// A blank row is still being filled in, so only warn once something was typed.
if (system.nameFormat && !formatHasDateToken(system.nameFormat)) {
formatSetting.descEl.createDiv({
cls: 'waypoint-settings-warning',
text: 'This name format has no date placeholder, so it will never match or create dated notes.',
});
}
this.addSystemTextSetting(container,
'Template file', 'Path to the template file. The .md extension is optional.',
system, 'templateFile', 'resources/template/journal', true,
);
this.addSystemTextSetting(container,
'Type property', `Fallback value for the 'type' frontmatter property, used when no template is found.`,
system, 'typeProperty', 'journal-note',
);
this.addSystemTextSetting(container,
'Icon', 'Lucide icon name for the menu item. Browse names at lucide.dev.',
system, 'icon', 'book-open',
);
new Setting(container)
.setName('Indicator colour')
.setDesc('Colour for this system’s dot when using “Colour by note system”.')
.addColorPicker((color) => {
color
.setValue(system.indicatorColor)
.onChange((value) => {
system.indicatorColor = value;
this.saveAndRefresh();
});
});
});
new Setting(container)
.addButton((btn) =>
btn
.setButtonText('Add date system')
.setCta()
.onClick(async () => {
this.settings.dateSystems.push(Object.assign(
{ id: `ds-${Date.now()}-${Math.random().toString(36).slice(2, 6)}` },
DEFAULT_DATE_SYSTEM,
));
await this.saveAndRefresh();
this.display();
}),
);
}
/** Returns the Setting so callers can append validation notices to its description. */
private addSystemTextSetting<K extends string>(
container: HTMLElement,
name: string,
desc: string,
obj: Record<K, string>,
key: K,
placeholder: string,
suggestTemplates?: boolean,
): Setting {
return new Setting(container)
.setName(name)
.setDesc(desc)
.addText((text) => {
text.setPlaceholder(placeholder);
text.setValue(obj[key]);
if (suggestTemplates) new TemplateFileSuggest(this.app, text.inputEl);
text.onChange((value) => {
obj[key] = value;
this.saveAndRefresh();
});
});
}
// ═══════════════════════════════ // ═══════════════════════════════
// Recent Files tab // Recent Files tab
// ═══════════════════════════════ // ═══════════════════════════════
@@ -159,7 +382,7 @@ export class WaypointSettingTab extends PluginSettingTab {
private renderRecentTab(container: HTMLElement): void { private renderRecentTab(container: HTMLElement): void {
new Setting(container) new Setting(container)
.setName('Max items') .setName('Max items')
.setDesc('Maximum number of recent files to track.') .setDesc('How many recently opened files, and separately how many recently changed files, to keep. A burst of synced changes cannot push out the files you opened.')
.addText((text) => { .addText((text) => {
text.inputEl.setAttr('type', 'number'); text.inputEl.setAttr('type', 'number');
text.inputEl.setAttr('placeholder', '50'); text.inputEl.setAttr('placeholder', '50');
@@ -173,20 +396,6 @@ export class WaypointSettingTab extends PluginSettingTab {
}; };
}); });
new Setting(container)
.setName('Update on')
.setDesc('When to add a file to the recent list.')
.addDropdown((dropdown) => {
dropdown
.addOption('file-open', 'File opened')
.addOption('file-edit', 'File changed')
.setValue(this.settings.recentFiles.updateOn)
.onChange((value: 'file-open' | 'file-edit') => {
this.settings.recentFiles.updateOn = value;
this.saveAndRefresh();
});
});
const pathDesc = new DocumentFragment(); const pathDesc = new DocumentFragment();
pathDesc.appendText('Regex patterns for paths to exclude. One per line.'); pathDesc.appendText('Regex patterns for paths to exclude. One per line.');
new Setting(container) new Setting(container)
@@ -216,6 +425,76 @@ export class WaypointSettingTab extends PluginSettingTab {
this.saveAndRefresh(); this.saveAndRefresh();
}; };
}); });
new Setting(container)
.setName('Type filter')
.setDesc('Show pills above the list to filter recent files by their frontmatter `type`.')
.addToggle((toggle) => {
toggle
.setValue(this.settings.recentFiles.showTypeFilter)
.onChange((value) => {
this.settings.recentFiles.showTypeFilter = value;
this.saveAndRefresh();
});
});
this.renderRecentTypes(container);
}
/** Frontmatter types with an icon each; also the pill list when the type filter is on. */
private renderRecentTypes(container: HTMLElement): void {
const types = this.settings.recentFiles.types;
new Setting(container)
.setHeading()
.setName('File types')
.setDesc('Frontmatter `type` values. A type\'s icon shows beside matching recent files. With the type filter on, these types are the pills, in this order; with no types listed, pills are detected automatically.');
types.forEach((entry, i) => {
new Setting(container)
.addText((text) => {
text.setPlaceholder('meeting');
text.setValue(entry.type);
text.inputEl.onblur = () => {
const value = text.getValue().trim();
if (value === entry.type) return;
entry.type = value;
this.saveAndRefresh();
};
})
.addExtraButton((btn) => {
btn
.setIcon(entry.icon || 'image-off')
.setTooltip(entry.icon ? `Icon: ${entry.icon}` : 'Choose icon')
.onClick(() => {
new IconSuggestModal(this.app, entry.icon, (icon) => {
entry.icon = icon;
this.saveAndRefresh();
this.display();
}).open();
});
})
.addExtraButton((btn) => {
btn
.setIcon('trash')
.setTooltip('Remove this type')
.onClick(() => {
types.splice(i, 1);
this.saveAndRefresh();
this.display();
});
});
});
new Setting(container)
.addButton((btn) => {
btn
.setButtonText('Add type')
.onClick(() => {
types.push({ type: '', icon: '' });
this.display();
});
});
} }
// ═══════════════════════════════ // ═══════════════════════════════
@@ -265,12 +544,12 @@ export class WaypointSettingTab extends PluginSettingTab {
); );
} }
private addSliderSetting( private addSliderSetting<K extends string>(
container: HTMLElement, container: HTMLElement,
name: string, name: string,
desc: string, desc: string,
obj: any, obj: Record<K, number>,
key: string, key: K,
min: number, min: number,
max: number, max: number,
step: number, step: number,
@@ -294,7 +573,55 @@ export class WaypointSettingTab extends PluginSettingTab {
} }
private async saveAndRefresh(): Promise<void> { private async saveAndRefresh(): Promise<void> {
await (this.plugin as any).saveSettings(); await this.plugin.saveSettings();
this.onSettingsChange(); this.onSettingsChange();
} }
// ═══════════════════════════════
// About tab
// ═══════════════════════════════
private renderAboutTab(container: HTMLElement): void {
const version = this.plugin.manifest.version;
const header = container.createDiv();
header.style.display = 'flex';
header.style.alignItems = 'center';
header.style.gap = '12px';
header.style.marginBottom = '16px';
const icon = header.createDiv();
icon.style.display = 'flex';
icon.style.alignItems = 'center';
icon.style.justifyContent = 'center';
icon.style.width = '48px';
icon.style.height = '48px';
icon.style.borderRadius = '12px';
icon.style.background = 'var(--interactive-accent)';
icon.style.color = 'var(--text-on-accent)';
icon.style.fontSize = '24px';
setIcon(icon, 'compass');
const titleGroup = header.createDiv();
const title = titleGroup.createEl('h2', { text: 'Waypoint Sidebar' });
title.style.margin = '0';
title.style.lineHeight = '1.2';
const subtitle = titleGroup.createDiv({ text: `v${version}` });
subtitle.style.color = 'var(--text-muted)';
subtitle.style.fontSize = 'var(--font-ui-small)';
const desc = container.createDiv();
desc.style.marginBottom = '20px';
desc.style.lineHeight = '1.6';
desc.style.color = 'var(--text-normal)';
desc.innerHTML = [
`<p><strong>Waypoint</strong> is a sidebar plugin that brings three essential panels into one view:</p>`,
`<ul style="padding-left: 20px; margin: 8px 0;">`,
`<li><strong>Calendar</strong> — a monthly grid for your periodic notes (daily, weekly, monthly, quarterly, yearly). Click any day, week, or month to open or create the corresponding note.</li>`,
`<li><strong>Recent Files</strong> — a list of recently opened files with type filtering, drag-and-drop, and right-click actions.</li>`,
`<li><strong>Bookmarks</strong> — custom bookmarks with icons, groups, nesting, and drag-and-drop reordering. Separate from Obsidian's native bookmarks.</li>`,
`</ul>`,
`<p style="color: var(--text-muted); font-size: var(--font-ui-small);">Made by Olivier. Licensed under MIT.</p>`,
].join('\n');
}
} }
+87 -2
View File
@@ -1,3 +1,5 @@
import type { RecentFilesShow } from 'src/utils/recent-files';
// ── Waypoint Settings ── // ── Waypoint Settings ──
export interface PeriodNoteSettings { export interface PeriodNoteSettings {
@@ -7,16 +9,68 @@ export interface PeriodNoteSettings {
typeProperty: string; typeProperty: string;
} }
/**
* A folder of notes whose filenames begin with a date — the vault's "systems":
* daily notes, a journal, meeting notes.
*
* `nameFormat` is a moment format string, so literal text needs bracket
* escaping (`YYYY-MM-DD - [Journal]`). When it contains `{title}` the system
* holds many notes per date and the token marks where the free-text title
* goes; without it a date maps to exactly one filename.
*/
export interface DateSystemSettings {
/** Stable across edits and reordering, so the settings UI can key rows. */
id: string;
/** Shown in the calendar's right-click menu. */
name: string;
folder: string;
nameFormat: string;
templateFile: string;
typeProperty: string;
/** Lucide icon name for the menu item. */
icon: string;
/** CSS colour for this system's calendar indicator. */
indicatorColor: string;
}
/** Field defaults for a newly added system, and the merge base for saved ones. */
export const DEFAULT_DATE_SYSTEM: Omit<DateSystemSettings, 'id'> = {
name: '',
folder: '',
nameFormat: 'YYYY-MM-DD - {title}',
templateFile: '',
typeProperty: '',
icon: 'file',
indicatorColor: '#64748b',
};
export interface CalendarSettings { export interface CalendarSettings {
firstDayOfWeek: number; // 0=Sunday, 1=Monday firstDayOfWeek: number; // 0=Sunday, 1=Monday
showNoteIndicators: boolean; showNoteIndicators: boolean;
/** Single neutral dot, or a dot per day-scoped date system. */
indicatorMode: 'any' | 'systems';
/** Colour used by the synthesized daily system in `systems` mode. */
dailyIndicatorColor: string;
}
/** A frontmatter `type` value: its icon in Recent Files and, when the type filter is on, a pill. */
export interface RecentFileType {
type: string;
/** Lucide icon name; empty for none. */
icon: string;
} }
export interface RecentFilesSettings { export interface RecentFilesSettings {
/** Kept per kind: the N most recently opened plus the N most recently changed. */
maxItems: number; maxItems: number;
updateOn: 'file-open' | 'file-edit'; /** Header filter: opened files, changed files, or both. */
show: RecentFilesShow;
omittedPaths: string[]; omittedPaths: string[];
omittedTags: string[]; omittedTags: string[];
/** Type pills above the list. */
showTypeFilter: boolean;
/** Configured types, in pill order; empty = pills auto-detected from frontmatter. */
types: RecentFileType[];
} }
export interface DisplaySettings { export interface DisplaySettings {
@@ -31,10 +85,14 @@ export interface DisplaySettings {
export interface WaypointSettings { export interface WaypointSettings {
calendar: CalendarSettings; calendar: CalendarSettings;
daily: PeriodNoteSettings; daily: PeriodNoteSettings;
/** Focus an open tab when opening a periodic note without an explicit leaf. */
reusePeriodicNoteTabs: boolean;
weekly: PeriodNoteSettings; weekly: PeriodNoteSettings;
monthly: PeriodNoteSettings; monthly: PeriodNoteSettings;
quarterly: PeriodNoteSettings; quarterly: PeriodNoteSettings;
yearly: PeriodNoteSettings; yearly: PeriodNoteSettings;
/** Day-scoped systems beyond the daily note, in menu order. */
dateSystems: DateSystemSettings[];
recentFiles: RecentFilesSettings; recentFiles: RecentFilesSettings;
display: DisplaySettings; display: DisplaySettings;
} }
@@ -43,6 +101,8 @@ export const DEFAULT_SETTINGS: WaypointSettings = {
calendar: { calendar: {
firstDayOfWeek: 1, // Monday firstDayOfWeek: 1, // Monday
showNoteIndicators: true, showNoteIndicators: true,
indicatorMode: 'systems',
dailyIndicatorColor: '#3b82f6',
}, },
daily: { daily: {
folder: 'periodic/daily', folder: 'periodic/daily',
@@ -50,6 +110,7 @@ export const DEFAULT_SETTINGS: WaypointSettings = {
nameFormat: 'YYYY-MM-DD', nameFormat: 'YYYY-MM-DD',
typeProperty: 'daily-note', typeProperty: 'daily-note',
}, },
reusePeriodicNoteTabs: false,
weekly: { weekly: {
folder: 'periodic/weekly', folder: 'periodic/weekly',
templateFile: 'Templates/Weekly note', templateFile: 'Templates/Weekly note',
@@ -74,11 +135,35 @@ export const DEFAULT_SETTINGS: WaypointSettings = {
nameFormat: 'YYYY', nameFormat: 'YYYY',
typeProperty: 'yearly-note', typeProperty: 'yearly-note',
}, },
dateSystems: [
{
id: 'journal',
name: 'Journal',
folder: 'periodic/journal',
nameFormat: 'YYYY-MM-DD - [Journal]',
templateFile: '',
typeProperty: 'journal',
icon: 'book-open',
indicatorColor: '#22c55e',
},
{
id: 'meetings',
name: 'Meeting',
folder: 'periodic/meetings',
nameFormat: 'YYYY-MM-DD - {title}',
templateFile: '',
typeProperty: 'meeting',
icon: 'users',
indicatorColor: '#a855f7',
},
],
recentFiles: { recentFiles: {
maxItems: 50, maxItems: 50,
updateOn: 'file-open', show: 'all',
omittedPaths: [], omittedPaths: [],
omittedTags: [], omittedTags: [],
showTypeFilter: true,
types: [],
}, },
display: { display: {
rowSize: 26, rowSize: 26,
+103
View File
@@ -0,0 +1,103 @@
// ── Date system filename helpers ──
//
// A "date system" is a folder of notes whose filenames begin with a date:
//
// periodic/daily/2026-09-07.md one per date
// periodic/journal/2026-09-07 - Journal.md one per date
// periodic/meetings/2026-09-07 - Meeting w Mark.md many per date
//
// The system's `nameFormat` is a moment format string. When it contains
// `{title}` the system holds many notes per date: the part before the token is
// the date prefix used to find them, and the token marks where a free-text
// title goes when creating one.
//
// This module imports nothing from 'obsidian' so it stays unit-testable in
// plain node. Callers do the moment formatting and pass the results in.
export const TITLE_TOKEN = '{title}';
export interface NameFormatParts {
/** Moment format for the text before the title. */
before: string;
/** Moment format for the text after the title. Empty for most systems. */
after: string;
/** True when the format carries a title token, i.e. many notes per date. */
hasTitle: boolean;
}
/**
* Split a name format around its title token.
*
* The split has to happen before moment sees the string: `t`, `i`, `l` and `e`
* are all live moment tokens, so formatting `{title}` directly would mangle it.
*/
export function splitNameFormat(nameFormat: string): NameFormatParts {
const idx = nameFormat.indexOf(TITLE_TOKEN);
if (idx < 0) return { before: nameFormat, after: '', hasTitle: false };
return {
before: nameFormat.slice(0, idx),
after: nameFormat.slice(idx + TITLE_TOKEN.length),
hasTitle: true,
};
}
/** Whether `path` sits in `folder` or any subfolder. An empty folder is the vault root. */
export function isInFolder(path: string, folder: string): boolean {
if (!folder) return true;
const prefix = folder.endsWith('/') ? folder : `${folder}/`;
return path.startsWith(prefix);
}
/**
* Whether `basename` is a note of a system whose formatted name parts are
* `before` and `after`.
*
* One-per-date systems must match the whole basename. Many-per-date systems
* match on the date prefix, since the middle is a free-text title.
*/
export function matchesSystemName(
basename: string,
before: string,
after: string,
hasTitle: boolean,
): boolean {
if (!hasTitle) return basename === before + after;
// A format of just `{title}` formats to an empty prefix, which would claim
// every file in the folder for every date. Treat it as matching nothing;
// the settings tab flags the format as missing a date instead.
if (!before) return false;
if (basename.length < before.length + after.length) return false;
return basename.startsWith(before) && basename.endsWith(after);
}
/**
* The free-text part of a many-per-date basename, for use as a menu label.
* Falls back to the whole basename when the affixes do not line up.
*/
export function titleFromBasename(basename: string, before: string, after: string): string {
const start = basename.startsWith(before) ? before.length : 0;
const end = after && basename.endsWith(after)
? basename.length - after.length
: basename.length;
if (end <= start) return basename;
return basename.slice(start, end).trim() || basename;
}
/**
* Characters Obsidian rejects in filenames, plus the link-syntax characters
* (`#^[]|`) it refuses to index cleanly. Collapsed to a dash so a typed title
* like "Meeting w/ Mark" still produces a creatable filename.
*/
const ILLEGAL_FILENAME_CHARS = /[\\/:*?"<>|#^[\]]/g;
export function sanitizeTitle(title: string): string {
return title.replace(ILLEGAL_FILENAME_CHARS, '-').replace(/\s+/g, ' ').trim();
}
/** Whether a name format resolves to a usable date prefix at all. */
export function formatHasDateToken(nameFormat: string): boolean {
const { before } = splitNameFormat(nameFormat);
// Strip bracket-escaped literals, then look for any moment date token.
const unescaped = before.replace(/\[[^\]]*\]/g, '');
return /[YMDQGWEwdgeo]/.test(unescaped);
}
+21
View File
@@ -0,0 +1,21 @@
// ── Path helpers ──
// Pure functions only: no 'obsidian' imports, so this stays unit-testable in plain node.
/**
* Remap a stored vault path after a rename.
*
* Obsidian's `vault.on('rename')` fires for folders as well as files, so a
* stored path can be affected either because it *is* the renamed item or
* because it lives inside a renamed folder.
*
* The nested check requires a `/` boundary, so renaming `notes/foo` leaves
* `notes/foobar.md` untouched.
*
* @returns the updated path, or `null` when `path` is unaffected.
*/
export function remapRenamedPath(path: string, oldPath: string, newPath: string): string | null {
if (!path || !oldPath) return null;
if (path === oldPath) return newPath;
if (path.startsWith(oldPath + '/')) return newPath + path.slice(oldPath.length);
return null;
}
+42
View File
@@ -0,0 +1,42 @@
// ── Recent files ordering ──
//
// Pure helpers (no 'obsidian' import) shared by the plugin, which trims the
// stored list, and the view, which filters it for display.
import type { RecentFileEntry } from 'src/models/bookmark';
/** Which recent files the sidebar lists. */
export type RecentFilesShow = 'all' | 'opened' | 'changed';
/** The timestamp `show` sorts by, or undefined when the entry is not listed. */
function sortKey(entry: RecentFileEntry, show: RecentFilesShow): number | undefined {
if (show === 'opened') return entry.openedAt;
if (show === 'changed') return entry.changedAt;
if (entry.openedAt === undefined) return entry.changedAt;
if (entry.changedAt === undefined) return entry.openedAt;
return Math.max(entry.openedAt, entry.changedAt);
}
/** Entries listed under `show`, most recent first. */
export function recentFilesFor(entries: RecentFileEntry[], show: RecentFilesShow): RecentFileEntry[] {
const keyed: { entry: RecentFileEntry; key: number }[] = [];
for (const entry of entries) {
const key = sortKey(entry, show);
if (key !== undefined) keyed.push({ entry, key });
}
keyed.sort((a, b) => b.key - a.key);
return keyed.map(k => k.entry);
}
/**
* Keep an entry while it is among the `max` most recently opened OR the `max`
* most recently changed files, so a burst of synced changes cannot push out
* the files you opened. Returns the kept entries most recent first.
*/
export function trimRecentFiles(entries: RecentFileEntry[], max: number): RecentFileEntry[] {
const kept = new Set<RecentFileEntry>([
...recentFilesFor(entries, 'opened').slice(0, max),
...recentFilesFor(entries, 'changed').slice(0, max),
]);
return recentFilesFor(entries, 'all').filter(entry => kept.has(entry));
}
+407 -271
View File
@@ -12,13 +12,28 @@ import {
Notice, Notice,
TFile, TFile,
moment, moment,
type PaneType,
} from 'obsidian'; } from 'obsidian';
import type WaypointPlugin from 'src/main'; import type WaypointPlugin from 'src/main';
import type { DateSystemNotes } from 'src/main';
import { getMonthGrid } from 'src/utils/date-utils'; import { getMonthGrid } from 'src/utils/date-utils';
import { BookmarkItem } from 'src/models/bookmark'; import { BookmarkItem } from 'src/models/bookmark';
import { recentFilesFor, type RecentFilesShow } from 'src/utils/recent-files';
export const WAYPOINT_VIEW_TYPE = 'waypoint-view'; export const WAYPOINT_VIEW_TYPE = 'waypoint-view';
/** Obsidian's internal drag manager — undocumented, so it has no public typings. */
interface DragManager {
dragFile(event: DragEvent, file: TFile): unknown;
onDragStart(event: DragEvent, draggable: unknown): void;
}
function getDragManager(app: App): DragManager {
// `dragManager` is an internal Obsidian API, absent from the public typings.
const internal = app as unknown as { dragManager: DragManager };
return internal.dragManager;
}
export class WaypointView extends ItemView { export class WaypointView extends ItemView {
private plugin: WaypointPlugin; private plugin: WaypointPlugin;
@@ -60,8 +75,10 @@ export class WaypointView extends ItemView {
this.contentEl.style.setProperty('--wp-icon-size', d.iconSize + 'px'); this.contentEl.style.setProperty('--wp-icon-size', d.iconSize + 'px');
this.contentEl.style.setProperty('--wp-cal-cell-size', d.calendarCellSize + 'px'); this.contentEl.style.setProperty('--wp-cal-cell-size', d.calendarCellSize + 'px');
this.renderFavorites(); // The lists scroll on their own on mobile so the calendar stays on screen.
this.renderRecentFiles(); const lists = this.contentEl.createDiv({ cls: 'waypoint-lists' });
this.renderFavorites(lists);
this.renderRecentFiles(lists);
this.renderCalendar(); this.renderCalendar();
}; };
@@ -72,11 +89,21 @@ export class WaypointView extends ItemView {
private currentDisplayMonth: number = moment().month(); // 0-indexed private currentDisplayMonth: number = moment().month(); // 0-indexed
private currentDisplayYear: number = moment().year(); private currentDisplayYear: number = moment().year();
private dragId: string | null = null; private dragId: string | null = null;
private dropZones = new WeakMap<HTMLElement, { above: boolean; into: boolean }>();
private recentFilesFilter: string | null = null; // null = show all, else filter by type private recentFilesFilter: string | null = null; // null = show all, else filter by type
/** Day picked with the date picker or the "Open date" command; cleared by month navigation. */
private selectedDate: moment.Moment | null = null;
/** Show `date`'s month and mark the day, without opening any note. */
showDate(date: moment.Moment): void {
this.currentDisplayMonth = date.month();
this.currentDisplayYear = date.year();
this.selectedDate = date.clone();
this.redraw();
}
private renderCalendar(): void { private renderCalendar(): void {
const section = this.contentEl.createDiv({ cls: 'waypoint-section' }); const section = this.contentEl.createDiv({ cls: 'waypoint-section waypoint-calendar-section' });
section.createDiv({ cls: 'waypoint-section-header', text: 'Calendar' });
const cal = section.createDiv({ cls: 'waypoint-calendar' }); const cal = section.createDiv({ cls: 'waypoint-calendar' });
@@ -97,7 +124,7 @@ export class WaypointView extends ItemView {
qEl.addEventListener('mousedown', (event: MouseEvent) => { qEl.addEventListener('mousedown', (event: MouseEvent) => {
if (event.button === 1) { if (event.button === 1) {
event.preventDefault(); event.preventDefault();
this.plugin.openPeriodNoteInLeaf('quarter', displayDate, this.app.workspace.getLeaf('tab')); this.plugin.openPeriodNote('quarter', displayDate, this.app.workspace.getLeaf('tab'));
} }
}); });
@@ -109,7 +136,7 @@ export class WaypointView extends ItemView {
mEl.addEventListener('mousedown', (event: MouseEvent) => { mEl.addEventListener('mousedown', (event: MouseEvent) => {
if (event.button === 1) { if (event.button === 1) {
event.preventDefault(); event.preventDefault();
this.plugin.openPeriodNoteInLeaf('month', displayDate, this.app.workspace.getLeaf('tab')); this.plugin.openPeriodNote('month', displayDate, this.app.workspace.getLeaf('tab'));
} }
}); });
@@ -121,7 +148,7 @@ export class WaypointView extends ItemView {
yEl.addEventListener('mousedown', (event: MouseEvent) => { yEl.addEventListener('mousedown', (event: MouseEvent) => {
if (event.button === 1) { if (event.button === 1) {
event.preventDefault(); event.preventDefault();
this.plugin.openPeriodNoteInLeaf('year', displayDate, this.app.workspace.getLeaf('tab')); this.plugin.openPeriodNote('year', displayDate, this.app.workspace.getLeaf('tab'));
} }
}); });
@@ -136,6 +163,7 @@ export class WaypointView extends ItemView {
todayBtn.addEventListener('click', () => { todayBtn.addEventListener('click', () => {
this.currentDisplayMonth = moment().month(); this.currentDisplayMonth = moment().month();
this.currentDisplayYear = moment().year(); this.currentDisplayYear = moment().year();
this.selectedDate = null;
this.redraw(); this.redraw();
}); });
@@ -143,6 +171,27 @@ export class WaypointView extends ItemView {
setIcon(nextBtn, 'chevron-right'); setIcon(nextBtn, 'chevron-right');
nextBtn.addEventListener('click', () => this.navigateMonth(1)); nextBtn.addEventListener('click', () => this.navigateMonth(1));
// Invisible native date input beside the button: the OS picker (native
// sheet on mobile) beats anything drawn here.
const pickBtn = todayGroup.createEl('button', { cls: 'waypoint-calendar-nav-btn waypoint-calendar-pick-btn' });
setIcon(pickBtn, 'calendar-search');
setTooltip(pickBtn, 'Go to date');
const pickInput = todayGroup.createEl('input', { type: 'date', cls: 'waypoint-calendar-pick-input' });
pickInput.tabIndex = -1;
pickInput.value = (this.selectedDate ?? now).format('YYYY-MM-DD');
pickInput.addEventListener('change', () => {
const picked = moment(pickInput.value, 'YYYY-MM-DD', true);
if (picked.isValid()) this.showDate(picked);
});
pickBtn.addEventListener('click', () => {
try {
pickInput.showPicker();
} catch {
// Older webviews without showPicker still open the picker on click.
pickInput.click();
}
});
// ── Calendar grid ── // ── Calendar grid ──
const table = cal.createEl('table'); const table = cal.createEl('table');
const thead = table.createEl('thead'); const thead = table.createEl('thead');
@@ -166,21 +215,28 @@ export class WaypointView extends ItemView {
this.plugin.settings.calendar.firstDayOfWeek, this.plugin.settings.calendar.firstDayOfWeek,
); );
const systemIndicators = this.plugin.settings.calendar.showNoteIndicators
&& this.plugin.settings.calendar.indicatorMode === 'systems'
? this.plugin.getDateSystemIndicators(weeks.reduce<moment.Moment[]>(
(dates, week) => dates.concat(week.days.map(day => day.date)),
[],
))
: null;
for (const week of weeks) { for (const week of weeks) {
const row = tbody.createEl('tr'); const row = tbody.createEl('tr');
// Week number cell // Week number cell
const wnCell = row.createEl('td', { cls: 'waypoint-weeknum' }); const wnCell = row.createEl('td', { cls: 'waypoint-weeknum' });
wnCell.setText(String(week.weekNumber)); wnCell.setText(String(week.weekNumber));
const weekStart = week.days[0].date;
wnCell.addEventListener('click', () => { wnCell.addEventListener('click', () => {
const monday = week.days[0].date; this.plugin.openPeriodNote('week', weekStart);
this.plugin.openPeriodNote('week', monday);
}); });
wnCell.addEventListener('mousedown', (event: MouseEvent) => { wnCell.addEventListener('mousedown', (event: MouseEvent) => {
if (event.button === 1) { if (event.button === 1) {
event.preventDefault(); event.preventDefault();
const file = this.app.workspace.getLeaf('tab'); this.plugin.openPeriodNote('week', weekStart, this.app.workspace.getLeaf('tab'));
this.plugin.openPeriodNoteInLeaf('week', monday, file);
} }
}); });
@@ -195,14 +251,27 @@ export class WaypointView extends ItemView {
cell.addClass('today'); cell.addClass('today');
} }
if (this.selectedDate && day.date.isSame(this.selectedDate, 'day')) {
cell.addClass('is-selected');
}
if (this.plugin.settings.calendar.showNoteIndicators) { if (this.plugin.settings.calendar.showNoteIndicators) {
const dateStr = day.date.format('YYYY-MM-DD'); const dateStr = day.date.format('YYYY-MM-DD');
const hasNote = this.plugin.app.vault.getFiles().some( if (this.plugin.settings.calendar.indicatorMode === 'any') {
f => f.extension === 'md' && f.basename === dateStr, if (this.plugin.hasNoteForDate(dateStr)) {
);
if (hasNote) {
cell.addClass('has-note'); cell.addClass('has-note');
} }
} else {
const indicators = systemIndicators?.get(dateStr) || [];
if (indicators.length > 0) {
const dots = cell.createDiv({ cls: 'waypoint-day-indicators' });
for (const indicator of indicators) {
const dot = dots.createSpan({ cls: 'waypoint-day-indicator' });
dot.style.setProperty('--waypoint-indicator-color', indicator.color);
setTooltip(dot, indicator.name);
}
}
}
} }
cell.addEventListener('click', () => { cell.addEventListener('click', () => {
@@ -211,10 +280,14 @@ export class WaypointView extends ItemView {
cell.addEventListener('mousedown', (event: MouseEvent) => { cell.addEventListener('mousedown', (event: MouseEvent) => {
if (event.button === 1) { if (event.button === 1) {
event.preventDefault(); event.preventDefault();
const file = this.app.workspace.getLeaf('tab'); this.plugin.openPeriodNote('day', day.date, this.app.workspace.getLeaf('tab'));
this.plugin.openPeriodNoteInLeaf('day', day.date, file);
} }
}); });
cell.addEventListener('contextmenu', (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
this.showDayContextMenu(event, day.date);
});
} }
} }
@@ -224,46 +297,153 @@ export class WaypointView extends ItemView {
const d = moment({ year: this.currentDisplayYear, month: this.currentDisplayMonth }).add(delta, 'month'); const d = moment({ year: this.currentDisplayYear, month: this.currentDisplayMonth }).add(delta, 'month');
this.currentDisplayMonth = d.month(); this.currentDisplayMonth = d.month();
this.currentDisplayYear = d.year(); this.currentDisplayYear = d.year();
this.selectedDate = null;
this.redraw(); this.redraw();
} }
/**
* Right-click menu for a day cell: every date system's existing notes for
* that date, plus the actions that would create the ones it is missing.
*/
private showDayContextMenu(event: MouseEvent, date: moment.Moment): void {
const menu = new Menu();
menu.addItem((i) => i.setTitle(date.format('dddd, MMMM D, YYYY')).setIsLabel(true));
for (const bucket of this.plugin.findDateSystemNotes(date)) {
// Many-per-date systems can always take another note; one-per-date
// systems only offer creation while their single note is missing.
const canCreate = bucket.multiple || bucket.notes.length === 0;
if (bucket.notes.length + (canCreate ? 1 : 0) === 0) continue;
menu.addSeparator();
for (const note of bucket.notes) {
menu.addItem((i) =>
i
.setTitle(note.label)
.setIcon(bucket.system.icon)
.onClick((evt) => this.focusFile(note.file, Keymap.isModEvent(evt))),
);
}
if (!canCreate) continue;
const noun = bucket.system.name.toLowerCase();
menu.addItem((i) =>
i
// The ellipsis promises the prompt that a free-text title needs.
.setTitle(bucket.multiple ? `New ${noun} note…` : `New ${noun} note`)
.setIcon('plus')
.onClick((evt) => this.createDateSystemNote(bucket, date, Keymap.isModEvent(evt))),
);
}
menu.showAtPosition({ x: event.clientX, y: event.clientY });
}
/**
* Creates a date system's note, asking for a title first when the system
* holds many notes per date. A held modifier opens the result in a new pane.
*/
private createDateSystemNote(bucket: DateSystemNotes, date: moment.Moment, newLeaf: PaneType | boolean): void {
if (!bucket.multiple) {
void this.plugin.openDateSystemNote(bucket.system, date, {
leaf: newLeaf ? this.app.workspace.getLeaf(newLeaf) : undefined,
});
return;
}
const name = bucket.system.name;
new PromptModal(
this.app,
{
title: `New ${name.toLowerCase()} note`,
placeholder: `${name} with…`,
cta: 'Create',
},
(title) => {
// `getLeaf` materialises the pane immediately, so the target pane is
// resolved only after the title is confirmed — cancelling the prompt
// must not leave an empty tab behind.
void this.plugin.openDateSystemNote(bucket.system, date, {
title,
leaf: newLeaf ? this.app.workspace.getLeaf(newLeaf) : undefined,
});
},
).open();
}
// ════════════════════════════════════════ // ════════════════════════════════════════
// Recent Files panel // Recent Files panel
// ════════════════════════════════════════ // ════════════════════════════════════════
private renderRecentFiles(): void { private renderRecentFiles(parent: HTMLElement): void {
const section = this.contentEl.createDiv({ cls: 'waypoint-section waypoint-recent-files' }); const settings = this.plugin.settings.recentFiles;
section.createDiv({ cls: 'waypoint-section-header', text: 'Recent Files' }); const section = parent.createDiv({ cls: 'waypoint-section waypoint-recent-files' });
const header = section.createDiv({ cls: 'waypoint-section-header' });
header.createSpan({ text: 'Recent Files' });
if (this.plugin.recentFiles.length === 0) { // ── Opened / changed switch ──
const showBar = header.createDiv({ cls: 'waypoint-recent-show' });
const showOptions: { value: RecentFilesShow; label: string; tooltip: string }[] = [
{ value: 'all', label: 'all', tooltip: 'Opened or changed' },
{ value: 'opened', label: 'opened', tooltip: 'Files you opened' },
{ value: 'changed', label: 'changed', tooltip: 'Files that changed, by you or in the background' },
];
for (const option of showOptions) {
const el = showBar.createSpan({
cls: `waypoint-recent-show-option${settings.show === option.value ? ' is-active' : ''}`,
text: option.label,
});
setTooltip(el, option.tooltip);
el.addEventListener('click', () => {
if (settings.show === option.value) return;
settings.show = option.value;
void this.plugin.saveSettings();
this.redraw();
});
}
const shownFiles = recentFilesFor(this.plugin.recentFiles, settings.show);
if (shownFiles.length === 0) {
section.createDiv({ cls: 'nav-file', text: 'No recent files' }); section.createDiv({ cls: 'nav-file', text: 'No recent files' });
return; return;
} }
const typeOf = (path: string): string | null => {
const tfile = this.app.vault.getFileByPath(path);
const type = tfile ? this.app.metadataCache.getFileCache(tfile)?.frontmatter?.type : null;
return typeof type === 'string' ? type : null;
};
// ── Type filter bar ── // ── Type filter bar ──
const typeCounts: Record<string, number> = {}; // Rows still being typed in settings have no name yet.
for (const file of this.plugin.recentFiles) { const types = settings.types.filter(t => t.type);
const tfile = this.app.vault.getAbstractFileByPath(file.path); if (!settings.showTypeFilter) {
if (tfile instanceof TFile) { this.recentFilesFilter = null;
const cache = this.app.metadataCache.getFileCache(tfile); } else {
const type = cache?.frontmatter?.type; const typeCounts = new Map<string, number>();
if (type && typeof type === 'string') { // Configured types keep their order and show even at 0; otherwise
typeCounts[type] = (typeCounts[type] || 0) + 1; // every frontmatter type present is a pill, most frequent first.
} for (const t of types) typeCounts.set(t.type, 0);
} for (const file of shownFiles) {
const type = typeOf(file.path);
if (type === null) continue;
if (types.length > 0 && !typeCounts.has(type)) continue;
typeCounts.set(type, (typeCounts.get(type) ?? 0) + 1);
} }
if (Object.keys(typeCounts).length > 0) { if (typeCounts.size > 0) {
const filterBar = section.createDiv({ cls: 'waypoint-recent-filter' }); const filterBar = section.createDiv({ cls: 'waypoint-recent-filter' });
// "All" pill
const allPill = filterBar.createSpan({ cls: `waypoint-recent-pill${!this.recentFilesFilter ? ' is-active' : ''}`, text: 'all' }); const allPill = filterBar.createSpan({ cls: `waypoint-recent-pill${!this.recentFilesFilter ? ' is-active' : ''}`, text: 'all' });
allPill.addEventListener('click', () => { allPill.addEventListener('click', () => {
this.recentFilesFilter = null; this.recentFilesFilter = null;
this.redraw(); this.redraw();
}); });
// Type pills const entries = [...typeCounts.entries()];
const sortedTypes = Object.entries(typeCounts).sort(([,a], [,b]) => b - a); if (types.length === 0) entries.sort((a, b) => b[1] - a[1]);
for (const [type, count] of sortedTypes) { for (const [type, count] of entries) {
const pill = filterBar.createSpan({ cls: `waypoint-recent-pill${this.recentFilesFilter === type ? ' is-active' : ''}` }); const pill = filterBar.createSpan({ cls: `waypoint-recent-pill${this.recentFilesFilter === type ? ' is-active' : ''}` });
pill.setText(`${type} ${count}`); pill.setText(`${type} ${count}`);
pill.addEventListener('click', () => { pill.addEventListener('click', () => {
@@ -272,20 +452,17 @@ export class WaypointView extends ItemView {
}); });
} }
} }
}
// ── Filter the file list ── // ── Filter the file list ──
let filteredFiles = this.plugin.recentFiles; const filteredFiles = this.recentFilesFilter
if (this.recentFilesFilter) { ? shownFiles.filter(file => typeOf(file.path) === this.recentFilesFilter)
filteredFiles = this.plugin.recentFiles.filter(file => { : shownFiles;
const tfile = this.app.vault.getAbstractFileByPath(file.path);
if (tfile instanceof TFile) { // Type icons. Every row reserves the icon slot once any type has an
const cache = this.app.metadataCache.getFileCache(tfile); // icon, so names stay aligned.
const type = cache?.frontmatter?.type; const typeIcons = new Map(types.filter(t => t.icon).map(t => [t.type, t.icon]));
return type === this.recentFilesFilter; const reserveIcon = typeIcons.size > 0;
}
return false;
});
}
const openFile = this.app.workspace.getActiveFile(); const openFile = this.app.workspace.getActiveFile();
const rootEl = section.createDiv({ cls: 'nav-folder mod-root' }); const rootEl = section.createDiv({ cls: 'nav-folder mod-root' });
@@ -294,9 +471,18 @@ export class WaypointView extends ItemView {
for (const file of filteredFiles) { for (const file of filteredFiles) {
const navFile = childrenEl.createDiv({ cls: 'tree-item nav-file' }); const navFile = childrenEl.createDiv({ cls: 'tree-item nav-file' });
const navFileTitle = navFile.createDiv({ cls: 'tree-item-self is-clickable nav-file-title' }); const navFileTitle = navFile.createDiv({ cls: 'tree-item-self is-clickable nav-file-title' });
if (reserveIcon) {
const iconEl = navFileTitle.createDiv({ cls: 'waypoint-recent-icon' });
const icon = typeIcons.get(typeOf(file.path) ?? '');
if (icon) setIcon(iconEl, icon);
}
const navFileTitleContent = navFileTitle.createDiv({ cls: 'tree-item-inner nav-file-title-content' }); const navFileTitleContent = navFileTitle.createDiv({ cls: 'tree-item-inner nav-file-title-content' });
navFileTitleContent.setText(file.basename); navFileTitleContent.setText(file.basename);
const spacer = navFileTitle.createDiv({ cls: 'tree-item-spacer' }); navFileTitle.createDiv({ cls: 'tree-item-spacer' });
if (file.changedInBackground) {
const changedEl = navFileTitle.createDiv({ cls: 'waypoint-recent-changed' });
setTooltip(changedEl, 'Changed in the background');
}
// Remove button // Remove button
const removeBtn = navFileTitle.createDiv({ cls: 'waypoint-recent-remove' }); const removeBtn = navFileTitle.createDiv({ cls: 'waypoint-recent-remove' });
@@ -317,8 +503,9 @@ export class WaypointView extends ItemView {
navFileTitle.addEventListener('dragstart', (event: DragEvent) => { navFileTitle.addEventListener('dragstart', (event: DragEvent) => {
const tfile = this.app.metadataCache.getFirstLinkpathDest(file.path, ''); const tfile = this.app.metadataCache.getFirstLinkpathDest(file.path, '');
if (tfile) { if (tfile) {
(this.app as any).dragManager.dragFile(event, tfile); const dragManager = getDragManager(this.app);
(this.app as any).dragManager.onDragStart(event, (this.app as any).dragManager.dragFile(event, tfile)); const draggable = dragManager.dragFile(event, tfile);
dragManager.onDragStart(event, draggable);
} }
}); });
@@ -376,10 +563,10 @@ export class WaypointView extends ItemView {
} }
} }
private focusFile(file: { path: string; basename: string }, newLeaf: boolean | string | 'split'): void { private focusFile(file: { path: string; basename: string }, newLeaf: PaneType | boolean): void {
const targetFile = this.app.vault.getFiles().find(f => f.path === file.path); const targetFile = this.app.vault.getFiles().find(f => f.path === file.path);
if (targetFile) { if (targetFile) {
const leaf = this.app.workspace.getLeaf(newLeaf as any); const leaf = this.app.workspace.getLeaf(newLeaf);
leaf.openFile(targetFile); leaf.openFile(targetFile);
} else { } else {
new Notice('Cannot find file'); new Notice('Cannot find file');
@@ -393,8 +580,8 @@ export class WaypointView extends ItemView {
// Favorites panel // Favorites panel
// ════════════════════════════════════════ // ════════════════════════════════════════
private renderFavorites(): void { private renderFavorites(parent: HTMLElement): void {
const section = this.contentEl.createDiv({ cls: 'waypoint-section waypoint-favorites' }); const section = parent.createDiv({ cls: 'waypoint-section waypoint-favorites' });
const headerEl = section.createDiv({ cls: 'waypoint-section-header' }); const headerEl = section.createDiv({ cls: 'waypoint-section-header' });
headerEl.setText('Waypoint Bookmarks'); headerEl.setText('Waypoint Bookmarks');
@@ -477,45 +664,7 @@ export class WaypointView extends ItemView {
rowEl.style.cursor = 'grab'; rowEl.style.cursor = 'grab';
// Drag events // Drag events
rowEl.addEventListener('dragstart', (e) => { this.attachBookmarkDragHandlers(rowEl, container, item, false);
this.dragId = item.id;
e.dataTransfer!.effectAllowed = 'move';
e.dataTransfer!.setData('text/plain', item.id);
rowEl.addClass('waypoint-bm-dragging');
});
rowEl.addEventListener('dragend', () => {
this.dragId = null;
container.querySelectorAll('.waypoint-bm-dragging, .waypoint-bm-drop-line, .waypoint-bm-drop-below, .waypoint-bm-drop-into').forEach(el => {
el.removeClass('waypoint-bm-dragging');
el.removeClass('waypoint-bm-drop-line');
el.removeClass('waypoint-bm-drop-below');
});
});
rowEl.addEventListener('dragenter', (e) => {
e.preventDefault();
if (!this.dragId || this.dragId === item.id) return;
this.showDropIndicator(rowEl, e, false);
});
rowEl.addEventListener('dragover', (e) => {
e.preventDefault();
if (!this.dragId || this.dragId === item.id) return;
this.showDropIndicator(rowEl, e, false);
});
rowEl.addEventListener('dragleave', () => {
rowEl.removeClass('waypoint-bm-drop-line');
rowEl.removeClass('waypoint-bm-drop-below');
rowEl.removeClass('waypoint-bm-drop-into');
});
rowEl.addEventListener('drop', (e) => {
e.preventDefault();
this.dragId = null;
rowEl.removeClass('waypoint-bm-drop-line');
rowEl.removeClass('waypoint-bm-drop-below');
const draggedId = e.dataTransfer?.getData('text/plain');
if (!draggedId || draggedId === item.id) return;
const dropAbove = (rowEl as any).__dropAbove;
this.moveBookmarkToPosition(draggedId, item.id, dropAbove);
});
// Context menu // Context menu
rowEl.addEventListener('contextmenu', (event: MouseEvent) => { rowEl.addEventListener('contextmenu', (event: MouseEvent) => {
@@ -536,45 +685,7 @@ export class WaypointView extends ItemView {
rowEl.style.cursor = 'grab'; rowEl.style.cursor = 'grab';
// Drag events // Drag events
rowEl.addEventListener('dragstart', (e) => { this.attachBookmarkDragHandlers(rowEl, container, item, false);
this.dragId = item.id;
e.dataTransfer!.effectAllowed = 'move';
e.dataTransfer!.setData('text/plain', item.id);
rowEl.addClass('waypoint-bm-dragging');
});
rowEl.addEventListener('dragend', () => {
this.dragId = null;
container.querySelectorAll('.waypoint-bm-dragging, .waypoint-bm-drop-line, .waypoint-bm-drop-below, .waypoint-bm-drop-into').forEach(el => {
el.removeClass('waypoint-bm-dragging');
el.removeClass('waypoint-bm-drop-line');
el.removeClass('waypoint-bm-drop-below');
});
});
rowEl.addEventListener('dragenter', (e) => {
e.preventDefault();
if (!this.dragId || this.dragId === item.id) return;
this.showDropIndicator(rowEl, e, false);
});
rowEl.addEventListener('dragover', (e) => {
e.preventDefault();
if (!this.dragId || this.dragId === item.id) return;
this.showDropIndicator(rowEl, e, false);
});
rowEl.addEventListener('dragleave', () => {
rowEl.removeClass('waypoint-bm-drop-line');
rowEl.removeClass('waypoint-bm-drop-below');
rowEl.removeClass('waypoint-bm-drop-into');
});
rowEl.addEventListener('drop', (e) => {
e.preventDefault();
this.dragId = null;
rowEl.removeClass('waypoint-bm-drop-line');
rowEl.removeClass('waypoint-bm-drop-below');
const draggedId = e.dataTransfer?.getData('text/plain');
if (!draggedId || draggedId === item.id) return;
const dropAbove = (rowEl as any).__dropAbove;
this.moveBookmarkToPosition(draggedId, item.id, dropAbove);
});
// Context menu // Context menu
rowEl.addEventListener('contextmenu', (event: MouseEvent) => { rowEl.addEventListener('contextmenu', (event: MouseEvent) => {
@@ -597,65 +708,7 @@ export class WaypointView extends ItemView {
} }
// ── Drag events ── // ── Drag events ──
rowEl.addEventListener('dragstart', (e) => { this.attachBookmarkDragHandlers(rowEl, container, item, true);
this.dragId = item.id;
e.dataTransfer!.effectAllowed = 'move';
e.dataTransfer!.setData('text/plain', item.id);
rowEl.addClass('waypoint-bm-dragging');
});
const canAcceptChildren = true; // all file/group bookmarks can accept drops
rowEl.addEventListener('dragend', () => {
this.dragId = null;
container.querySelectorAll('.waypoint-bm-dragging, .waypoint-bm-drop-line, .waypoint-bm-drop-below, .waypoint-bm-drop-into').forEach(el => {
el.removeClass('waypoint-bm-dragging');
el.removeClass('waypoint-bm-drop-line');
el.removeClass('waypoint-bm-drop-below');
el.removeClass('waypoint-bm-drop-into');
});
});
rowEl.addEventListener('dragenter', (e) => {
e.preventDefault();
if (!this.dragId || this.dragId === item.id) return;
this.showDropIndicator(rowEl, e, canAcceptChildren);
});
rowEl.addEventListener('dragover', (e) => {
e.preventDefault();
if (!this.dragId || this.dragId === item.id) return;
this.showDropIndicator(rowEl, e, canAcceptChildren);
});
rowEl.addEventListener('dragleave', () => {
rowEl.removeClass('waypoint-bm-drop-line');
rowEl.removeClass('waypoint-bm-drop-below');
rowEl.removeClass('waypoint-bm-drop-into');
});
rowEl.addEventListener('drop', (e) => {
e.preventDefault();
this.dragId = null;
rowEl.removeClass('waypoint-bm-drop-line');
rowEl.removeClass('waypoint-bm-drop-below');
rowEl.removeClass('waypoint-bm-drop-into');
const draggedId = e.dataTransfer?.getData('text/plain');
if (!draggedId || draggedId === item.id) return;
const dropInto = (rowEl as any).__dropInto;
if (dropInto && canAcceptChildren) {
if (isGroup) {
this.moveBookmarkToGroup(draggedId, item.id);
} else {
this.createParentNoteAndMove(draggedId, item.id);
}
} else {
const dropAbove = (rowEl as any).__dropAbove;
this.moveBookmarkToPosition(draggedId, item.id, dropAbove);
}
});
// ── Group: chevron + icon + label ── // ── Group: chevron + icon + label ──
if (isGroup) { if (isGroup) {
@@ -677,7 +730,7 @@ export class WaypointView extends ItemView {
const tfile = this.app.vault.getFileByPath(item.filePath); const tfile = this.app.vault.getFileByPath(item.filePath);
if (tfile) { if (tfile) {
const newLeaf = Keymap.isModEvent(event); const newLeaf = Keymap.isModEvent(event);
this.app.workspace.getLeaf(newLeaf as any).openFile(tfile); this.app.workspace.getLeaf(newLeaf).openFile(tfile);
return; return;
} }
} }
@@ -729,7 +782,7 @@ export class WaypointView extends ItemView {
const tfile = this.app.vault.getFileByPath(item.filePath); const tfile = this.app.vault.getFileByPath(item.filePath);
if (tfile) { if (tfile) {
const newLeaf = Keymap.isModEvent(event); const newLeaf = Keymap.isModEvent(event);
this.app.workspace.getLeaf(newLeaf as any).openFile(tfile); this.app.workspace.getLeaf(newLeaf).openFile(tfile);
} else { } else {
new Notice('File not found'); new Notice('File not found');
this.plugin.removeBookmark(item.id); this.plugin.removeBookmark(item.id);
@@ -913,6 +966,75 @@ export class WaypointView extends ItemView {
menu.showAtPosition({ x: event.clientX, y: event.clientY }); menu.showAtPosition({ x: event.clientX, y: event.clientY });
} }
/**
* Attach the shared bookmark drag-and-drop listeners to a row element.
* `canAcceptChildren` selects 3-zone (above/into/below) drop targeting for
* file and group rows; separators and spacers use 2-zone (above/below).
*/
private attachBookmarkDragHandlers(
rowEl: HTMLElement,
container: HTMLElement,
item: BookmarkItem,
canAcceptChildren: boolean,
): void {
const clearIndicators = (): void => {
rowEl.removeClass('waypoint-bm-drop-line');
rowEl.removeClass('waypoint-bm-drop-below');
rowEl.removeClass('waypoint-bm-drop-into');
};
rowEl.addEventListener('dragstart', (e) => {
this.dragId = item.id;
e.dataTransfer!.effectAllowed = 'move';
e.dataTransfer!.setData('text/plain', item.id);
rowEl.addClass('waypoint-bm-dragging');
});
rowEl.addEventListener('dragend', () => {
this.dragId = null;
container.querySelectorAll('.waypoint-bm-dragging, .waypoint-bm-drop-line, .waypoint-bm-drop-below, .waypoint-bm-drop-into').forEach(el => {
el.removeClass('waypoint-bm-dragging');
el.removeClass('waypoint-bm-drop-line');
el.removeClass('waypoint-bm-drop-below');
el.removeClass('waypoint-bm-drop-into');
});
});
rowEl.addEventListener('dragenter', (e) => {
e.preventDefault();
if (!this.dragId || this.dragId === item.id) return;
this.showDropIndicator(rowEl, e, canAcceptChildren);
});
rowEl.addEventListener('dragover', (e) => {
e.preventDefault();
if (!this.dragId || this.dragId === item.id) return;
this.showDropIndicator(rowEl, e, canAcceptChildren);
});
rowEl.addEventListener('dragleave', clearIndicators);
rowEl.addEventListener('drop', (e) => {
e.preventDefault();
this.dragId = null;
clearIndicators();
const draggedId = e.dataTransfer?.getData('text/plain');
if (!draggedId || draggedId === item.id) return;
const zone = this.dropZones.get(rowEl);
if (canAcceptChildren && zone?.into) {
if (item.type === 'group') {
this.moveBookmarkToGroup(draggedId, item.id);
} else {
this.createParentNoteAndMove(draggedId, item.id);
}
} else {
this.moveBookmarkToPosition(draggedId, item.id, zone?.above ?? false);
}
});
}
private showDropIndicator(el: HTMLElement, e: MouseEvent, isGroupLike: boolean): void { private showDropIndicator(el: HTMLElement, e: MouseEvent, isGroupLike: boolean): void {
// Clear all indicators // Clear all indicators
const parent = el.parentElement; const parent = el.parentElement;
@@ -934,25 +1056,21 @@ export class WaypointView extends ItemView {
if (y < topThreshold) { if (y < topThreshold) {
el.addClass('waypoint-bm-drop-line'); el.addClass('waypoint-bm-drop-line');
(el as any).__dropAbove = true; this.dropZones.set(el, { above: true, into: false });
(el as any).__dropInto = false;
} else if (y > bottomThreshold) { } else if (y > bottomThreshold) {
el.addClass('waypoint-bm-drop-line'); el.addClass('waypoint-bm-drop-line');
el.addClass('waypoint-bm-drop-below'); el.addClass('waypoint-bm-drop-below');
(el as any).__dropAbove = false; this.dropZones.set(el, { above: false, into: false });
(el as any).__dropInto = false;
} else { } else {
el.addClass('waypoint-bm-drop-into'); el.addClass('waypoint-bm-drop-into');
(el as any).__dropAbove = false; this.dropZones.set(el, { above: false, into: true });
(el as any).__dropInto = true;
} }
} else { } else {
// 2-zone: top half = above, bottom half = below // 2-zone: top half = above, bottom half = below
const above = y < rect.top + rect.height / 2; const above = y < rect.top + rect.height / 2;
el.addClass('waypoint-bm-drop-line'); el.addClass('waypoint-bm-drop-line');
if (!above) el.addClass('waypoint-bm-drop-below'); if (!above) el.addClass('waypoint-bm-drop-below');
(el as any).__dropAbove = above; this.dropZones.set(el, { above, into: false });
(el as any).__dropInto = false;
} }
} }
@@ -1099,7 +1217,7 @@ export class WaypointView extends ItemView {
} }
private promptRename(item: BookmarkItem): void { private promptRename(item: BookmarkItem): void {
new RenameModal(this.app, item.label, (newLabel) => { new PromptModal(this.app, { title: 'Rename bookmark', initialValue: item.label }, (newLabel) => {
if (newLabel && newLabel.trim()) { if (newLabel && newLabel.trim()) {
this.plugin.updateBookmark(item.id, { label: newLabel.trim() }); this.plugin.updateBookmark(item.id, { label: newLabel.trim() });
} }
@@ -1108,31 +1226,40 @@ export class WaypointView extends ItemView {
private promptIcon(item: BookmarkItem): void { private promptIcon(item: BookmarkItem): void {
new IconSuggestModal(this.app, item.icon, (iconName) => { new IconSuggestModal(this.app, item.icon, (iconName) => {
if (iconName) { // An empty string is a valid value meaning "no icon", so always apply.
this.plugin.updateBookmark(item.id, { icon: iconName }); this.plugin.updateBookmark(item.id, { icon: iconName });
}
}).open(); }).open();
} }
} }
// ── Rename modal ── // ── Text prompt modal ──
class RenameModal extends Modal { interface PromptModalOptions {
private currentValue: string; title: string;
placeholder?: string;
initialValue?: string;
/** Submit button label. Defaults to 'Save'. */
cta?: string;
}
/** Single-line text prompt, shared by bookmark renaming and note creation. */
class PromptModal extends Modal {
private options: PromptModalOptions;
private onSubmit: (value: string) => void; private onSubmit: (value: string) => void;
constructor(app: App, currentValue: string, onSubmit: (value: string) => void) { constructor(app: App, options: PromptModalOptions, onSubmit: (value: string) => void) {
super(app); super(app);
this.currentValue = currentValue; this.options = options;
this.onSubmit = onSubmit; this.onSubmit = onSubmit;
} }
onOpen(): void { onOpen(): void {
this.titleEl.setText('Rename bookmark'); this.titleEl.setText(this.options.title);
const input = this.contentEl.createEl('input', { const input = this.contentEl.createEl('input', {
type: 'text', type: 'text',
value: this.currentValue, value: this.options.initialValue ?? '',
placeholder: this.options.placeholder ?? '',
}); });
input.style.width = '100%'; input.style.width = '100%';
input.style.marginBottom = '12px'; input.style.marginBottom = '12px';
@@ -1145,7 +1272,7 @@ class RenameModal extends Modal {
cancelBtn.style.marginRight = '8px'; cancelBtn.style.marginRight = '8px';
cancelBtn.addEventListener('click', () => this.close()); cancelBtn.addEventListener('click', () => this.close());
const saveBtn = btnContainer.createEl('button', { text: 'Save', cls: 'mod-cta' }); const saveBtn = btnContainer.createEl('button', { text: this.options.cta ?? 'Save', cls: 'mod-cta' });
saveBtn.addEventListener('click', () => { saveBtn.addEventListener('click', () => {
this.onSubmit(input.value); this.onSubmit(input.value);
this.close(); this.close();
@@ -1166,7 +1293,32 @@ class RenameModal extends Modal {
// ── Icon picker modal (full Lucide icon set, grid layout) ── // ── Icon picker modal (full Lucide icon set, grid layout) ──
class IconSuggestModal extends Modal { // Lucide icon metadata, fetched at most once per session and shared by every
// picker. Concurrent opens await the same in-flight promise; a failed fetch is
// not cached, so a later open retries once the network is back.
let iconCatalog: Promise<Record<string, string[]>> | null = null;
function loadIconCatalog(): Promise<Record<string, string[]>> {
if (!iconCatalog) {
iconCatalog = (async () => {
try {
const res = await fetch('https://cdn.jsdelivr.net/npm/lucide-static@0.517.0/tags.json');
return (await res.json()) as Record<string, string[]>;
} catch {
try {
const res = await fetch('https://lucide.dev/api/tags');
return (await res.json()) as Record<string, string[]>;
} catch {
iconCatalog = null;
return FALLBACK_ICONS;
}
}
})();
}
return iconCatalog;
}
export class IconSuggestModal extends Modal {
private onSubmit: (icon: string) => void; private onSubmit: (icon: string) => void;
private selected: string; private selected: string;
private allIcons: string[] = []; private allIcons: string[] = [];
@@ -1241,15 +1393,6 @@ class IconSuggestModal extends Modal {
const statusEl = statusRow.createSpan(); const statusEl = statusRow.createSpan();
statusEl.setText('Loading\u2026'); statusEl.setText('Loading\u2026');
const clearEl = statusRow.createSpan();
clearEl.style.cursor = 'var(--cursor)';
clearEl.style.color = 'var(--text-accent)';
clearEl.setText('No icon');
clearEl.addEventListener('click', () => {
this.onSubmit('');
this.close();
});
// ── Load icons ── // ── Load icons ──
this.loadIcons().then(() => { this.loadIcons().then(() => {
this.loaded = true; this.loaded = true;
@@ -1258,7 +1401,7 @@ class IconSuggestModal extends Modal {
}); });
// ── Render grid ── // ── Render grid ──
let debounce: any = null; let debounce: number | undefined;
const renderGrid = (query: string) => { const renderGrid = (query: string) => {
grid.empty(); grid.empty();
@@ -1284,16 +1427,15 @@ class IconSuggestModal extends Modal {
return; return;
} }
for (var i = 0; i < matches.length; i++) { for (const name of matches) {
var name = matches[i]; const tile = grid.createDiv();
var tile = grid.createDiv();
tile.setAttr('data-icon', name); tile.setAttr('data-icon', name);
tile.style.display = 'flex'; tile.style.display = 'flex';
tile.style.alignItems = 'center'; tile.style.alignItems = 'center';
tile.style.justifyContent = 'center'; tile.style.justifyContent = 'center';
tile.style.aspectRatio = '1'; tile.style.aspectRatio = '1';
tile.style.borderRadius = '6px'; tile.style.borderRadius = '6px';
tile.style.cursor = 'var(--cursor)'; tile.style.cursor = 'var(--cursor-link, pointer)';
tile.style.transition = 'background 80ms'; tile.style.transition = 'background 80ms';
tile.setAttr('title', name); tile.setAttr('title', name);
@@ -1304,27 +1446,26 @@ class IconSuggestModal extends Modal {
tile.style.color = 'var(--text-muted)'; tile.style.color = 'var(--text-muted)';
} }
var svg = tile.createSpan(); const svg = tile.createSpan();
svg.style.display = 'flex'; svg.style.display = 'flex';
setIcon(svg, name); setIcon(svg, name);
;(function(_self, _tile, _name, _query, _grid, _previewIcon, _previewLabel) { tile.addEventListener('mouseenter', () => {
_tile.addEventListener('mouseenter', function() { if (name !== this.selected) tile.style.background = 'var(--background-modifier-hover)';
if (_name !== _self.selected) _tile.style.background = 'var(--background-modifier-hover)';
}); });
_tile.addEventListener('mouseleave', function() { tile.addEventListener('mouseleave', () => {
if (_name !== _self.selected) _tile.style.background = ''; if (name !== this.selected) tile.style.background = '';
}); });
_tile.addEventListener('click', function() { tile.addEventListener('click', () => {
_self.selected = _name; this.selected = name;
renderGrid(_query); renderGrid(query);
_previewIcon.empty(); previewIcon.empty();
setIcon(_previewIcon, _name); setIcon(previewIcon, name);
_previewLabel.setText(_name); previewLabel.setText(name);
_grid.querySelectorAll('div[data-icon]').forEach(function(_el) { grid.querySelectorAll('div[data-icon]').forEach((node) => {
var el = _el as HTMLElement; const el = node as HTMLElement;
if (el.getAttr('data-icon') === _name) { if (el.getAttr('data-icon') === name) {
el.style.background = 'var(--interactive-accent)'; el.style.background = 'var(--interactive-accent)';
el.style.color = 'var(--text-on-accent)'; el.style.color = 'var(--text-on-accent)';
} else { } else {
@@ -1333,31 +1474,39 @@ class IconSuggestModal extends Modal {
} }
}); });
}); });
})(this, tile, name, query, grid, previewIcon, previewLabel);
} }
statusEl.setText(matches.length + ' of ' + this.allIcons.length + ' icons'); statusEl.setText(matches.length + ' of ' + this.allIcons.length + ' icons');
}; };
input.addEventListener('input', function() { input.addEventListener('input', () => {
if (debounce !== null) clearTimeout(debounce); window.clearTimeout(debounce);
debounce = setTimeout(function() { renderGrid(input.value); }, 60); debounce = window.setTimeout(() => renderGrid(input.value), 60);
}); });
input.addEventListener('keydown', function(e: KeyboardEvent) { input.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.key === 'Escape') this.close(); if (e.key === 'Escape') this.close();
}.bind(this)); });
// ── Buttons ── // ── Buttons ──
var btns = modal.createDiv({ cls: 'modal-button-container' }); const btns = modal.createDiv({ cls: 'modal-button-container' });
var cancel = btns.createEl('button', { text: 'Cancel' });
cancel.addEventListener('click', function() { this.close(); }.bind(this)); // Clearing the icon commits a value and closes, exactly like Save, so it
var saveBtn = btns.createEl('button', { text: 'Save', cls: 'mod-cta' }); // belongs with the buttons rather than as a bare span in the status row.
const clearBtn = btns.createEl('button', { text: 'No icon', cls: 'waypoint-icon-clear' });
clearBtn.addEventListener('click', () => {
this.onSubmit('');
this.close();
});
const cancel = btns.createEl('button', { text: 'Cancel' });
cancel.addEventListener('click', () => this.close());
const saveBtn = btns.createEl('button', { text: 'Save', cls: 'mod-cta' });
saveBtn.style.marginLeft = '8px'; saveBtn.style.marginLeft = '8px';
saveBtn.addEventListener('click', function() { saveBtn.addEventListener('click', () => {
this.onSubmit(this.selected); this.onSubmit(this.selected);
this.close(); this.close();
}.bind(this)); });
} }
onClose(): void { onClose(): void {
@@ -1365,22 +1514,9 @@ class IconSuggestModal extends Modal {
} }
private async loadIcons(): Promise<void> { private async loadIcons(): Promise<void> {
try { const catalog = await loadIconCatalog();
var r = await fetch('https://cdn.jsdelivr.net/npm/lucide-static@0.517.0/tags.json'); this.tagsMap = catalog;
var d = await r.json(); this.allIcons = Object.keys(catalog).sort();
this.tagsMap = d as Record<string, string[]>;
this.allIcons = Object.keys(d).sort();
} catch (_e) {
try {
var r2 = await fetch('https://lucide.dev/api/tags');
var d2 = await r2.json();
this.tagsMap = d2 as Record<string, string[]>;
this.allIcons = Object.keys(d2).sort();
} catch (_e2) {
this.tagsMap = {};
this.allIcons = Object.keys(FALLBACK_ICONS).sort();
}
}
} }
} }
+227 -30
View File
@@ -13,7 +13,7 @@
flex-shrink: 0; flex-shrink: 0;
} }
.waypoint-view .waypoint-section:last-child { .waypoint-view .waypoint-calendar-section {
margin-top: auto; margin-top: auto;
margin-bottom: 0; margin-bottom: 0;
} }
@@ -36,7 +36,7 @@
margin-left: auto; margin-left: auto;
background: none; background: none;
border: none; border: none;
cursor: var(--cursor); cursor: var(--cursor-link, pointer);
color: var(--text-faint); color: var(--text-faint);
padding: 2px 4px; padding: 2px 4px;
border-radius: 4px; border-radius: 4px;
@@ -58,29 +58,34 @@
.waypoint-calendar { .waypoint-calendar {
font-size: var(--font-ui-small); font-size: var(--font-ui-small);
padding: 8px;
border: 1px solid var(--background-modifier-border);
border-radius: 10px;
background: var(--background-primary-alt);
} }
.waypoint-calendar-top { .waypoint-calendar-top {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
margin-bottom: 10px; margin-bottom: 8px;
} }
.waypoint-calendar-breadcrumb { .waypoint-calendar-breadcrumb {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 6px; gap: 4px;
font-size: var(--font-ui-medium); font-size: var(--font-ui-medium);
font-weight: var(--font-semibold); font-weight: var(--font-semibold);
padding: 4px 0; padding: 2px 0;
} }
.waypoint-calendar-breadcrumb .waypoint-clickable { .waypoint-calendar-breadcrumb .waypoint-clickable {
color: var(--text-muted); color: var(--text-muted);
cursor: var(--cursor); cursor: var(--cursor-link, pointer);
padding: 1px 4px; padding: 2px 4px;
border-radius: 4px; border-radius: 4px;
transition: color 80ms, background-color 80ms;
} }
.waypoint-calendar-breadcrumb .waypoint-clickable:hover { .waypoint-calendar-breadcrumb .waypoint-clickable:hover {
@@ -90,23 +95,39 @@
.waypoint-calendar .waypoint-separator { .waypoint-calendar .waypoint-separator {
color: var(--text-faint); color: var(--text-faint);
margin: 0 2px; margin: 0;
} }
.waypoint-calendar-today-group { .waypoint-calendar-today-group {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 2px; gap: 1px;
position: relative;
}
/* Anchors the native picker under the date button without taking space. */
.waypoint-calendar-today-group .waypoint-calendar-pick-input {
position: absolute;
right: 0;
bottom: 0;
width: 1px;
height: 1px;
padding: 0;
border: 0;
opacity: 0;
pointer-events: none;
} }
.waypoint-calendar-today-group button { .waypoint-calendar-today-group button {
background: none; background: none;
border: none; border: none;
cursor: var(--cursor); cursor: var(--cursor-link, pointer);
padding: 2px 6px; padding: 2px 5px;
border-radius: 4px; border-radius: 4px;
color: var(--text-muted); color: var(--text-muted);
font-size: var(--font-ui-small); font-size: var(--font-ui-small);
transition: color 80ms, background-color 80ms;
box-shadow: none;
} }
.waypoint-calendar-today-group button:hover { .waypoint-calendar-today-group button:hover {
@@ -121,30 +142,34 @@
.waypoint-calendar table { .waypoint-calendar table {
table-layout: fixed; table-layout: fixed;
width: 100%; width: 100%;
border-collapse: collapse; border-collapse: separate;
border-spacing: 2px 3px;
} }
.waypoint-calendar th, .waypoint-calendar th,
.waypoint-calendar td { .waypoint-calendar td {
text-align: center; text-align: center;
padding: 4px 2px; padding: 0;
font-size: var(--font-ui-small); font-size: var(--font-ui-small);
line-height: 1.6;
} }
.waypoint-calendar th { .waypoint-calendar th {
padding-bottom: 2px;
font-weight: var(--font-medium); font-weight: var(--font-medium);
color: var(--text-faint); color: var(--text-faint);
font-size: calc(var(--font-ui-small) * 0.85); font-size: calc(var(--font-ui-small) * 0.78);
letter-spacing: 0.04em;
text-transform: uppercase;
} }
.waypoint-calendar .waypoint-weeknum { .waypoint-calendar .waypoint-weeknum {
font-size: calc(var(--font-ui-small) * 0.75); width: 18px;
font-size: calc(var(--font-ui-small) * 0.72);
color: var(--text-faint); color: var(--text-faint);
font-weight: var(--font-light); font-weight: var(--font-light);
cursor: var(--cursor); cursor: var(--cursor-link, pointer);
padding: 2px 0;
border-radius: 4px; border-radius: 4px;
transition: color 80ms, background-color 80ms;
} }
.waypoint-calendar .waypoint-weeknum:hover { .waypoint-calendar .waypoint-weeknum:hover {
@@ -153,42 +178,106 @@
} }
.waypoint-calendar .waypoint-day { .waypoint-calendar .waypoint-day {
cursor: var(--cursor); cursor: var(--cursor-link, pointer);
min-height: var(--wp-cal-cell-size, 32px); height: var(--wp-cal-cell-size, 32px);
padding: 2px 0; box-sizing: border-box;
padding: 2px 0 7px;
border-radius: 6px; border-radius: 6px;
position: relative; position: relative;
width: 100%; width: 100%;
vertical-align: middle; vertical-align: middle;
transition: color 80ms, background-color 80ms, box-shadow 80ms;
} }
.waypoint-calendar .waypoint-day:hover { .waypoint-calendar .waypoint-day:hover {
background-color: var(--background-modifier-active-hover); background-color: var(--background-modifier-hover);
} }
.waypoint-calendar .waypoint-day.other-month { .waypoint-calendar .waypoint-day.other-month {
opacity: 0.35; color: var(--text-faint);
opacity: 0.5;
} }
.waypoint-calendar .waypoint-day.today { .waypoint-calendar .waypoint-day.today {
color: var(--text-accent); color: var(--text-accent);
border: 1px solid var(--text-accent);
font-weight: var(--font-semibold); font-weight: var(--font-semibold);
box-shadow: inset 0 0 0 1px var(--text-accent);
} }
.waypoint-calendar .waypoint-day.today:hover {
background-color: var(--background-modifier-active-hover);
}
/* Day jumped to with the date picker or the "Open date" command. */
.waypoint-calendar .waypoint-day.is-selected {
color: var(--text-on-accent);
background-color: var(--interactive-accent);
}
.waypoint-calendar .waypoint-day.is-selected:hover {
background-color: var(--interactive-accent-hover);
}
/* Lists wrap only so mobile can scroll them apart from the calendar. */
.waypoint-lists {
display: contents;
}
/* Mobile drawer: the whole calendar stays on screen; the lists scroll above it. */
.is-mobile .waypoint-view {
overflow-y: hidden;
}
.is-mobile .waypoint-view .waypoint-lists {
display: block;
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
margin-bottom: 8px;
}
/* Mobile's wide default buttons push the date button out of the calendar. */
.is-mobile .waypoint-calendar-today-group button {
width: auto;
padding: 4px 8px;
}
/* Single-dot mode preserves the pre-date-systems indicator. */
.waypoint-calendar .waypoint-day.has-note::after { .waypoint-calendar .waypoint-day.has-note::after {
content: ''; content: '';
display: block; position: absolute;
left: 50%;
bottom: 3px;
width: 4px; width: 4px;
height: 4px; height: 4px;
border-radius: 50%; border-radius: 50%;
background-color: var(--text-faint); background-color: var(--text-faint);
margin: 0 auto; transform: translateX(-50%);
} }
.waypoint-calendar .waypoint-day.today.has-note::after { .waypoint-calendar .waypoint-day.today.has-note::after {
background-color: var(--text-accent); background-color: var(--text-accent);
} }
/* Colour-by-system mode: one dot per matching system, in Settings order. */
.waypoint-day-indicators {
position: absolute;
right: 0;
bottom: 3px;
left: 0;
display: flex;
justify-content: center;
gap: 3px;
}
.waypoint-day-indicator {
width: 5px;
height: 5px;
border-radius: 50%;
background-color: var(--waypoint-indicator-color);
box-shadow: 0 0 0 1px var(--background-primary);
}
/* ── Recent Files ── */ /* ── Recent Files ── */
.waypoint-recent-filter { .waypoint-recent-filter {
@@ -204,7 +293,7 @@
background: var(--background-modifier-hover); background: var(--background-modifier-hover);
padding: 1px 6px; padding: 1px 6px;
border-radius: 10px; border-radius: 10px;
cursor: var(--cursor); cursor: var(--cursor-link, pointer);
transition: color 80ms, background 80ms; transition: color 80ms, background 80ms;
user-select: none; user-select: none;
} }
@@ -227,6 +316,8 @@
padding: 2px 28px 2px 4px; padding: 2px 28px 2px 4px;
font-size: var(--font-ui-small); font-size: var(--font-ui-small);
position: relative; position: relative;
/* Obsidian's baseline alignment puts the type icon above the text's centre. */
align-items: center;
} }
.waypoint-recent-files .waypoint-recent-remove { .waypoint-recent-files .waypoint-recent-remove {
@@ -235,7 +326,7 @@
top: 50%; top: 50%;
transform: translateY(-50%); transform: translateY(-50%);
opacity: 0; opacity: 0;
cursor: var(--cursor); cursor: var(--cursor-link, pointer);
color: var(--text-faint); color: var(--text-faint);
display: flex; display: flex;
align-items: center; align-items: center;
@@ -253,6 +344,64 @@
color: var(--text-accent); color: var(--text-accent);
} }
/* Header switch: all / opened / changed. */
.waypoint-recent-show {
margin-left: auto;
display: flex;
gap: 2px;
text-transform: none;
letter-spacing: normal;
font-weight: var(--font-normal);
}
.waypoint-recent-show-option {
font-size: var(--font-ui-smaller);
color: var(--text-faint);
padding: 0 6px;
border-radius: 10px;
cursor: var(--cursor-link, pointer);
user-select: none;
transition: color 80ms, background 80ms;
}
.waypoint-recent-show-option:hover {
color: var(--text-normal);
background: var(--background-modifier-hover);
}
.waypoint-recent-show-option.is-active {
color: var(--text-normal);
background: var(--background-modifier-active-hover);
}
/* Icon of the file's configured frontmatter type; empty slots keep names aligned. */
.waypoint-recent-files .waypoint-recent-icon {
flex-shrink: 0;
display: flex;
align-items: center;
width: 16px;
/* Same box with or without an icon, and shorter than a text line, so rows keep one height. */
height: 14px;
margin-right: 6px;
color: var(--text-muted);
transform: translateY(-2px);
}
.waypoint-recent-files .waypoint-recent-icon svg {
width: 14px;
height: 14px;
}
/* Changed in the background (sync, another plugin) since last opened. */
.waypoint-recent-files .waypoint-recent-changed {
flex-shrink: 0;
width: 6px;
height: 6px;
margin-left: 6px;
border-radius: 50%;
background-color: var(--interactive-accent);
}
/* ── Favorites ── */ /* ── Favorites ── */
.waypoint-favorites .waypoint-bookmark-item { .waypoint-favorites .waypoint-bookmark-item {
@@ -262,7 +411,7 @@
padding: 2px 8px 2px 4px; padding: 2px 8px 2px 4px;
font-size: var(--wp-font-size, 13px); font-size: var(--wp-font-size, 13px);
min-height: var(--wp-row-size, 26px); min-height: var(--wp-row-size, 26px);
cursor: var(--cursor); cursor: var(--cursor-link, pointer);
border-radius: 4px; border-radius: 4px;
user-select: none; user-select: none;
position: relative; position: relative;
@@ -309,6 +458,27 @@
display: none; display: none;
} }
[data-type="waypoint-view"] button.waypoint-header-more,
button.waypoint-calendar-nav-btn,
button.waypoint-calendar-today-btn {
background-color: transparent;
box-shadow: none;
}
.waypoint-calendar-breadcrumb {
gap: 4px;
.waypoint-clickable {
padding: 0px;
&:hover {
background-color: transparent;
}
}
}
/* ── Drag-and-drop ── */ /* ── Drag-and-drop ── */
.waypoint-bm-dragging { .waypoint-bm-dragging {
@@ -361,6 +531,7 @@
.waypoint-settings-tabs { .waypoint-settings-tabs {
display: flex; display: flex;
flex-wrap: wrap;
gap: 4px; gap: 4px;
margin-bottom: 20px; margin-bottom: 20px;
border-bottom: 1px solid var(--background-modifier-border); border-bottom: 1px solid var(--background-modifier-border);
@@ -370,7 +541,7 @@
.waypoint-settings-tab { .waypoint-settings-tab {
background: none; background: none;
border: none; border: none;
cursor: var(--cursor); cursor: var(--cursor-link, pointer);
color: var(--text-muted); color: var(--text-muted);
padding: 6px 14px; padding: 6px 14px;
border-radius: 6px 6px 0 0; border-radius: 6px 6px 0 0;
@@ -390,3 +561,29 @@
border-bottom: 2px solid var(--text-accent); border-bottom: 2px solid var(--text-accent);
margin-bottom: -9px; margin-bottom: -9px;
} }
/* Wrapped rows cannot sit on the bar's bottom border, so mobile tabs are pills. */
.is-mobile .waypoint-settings-tab {
border-radius: 6px;
}
.is-mobile .waypoint-settings-tab.is-active {
border-bottom: none;
margin-bottom: 0;
}
/* ── Icon picker ── */
/* Sits left of Cancel/Save so clearing reads as a separate, secondary action. */
.waypoint-icon-clear {
margin-right: auto;
cursor: var(--cursor-link, pointer);
}
/* ── Settings: date systems ── */
.waypoint-settings-warning {
margin-top: 4px;
color: var(--text-error);
font-size: var(--font-ui-smaller);
}
+2 -1
View File
@@ -15,7 +15,8 @@
"DOM", "DOM",
"ES5", "ES5",
"ES6", "ES6",
"ES7" "ES7",
"ES2017"
], ],
"paths": { "paths": {
"src/*": ["./src/*"] "src/*": ["./src/*"]