From e66f089176ddc9110a5bd6e83c6a98f103abff55 Mon Sep 17 00:00:00 2001 From: Knotty Wyvern Date: Thu, 29 Oct 2026 20:54:29 -0700 Subject: [PATCH] Make Project Management a native feature MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Move the storage and model of the plugin into src/lib/features/pm/ as pure TypeScript, so the skill can still bundle them. - Move the DOM interface onto the host menus, the shared tooltip, and the host icons. - A ribbon button opens Project Management. Board tabs keep the owner runestone.pm and the board- view IDs through view patterns. - Read only .runestone/pm/. Offer the plugin migration, with backups, for legacy notes. - A save, move, or delete reads only that card again. Watcher paths reach the feature. - Add Settings → Project Management and the projectManagement section. View states move to localStorage. - Background reads the boards from workspace.json. Remove api.backgrounds and the boards service. - Add yaml 2.9.1. Use the host markdown-it. - Move 18 plugin test files to tests/unit/features/pm/ and add native tests. --- THIRD_PARTY_NOTICES.md | 21 + docs/menu-surfaces.json | 174 +- package.json | 3 +- packages/plugin-sdk/src/api.ts | 2 - packages/plugin-sdk/src/backgrounds.ts | 21 - packages/plugin-sdk/src/features.ts | 3 - packages/plugin-sdk/src/index.ts | 1 - pnpm-lock.yaml | 41 +- scripts/featureChunks.mjs | 2 +- scripts/measure/scenarios.mjs | 14 +- scripts/menuSurfaceAudit.mjs | 2 +- src-tauri/src/features.rs | 5 +- src-tauri/src/preferences.rs | 2 +- .../features/ProjectManagementSettings.svelte | 120 + .../background/BackgroundSettings.svelte | 22 +- src/lib/features/catalog.ts | 33 +- src/lib/features/loader.ts | 1 + src/lib/features/migration.ts | 20 +- src/lib/features/pm/index.ts | 132 + src/lib/features/pm/model/all-tasks.ts | 76 + src/lib/features/pm/model/background.ts | 13 + .../features/pm/model/description-format.ts | 27 + src/lib/features/pm/model/markdown.ts | 31 + src/lib/features/pm/model/model.ts | 249 ++ src/lib/features/pm/model/store.ts | 902 +++++ .../features/pm/model/transient-background.ts | 56 + .../features/pm/model/workspace-default.ts | 21 + src/lib/features/pm/storage/board.ts | 374 ++ src/lib/features/pm/storage/cards.ts | 163 + src/lib/features/pm/storage/catalog.ts | 140 + src/lib/features/pm/storage/deleted-cards.ts | 23 + .../features/pm/storage/description-draft.ts | 33 + src/lib/features/pm/storage/images.ts | 69 + src/lib/features/pm/storage/labels.ts | 141 + src/lib/features/pm/storage/legacy.ts | 78 + src/lib/features/pm/storage/migration.ts | 152 + src/lib/features/pm/storage/notes.ts | 211 ++ src/lib/features/pm/storage/order.ts | 41 + src/lib/features/pm/storage/persistence.ts | 61 + src/lib/features/pm/storage/scan.ts | 82 + src/lib/features/pm/ui/choices-ui.ts | 62 + src/lib/features/pm/ui/colors.ts | 75 + src/lib/features/pm/ui/description-find.ts | 132 + src/lib/features/pm/ui/description-ui.ts | 250 ++ src/lib/features/pm/ui/details-ui.ts | 130 + src/lib/features/pm/ui/host.ts | 56 + src/lib/features/pm/ui/images-ui.ts | 359 ++ src/lib/features/pm/ui/labels-ui.ts | 355 ++ src/lib/features/pm/ui/priority-ui.ts | 47 + src/lib/features/pm/ui/relations-ui.ts | 180 + src/lib/features/pm/ui/style.css | 1829 ++++++++++ src/lib/features/pm/ui/tags.ts | 168 + src/lib/features/pm/ui/ui.ts | 3160 +++++++++++++++++ src/lib/features/pm/views.ts | 21 + src/lib/features/pm/workspace.ts | 27 + src/lib/features/pmBoards.ts | 72 + src/lib/features/pmSettings.ts | 81 + src/lib/features/session.ts | 43 +- src/lib/features/types.ts | 15 +- src/lib/i18n/messages.ts | 3 + src/lib/layout/PluginRibbon.svelte | 9 +- src/lib/layout/SettingsDialog.svelte | 6 +- src/lib/layout/Workbench.svelte | 6 +- src/lib/plugins/backgroundContracts.ts | 16 +- src/lib/plugins/backgrounds.ts | 5 +- src/lib/plugins/external.ts | 51 +- src/lib/plugins/externalSession.ts | 21 +- src/lib/settings/store.ts | 3 +- tests/smoke/_harness/index.mjs | 2 +- tests/smoke/features/pm.smoke.mjs | 160 + tests/smoke/features/settings.smoke.mjs | 4 +- tests/smoke/find/pluginViews.smoke.mjs | 44 +- tests/unit/features/features.spec.ts | 32 +- tests/unit/features/pdf.spec.ts | 2 +- tests/unit/features/pm/_memory.ts | 79 + tests/unit/features/pm/all-tasks.spec.ts | 66 + tests/unit/features/pm/backlog-fixes.spec.ts | 60 + tests/unit/features/pm/board.spec.ts | 237 ++ tests/unit/features/pm/card-details.spec.ts | 75 + tests/unit/features/pm/card-fields.spec.ts | 69 + tests/unit/features/pm/card-workflow.spec.ts | 296 ++ tests/unit/features/pm/core.spec.ts | 198 ++ tests/unit/features/pm/deleted-cards.spec.ts | 63 + .../features/pm/description-format.spec.ts | 31 + tests/unit/features/pm/images.spec.ts | 107 + tests/unit/features/pm/labels.spec.ts | 364 ++ tests/unit/features/pm/legacy-offer.spec.ts | 118 + .../unit/features/pm/multiple-boards.spec.ts | 514 +++ tests/unit/features/pm/native.spec.ts | 187 + tests/unit/features/pm/october-cards.spec.ts | 63 + tests/unit/features/pm/partial-reload.spec.ts | 142 + tests/unit/features/pm/private-cards.spec.ts | 278 ++ .../unit/features/pm/scan-performance.spec.ts | 195 + .../features/pm/storage-migration.spec.ts | 330 ++ tests/unit/features/pm/subtask-cards.spec.ts | 32 + .../features/pm/transient-background.spec.ts | 149 + tests/unit/features/terminal.spec.ts | 14 +- tests/unit/sdk/features.spec.ts | 12 +- tests/unit/settings/migration.spec.ts | 3 +- tests/unit/theme/backgrounds.spec.ts | 32 +- 100 files changed, 14412 insertions(+), 290 deletions(-) delete mode 100644 packages/plugin-sdk/src/backgrounds.ts create mode 100644 src/lib/features/ProjectManagementSettings.svelte create mode 100644 src/lib/features/pm/index.ts create mode 100644 src/lib/features/pm/model/all-tasks.ts create mode 100644 src/lib/features/pm/model/background.ts create mode 100644 src/lib/features/pm/model/description-format.ts create mode 100644 src/lib/features/pm/model/markdown.ts create mode 100644 src/lib/features/pm/model/model.ts create mode 100644 src/lib/features/pm/model/store.ts create mode 100644 src/lib/features/pm/model/transient-background.ts create mode 100644 src/lib/features/pm/model/workspace-default.ts create mode 100644 src/lib/features/pm/storage/board.ts create mode 100644 src/lib/features/pm/storage/cards.ts create mode 100644 src/lib/features/pm/storage/catalog.ts create mode 100644 src/lib/features/pm/storage/deleted-cards.ts create mode 100644 src/lib/features/pm/storage/description-draft.ts create mode 100644 src/lib/features/pm/storage/images.ts create mode 100644 src/lib/features/pm/storage/labels.ts create mode 100644 src/lib/features/pm/storage/legacy.ts create mode 100644 src/lib/features/pm/storage/migration.ts create mode 100644 src/lib/features/pm/storage/notes.ts create mode 100644 src/lib/features/pm/storage/order.ts create mode 100644 src/lib/features/pm/storage/persistence.ts create mode 100644 src/lib/features/pm/storage/scan.ts create mode 100644 src/lib/features/pm/ui/choices-ui.ts create mode 100644 src/lib/features/pm/ui/colors.ts create mode 100644 src/lib/features/pm/ui/description-find.ts create mode 100644 src/lib/features/pm/ui/description-ui.ts create mode 100644 src/lib/features/pm/ui/details-ui.ts create mode 100644 src/lib/features/pm/ui/host.ts create mode 100644 src/lib/features/pm/ui/images-ui.ts create mode 100644 src/lib/features/pm/ui/labels-ui.ts create mode 100644 src/lib/features/pm/ui/priority-ui.ts create mode 100644 src/lib/features/pm/ui/relations-ui.ts create mode 100644 src/lib/features/pm/ui/style.css create mode 100644 src/lib/features/pm/ui/tags.ts create mode 100644 src/lib/features/pm/ui/ui.ts create mode 100644 src/lib/features/pm/views.ts create mode 100644 src/lib/features/pm/workspace.ts create mode 100644 src/lib/features/pmBoards.ts create mode 100644 src/lib/features/pmSettings.ts create mode 100644 tests/smoke/features/pm.smoke.mjs create mode 100644 tests/unit/features/pm/_memory.ts create mode 100644 tests/unit/features/pm/all-tasks.spec.ts create mode 100644 tests/unit/features/pm/backlog-fixes.spec.ts create mode 100644 tests/unit/features/pm/board.spec.ts create mode 100644 tests/unit/features/pm/card-details.spec.ts create mode 100644 tests/unit/features/pm/card-fields.spec.ts create mode 100644 tests/unit/features/pm/card-workflow.spec.ts create mode 100644 tests/unit/features/pm/core.spec.ts create mode 100644 tests/unit/features/pm/deleted-cards.spec.ts create mode 100644 tests/unit/features/pm/description-format.spec.ts create mode 100644 tests/unit/features/pm/images.spec.ts create mode 100644 tests/unit/features/pm/labels.spec.ts create mode 100644 tests/unit/features/pm/legacy-offer.spec.ts create mode 100644 tests/unit/features/pm/multiple-boards.spec.ts create mode 100644 tests/unit/features/pm/native.spec.ts create mode 100644 tests/unit/features/pm/october-cards.spec.ts create mode 100644 tests/unit/features/pm/partial-reload.spec.ts create mode 100644 tests/unit/features/pm/private-cards.spec.ts create mode 100644 tests/unit/features/pm/scan-performance.spec.ts create mode 100644 tests/unit/features/pm/storage-migration.spec.ts create mode 100644 tests/unit/features/pm/subtask-cards.spec.ts create mode 100644 tests/unit/features/pm/transient-background.spec.ts diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 01410a1..a17955f 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -8,6 +8,7 @@ The license texts follow the table. The browser engine has its own notices in [b | `pdfjs-dist` (PDF.js) | 6.4.299 | Apache-2.0 | https://github.com/mozilla/pdf.js | The PDF Viewer feature (`src/lib/features/pdf/`) | | `@xterm/xterm` | 6.0.0 | MIT | https://github.com/xtermjs/xterm.js | The Terminal feature (`src/lib/features/terminal/`) | | `@xterm/addon-fit` | 0.11.0 | MIT | https://github.com/xtermjs/xterm.js/tree/master/addons/addon-fit | The Terminal feature | +| `yaml` | 2.9.1 | ISC | https://github.com/eemeli/yaml | The Project Management feature (`src/lib/features/pm/`) | ## PDF.js @@ -1008,3 +1009,23 @@ 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. ``` + +## yaml + +From `yaml/LICENSE`. + +```text +Copyright Eemeli Aro + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +``` diff --git a/docs/menu-surfaces.json b/docs/menu-surfaces.json index 10d1e89..0760ecf 100644 --- a/docs/menu-surfaces.json +++ b/docs/menu-surfaces.json @@ -1,9 +1,7 @@ { - "date": "2026-10-15", + "date": "2026-10-29", "scope": [ "RuneStone", - "RuneStone_Project_Management", - "RuneStone_Background_Slideshow", "RuneStone_Local_Autocomplete", "RuneStone_CSV_Viewer" ], @@ -172,97 +170,6 @@ "design": "Shared action menu", "check": "tests/smoke/menus/consistency.smoke.mjs" }, - "RuneStone_Project_Management/src/choices-ui.ts": { - "counts": { - "action": 1 - }, - "design": "Shared action menus and searchable picker classes; older-host fallback retained", - "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" - }, - "RuneStone_Project_Management/src/details-ui.ts": { - "counts": { - "picker": 1, - "localPopup": 4 - }, - "design": "Shared action menus and searchable picker classes; older-host fallback retained", - "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" - }, - "RuneStone_Project_Management/src/labels-ui.ts": { - "counts": { - "picker": 1, - "localPopup": 3 - }, - "design": "Shared action menus and searchable picker classes; older-host fallback retained", - "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" - }, - "RuneStone_Project_Management/src/preferences.ts": { - "counts": { - "action": 1, - "nativeChoice": 1 - }, - "design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained", - "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" - }, - "RuneStone_Project_Management/src/priority-ui.ts": { - "counts": { - "action": 1, - "picker": 1, - "localPopup": 3 - }, - "design": "Shared action menus and searchable picker classes; older-host fallback retained", - "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" - }, - "RuneStone_Project_Management/src/relations-ui.ts": { - "counts": { - "nativeChoice": 1, - "picker": 1, - "localPopup": 5 - }, - "design": "Shared relationship choice and direct searchable picker rows; older-host choice fallback retained", - "check": "RuneStone_Project_Management/tests/relations-menu.spec.ts; tests/menu-audit.spec.ts; tests/related-cards.spec.ts" - }, - "RuneStone_Project_Management/src/tags.ts": { - "counts": { - "picker": 2, - "localPopup": 2 - }, - "design": "Shared action menus and searchable picker classes; older-host fallback retained", - "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" - }, - "RuneStone_Project_Management/src/ui.ts": { - "counts": { - "action": 4, - "nativeChoice": 13, - "picker": 1, - "localPopup": 1 - }, - "design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained", - "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts; tests/list-limits.spec.ts; tests/all-tasks.spec.ts; tests/card-board-details.spec.ts" - }, - "RuneStone_Background_Slideshow/src/contracts.ts": { - "counts": { - "action": 1 - }, - "design": "API type declaration, no renderer", - "check": "pnpm check" - }, - "RuneStone_Background_Slideshow/src/image-settings-ui.ts": { - "counts": { - "action": 1, - "nativeChoice": 1, - "picker": 2, - "localPopup": 3 - }, - "design": "Host action menus and shared searchable image picker; native image select only on older hosts", - "check": "RuneStone_Background_Slideshow/tests/settings.smoke.mjs" - }, - "RuneStone_Background_Slideshow/src/settings.ts": { - "counts": { - "action": 1 - }, - "design": "Host action menus and shared searchable image picker; native image select only on older hosts", - "check": "RuneStone_Background_Slideshow/tests/settings.smoke.mjs" - }, "RuneStone_Local_Autocomplete/src/main.mjs": { "counts": { "action": 1, @@ -288,13 +195,6 @@ "design": "Shared action menu for interface language; settings retain ordinary controls", "check": "tests/smoke/settings/displayLanguage.smoke.mjs; tests/smoke/menus/consistency.smoke.mjs" }, - "RuneStone_Project_Management/src/workspace-default.ts": { - "counts": { - "nativeChoice": 1 - }, - "design": "Uses the host menu. Keeps a native selector for older hosts.", - "check": "RuneStone_Project_Management/tests/october-cards.spec.ts with PM_HOST_URL; both themes, narrow layout, keyboard focus" - }, "RuneStone/src/lib/features/background/BackgroundSettings.svelte": { "counts": { "action": 1, @@ -334,6 +234,78 @@ }, "design": "Shared action menu for the default profile in Settings → Terminal", "check": "tests/smoke/features/terminal.smoke.mjs" + }, + "RuneStone/src/lib/features/pm/ui/host.ts": { + "counts": { + "action": 2 + }, + "design": "The host layer of Project Management: showActionMenu of managedActionMenu.ts and the shared tooltip", + "check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs" + }, + "RuneStone/src/lib/features/pm/ui/choices-ui.ts": { + "counts": { + "action": 1 + }, + "design": "Shared choice adapter: the native selects stay hidden for their values, and the host action menu shows the choices", + "check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs" + }, + "RuneStone/src/lib/features/pm/ui/priority-ui.ts": { + "counts": { + "action": 1 + }, + "design": "Shared action menu for the card priority", + "check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs" + }, + "RuneStone/src/lib/features/pm/ui/details-ui.ts": { + "counts": { + "picker": 1, + "localPopup": 4 + }, + "design": "Shared searchable picker classes (rs-picker) for the optional card details", + "check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs" + }, + "RuneStone/src/lib/features/pm/ui/labels-ui.ts": { + "counts": { + "picker": 1, + "localPopup": 3 + }, + "design": "Shared searchable picker classes (rs-picker) for labels", + "check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs" + }, + "RuneStone/src/lib/features/pm/ui/relations-ui.ts": { + "counts": { + "nativeChoice": 1, + "picker": 1, + "localPopup": 5 + }, + "design": "Shared relationship choice through the choice adapter and direct searchable picker rows", + "check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs" + }, + "RuneStone/src/lib/features/pm/ui/tags.ts": { + "counts": { + "picker": 2, + "localPopup": 2 + }, + "design": "Shared searchable picker classes (rs-picker) for tag suggestions", + "check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs" + }, + "RuneStone/src/lib/features/pm/ui/ui.ts": { + "counts": { + "action": 3, + "nativeChoice": 12, + "picker": 1, + "localPopup": 1 + }, + "design": "Board, list, card, scope, and background menus use the host action menu. Native selects stay hidden behind the shared choice adapter", + "check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs" + }, + "RuneStone/src/lib/features/ProjectManagementSettings.svelte": { + "counts": { + "action": 1, + "localPopup": 2 + }, + "design": "Shared action menu for the priority levels and the default board in Settings → Project Management", + "check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs" } } } diff --git a/package.json b/package.json index 8252049..27d077d 100644 --- a/package.json +++ b/package.json @@ -58,7 +58,8 @@ "@xterm/xterm": "6.0.0", "markdown-it": "^15.0.2", "mermaid": "^12.0.0", - "pdfjs-dist": "6.4.299" + "pdfjs-dist": "6.4.299", + "yaml": "2.9.1" }, "devDependencies": { "@sveltejs/adapter-static": "^3.0.10", diff --git a/packages/plugin-sdk/src/api.ts b/packages/plugin-sdk/src/api.ts index cb048dc..5911ee8 100644 --- a/packages/plugin-sdk/src/api.ts +++ b/packages/plugin-sdk/src/api.ts @@ -1,4 +1,3 @@ -import type { BackgroundApi } from "./backgrounds.ts"; import type { CompletionApi } from "./completion.ts"; import type { Contributions } from "./contributions.ts"; import type { ActionIcon } from "./icons.ts"; @@ -63,7 +62,6 @@ export interface UiApi { showActionMenu(options: ActionMenuOptions): { close(): export interface PluginApi { files?: FilesApi; services?: ServicesApi; - backgrounds?: BackgroundApi; ui?: UiApi; completion?: CompletionApi; readonly id: string; diff --git a/packages/plugin-sdk/src/backgrounds.ts b/packages/plugin-sdk/src/backgrounds.ts deleted file mode 100644 index 55c4095..0000000 --- a/packages/plugin-sdk/src/backgrounds.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** Background image frames behind the RuneStone interface. */ -export interface BackgroundFrame { - url: string; - blurredUrl?: string; - overlay: number; - position: 'center' | 'top left' | 'top' | 'top right' | 'left' | 'right' | 'bottom left' | 'bottom' | 'bottom right'; - size: 'cover' | 'contain' | 'auto'; - previous?: Omit; - transitionMs?: number; -} - -/** - * The background frames of each target in one window. A plugin can show a frame and read the current frame. - * Use the `FilesApi` folder grants to read image files. - */ -export interface BackgroundApi { - readonly version: 1; - set(target: string, frame: BackgroundFrame | null): void; - get(target: string): BackgroundFrame | null; - subscribe(listener: (target: string) => void): () => void; -} diff --git a/packages/plugin-sdk/src/features.ts b/packages/plugin-sdk/src/features.ts index 30b6f08..c259570 100644 --- a/packages/plugin-sdk/src/features.ts +++ b/packages/plugin-sdk/src/features.ts @@ -1,5 +1,4 @@ import type { FilesApi, PluginApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts"; -import type { BackgroundApi } from "./backgrounds.ts"; import type { CompletionApi } from "./completion.ts"; /** @@ -9,7 +8,6 @@ import type { CompletionApi } from "./completion.ts"; export interface PluginFeatures { files: FilesApi; services: ServicesApi; - backgrounds: BackgroundApi; completion: CompletionApi; "completion.transport": NonNullable; "ui.showActionMenu": UiApi["showActionMenu"]; @@ -34,7 +32,6 @@ export type PluginFeature = keyof PluginFeatures; const descriptions: { [K in PluginFeature]: string } = { files: "the folder grant API", services: "the plugin service API", - backgrounds: "the background API", completion: "the completion API", "completion.transport": "the completion model transport", "ui.showActionMenu": "the shared action menu", diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts index 7046e25..6b53fb3 100644 --- a/packages/plugin-sdk/src/index.ts +++ b/packages/plugin-sdk/src/index.ts @@ -1,7 +1,6 @@ // The public types and helpers of the RuneStone plugin API. // The icon and tooltip helpers use the DOM. Import them from "@runestone/plugin-sdk/icons" and "@runestone/plugin-sdk/tooltip". export type * from "./api.ts"; -export type * from "./backgrounds.ts"; export type * from "./completion.ts"; export type * from "./contributions.ts"; export type * from "./menu.ts"; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5d77ce7..b7ca33e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -104,16 +104,19 @@ importers: pdfjs-dist: specifier: 6.4.299 version: 6.4.299 + yaml: + specifier: 2.9.1 + version: 2.9.1 devDependencies: '@sveltejs/adapter-static': specifier: ^3.0.10 - version: 3.0.10(@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0(@types/node@24.19.2))) + version: 3.0.10(@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1))) '@sveltejs/kit': specifier: ^2.65.1 - version: 2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0(@types/node@24.19.2)) + version: 2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)) '@sveltejs/vite-plugin-svelte': specifier: ^7.1.2 - version: 7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)) + version: 7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)) '@tauri-apps/cli': specifier: ^2 version: 2.11.4 @@ -134,7 +137,7 @@ importers: version: 6.0.3 vite: specifier: ^8.0.16 - version: 8.3.0(@types/node@24.19.2) + version: 8.3.0(@types/node@24.19.2)(yaml@2.9.1) packages: @@ -1489,6 +1492,11 @@ packages: w3c-keyname@2.2.8: resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==} + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} + engines: {node: '>= 14.6'} + hasBin: true + zimmerframe@1.1.5: resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==} @@ -1860,15 +1868,15 @@ snapshots: dependencies: acorn: 8.18.0 - '@sveltejs/adapter-static@3.0.10(@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0(@types/node@24.19.2)))': + '@sveltejs/adapter-static@3.0.10(@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)))': dependencies: - '@sveltejs/kit': 2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0(@types/node@24.19.2)) + '@sveltejs/kit': 2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)) - '@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0(@types/node@24.19.2))': + '@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1))': dependencies: '@standard-schema/spec': 1.1.0 '@sveltejs/acorn-typescript': 1.0.13(acorn@8.18.0) - '@sveltejs/vite-plugin-svelte': 7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)) + '@sveltejs/vite-plugin-svelte': 7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)) '@types/cookie': 0.6.0 acorn: 8.18.0 cookie: 0.6.0 @@ -1880,20 +1888,20 @@ snapshots: set-cookie-parser: 3.1.2 sirv: 3.0.2 svelte: 5.57.1 - vite: 8.3.0(@types/node@24.19.2) + vite: 8.3.0(@types/node@24.19.2)(yaml@2.9.1) optionalDependencies: typescript: 6.0.3 '@sveltejs/load-config@0.2.3': {} - '@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2))': + '@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1))': dependencies: deepmerge: 4.3.1 magic-string: 1.4.1 obug: 2.2.1 svelte: 5.57.1 - vite: 8.3.0(@types/node@24.19.2) - vitefu: 1.1.3(vite@8.3.0(@types/node@24.19.2)) + vite: 8.3.0(@types/node@24.19.2)(yaml@2.9.1) + vitefu: 1.1.3(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)) '@tauri-apps/api@2.11.1': {} @@ -2860,7 +2868,7 @@ snapshots: uuid@14.0.2: {} - vite@8.3.0(@types/node@24.19.2): + vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -2870,11 +2878,14 @@ snapshots: optionalDependencies: '@types/node': 24.19.2 fsevents: 2.3.3 + yaml: 2.9.1 - vitefu@1.1.3(vite@8.3.0(@types/node@24.19.2)): + vitefu@1.1.3(vite@8.3.0(@types/node@24.19.2)(yaml@2.9.1)): optionalDependencies: - vite: 8.3.0(@types/node@24.19.2) + vite: 8.3.0(@types/node@24.19.2)(yaml@2.9.1) w3c-keyname@2.2.8: {} + yaml@2.9.1: {} + zimmerframe@1.1.5: {} diff --git a/scripts/featureChunks.mjs b/scripts/featureChunks.mjs index d867046..e47ba92 100644 --- a/scripts/featureChunks.mjs +++ b/scripts/featureChunks.mjs @@ -12,7 +12,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; /** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */ -export const FEATURE_FOLDERS = ["git", "background", "terminal", "pdf"]; +export const FEATURE_FOLDERS = ["git", "background", "terminal", "pdf", "pm"]; /** Libraries that only features need. */ export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"]; diff --git a/scripts/measure/scenarios.mjs b/scripts/measure/scenarios.mjs index a72fff7..c9226f5 100644 --- a/scripts/measure/scenarios.mjs +++ b/scripts/measure/scenarios.mjs @@ -71,8 +71,11 @@ export const TABLE = { pm: { plugin: { id: "runestone.pm", repo: "runestone-pm", tag: "v0.2.49", zip: `${PLUGIN_RELEASES}/RuneStone_Project_Management/releases/runestone.pm-0.2.49.zip` }, nativeKey: "pm", - /** Where the view opens: `palette`, or `menu:`. */ - openIn: { plugin: "menu:Plug-in views", native: "menu:Plug-in views" }, + /** + * Where the view opens: `palette`, `menu:`, or `ribbon:`. Native: the static + * ribbon button opens the default board or All tasks, and the first click loads the feature (src/lib/features/pm/). + */ + openIn: { plugin: "menu:Plug-in views", native: "ribbon:Project Management" }, title: "Project Management", card: { plugin: ".pm-card", native: ".pm-card" }, minCards: 50, @@ -101,9 +104,14 @@ export async function runPaletteCommand(page, title) { await input.press("Enter"); } -/** Run a command from the palette or from a ribbon menu. `where` is `palette` or `menu:`. */ +/** + * Run a command from the palette, from a ribbon menu, or from a ribbon button. + * `where` is `palette`, `menu:`, or `ribbon: + +
+
Default board

{boardNote || "Choose the board that opens in this workspace. Restored tabs keep their board."}

+ +
+ + {#if error}{/if} +

{message}

+ + + diff --git a/src/lib/features/background/BackgroundSettings.svelte b/src/lib/features/background/BackgroundSettings.svelte index 14ed593..7399f18 100644 --- a/src/lib/features/background/BackgroundSettings.svelte +++ b/src/lib/features/background/BackgroundSettings.svelte @@ -9,7 +9,8 @@ import Icon from "$lib/ui/Icon.svelte"; import { showActionMenu } from "$lib/ui/managedActionMenu"; import { onSettingsChange } from "$lib/settings/store"; - import { serviceHub } from "$lib/plugins/services"; + import { featureSwitches } from "$lib/features/state"; + import { readBoardCatalog } from "../pmBoards"; import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, saveAppearance, type Appearance } from "$lib/theme/appearance"; import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages"; import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings"; @@ -17,8 +18,7 @@ import { imageNames } from "./imageSettings"; import ImageEditor from "./ImageEditor.svelte"; - /** The Project Management service that lists the boards of the workspace as `{ id, name }[]`. Stage 7-5 makes it native. */ - const BOARD_SERVICE = ["runestone.pm", "boards"] as const; + /** The background targets of single boards need a UUID board ID. */ const boardId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; let settings = $state(readBackground()); @@ -148,20 +148,17 @@ save({ ...settings, targets: on ? [...new Set([...settings.targets, id])] : settings.targets.filter(target => target !== id) }); } - async function discoverBoards() { + /** The active boards of `.runestone/pm/workspace.json`. It needs no Project Management code. */ + async function discoverBoards(on: boolean) { const revision = ++boardRevision; - const service = serviceHub.get(...BOARD_SERVICE, () => !disposed); - if (!service || typeof service.list !== "function") { + if (!on) { boards = []; boardsNote = tr("Turn on Project Management to show the background on one board."); return; } try { - const rows = await service.list(); + const catalog = await readBoardCatalog(); if (disposed || revision !== boardRevision) return; - boards = (Array.isArray(rows) ? rows : []).flatMap((row: unknown) => { - if (!row || typeof row !== "object" || !("id" in row) || typeof row.id !== "string" || !boardId.test(row.id)) return []; - return [{ id: row.id, name: "name" in row && typeof row.name === "string" && row.name ? row.name : row.id }]; - }).filter((board, index, rows) => rows.findIndex(other => other.id === board.id) === index); + boards = catalog.boards.filter(board => !board.archived && boardId.test(board.id)).map(board => ({ id: board.id, name: board.name })); boardsNote = boards.length ? "" : tr("The workspace has no boards."); } catch (reason) { if (!disposed && revision === boardRevision) boardsNote = tr("Could not read the workspace boards: {error}", { error: reason instanceof Error ? reason.message : String(reason) }); @@ -190,9 +187,8 @@ onMount(() => { const read = () => { settings = readBackground(); appearance = readAppearance(); }; - const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), serviceHub.subscribe((plugin, name) => { if (plugin === BOARD_SERVICE[0] && name === BOARD_SERVICE[1]) void discoverBoards(); })]; + const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), featureSwitches.subscribe(switches => { void discoverBoards(switches.pm); })]; void folderHost.current().then(value => { if (!disposed) { folder = value; void inspectFolder(); } }, () => { folder = null; }); - void discoverBoards(); return () => stops.forEach(stop => stop()); }); onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); }); diff --git a/src/lib/features/catalog.ts b/src/lib/features/catalog.ts index b9f5030..1e1ad69 100644 --- a/src/lib/features/catalog.ts +++ b/src/lib/features/catalog.ts @@ -5,7 +5,7 @@ import { message, tr } from "../i18n/index.ts"; import type { PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts"; import { identifyPdf } from "./pdfDocument.ts"; -export type FeatureId = "git" | "background" | "terminal" | "pdf"; +export type FeatureId = "git" | "background" | "terminal" | "pdf" | "pm"; /** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */ export interface FeatureViewInfo { @@ -16,6 +16,21 @@ export interface FeatureViewInfo { icon?: PluginView["icon"]; /** Show a navigation button for the view. */ navigation?: boolean; + /** True when a launch, such as a ribbon button, asks the feature which view to open (`FeatureInstance.launch`). */ + launch?: boolean; +} + +/** + * A family of editor views whose IDs follow a pattern, for example one tab for each board. The session answers for each + * matching ID before the feature module loads, so a tab transfer from another window can restore it. + * The feature gives the real title later (`FeatureContext.setViewTitle`). + */ +export interface FeatureViewPattern { + /** Matches the whole view ID. */ + match: RegExp; + /** The title until the feature gives one. */ + title: () => string; + icon?: PluginView["icon"]; } /** A command of a feature. The command palette lists it. */ @@ -58,6 +73,8 @@ export interface FeatureEntry { /** True when the first start gives the switch the state of the old package. False when every user gets `defaultOn`. */ followsPackage: boolean; views: readonly FeatureViewInfo[]; + /** Editor views with IDs that follow a pattern. */ + viewPatterns?: readonly FeatureViewPattern[]; commands: readonly FeatureCommandInfo[]; documentTypes: readonly FeatureDocumentInfo[]; } @@ -114,6 +131,20 @@ export const FEATURES: readonly FeatureEntry[] = [ { id: "pdf", title: () => tr("PDF document"), icon: "file", extensions: ["pdf"], content: "binary", identify: identifyPdf }, ], }, + { + // Project Management replaces the Project Management plugin. It reads only `.runestone/pm/` in the workspace, so the + // file tree reads no Markdown file for it. Its ribbon button opens `planning`: the default board of the workspace, or + // All tasks. Each board has its own tab, `board-`, as in the plugin, so tab transfers between + // the plugin and the feature work. Its settings are in Settings → Project Management (`ProjectManagementSettings.svelte`). + id: "pm", owner: "runestone.pm", name: message("Project Management"), + description: message("Plan work on Kanban boards, in All tasks, and on Gantt and calendar views. The cards stay in the workspace."), + keywords: "project management kanban board card task list gantt calendar label priority backlog todo plan", + defaultOn: true, followsPackage: true, + views: [{ id: "planning", title: () => tr("Project Management"), placement: "editor", icon: "kanban", launch: true }], + viewPatterns: [{ match: /^board-(?:[0-9a-f]{2})+$/, title: () => tr("Project Management"), icon: "kanban" }], + commands: [], + documentTypes: [], + }, ]; export function featureEntry(id: FeatureId): FeatureEntry { diff --git a/src/lib/features/loader.ts b/src/lib/features/loader.ts index 4bebc05..17c7504 100644 --- a/src/lib/features/loader.ts +++ b/src/lib/features/loader.ts @@ -9,6 +9,7 @@ const imports: Record Promise> = { background: () => import("./background/index.ts"), terminal: () => import("./terminal/index.ts"), pdf: () => import("./pdf/index.ts"), + pm: () => import("./pm/index.ts"), }; const modules = new Map>(); diff --git a/src/lib/features/migration.ts b/src/lib/features/migration.ts index fd6c76c..55cfbab 100644 --- a/src/lib/features/migration.ts +++ b/src/lib/features/migration.ts @@ -2,7 +2,8 @@ // or the default of the feature when the feature does not follow its package (`followsPackage`). // `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing. // The first start also makes the `background` section from the old Background Slideshow settings (`backgroundSettings.ts`), -// and the `terminal` section from the localStorage key of the Terminal plugin (`terminalSettings.ts`). +// the `terminal` section from the localStorage key of the Terminal plugin (`terminalSettings.ts`), and the +// `projectManagement` section and the tab view states from the kept Project Management settings (`pmSettings.ts`). import { invoke, isTauri } from "@tauri-apps/api/core"; import { readSection, writeSection } from "../settings/store.ts"; import { readAppearance } from "../theme/appearance.ts"; @@ -10,6 +11,7 @@ import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "./cat import { storedSwitches } from "./state.ts"; import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts"; import { LEGACY_TERMINAL_KEY, migrateTerminal, writeTerminal, type TerminalMigrationHost } from "./terminalSettings.ts"; +import { migrateProjectManagement, writeProjectManagement, type ProjectManagementMigrationHost } from "./pmSettings.ts"; /** What the host reports about one old plugin package. */ export interface LegacyPlugin { @@ -44,6 +46,12 @@ const desktopBackground: BackgroundMigrationHost = { write: writeBackground, }; +const desktopProjectManagement: ProjectManagementMigrationHost = { + missing: () => readSection("projectManagement") === undefined, + write: writeProjectManagement, + get storage() { return localStorage; }, +}; + const desktopTerminal: TerminalMigrationHost = { missing: () => readSection("terminal") === undefined, legacy: () => localStorage.getItem(LEGACY_TERMINAL_KEY), @@ -51,12 +59,13 @@ const desktopTerminal: TerminalMigrationHost = { }; /** - * Give each feature without a stored switch the state of its old package, and make a missing `background` or `terminal` section. + * Give each feature without a stored switch the state of its old package, and make a missing `background`, `terminal`, + * or `projectManagement` section. * It runs before the first render. When the host cannot report the packages, nothing is written, so the next start tries again. * The `terminal` section needs no package report, so it migrates also then. */ export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground, - terminal: TerminalMigrationHost = desktopTerminal): Promise { + terminal: TerminalMigrationHost = desktopTerminal, projectManagement: ProjectManagementMigrationHost = desktopProjectManagement): Promise { try { await migrateTerminal(terminal); } catch (reason) { console.error("RuneStone could not copy the old terminal settings.", reason); } const current = host.read(); @@ -64,7 +73,9 @@ export async function migrateFeatures(host: MigrationHost = desktopHost, backgro const missing = FEATURES.filter(entry => stored[entry.id] === undefined); const backgroundOwner = featureEntry("background").owner; const backgroundMissing = background.missing(); - const owners = [...new Set([...missing.map(entry => entry.owner), ...backgroundMissing ? [backgroundOwner] : []])]; + const pmOwner = featureEntry("pm").owner; + const pmMissing = projectManagement.missing(); + const owners = [...new Set([...missing.map(entry => entry.owner), ...backgroundMissing ? [backgroundOwner] : [], ...pmMissing ? [pmOwner] : []])]; if (!owners.length) return []; let legacy: LegacyPlugin[]; try { legacy = await host.legacy(owners); } @@ -78,6 +89,7 @@ export async function migrateFeatures(host: MigrationHost = desktopHost, backgro await host.write(next); } if (backgroundMissing) await migrateBackground(legacy.find(item => item.id === backgroundOwner), background); + if (pmMissing) await migrateProjectManagement(legacy.find(item => item.id === pmOwner), projectManagement); return missing.map(entry => entry.id); } diff --git a/src/lib/features/pm/index.ts b/src/lib/features/pm/index.ts new file mode 100644 index 0000000..9c91430 --- /dev/null +++ b/src/lib/features/pm/index.ts @@ -0,0 +1,132 @@ +// The Project Management feature. `loader.ts` imports this module at the first use: the ribbon button, a board tab, +// or a tab transfer from another window. The views are `planning` (All tasks) and `board-`. +// The storage code (`storage/`) and the domain code (`model/`) use no host module, so the skill helper can bundle them. +import { invoke } from "@tauri-apps/api/core"; +import { backgroundHub } from "../../plugins/backgrounds.ts"; +import { onProjectManagementChange, readProjectManagement, readViewStates, writeProjectManagement, writeViewStates } from "../pmSettings.ts"; +import type { FeatureContext, FeatureInstance } from "../types.ts"; +import { boardKey, isManagedBoard, readCatalog } from "./storage/catalog.ts"; +import { findLegacy, hasLegacy, type LegacyContent } from "./storage/legacy.ts"; +import { isHiddenCard } from "./storage/persistence.ts"; +import type { BoardReference } from "./storage/board.ts"; +import { TaskStore } from "./model/store.ts"; +import { hostMenus } from "./ui/host.ts"; +import { mountPM, parseViewState, type PMViewState } from "./ui/ui.ts"; +import { hostWorkspace } from "./workspace.ts"; +import { boardOfView, boardViewId, PLANNING } from "./views.ts"; + +export function start(context: FeatureContext): FeatureInstance { + const workspace = hostWorkspace(context.onWorkspaceChange); + const preferences = readProjectManagement(); + const stopPreferences = onProjectManagementChange(() => Object.assign(preferences, readProjectManagement())); + const states = new Map(Object.entries(readViewStates()).map(([key, value]) => [key, parseViewState(value)])); + const dirty = new Set(); + let saveTimer: ReturnType | undefined; + let disposed = false; + const mounted = new Set<() => void>(); + /** The legacy data of each workspace root. A migration reads it again. */ + const legacy = new Map>(); + + const flush = () => { + clearTimeout(saveTimer); + if (!dirty.size) return; + writeViewStates(Object.fromEntries([...dirty].map(key => [key, structuredClone(states.get(key))]))); + dirty.clear(); + }; + const persist = (id: string) => { + if (disposed) return; + dirty.add(id); + clearTimeout(saveTimer); + saveTimer = setTimeout(flush, 200); + }; + const root = () => invoke("workspace_last_path").catch(() => null); + const legacyContent = async (fresh = false) => { + const key = await root() ?? ""; + if (fresh) legacy.delete(key); + let pending = legacy.get(key); + if (!pending) { + pending = findLegacy(workspace, () => { if (disposed) throw new Error("Project Management is off."); }); + pending.catch(() => legacy.delete(key)); + legacy.set(key, pending); + } + return pending; + }; + /** Copy the legacy boards, the root label file, and every legacy task note to `.runestone/pm/`, with backups. */ + const migrate = async () => { + const store = new TaskStore(workspace, undefined, { legacy: true }); + try { + await store.reload(); + const cards = store.tasks.filter(task => !isHiddenCard(task.path)).map(task => task.id); + return await store.migrateStorage(cards); + } finally { + store.dispose(); + void legacyContent(true).catch(() => undefined); + } + }; + + const openBoard = async (path: string, from?: string) => { + const snapshot = await readCatalog(workspace); + const board = isManagedBoard(path) ? snapshot.value.boards.find(item => boardKey(item.value.id) === path) : undefined; + if (!board) throw new Error("This board is unavailable. Refresh Project Management."); + const id = boardViewId(board.value.id); + context.setViewTitle(id, board.name); + if (from) context.replaceView(from, id); else context.openView(id); + }; + + function mountView(view: string, element: HTMLElement) { + const boardId = view === PLANNING ? null : boardOfView(view); + if (view !== PLANNING && !boardId) throw new Error("This view is unavailable."); + const reference: BoardReference | undefined = boardId ? { id: boardId, path: boardKey(boardId) } : undefined; + if (!states.has(view)) states.set(view, {}); + const store = new TaskStore(workspace, reference, { legacy: false }); + if (boardId) { + void readCatalog(workspace).then(snapshot => { + const board = snapshot.value.boards.find(item => item.value.id === boardId); + if (board && !disposed) context.setViewTitle(view, board.name); + }, () => undefined); + } + const cleanup = mountPM(element, store, { + ui: hostMenus, + backgrounds: backgroundHub, + state: states.get(view), + stateChanged: () => persist(view), + preferences, + savePreferences: value => writeProjectManagement(value), + openBoard: (path, replace) => openBoard(path, replace ? view : undefined), + openAll: replace => { if (replace) context.replaceView(view, PLANNING); else context.openView(PLANNING); }, + boardRenamed: name => { if (boardId) context.setViewTitle(view, name); }, + boardDeleted: () => { if (boardId) context.closeView(view); }, + watch: workspace.watch, + legacy: { find: legacyContent, has: hasLegacy, migrate }, + }); + mounted.add(cleanup); + return () => { mounted.delete(cleanup); cleanup(); }; + } + + return { + mount: mountView, + async launch(view) { + if (view !== PLANNING) { context.openView(view); return; } + // The default board of the workspace is in the catalog. A missing, archived, or damaged default opens All tasks. + try { + const { value } = await readCatalog(workspace); + const board = value.boards.find(item => item.value.id === value.defaultBoardId && !item.archived); + if (board) { await openBoard(boardKey(board.value.id)); return; } + } catch { /* All tasks shows the storage problem. */ } + context.openView(PLANNING); + }, + saveTabState: view => structuredClone(states.get(view) ?? {}), + restoreTabState(view, value) { + if (view !== PLANNING && !boardOfView(view)) throw new Error("This view is unavailable."); + states.set(view, parseViewState(value)); + persist(view); + }, + dispose() { + disposed = true; + flush(); + stopPreferences(); + for (const cleanup of [...mounted]) cleanup(); + mounted.clear(); + }, + }; +} diff --git a/src/lib/features/pm/model/all-tasks.ts b/src/lib/features/pm/model/all-tasks.ts new file mode 100644 index 0000000..cad5c45 --- /dev/null +++ b/src/lib/features/pm/model/all-tasks.ts @@ -0,0 +1,76 @@ +import { defaultBoard, type BoardDocument, type BoardList } from "../storage/board.ts"; +import type { Task } from "./model.ts"; + +export interface TaskColumn { + list?: BoardList; + tasks: Task[]; + allowCreate?: boolean; +} + +/** Merge equal list names without changing the cards' board placements. */ +export function allTaskColumns(boards: BoardDocument[], tasks: Task[]): TaskColumn[] { + const active = boards.filter(board => !board.archived); + const columns = new Map(); + const assigned = new Set(); + const append = (list: BoardList | undefined, members: Task[], allowCreate = false) => { + const key = list ? `list:${list.name.trim().toLowerCase()}` : "unlisted"; + let column = columns.get(key); + if (!column) { + column = { list: list ? { id: allowCreate ? list.id : key, name: list.name, status: list.status, collapsed: false } : undefined, tasks: [], allowCreate }; + columns.set(key, column); + } + const included = new Set(column.tasks.map(task => task.id)); + for (const task of members) if (!included.has(task.id)) { + column.tasks.push(task); + included.add(task.id); + } + }; + for (const board of active) { + const members = tasks.filter(task => Object.hasOwn(task.placements ?? {}, board.id)); + for (const task of members) assigned.add(task.id); + for (const list of board.value.lists) + append(list, members.filter(task => task.placements![board.id].listId === list.id)); + const unlisted = members.filter(task => !board.value.lists.some(list => list.id === task.placements![board.id].listId)); + if (unlisted.length) append(undefined, unlisted); + } + const standalone = tasks.filter(task => !assigned.has(task.id)); + if (standalone.length || !active.length) { + for (const list of defaultBoard("all-tasks").lists) + append(list, standalone.filter(task => task.status === list.status), true); + } + return [...columns.values()]; +} + +export interface TaskBoardGroup { + boardIds: string[]; + name: string; + tasks: Task[]; +} + +/** Keep shared cards once and name every board represented in this column. */ +export function allTaskGroups(boards: BoardDocument[], column: TaskColumn): TaskBoardGroup[] { + const active = boards.filter(board => !board.archived); + const groups = new Map(); + for (const task of column.tasks) { + const owners = active.filter(board => { + const placement = task.placements?.[board.id]; + if (!placement) return false; + const list = board.value.lists.find(list => list.id === placement.listId); + return column.list + ? list?.name.trim().toLowerCase() === column.list.name.trim().toLowerCase() + : !list; + }); + const boardIds = owners.map(board => board.id); + const key = JSON.stringify(boardIds); + let group = groups.get(key); + if (!group) { + group = { boardIds, name: owners.length ? owners.map(board => board.name).join(" · ") : "No active board", tasks: [] }; + groups.set(key, group); + } + group.tasks.push(task); + } + return [...groups.values()].sort((a, b) => { + const order = (group: TaskBoardGroup) => group.boardIds.length ? active.findIndex(board => board.id === group.boardIds[0]) : active.length; + return order(a) - order(b); + }); +} diff --git a/src/lib/features/pm/model/background.ts b/src/lib/features/pm/model/background.ts new file mode 100644 index 0000000..927f966 --- /dev/null +++ b/src/lib/features/pm/model/background.ts @@ -0,0 +1,13 @@ +export const backgroundPositions = ["center", "top left", "top", "top right", "left", "right", "bottom left", "bottom", "bottom right"] as const; +export const backgroundSizes = ["cover", "contain", "auto"] as const; +export interface BackgroundAppearance { overlay: number; position: typeof backgroundPositions[number]; size: typeof backgroundSizes[number] } +export function parseBackground(value: unknown): BackgroundAppearance { + const raw = value as Partial | null; + return { overlay: typeof raw?.overlay === "number" && Number.isFinite(raw.overlay) ? Math.max(-1, Math.min(1, raw.overlay)) : 0, + position: backgroundPositions.includes(raw?.position as any) ? raw!.position! : "center", + size: backgroundSizes.includes(raw?.size as any) ? raw!.size! : "cover" }; +} +export function backgroundOverlay(value: number) { + const color = value < 0 ? `rgba(255,255,255,${-value})` : `rgba(0,0,0,${value})`; + return `linear-gradient(${color}, ${color})`; +} diff --git a/src/lib/features/pm/model/description-format.ts b/src/lib/features/pm/model/description-format.ts new file mode 100644 index 0000000..b10e7f3 --- /dev/null +++ b/src/lib/features/pm/model/description-format.ts @@ -0,0 +1,27 @@ +export function headingEdit(value: string, selectionStart: number, selectionEnd: number) { + const start = selectionStart === 0 ? 0 : value.lastIndexOf("\n", selectionStart - 1) + 1; + const last = selectionEnd > selectionStart && value[selectionEnd - 1] === "\n" + ? selectionEnd - 1 : selectionEnd; + const next = value.indexOf("\n", last); + const end = next < 0 ? value.length : next; + const edits: { start: number; removed: number; added: number }[] = []; + let offset = start; + const text = value.slice(start, end).split("\n").map(line => { + const prefix = /^( {0,3})(#{1,6})(?:[\t ]+|$)/.exec(line); + const removed = prefix?.[0].length ?? 0; + const replacement = `${prefix?.[1] ?? ""}## `; + edits.push({ start: offset, removed, added: replacement.length }); + offset += line.length + 1; + return replacement + line.slice(removed); + }).join("\n"); + const position = (original: number) => { + let result = original; + for (const edit of edits) { + if (original < edit.start) break; + result += original < edit.start + edit.removed + ? edit.added - (original - edit.start) : edit.added - edit.removed; + } + return result; + }; + return { start, end, text, selectionStart: position(selectionStart), selectionEnd: position(selectionEnd) }; +} diff --git a/src/lib/features/pm/model/markdown.ts b/src/lib/features/pm/model/markdown.ts new file mode 100644 index 0000000..80264ed --- /dev/null +++ b/src/lib/features/pm/model/markdown.ts @@ -0,0 +1,31 @@ +import MarkdownIt from "markdown-it"; +import { imagePath } from "../storage/images.ts"; + +const markdown = new MarkdownIt({ html: false, linkify: false, breaks: true }); +markdown.validateLink = (url) => /^(https?:|mailto:|#|pm-image:)/i.test(url); +markdown.renderer.rules.link_open = (tokens, index, options, _env, self) => { + const token = tokens[index]; + const href = String(token.attrGet("href") ?? ""); + if (!/^(https?:|mailto:|#)/i.test(href)) token.attrs = []; + else { + token.attrSet("target", "_blank"); + token.attrSet("rel", "noopener noreferrer"); + } + return self.renderToken(tokens, index, options); +}; +// Image sources come only from the validated workspace image store, never from Markdown URLs. +markdown.renderer.rules.image = (tokens, index) => { + const token = tokens[index]; + const id = String(token.attrGet("src") ?? "").replace(/^pm-image:/, ""); + const name = markdown.utils.escapeHtml(token.content || "Image"); + try { + imagePath(id); + return `${name}`; + } catch { + return `Image: ${name} (use Add image to import)`; + } +}; + +export function renderMarkdown(source: string): string { + return markdown.render(source); +} diff --git a/src/lib/features/pm/model/model.ts b/src/lib/features/pm/model/model.ts new file mode 100644 index 0000000..58c8e23 --- /dev/null +++ b/src/lib/features/pm/model/model.ts @@ -0,0 +1,249 @@ +export const statuses = ["todo", "doing", "done"] as const; +export type Status = (typeof statuses)[number]; +export const priorities = ["highest", "high", "medium", "low", "lowest"] as const; +export type PriorityLevels = 2 | 3 | 5; +export function availablePriorities(levels: PriorityLevels): readonly Priority[] { + return levels === 2 ? ["high", "low"] : levels === 3 ? ["high", "medium", "low"] : priorities; +} +export type Priority = (typeof priorities)[number]; +export const priorityNames: Record = { highest: "Highest", high: "High", medium: "Medium", low: "Low", lowest: "Lowest" }; +export const statusNames: Record = { + todo: "To do", + doing: "In progress", + done: "Done", +}; +export const cardColors = { + red: "#df7373", + orange: "#d99554", + amber: "#dda83e", + yellow: "#c5ae4f", + lime: "#a4bd58", + green: "#63ad84", + teal: "#4cafa6", + cyan: "#53b8cf", + blue: "#729fe0", + indigo: "#8790df", + purple: "#ac89d8", + magenta: "#cb75c8", + pink: "#d784b0", + brown: "#b48b68", + slate: "#8398ae", + gray: "#a4a6ad", +} as const; +export interface Plan { + start: string; + end: string; +} +export interface Session { + id: string; + start: string; + end: string; + timeZone: string; +} +export interface TaskFields { + createdAt?: string; + title?: string; + order?: string; + color?: string; + assignees?: string[]; + customFields?: { name: string; value: string }[]; + listId?: string | null; + placements?: Record; + status: Status; + tags: string[]; + labels?: string[]; + priority?: Priority | null; + coverImage?: string | null; + attachments?: { id: string; name: string }[]; + subtasks?: { id: string; title: string; done: boolean; taskId?: string }[]; + links?: { taskId: string; relation: "relates" | "blocks" | "blocked-by" }[]; + due?: { date: string }; + plan?: Plan; + sessions: Session[]; + archived: boolean; +} +export interface Task extends TaskFields { + id: string; + path: string; + title: string; + body: string; + source: string; +} +export interface Entry { + name: string; + rel_path: string; + kind: string; +} +export interface Workspace { + list(path?: string): Promise; + listMarkdown?(): Promise; + read(path: string): Promise; + readMany?(paths: string[]): Promise<{ path: string; source?: string; error?: string }[]>; + readOptional?(path: string): Promise; + write(path: string, contents: string, expected: string): Promise; + create?(path: string, contents: string): Promise; + subscribe?(listener: () => void): () => void; +} +export function validDate(value: unknown): value is string { + if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) + return false; + const date = new Date(`${value}T00:00:00Z`); + return !isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value; +} +export function addDays(value: string, days: number): string { + if (!validDate(value)) throw new Error("Enter a valid calendar date."); + const date = new Date(`${value}T12:00:00Z`); + date.setUTCDate(date.getUTCDate() + days); + return date.toISOString().slice(0, 10); +} +export function dayDistance(start: string, end: string): number { + return Math.round( + (Date.parse(`${end}T12:00:00Z`) - Date.parse(`${start}T12:00:00Z`)) / + 86_400_000, + ); +} +export function localDay(date = new Date()): string { + return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; +} +export function localTime(instant: string): string { + const date = new Date(instant); + return `${localDay(date)}T${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`; +} +export function localInstant(value: string): string { + const date = new Date(value); + if (isNaN(date.getTime()) || localTime(date.toISOString()) !== value) + throw new Error("Enter an existing local date and time."); + return date.toISOString(); +} +export function validateFields(fields: TaskFields): void { + if (fields.createdAt !== undefined && (typeof fields.createdAt !== "string" || + !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(fields.createdAt) || + !validDate(fields.createdAt.slice(0, 10)) || !Number.isFinite(Date.parse(fields.createdAt)))) + throw new Error("The card creation timestamp is invalid."); + if (fields.attachments !== undefined && (!Array.isArray(fields.attachments) || fields.attachments.some(item => !item || typeof item.id !== "string" || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(item.id) || typeof item.name !== "string" || !item.name.trim() || item.name.length > 255) || new Set(fields.attachments.map(item => item.id)).size !== fields.attachments.length)) + throw new Error("Each image attachment needs a unique image ID and a name of 1 to 255 characters."); + if (fields.priority !== undefined && fields.priority !== null && !priorities.includes(fields.priority)) + throw new Error("Choose a supported priority or No priority."); + if (fields.coverImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(fields.coverImage)) + throw new Error("Choose an image from this card."); + if (fields.subtasks !== undefined && (!Array.isArray(fields.subtasks) || fields.subtasks.some(item => !item || typeof item.id !== "string" || !item.id || typeof item.title !== "string" || !item.title.trim() || item.title.length > 200 || typeof item.done !== "boolean" || (item.taskId !== undefined && (typeof item.taskId !== "string" || !item.taskId))) || new Set(fields.subtasks.map(item => item.id)).size !== fields.subtasks.length)) + throw new Error("Each subtask needs a unique ID, a title, and a completion state."); + if (fields.links !== undefined && (!Array.isArray(fields.links) || fields.links.some(item => !item || typeof item.taskId !== "string" || !item.taskId || !["relates", "blocks", "blocked-by"].includes(item.relation)) || new Set(fields.links.map(item => item.taskId)).size !== fields.links.length)) + throw new Error("Choose each linked card once and select its relationship."); + if ( + fields.title !== undefined && + (typeof fields.title !== "string" || + !fields.title.trim() || + fields.title.length > 100 || + /[\x00-\x1f]/.test(fields.title)) + ) + throw new Error("Enter a card title of 1 to 100 characters."); + const validOrder = (value: unknown) => + value === undefined || + (typeof value === "string" && /^[0-9a-z]*[1-9a-z]$/.test(value)); + if (!validOrder(fields.order)) + throw new Error("The card order is invalid. Refresh the board."); + if (fields.placements !== undefined) { + if ( + !fields.placements || + typeof fields.placements !== "object" || + Array.isArray(fields.placements) + ) + throw new Error("Board placements must be a mapping."); + for (const [id, placement] of Object.entries(fields.placements)) { + if ( + !id.trim() || + !placement || + typeof placement !== "object" || + Array.isArray(placement) || + (placement.listId !== null && + (typeof placement.listId !== "string" || !placement.listId)) || + !validOrder(placement.order) + ) + throw new Error( + "Each board placement needs a board ID and a valid list ID.", + ); + } + } + if ( + fields.color !== undefined && + (typeof fields.color !== "string" || + !Object.hasOwn(cardColors, fields.color)) + ) + throw new Error("Choose a supported card color."); + if ( + fields.assignees !== undefined && + (!Array.isArray(fields.assignees) || + fields.assignees.some((name) => typeof name !== "string" || !name.trim())) + ) + throw new Error("Assignments must contain names."); + if (fields.customFields !== undefined) { + if ( + !Array.isArray(fields.customFields) || + fields.customFields.some( + (field) => + !field || + typeof field.name !== "string" || + !field.name.trim() || + typeof field.value !== "string", + ) + ) + throw new Error("Each custom field needs a name and a text value."); + const names = fields.customFields.map((field) => + field.name.trim().toLocaleLowerCase(), + ); + if (new Set(names).size !== names.length) + throw new Error("Use a different name for each custom field."); + } + if ( + fields.listId !== undefined && + fields.listId !== null && + (typeof fields.listId !== "string" || !fields.listId) + ) + throw new Error("The task has an invalid list ID."); + if (!statuses.includes(fields.status)) + throw new Error("Choose a supported task status."); + if ( + !Array.isArray(fields.tags) || + fields.tags.some((tag) => typeof tag !== "string") + ) + throw new Error("Tags must be text."); + if ( + fields.labels !== undefined && + (!Array.isArray(fields.labels) || + fields.labels.some( + (id) => typeof id !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(id), + ) || + new Set(fields.labels).size !== fields.labels.length) + ) + throw new Error("Labels must contain unique saved label IDs."); + if (fields.due && !validDate(fields.due.date)) + throw new Error("Enter a valid deadline date."); + if ( + fields.plan && + (!validDate(fields.plan.start) || + !validDate(fields.plan.end) || + fields.plan.end <= fields.plan.start) + ) { + throw new Error("The planned end must follow the start."); + } + const ids = new Set(); + for (const session of fields.sessions) { + const instant = + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/; + if ( + !session.id || + ids.has(session.id) || + !instant.test(session.start) || + !instant.test(session.end) || + !validDate(session.start.slice(0, 10)) || + !validDate(session.end.slice(0, 10)) || + !Number.isFinite(Date.parse(session.start)) || + !Number.isFinite(Date.parse(session.end)) || + Date.parse(session.end) <= Date.parse(session.start) + ) + throw new Error("Each session needs a unique ID and a valid time range."); + new Intl.DateTimeFormat("en", { timeZone: session.timeZone }).format(); + ids.add(session.id); + } +} diff --git a/src/lib/features/pm/model/store.ts b/src/lib/features/pm/model/store.ts new file mode 100644 index 0000000..02c1f6c --- /dev/null +++ b/src/lib/features/pm/model/store.ts @@ -0,0 +1,902 @@ +import { readTask, editTask, adoptNote, split } from "../storage/notes.ts"; +import { createCard, readCards, cardOrigin, cardPath, migrateCards, parseCard, prepareCards } from "../storage/cards.ts"; +import { cardsFolder, cardsMarker, isHiddenCard, readOptional, saveDocument, storageRoot } from "../storage/persistence.ts"; +import { deletedCardsPath, readDeletedCards, recordCardDeletion } from "../storage/deleted-cards.ts"; +import { mapConcurrent, markdownPaths, readSources } from "../storage/scan.ts"; +import type { Task, TaskFields, Workspace } from "./model.ts"; +import { cardOrder, compareCards, orderBetween } from "../storage/order.ts"; +import { LabelStore, labelsPath, parseLabels, type LabelSnapshot, type SavedLabel } from "../storage/labels.ts"; +import { + catalogPath, + readCatalog, + managedDocuments, + isManagedBoard, + createBoard, +} from "../storage/catalog.ts"; +import { migrateStorage } from "../storage/migration.ts"; +import { + BoardStore, + boardDocument, + type BoardDocument, + type BoardReference, +} from "../storage/board.ts"; + +const workspaceTasks = new WeakMap(); + +export interface TaskStoreOptions { + /** + * True (the default) also reads the visible Markdown notes of the legacy format: boards and task notes in the workspace. + * The migration and the read-only skill helper use it. False reads only `.runestone/pm/`, and a save, a delete, + * or a move reads only the changed files again. The native feature of RuneStone uses false. + */ + legacy?: boolean; +} + +const message = (error: unknown) => error instanceof Error ? error.message : String(error); + +/** The files of `.runestone/pm/` that the hidden mode reads, with the problem of each file. */ +interface HiddenState { + cards: Map; + cardIssues: Map; + cardsError: string; + catalog: { source: string | null; boards: BoardDocument[]; error: string }; + labels: { snapshot?: LabelSnapshot; error: string }; + deleted: { ids: Set; error: string }; +} + +export class TaskStore { + tasks: Task[] = []; + boards: BoardDocument[] = []; + legacyBoards: BoardDocument[] = []; + issues: string[] = []; + private queue: Promise = Promise.resolve(); + private disposed = false; + private loaded = false; + private revision = 0; + private hidden?: HiddenState; + readonly legacy: boolean; + readonly workspace: Workspace; + readonly board: BoardStore; + readonly labels: LabelStore; + constructor(workspace: Workspace, board?: BoardReference, options: TaskStoreOptions = {}) { + this.workspace = workspace; + this.legacy = options.legacy ?? true; + this.tasks = workspaceTasks.get(workspace) ?? []; + this.board = new BoardStore(workspace, board); + this.labels = new LabelStore(workspace); + } + get scopedTasks() { + const id = this.board.reference?.id; + return id + ? this.board.available + ? this.tasks.filter((task) => Object.hasOwn(task.placements ?? {}, id)) + : [] + : this.tasks; + } + dispose() { + this.disposed = true; + } + private check() { + if (this.disposed) + throw new Error("The Project Management view is closed. Reopen it before saving."); + } + /** Read all Project Management data again. */ + async reload(): Promise { + if (this.legacy) return this.reloadLegacy(); + this.check(); + const revision = ++this.revision; + const previous = this.hidden?.cards ?? new Map(this.tasks.map((task) => [task.path, task])); + const state: HiddenState = { + cards: new Map(), cardIssues: new Map(), cardsError: "", + catalog: { source: null, boards: [], error: "" }, labels: { error: "" }, deleted: { ids: new Set(), error: "" }, + }; + try { + // Direct reads are necessary because the host hides .runestone from root listings. + if ((await readOptional(this.workspace, cardsMarker)) !== null) { + const paths = (await this.workspace.list(cardsFolder)) + .filter((entry) => entry.kind !== "folder" && isHiddenCard(entry.rel_path)).map((entry) => entry.rel_path); + const sources = await readSources(this.workspace, paths); + for (const path of paths) this.acceptCard(state, path, sources.get(path)!, previous.get(path)); + } + } catch (error) { + state.cardsError = message(error); + } + await Promise.all([this.readHiddenCatalog(state), this.readHiddenLabels(state), this.readHiddenDeleted(state)]); + this.check(); + if (revision !== this.revision) return; + this.hidden = state; + this.publishHidden(); + } + /** + * Read only the changed files of `.runestone/pm/` again, for example after a watcher event. + * Paths outside `.runestone/pm/` change nothing. A change of a folder, of the storage markers, or an unknown change + * (`undefined`) reads everything again. The legacy mode always reads everything again. + */ + reloadPaths(paths?: readonly string[]): Promise { + return this.run(() => this.reloadFor(paths)); + } + private async reloadFor(paths?: readonly string[]) { + if (this.legacy || !this.hidden || !paths) return this.reload(); + const relevant = [...new Set(paths)].filter((path) => path === ".runestone" || path === storageRoot || path.startsWith(storageRoot + "/")); + // A folder or the card marker can change many cards at once. + if (relevant.some((path) => [".runestone", storageRoot, cardsFolder, cardsMarker].includes(path))) return this.reload(); + const cards = relevant.filter((path) => isHiddenCard(path) && path.lastIndexOf("/") === cardsFolder.length); + const files = relevant.filter((path) => [catalogPath, labelsPath, deletedCardsPath].includes(path)); + // Images, drafts, backups, and the Git exclusion change no card, board, or label. + if (!cards.length && !files.length) return; + this.check(); + const state = this.hidden; + ++this.revision; + const work: Promise[] = []; + if (cards.length) work.push((async () => { + const sources = await readSources(this.workspace, cards); + for (const path of cards) { + const result = sources.get(path)!; + // A missing file is a deleted card. The host reports another read error for it. + if (result.source === undefined && (await readOptional(this.workspace, path)) === null) { + state.cards.delete(path); + state.cardIssues.delete(path); + } else this.acceptCard(state, path, result, state.cards.get(path)); + } + })()); + if (relevant.includes(catalogPath)) work.push(this.readHiddenCatalog(state)); + if (relevant.includes(labelsPath)) work.push(this.readHiddenLabels(state)); + if (relevant.includes(deletedCardsPath)) work.push(this.readHiddenDeleted(state)); + await Promise.all(work); + this.check(); + if (this.hidden === state) this.publishHidden(); + } + private acceptCard(state: HiddenState, path: string, result: { source?: string; error?: string }, cached?: Task) { + try { + if (result.error || result.source === undefined) throw new Error(result.error ?? "The card is unavailable."); + state.cards.set(path, cached?.source === result.source ? cached : parseCard(path, result.source)); + state.cardIssues.delete(path); + } catch (error) { + state.cards.delete(path); + state.cardIssues.set(path, message(error)); + } + } + private async readHiddenCatalog(state: HiddenState) { + try { + const catalog = await readCatalog(this.workspace); + state.catalog = { source: catalog.source, boards: managedDocuments(catalog.value, catalog.source ?? ""), error: "" }; + } catch (error) { + // Do not expose boards as writable when hidden storage cannot be read. + state.catalog = { source: null, boards: [], error: message(error) }; + } + } + private async readHiddenLabels(state: HiddenState) { + try { state.labels = { snapshot: await this.labels.read(), error: "" }; } + catch (error) { state.labels = { error: message(error) }; } + } + private async readHiddenDeleted(state: HiddenState) { + try { state.deleted = { ids: new Set((await readDeletedCards(this.workspace)).ids), error: "" }; } + catch (error) { state.deleted = { ids: new Set(), error: message(error) }; } + } + /** Make the public fields from the hidden files. One invalid card file hides all cards, as in the legacy mode. */ + private publishHidden() { + const state = this.hidden!; + const issues: string[] = [...[...state.cardIssues].map(([path, issue]) => `${path}: ${issue}`)]; + if (state.cardsError) issues.push("Hidden cards: " + state.cardsError); + if (state.catalog.error) issues.push("Hidden Project Management storage: " + state.catalog.error); + if (state.labels.error) issues.push("Saved labels: " + state.labels.error); + if (state.deleted.error) issues.push("Deleted cards: " + state.deleted.error); + this.labels.load(state.labels.snapshot, state.labels.error); + const blocked = !!(state.cardsError || state.cardIssues.size || state.deleted.error); + this.tasks = blocked ? [] : [...state.cards.values()] + .filter((task) => !state.deleted.ids.has(task.id)) + .sort((a, b) => a.title.localeCompare(b.title)); + this.boards = [...state.catalog.boards].sort((a, b) => a.name.localeCompare(b.name)); + this.legacyBoards = []; + if (this.board.reference) { + this.board.load(this.boards.find((board) => board.id === this.board.reference!.id)); + if (!this.board.available) + issues.push("This board is missing, invalid, or duplicated. Task notes remain available in All tasks."); + } + this.issues = issues; + workspaceTasks.set(this.workspace, this.tasks); + this.loaded = true; + } + private async reloadLegacy(): Promise { + this.check(); + const revision = ++this.revision; + const tasks: Task[] = [], + issues: string[] = []; + const boards: BoardDocument[] = []; + const previous = new Map(this.tasks.map((task) => [task.path, task])); + const paths = await markdownPaths(this.workspace, () => this.check()); + const sources = await readSources(this.workspace, paths); + const documents = await mapConcurrent(paths, async (path) => { + this.check(); + try { + const result = sources.get(path)!; + if (result.error || result.source === undefined) throw new Error(result.error ?? "The file is unavailable."); + const source = result.source; + const cached = previous.get(path); + if (cached?.source === source) return { task: cached }; + const board = boardDocument(source, path); + return board ? { board } : { task: readTask(path, source) }; + } catch (error) { + return { + issue: `${path}: ${error instanceof Error ? error.message : String(error)}`, + }; + } + }); + for (const document of documents) { + if (document.board) boards.push(document.board); + if (document.task) tasks.push(document.task); + if (document.issue) issues.push(document.issue); + } + try { + const hidden = await readCards(this.workspace, previous); + issues.push(...hidden.issues); + if (hidden.issues.length) tasks.length = 0; + for (const card of hidden.tasks) { + const originals = tasks.filter((task) => task.id === card.id); + const origin = originals.length ? cardOrigin(card.source) : undefined; + for (const original of originals) { + if ( + origin?.path === original.path && + origin.source === original.source + ) + tasks.splice(tasks.indexOf(original), 1); + else + issues.push( + `The original card differs from hidden storage: ${original.path}. Preserve both versions.`, + ); + } + } + tasks.push(...hidden.tasks); + } catch (error) { + issues.push( + "Hidden cards: " + + (error instanceof Error ? error.message : String(error)), + ); + // Block legacy edits when the hidden store cannot be checked for migrated IDs. + tasks.length = 0; + } + let legacyBoards = [...boards]; + try { + const catalog = await readCatalog(this.workspace); + for (let index = boards.length - 1; index >= 0; index--) + if (catalog.value.deletedBoardIds?.includes(boards[index].id)) + boards.splice(index, 1); + legacyBoards = [...boards]; + for (const managed of catalog.value.boards) { + const matches = boards.filter((board) => board.id === managed.value.id); + for (const board of matches) { + if ( + managed.original?.path === board.path && + managed.original.source === board.source + ) + boards.splice(boards.indexOf(board), 1); + else + issues.push( + `Legacy board differs from hidden storage: ${board.path}. Preserve both versions before cleanup.`, + ); + } + } + boards.push(...managedDocuments(catalog.value, catalog.source ?? "")); + } catch (error) { + issues.push( + "Hidden Project Management storage: " + + (error instanceof Error ? error.message : String(error)), + ); + // Do not expose legacy boards as writable when hidden storage cannot be read. + boards.length = 0; + } + let labels: LabelSnapshot | undefined, + labelError = ""; + try { + labels = await this.labels.read(); + } catch (error) { + labelError = error instanceof Error ? error.message : String(error); + issues.push("Saved labels: " + labelError); + } + this.check(); + if (revision !== this.revision) return; + this.labels.load(labels, labelError); + this.legacyBoards = legacyBoards; + const counts = new Map(); + for (const task of tasks) + counts.set(task.id, (counts.get(task.id) ?? 0) + 1); + for (const [id, count] of counts) + if (count > 1) + issues.push( + `Duplicate task ID ${id}: resolve the copied notes before editing them.`, + ); + let deletedIds = new Set(); + try { deletedIds = new Set((await readDeletedCards(this.workspace)).ids); } + catch (error) { + issues.push("Deleted cards: " + (error instanceof Error ? error.message : String(error))); + tasks.length = 0; + } + this.check(); + if (revision !== this.revision) return; + this.tasks = tasks + .filter((task) => counts.get(task.id) === 1 && !deletedIds.has(task.id)) + .sort((a, b) => a.title.localeCompare(b.title)); + const boardCounts = new Map(); + for (const board of boards) + boardCounts.set(board.id, (boardCounts.get(board.id) ?? 0) + 1); + for (const [id, count] of boardCounts) + if (count > 1) + issues.push( + `Duplicate board ID ${id}: resolve the copied boards before editing them.`, + ); + this.boards = boards + .filter((board) => boardCounts.get(board.id) === 1) + .sort((a, b) => a.name.localeCompare(b.name)); + if (this.board.reference) { + this.board.load( + this.boards.find((board) => board.id === this.board.reference!.id), + ); + if (!this.board.available) + issues.push( + "This board is missing, invalid, or duplicated. Task notes remain available in All tasks.", + ); + } + this.issues = issues; + workspaceTasks.set(this.workspace, this.tasks); + this.loaded = true; + } + private run(action: () => Promise): Promise { + const result = this.queue.then(() => { + this.check(); + return action(); + }); + this.queue = result.catch(() => {}); + return result; + } + save( + task: Task, + patch: Partial & { body?: string }, + applyListStatus = false, + ): Promise { + return this.run(() => this.saveTask(task, patch, applyListStatus)); + } + deleteCard(task: Task): Promise { + return this.run(async () => { + await this.reloadFor([task.path]); + const current = this.tasks.find(item => item.id === task.id && item.path === task.path); + if (!current || current.source !== task.source) + throw new Error("The card changed or is unavailable. Refresh before deleting it."); + await recordCardDeletion(this.workspace, task.id); + await this.reloadFor([deletedCardsPath]); + }); + } + unlinkIncoming(targetId: string, sources: Task[]): Promise { + if (!sources.length) return Promise.resolve(); + return this.run(async () => { + await this.reloadFor(sources.map(source => source.path)); + const current = sources.map(source => { + const found = this.tasks.find(task => task.id === source.id && task.path === source.path); + if (found && !found.links?.some(link => link.taskId === targetId)) return undefined; + if (!found || found.source !== source.source) + throw new Error("A linked card changed. Refresh before removing its link."); + return found; + }); + for (const source of current) { + if (!source) continue; + await this.saveTask(source, { links: source.links?.filter(link => link.taskId !== targetId) }, false, undefined, true); + } + }); + } + private async saveTask( + task: Task, + patch: Partial & { body?: string }, + applyListStatus: boolean, + beforeId?: string | null, + reloaded = false, + placementBoardId = this.board.reference?.id, + ): Promise { + if (!reloaded) await this.reloadFor([task.path]); + const current = this.tasks.find( + (item) => item.id === task.id && item.path === task.path, + ); + if (!current || current.source !== task.source) + throw new Error( + "The task changed or has a duplicate ID. Cancel, refresh, and review the note before saving.", + ); + const next = { ...patch }; + if (Object.hasOwn(next, "listId")) { + if (this.board.archived) + throw new Error("Restore this board before moving cards."); + const listId = next.listId ?? null; + const list = this.board.value.lists.find((list) => list.id === listId); + if (listId !== null && !list) + throw new Error("This list no longer exists. Refresh the board."); + const previousList = this.board.listFor(task); + if (applyListStatus && listId !== (previousList?.id ?? null)) { + if (list?.status) next.status = list.status; + else if (previousList?.status === "done" && task.status === "done") next.status = "todo"; + } + const id = this.board.reference?.id; + if (id) { + if (!this.board.available) + throw new Error("The board is unavailable. Reopen it before saving."); + const placement = { ...task.placements?.[id], listId }; + if ( + listId !== (this.board.listFor(task)?.id ?? null) || + beforeId !== undefined + ) + placement.order = this.position(task, listId, beforeId); + next.placements = { ...task.placements, [id]: placement }; + } else if ( + beforeId !== undefined || + (list?.status && task.status !== list.status) + ) { + next.order = this.position(task, listId, beforeId); + } + next.listId = undefined; + } + if (next.status !== undefined && next.status !== task.status) { + const placements = { ...(next.placements ?? task.placements) }; + for (const board of this.boards) { + if (board.id === placementBoardId) continue; + const placement = placements[board.id]; + const listId = board.value.defaults[next.status]; + if ( + !placement || + listId === null || + placement.listId === listId || + !board.value.lists.some((list) => list.id === listId) + ) + continue; + const cards = this.tasks + .filter( + (card) => + card.id !== task.id && + card.archived === task.archived && + card.placements?.[board.id]?.listId === listId, + ) + .sort((a, b) => compareCards(a, b, board.id)); + const last = cards.at(-1); + placements[board.id] = { + ...placement, + listId, + order: orderBetween(last ? cardOrder(last, board.id) : undefined), + }; + next.placements = placements; + } + } + const source = editTask(task, next); + await saveDocument(this.workspace, task.path, source, task.source); + this.accept(task.path, source); + } + private accept(path: string, source: string) { + ++this.revision; + if (this.hidden && isHiddenCard(path)) { + this.hidden.cards.set(path, readTask(path, source)!); + this.hidden.cardIssues.delete(path); + this.publishHidden(); + return; + } + this.tasks = [ + ...this.tasks.filter((task) => task.path !== path), + readTask(path, source)!, + ].sort((a, b) => a.title.localeCompare(b.title)); + workspaceTasks.set(this.workspace, this.tasks); + } + cardsInList(listId: string | null, archived = false): Task[] { + return this.scopedTasks + .filter( + (task) => + task.archived === archived && + (this.board.listFor(task)?.id ?? null) === listId, + ) + .sort((a, b) => compareCards(a, b, this.board.reference?.id)); + } + archiveList(listId: string): Promise { + return this.run(async () => { + await this.reloadFor(this.cardsInList(listId).map(task => task.path)); + if (!this.board.editable || !this.board.value.lists.some((list) => list.id === listId)) + throw new Error("The list is unavailable. Refresh the board."); + if (this.issues.length) + throw new Error("Resolve workspace issues before archiving cards: " + this.issues.join(" ")); + for (const task of this.cardsInList(listId)) { + const source = editTask(task, { archived: true }); + await saveDocument(this.workspace, task.path, source, task.source); + this.accept(task.path, source); + } + }); + } + private position( + task: Task | undefined, + listId: string | null, + beforeId?: string | null, + ): string { + const cards = this.cardsInList(listId, task?.archived).filter( + (card) => card.id !== task?.id, + ); + const index = + beforeId == null + ? cards.length + : cards.findIndex((card) => card.id === beforeId); + if (index < 0) throw new Error("The target card moved. Refresh the board."); + const id = this.board.reference?.id; + return orderBetween( + index > 0 ? cardOrder(cards[index - 1], id) : undefined, + index < cards.length ? cardOrder(cards[index], id) : undefined, + ); + } + async createOrLink(title: string, fields: TaskFields): Promise { + const path = title.trim().replaceAll("\\", "/").replace(/^\.\//, ""); + if (!/\.(md|markdown|mdown)$/i.test(path)) return this.create(title, fields, ""); + if (/^(?:[a-z]+:|\/)/i.test(path) || path.split("/").some(part => !part || part === "." || part === "..")) + throw new Error("Use a relative Markdown path inside this workspace."); + const added = await this.adopt(path); + const task = this.tasks.find(item => item.id === added.id && item.path === added.path); + if (!task) throw new Error("The linked card is unavailable. Refresh the board."); + if (this.board.reference) await this.moveTask(task, fields.listId ?? null); + } + create(title: string, fields: TaskFields, body: string, destinationId?: string): Promise { + return this.run(async () => { + if (!this.workspace.create) + throw new Error( + "This RuneStone version cannot create plugin notes. Add an existing note or install the host bridge.", + ); + if (!this.loaded) await this.reload(); + ++this.revision; + if (destinationId !== undefined) await this.reloadFor([catalogPath]); + const destination = destinationId === undefined ? undefined : this.boards.find(board => board.id === destinationId && !board.archived); + if (destinationId !== undefined && !destination) throw new Error("Choose an available, active board for this card."); + const id = destination?.id ?? this.board.reference?.id; + if (id && !destination && !this.board.available) + throw new Error("The board is unavailable. Reopen it before saving."); + // Named-board creation reads the current board without a workspace scan. + await this.board.reload(); + if (this.board.archived) + throw new Error("Restore this board before adding cards."); + const targetBoard = destination?.value ?? this.board.value; + const listId = + fields.listId === undefined + ? targetBoard.defaults[fields.status] + : fields.listId; + if ( + id && + listId !== null && + !targetBoard.lists.some((list) => list.id === listId) + ) + throw new Error("This list no longer exists. Refresh the board."); + const lastGlobalCard = this.tasks + .filter( + (task) => + task.status === fields.status && task.archived === fields.archived, + ) + .sort((a, b) => compareCards(a, b)) + .at(-1); + const lastDestinationCard = destination && id + ? this.tasks.filter(task => !task.archived && task.placements?.[id]?.listId === listId) + .sort((a, b) => compareCards(a, b, id)).at(-1) + : undefined; + const placementOrder = destination && id + ? orderBetween(lastDestinationCard ? cardOrder(lastDestinationCard, id) : undefined) + : this.position(undefined, listId); + const note = await createCard( + this.workspace, + title, + { + ...fields, + order: + fields.order ?? + orderBetween( + lastGlobalCard ? cardOrder(lastGlobalCard) : undefined, + ), + listId: undefined, + ...(id + ? { + placements: { + [id]: { listId, order: placementOrder }, + }, + } + : {}), + }, + body, + ); + this.accept(note.path, note.source); + }); + } + openSubtask(parentId: string, subtaskId: string): Promise { + return this.run(async () => { + await this.reloadFor([cardPath(parentId)]); + const parent = this.tasks.find(task => task.id === parentId); + const item = parent?.subtasks?.find(item => item.id === subtaskId); + if (!parent || !item) throw new Error("The subtask is unavailable. Refresh the board."); + if (item.taskId) { + const target = this.tasks.find(task => task.id === item.taskId); + if (!target) throw new Error("The subtask card is unavailable. Refresh the board."); + return target; + } + // A stable ID lets a retry recover after the child saves but the parent fails. + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(["subtask", parent.id, item.id]))); + const id = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join(""); + let target = this.tasks.find(task => task.id === id); + if (!target) { + const placements = Object.fromEntries(Object.keys(parent.placements ?? {}).map(boardId => { + const board = this.boards.find(board => board.id === boardId); + return [boardId, { listId: board?.value.defaults[item.done ? "done" : "todo"] ?? null }]; + })); + const note = await createCard(this.workspace, item.title, { + status: item.done ? "done" : "todo", tags: [], sessions: [], archived: false, placements, + }, "", id); + this.accept(note.path, note.source); + target = this.tasks.find(task => task.path === cardPath(id)); + } + await this.saveTask(parent, { subtasks: parent.subtasks!.map(subtask => subtask.id === subtaskId ? { ...subtask, taskId: id } : subtask) }, false); + return target!; + }); + } + moveTask( + task: Task, + listId: string | null, + beforeId?: string | null, + ): Promise { + return this.run(() => this.saveTask(task, { listId }, true, beforeId)); + } + removeFromBoard(task: Task): Promise { + const id = this.board.reference?.id; + if (!id) + return Promise.reject(new Error("Open a board before removing a card.")); + const placements = { ...task.placements }; + delete placements[id]; + return this.save(task, { placements }); + } + saveToBoard(task: Task, destinationId: string, listId: string | null, patch: Partial & { body?: string }): Promise { + return this.run(async () => { + await this.reloadFor([task.path]); + const destination = this.boards.find(board => board.id === destinationId); + if (!destination || destination.archived || (listId !== null && !destination.value.lists.some(list => list.id === listId))) + throw new Error("The destination board or list is unavailable. Refresh the board."); + if (this.board.reference && (!this.board.available || this.board.archived)) throw new Error("Open an available, active board before moving a card."); + const placements = { ...task.placements }; + if (this.board.reference) delete placements[this.board.reference.id]; + const last = this.tasks.filter(item => item.id !== task.id && item.placements?.[destinationId]?.listId === listId).sort((a, b) => compareCards(a, b, destinationId)).at(-1); + placements[destinationId] = { listId, order: orderBetween(last ? cardOrder(last, destinationId) : undefined) }; + const { listId: ignoredList, status: ignoredStatus, ...details } = patch; + const destinationList = destination.value.lists.find(list => list.id === listId); + const previousList = destination.value.lists.find(list => list.id === task.placements?.[destinationId]?.listId); + const status = destinationList?.status ?? (previousList?.status === "done" && task.status === "done" ? "todo" : task.status); + await this.saveTask(task, { ...details, status, placements }, false, undefined, true, destinationId); + }); + } + transferTask( + task: Task, + destinationId: string, + listId: string | null, + ): Promise { + return this.run(async () => { + await this.reloadFor([task.path]); + const sourceId = this.board.reference?.id; + if (!sourceId || !this.board.available || this.board.archived) + throw new Error("Open an available, active board before moving a card."); + const current = this.tasks.find( + (item) => item.id === task.id && item.path === task.path, + ); + if (!current || current.source !== task.source) + throw new Error("The card changed. Cancel, refresh, and review it before moving."); + if (!Object.hasOwn(current.placements ?? {}, sourceId)) + throw new Error("This card no longer belongs to the source board."); + if (sourceId === destinationId) + throw new Error("Choose a different destination board."); + const destination = this.boards.find((board) => board.id === destinationId); + if (!destination || destination.archived) + throw new Error("The destination board is unavailable or archived. Choose another board."); + if (listId !== null && !destination.value.lists.some((list) => list.id === listId)) + throw new Error("The destination list no longer exists. Choose another list."); + const last = this.tasks + .filter((card) => card.id !== task.id && card.archived === task.archived && + Object.hasOwn(card.placements ?? {}, destinationId) && + (destination.value.lists.some((list) => list.id === card.placements![destinationId].listId) + ? card.placements![destinationId].listId : null) === listId) + .sort((a, b) => compareCards(a, b, destinationId)).at(-1); + const placements = { ...current.placements }; + delete placements[sourceId]; + placements[destinationId] = { + ...placements[destinationId], + listId, + order: orderBetween(last ? cardOrder(last, destinationId) : undefined), + }; + // One guarded write changes membership without synchronizing other boards. + const source = editTask(current, { placements }); + await saveDocument(this.workspace, current.path, source, current.source); + this.accept(current.path, source); + }); + } + changeBoard(change: () => Promise, reload = true): Promise { + return this.run(async () => { + await change(); + // The hidden mode reads only the catalog again. The saved board then keeps the current catalog text. + if (this.hidden) await this.reloadFor([catalogPath]); + else if (reload) await this.reload(); + else this.boards = this.boards.map(board => board.id === this.board.reference?.id + ? { ...board, value: this.board.value } : board); + }); + } + saveLabels( + labels: SavedLabel[], + expected: string | null | undefined, + ): Promise { + return this.run(async () => { + this.labels.checkSave(labels, expected); + const removed = new Set(parseLabels(expected ?? null).labels + .filter((label) => !labels.some((next) => next.id === label.id)).map((label) => label.id)); + if (removed.size) { + await this.reloadFor([labelsPath]); + if (this.labels.source !== expected) + throw new Error("Saved labels changed. Refresh before deleting labels."); + if (this.issues.length) + throw new Error("Resolve workspace issues before deleting labels: " + this.issues.join(" ")); + // Keep definitions until every guarded card write succeeds, so a retry is safe. + for (const task of this.tasks) + if (task.labels?.some((id) => removed.has(id))) { + const source = editTask(task, { labels: task.labels.filter((id) => !removed.has(id)) }); + await saveDocument(this.workspace, task.path, source, task.source); + this.accept(task.path, source); + } + } + await this.labels.save(labels, expected, true); + ++this.revision; + if (this.hidden) await this.reloadFor([labelsPath]); + }); + } + createBoard(name: string) { + return this.run(async () => { + const reference = await createBoard(this.workspace, name); + await this.reloadFor([catalogPath]); + return reference; + }); + } + migrateStorage(cardIds: string[] = []) { + return this.run(async () => { + await this.reload(); + if (this.issues.length) + throw new Error( + "Resolve the workspace issues before migration: " + + this.issues.join(" "), + ); + const selected = cardIds.map((id) => { + const task = this.tasks.find((task) => task.id === id); + if (!task) + throw new Error( + "A selected card is unavailable. Refresh before migration.", + ); + return task; + }); + const result = await migrateStorage( + this.workspace, + this.legacyBoards, + selected, + ); + await this.reload(); + return result; + }); + } + renameBoard( + name: string, + rename?: (document: BoardReference, name: string) => Promise, + ): Promise { + return this.run(async () => { + await this.reloadFor([catalogPath]); + if (!this.board.editable) + throw new Error("Open an available board before renaming it."); + const reference = this.board.reference!; + if (isManagedBoard(reference.path)) { + await this.board.manage({ name }); + await this.reloadFor([catalogPath]); + return; + } + if (!rename) throw new Error("Migrate this board before renaming it."); + const path = await rename({ ...reference }, name.trim()); + reference.path = path; + await this.reload(); + }); + } + /** + * Add a note to Project Management and return its card. The legacy mode adds the properties to the note itself. + * The hidden mode leaves the note unchanged: it copies a plain note into a new private card, and it migrates a + * legacy task note with a backup. The card then gets a placement on the open board. + */ + adopt(path: string): Promise { + if (!this.legacy) return this.run(() => this.adoptHidden(path)); + return this.run(async () => { + if (!/\.(md|markdown|mdown)$/i.test(path)) + throw new Error("Choose a Markdown note from this workspace."); + await this.reload(); + const id = this.board.reference?.id; + if (id && !this.board.available) + throw new Error( + "The board is unavailable. Reopen it before adding a note.", + ); + if (this.board.archived) + throw new Error("Restore this board before adding cards."); + const source = await this.workspace.read(path); + let next = adoptNote(path, source); + const task = readTask(path, next)!; + if ( + this.tasks.some( + (other) => other.id === task.id && other.path !== path, + ) || + this.issues.some((issue) => + issue.startsWith(`Duplicate task ID ${task.id}:`), + ) + ) + throw new Error("Resolve this task's duplicate ID before adding it."); + if (id && !Object.hasOwn(task.placements ?? {}, id)) + next = editTask(task, { + placements: { + ...task.placements, + [id]: { + listId: this.board.value.defaults[task.status], + order: this.position( + task, + this.board.value.defaults[task.status], + ), + }, + }, + }); + if (next !== source) + await saveDocument(this.workspace, path, next, source); + await this.reload(); + const added = this.tasks.find(item => item.path === path); + if (!added) throw new Error("The linked card is unavailable. Refresh the board."); + return added; + }); + } + private async adoptHidden(path: string): Promise { + if (!/\.(md|markdown|mdown)$/i.test(path)) + throw new Error("Choose a Markdown note from this workspace."); + const id = this.board.reference?.id; + if (id && !this.board.available) + throw new Error("The board is unavailable. Reopen it before adding a note."); + if (this.board.archived) + throw new Error("Restore this board before adding cards."); + let card: Task | undefined; + if (isHiddenCard(path)) { + await this.reloadFor([path]); + card = this.tasks.find(task => task.path === path); + if (!card) throw new Error("The linked card is unavailable. Refresh the board."); + } else { + const source = await this.workspace.read(path); + const note = readTask(path, source); + if (note) { + // A task note of the legacy format keeps its ID. The migration copies it with a backup. + await this.reloadFor([cardPath(note.id)]); + card = this.tasks.find(task => task.id === note.id); + if (!card) { + await migrateCards(this.workspace, [note]); + await this.reloadFor([cardPath(note.id)]); + card = this.tasks.find(task => task.id === note.id); + } + if (!card) throw new Error("The linked card is unavailable. Refresh the board."); + } else { + const { doc, body, match, newline } = split(source); + if (doc.has("runestone_pm")) + throw new Error("This document already contains Project Management data and cannot become a task."); + const cardId = crypto.randomUUID(); + const last = this.tasks.filter(task => task.status === "todo" && !task.archived).sort((a, b) => compareCards(a, b)).at(-1); + doc.set("runestone_pm", { + schema: 1, id: cardId, kind: "task", + title: path.split("/").at(-1)!.replace(/\.(md|markdown|mdown)$/i, ""), + createdAt: new Date().toISOString(), + order: orderBetween(last ? cardOrder(last) : undefined), + status: "todo", tags: [], sessions: [], archived: false, + }); + const copy = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`; + const target = cardPath(cardId); + parseCard(target, copy); + await prepareCards(this.workspace); + await saveDocument(this.workspace, target, copy, null); + this.accept(target, copy); + card = this.tasks.find(task => task.path === target)!; + } + } + if (id && !Object.hasOwn(card.placements ?? {}, id)) { + const listId = this.board.value.defaults[card.status]; + await this.saveTask(card, { placements: { ...card.placements, [id]: { listId, order: this.position(card, listId) } } }, false, undefined, true); + const placed = card.id; + card = this.tasks.find(task => task.id === placed)!; + } + return card; + } +} diff --git a/src/lib/features/pm/model/transient-background.ts b/src/lib/features/pm/model/transient-background.ts new file mode 100644 index 0000000..6eee734 --- /dev/null +++ b/src/lib/features/pm/model/transient-background.ts @@ -0,0 +1,56 @@ +import type { BackgroundAppearance } from "./background.ts"; + +/** One background frame. It has the shape of `BackgroundFrame` in `src/lib/plugins/backgroundContracts.ts`. */ +export interface BackgroundFrame extends BackgroundAppearance { + url: string; + blurredUrl?: string; + previous?: BackgroundAppearance & { url: string; blurredUrl?: string }; + transitionMs?: number; +} +/** The part of the host background hub (`backgroundHub` in `src/lib/plugins/backgrounds.ts`) that the boards read. */ +export interface PMBackgroundApi { + get(target: string): BackgroundFrame | null; + subscribe(listener: (target: string) => void): () => void; +} + +function sameImage(a: BackgroundAppearance & { url: string; blurredUrl?: string }, b: BackgroundAppearance & { url: string; blurredUrl?: string }) { + return a.url === b.url && a.blurredUrl === b.blurredUrl && a.overlay === b.overlay && a.position === b.position && a.size === b.size; +} + +function sameFrame(a: BackgroundFrame, b: BackgroundFrame | null | undefined) { + return !!b && sameImage(a, b) && (a.transitionMs ?? 0) === (b.transitionMs ?? 0) + && (a.previous ? !!b.previous && sameImage(a.previous, b.previous) : !b.previous); +} + +export function watchBackground( + target: string, + api: PMBackgroundApi | undefined, + saved: () => Promise, + apply: (frame: BackgroundFrame | null) => void, +) { + let revision = 0; + let closed = false; + async function refresh() { + if (closed) return; + const current = ++revision; + try { + const frame = api?.get(target) ?? (target !== "pm-all" ? api?.get("pm-all") : null) ?? await saved(); + // A shared slideshow uses the host image coordinates across every pane. + if (!closed && current === revision) apply(frame && sameFrame(frame, api?.get("app")) ? null : frame); + } catch { + if (!closed && current === revision) apply(null); + } + } + const unsubscribe = api?.subscribe(changed => { + if (changed === target || changed === "pm-all" || changed === "app") void refresh(); + }); + return { + refresh, + dispose() { + if (closed) return; + closed = true; + ++revision; + unsubscribe?.(); + }, + }; +} diff --git a/src/lib/features/pm/model/workspace-default.ts b/src/lib/features/pm/model/workspace-default.ts new file mode 100644 index 0000000..ca9b4aa --- /dev/null +++ b/src/lib/features/pm/model/workspace-default.ts @@ -0,0 +1,21 @@ +import type { Workspace } from "./model.ts"; +import { boardKey, readCatalog } from "../storage/catalog.ts"; +import { boardDocument } from "../storage/board.ts"; + +/** + * The board that opens first in this workspace: the `pm-board:` key of a saved board, the path of a legacy Markdown board, + * or undefined for All tasks. Settings → Project Management writes `defaultBoardId` and `defaultBoardPath` of the catalog. + */ +export async function defaultBoardPath(workspace: Workspace): Promise { + const snapshot = await readCatalog(workspace); + if (typeof snapshot.value.defaultBoardId !== "string") return; + const board = snapshot.value.boards.find(board => board.value.id === snapshot.value.defaultBoardId); + if (board) return board.archived ? undefined : boardKey(board.value.id); + if (snapshot.value.deletedBoardIds?.includes(snapshot.value.defaultBoardId)) return; + const path = snapshot.value.defaultBoardPath; + if (typeof path !== "string" || path.startsWith(".") || path.includes("\\") || path.split("/").some(part => !part || part === "..")) return; + try { + const legacy = boardDocument(await workspace.read(path), path); + return legacy?.id === snapshot.value.defaultBoardId && !legacy.archived ? path : undefined; + } catch { return; } +} diff --git a/src/lib/features/pm/storage/board.ts b/src/lib/features/pm/storage/board.ts new file mode 100644 index 0000000..536332d --- /dev/null +++ b/src/lib/features/pm/storage/board.ts @@ -0,0 +1,374 @@ +import { statuses, type Status, type Task, type Workspace } from "../model/model.ts"; +import { Document } from "yaml"; +import { split } from "./notes.ts"; +import { + isManagedBoard, + readCatalog, + managedDocuments, + writeCatalog, + validateName, +} from "./catalog.ts"; + +export interface BoardReference { + id: string; + path: string; +} +export interface BoardDocument extends BoardReference { + name: string; + value: Board; + source: string; + archived?: boolean; +} +export interface BoardList { + id: string; + name: string; + status: Status | null; + collapsed: boolean; + maxCards?: number; +} +export interface Board { + schema: 1; + kind: "board"; + id: string; + lists: BoardList[]; + backgroundImage?: string | null; + backgroundAppearance?: import("../model/background.ts").BackgroundAppearance; + defaults: Record; +} +export function defaultBoard(id: string = crypto.randomUUID()): Board { + return { + schema: 1, + kind: "board", + id, + lists: [ + { id: "todo", name: "To do", status: "todo", collapsed: false }, + { id: "doing", name: "In progress", status: "doing", collapsed: false }, + { id: "done", name: "Done", status: "done", collapsed: false }, + ], + defaults: { todo: "todo", doing: "doing", done: "done" }, + }; +} +export function parseBoard(source: string): Board { + const value = split(source).doc.toJS({ maxAliasCount: 50 }).runestone_pm; + if ( + !value || + value.schema !== 1 || + value.kind !== "board" || + typeof value.id !== "string" || + !value.id.trim() || + !Array.isArray(value.lists) || + !value.defaults + ) + throw new Error( + "The board file has an unsupported format. Restore or repair it before editing lists.", + ); + if (value.backgroundImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(value.backgroundImage)) throw new Error("The board background image is invalid."); + const ids = new Set(); + for (const list of value.lists) { + if ( + !list || + typeof list.id !== "string" || + !list.id || + ids.has(list.id) || + typeof list.name !== "string" || + !list.name.trim() || + list.name.length > 80 || + (list.status !== null && !statuses.includes(list.status)) || + typeof list.collapsed !== "boolean" || + (list.maxCards !== undefined && (!Number.isSafeInteger(list.maxCards) || list.maxCards < 1)) + ) + throw new Error( + "The board contains an invalid list. Repair the board file before editing.", + ); + ids.add(list.id); + } + for (const status of statuses) + if (value.defaults[status] !== null && !ids.has(value.defaults[status])) + throw new Error("The board has an invalid default list."); + return value; +} +export function boardDocument( + source: string, + path: string, +): BoardDocument | null { + const value = split(source).doc.toJS({ maxAliasCount: 50 }).runestone_pm; + if (value?.kind !== "board") return null; + const board = parseBoard(source); + return { + id: board.id, + path, + name: path + .split("/") + .at(-1)! + .replace(/\.(md|markdown|mdown)$/i, ""), + value: board, + source, + }; +} +export function newBoardSource(): string { + return `---\n${new Document({ runestone_pm: defaultBoard() }).toString({ lineWidth: 0 })}---\n`; +} +export class BoardStore { + value = defaultBoard("all-tasks"); + name = "All tasks"; + available = true; + archived = false; + private source: string | null = null; + private workspace: Workspace; + readonly reference?: BoardReference; + constructor(workspace: Workspace, reference?: BoardReference) { + this.workspace = workspace; + this.reference = reference ? { ...reference } : undefined; + } + get editable() { + return ( + !!this.reference && + this.available && + !this.archived && + this.source !== null + ); + } + async reload() { + if (!this.reference) return; + if (!isManagedBoard(this.reference.path) && this.workspace.readOptional) { + const snapshot = await readCatalog(this.workspace); + if (snapshot.value.deletedBoardIds?.includes(this.reference.id)) { + this.load(); + throw new Error("This board was deleted. Open All tasks to find its cards."); + } + const managed = snapshot.value.boards.find( + (board) => board.value.id === this.reference!.id, + ); + if (managed) { + const current = await this.workspace.readOptional(this.reference.path); + if ( + managed.original?.path !== this.reference.path || + (current !== null && current !== managed.original.source) + ) + throw new Error( + "The legacy board differs from hidden storage. Preserve both versions.", + ); + this.load( + managedDocuments(snapshot.value, snapshot.source!).find( + (board) => board.id === this.reference!.id, + ), + ); + return; + } + } + if (isManagedBoard(this.reference.path)) { + const snapshot = await readCatalog(this.workspace); + this.load( + managedDocuments(snapshot.value, snapshot.source ?? "").find( + (board) => board.id === this.reference!.id, + ), + ); + if (!this.available) + throw new Error("This board is unavailable. Refresh Project Management."); + return; + } + const source = await this.workspace.read(this.reference.path); + const document = boardDocument(source, this.reference.path); + if (!document || document.id !== this.reference.id) + throw new Error("The board changed. Reopen it from navigation."); + this.load(document); + } + load(document?: BoardDocument) { + if (!this.reference) return; + this.available = !!document; + this.source = document?.source ?? null; + if (document) { + this.reference.path = document.path; + this.value = document.value; + this.name = document.name; + this.archived = document.archived ?? false; + } + } + listFor( + task: Pick, + ): BoardList | undefined { + const id = this.reference + ? (task.placements?.[this.reference.id]?.listId ?? + (task.listId !== undefined ? task.listId : null)) + : this.value.defaults[task.status]; + return this.value.lists.find((list) => list.id === id); + } + async update(change: (board: Board) => void) { + if (!this.editable) + throw new Error("Open an available board to edit its lists."); + const expected = this.source; + if (!isManagedBoard(this.reference!.path) && this.workspace.readOptional) { + const snapshot = await readCatalog(this.workspace); + if (snapshot.value.deletedBoardIds?.includes(this.reference!.id)) + throw new Error("This board was deleted. Open All tasks to find its cards."); + if ( + snapshot.value.boards.some( + (board) => board.value.id === this.reference!.id, + ) + ) + throw new Error( + "This board moved to hidden storage. Refresh before editing.", + ); + } + if (isManagedBoard(this.reference!.path)) { + const snapshot = await readCatalog(this.workspace); + if (snapshot.source !== expected) + throw new Error("The board changed. Refresh before editing its lists."); + const board = snapshot.value.boards.find( + (item) => item.value.id === this.reference!.id, + ); + if (!board) throw new Error("The board is unavailable."); + change(board.value); + this.source = await writeCatalog( + this.workspace, + snapshot.value, + expected, + ); + this.value = board.value; + return; + } + const current = await this.workspace.read(this.reference!.path); + if (current !== expected) + throw new Error("The board changed. Refresh before editing its lists."); + const next = structuredClone(this.value); + change(next); + const { doc, body, newline, match } = split(expected!); + for (const key of ["lists", "defaults", "backgroundImage", "backgroundAppearance"] as const) + if (next[key] !== undefined) doc.setIn(["runestone_pm", key], next[key]); + const source = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`; + parseBoard(source); + await this.workspace.write(this.reference!.path, source, expected!); + this.source = source; + this.value = next; + } + async deleteBoard() { + if (!this.reference || !this.available || this.source === null) + throw new Error("Open an available board before deleting it."); + const { id, path } = this.reference; + const snapshot = await readCatalog(this.workspace); + if (snapshot.value.deletedBoardIds?.includes(id)) + throw new Error("This board was already deleted. Refresh Project Management."); + if (isManagedBoard(path)) { + if (snapshot.source !== this.source) + throw new Error("The board changed. Cancel, refresh, and review it before deleting."); + if (!snapshot.value.boards.some((board) => board.value.id === id)) + throw new Error("The board is unavailable. Refresh Project Management."); + } else { + if (snapshot.value.boards.some((board) => board.value.id === id)) + throw new Error("This board moved to hidden storage. Refresh before deleting."); + if ((await this.workspace.read(path)) !== this.source) + throw new Error("The board changed. Cancel, refresh, and review it before deleting."); + } + snapshot.value.boards = snapshot.value.boards.filter((board) => board.value.id !== id); + // Keep originals and card memberships intact. The record prevents legacy rediscovery. + snapshot.value.deletedBoardIds = [...(snapshot.value.deletedBoardIds ?? []), id]; + await writeCatalog(this.workspace, snapshot.value, snapshot.source); + this.load(); + } + async manage(patch: { name?: string; archived?: boolean }) { + if ( + !this.reference || + !isManagedBoard(this.reference.path) || + !this.available + ) + throw new Error("Migrate this board before managing hidden storage."); + const snapshot = await readCatalog(this.workspace); + if (snapshot.source !== this.source) + throw new Error("The board changed. Refresh before saving."); + const board = snapshot.value.boards.find( + (item) => item.value.id === this.reference!.id, + )!; + if (patch.name !== undefined) { + validateName(patch.name); + if ( + snapshot.value.boards.some( + (item) => + item !== board && + item.name.toLocaleLowerCase() === + patch.name!.trim().toLocaleLowerCase(), + ) + ) + throw new Error("A board with this name already exists."); + board.name = patch.name.trim(); + } + if (patch.archived !== undefined) board.archived = patch.archived; + this.source = await writeCatalog( + this.workspace, + snapshot.value, + snapshot.source, + ); + this.name = board.name; + this.archived = board.archived ?? false; + } + async add(name: string, status: Status | null) { + await this.update((board) => { + this.checkName(board, name); + board.lists.push({ + id: crypto.randomUUID(), + name: name.trim(), + status, + collapsed: false, + }); + }); + } + async edit(id: string, name: string, status: Status | null) { + await this.update((board) => { + this.checkName(board, name, id); + const list = this.requireList(board, id); + list.name = name.trim(); + list.status = status; + }); + } + async collapse(id: string) { + await this.update((board) => { + const list = this.requireList(board, id); + list.collapsed = !list.collapsed; + }); + } + async setLimit(id: string, maximum?: number) { + if (maximum !== undefined && (!Number.isSafeInteger(maximum) || maximum < 1)) + throw new Error("Enter a whole number of at least 1, or leave the maximum blank."); + await this.update((board) => { + const list = this.requireList(board, id); + if (maximum === undefined) delete list.maxCards; + else list.maxCards = maximum; + }); + } + async move(id: string, index: number) { + await this.update((board) => { + const list = this.requireList(board, id); + board.lists = board.lists.filter((item) => item.id !== id); + board.lists.splice( + Math.max(0, Math.min(index, board.lists.length)), + 0, + list, + ); + }); + } + async remove(id: string) { + await this.update((board) => { + this.requireList(board, id); + board.lists = board.lists.filter((list) => list.id !== id); + for (const status of statuses) + if (board.defaults[status] === id) board.defaults[status] = null; + }); + } + private requireList(board: Board, id: string) { + const list = board.lists.find((item) => item.id === id); + if (!list) + throw new Error("This list no longer exists. Refresh the board."); + return list; + } + private checkName(board: Board, name: string, except?: string) { + if (!name.trim() || name.trim().length > 80) + throw new Error("Enter a list name of 1 to 80 characters."); + if ( + board.lists.some( + (list) => + list.id !== except && + list.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(), + ) + ) + throw new Error("A list with this name already exists."); + } +} diff --git a/src/lib/features/pm/storage/cards.ts b/src/lib/features/pm/storage/cards.ts new file mode 100644 index 0000000..6a515f3 --- /dev/null +++ b/src/lib/features/pm/storage/cards.ts @@ -0,0 +1,163 @@ +import { readTask, newTask, split } from "./notes.ts"; +import type { Task, TaskFields, Workspace } from "../model/model.ts"; +import { backupFile, type OriginalFile } from "./catalog.ts"; +import { legacyPosition } from "./order.ts"; +import { mapConcurrent, readSources } from "./scan.ts"; +import { + cardsFolder, + cardsMarker, + isHiddenCard, + readOptional, + saveDocument, +} from "./persistence.ts"; + +export function cardPath(id: string) { + const key = Array.from(new TextEncoder().encode(id), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); + return `${cardsFolder}/${key}.md`; +} +export function cardOrigin(source: string): OriginalFile | undefined { + const origin = split(source).doc.toJS({ + maxAliasCount: 50, + }).runestone_pm_origin; + if (origin === undefined) return; + if ( + !origin || + typeof origin.path !== "string" || + typeof origin.source !== "string" || + typeof origin.backup !== "string" || + origin.path.startsWith(".") || + origin.path.includes("\\") || + origin.path + .split("/") + .some((part: string) => !part || part === "." || part === "..") || + origin.backup !== `.runestone/pm/backups/${origin.path}` + ) + throw new Error( + "The card migration record is invalid. Keep the original note.", + ); + return origin; +} +/** Read one hidden card file. It throws when the file is invalid or when its name does not match the card ID. */ +export function parseCard(path: string, source: string): Task { + cardOrigin(source); + const task = readTask(path, source); + if (!task || cardPath(task.id) !== path) + throw new Error("The hidden card ID does not match its storage path."); + return task; +} +export async function prepareCards(workspace: Workspace) { + const marker = await readOptional(workspace, cardsMarker); + if (marker !== null) return; + try { + await saveDocument(workspace, cardsMarker, "*\n", null); + } catch (error) { + if ((await readOptional(workspace, cardsMarker)) !== "*\n") throw error; + } +} +export async function readCards( + workspace: Workspace, + previous: ReadonlyMap = new Map(), +): Promise<{ tasks: Task[]; issues: string[] }> { + const tasks: Task[] = [], + issues: string[] = []; + // Direct reads are necessary because the host hides .runestone from root listings. + if ( + !workspace.readOptional || + (await workspace.readOptional(cardsMarker)) === null + ) + return { tasks, issues }; + const entries = (await workspace.list(cardsFolder)).filter( + (entry) => entry.kind !== "folder" && isHiddenCard(entry.rel_path), + ); + const sources = await readSources(workspace, entries.map(entry => entry.rel_path)); + const documents = await mapConcurrent(entries, async (entry) => { + try { + const result = sources.get(entry.rel_path)!; + if (result.error || result.source === undefined) throw new Error(result.error ?? "The card is unavailable."); + const source = result.source; + const cached = previous.get(entry.rel_path); + if (cached?.source === source) return { task: cached }; + return { task: parseCard(entry.rel_path, source) }; + } catch (error) { + return { + issue: `${entry.rel_path}: ${error instanceof Error ? error.message : String(error)}`, + }; + } + }); + for (const document of documents) { + if (document.task) tasks.push(document.task); + if (document.issue) issues.push(document.issue); + } + return { tasks, issues }; +} +export async function createCard( + workspace: Workspace, + title: string, + fields: TaskFields, + body: string, + id: string = crypto.randomUUID(), +) { + // The storage name is independent of the title, so punctuation and duplicate titles are safe. + const note = newTask(id, { ...fields, title: title.trim() }, body, id); + const path = cardPath(id); + await prepareCards(workspace); + await saveDocument(workspace, path, note.source, null); + return { path, source: note.source }; +} +export async function migrateCards(workspace: Workspace, tasks: Task[]) { + for (const task of tasks) { + if (isHiddenCard(task.path)) continue; + if ((await workspace.read(task.path)) !== task.source) + throw new Error( + `The card changed: ${task.path}. Refresh before migration.`, + ); + const destination = await readOptional(workspace, cardPath(task.id)); + if (destination !== null) { + const origin = cardOrigin(destination); + if (origin?.path !== task.path || origin.source !== task.source) + throw new Error( + `A different hidden card already uses the ID from ${task.path}.`, + ); + } + if (split(task.source).doc.has("runestone_pm_origin")) + throw new Error( + `The note already contains a migration record: ${task.path}. Review it before migration.`, + ); + } + for (const task of tasks) { + if (isHiddenCard(task.path)) continue; + const original = await backupFile(workspace, task.path, task.source); + const path = cardPath(task.id); + if ((await readOptional(workspace, path)) !== null) continue; + const { doc, body, newline, match } = split(task.source); + doc.set("runestone_pm_origin", original); + if (task.order === undefined) + doc.setIn(["runestone_pm", "order"], legacyPosition(task.path)); + for (const [id, placement] of Object.entries(task.placements ?? {})) + if (placement.order === undefined) + doc.setIn( + ["runestone_pm", "placements", id, "order"], + legacyPosition(task.path), + ); + const source = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`; + const copied = readTask(path, source)!; + if ( + copied.id !== task.id || + copied.title !== task.title || + copied.body !== task.body + ) + throw new Error( + `The card copy differs from ${task.path}. Keep the original.`, + ); + if ((await workspace.read(task.path)) !== task.source) + throw new Error(`The card changed: ${task.path}. Retry migration.`); + await prepareCards(workspace); + await saveDocument(workspace, path, source, null); + if ((await workspace.read(path)) !== source) + throw new Error( + `The saved card check failed: ${task.path}. Keep the original.`, + ); + } +} diff --git a/src/lib/features/pm/storage/catalog.ts b/src/lib/features/pm/storage/catalog.ts new file mode 100644 index 0000000..cb148d9 --- /dev/null +++ b/src/lib/features/pm/storage/catalog.ts @@ -0,0 +1,140 @@ +import { Document } from "yaml"; +import { + defaultBoard, + parseBoard, + type Board, + type BoardDocument, +} from "./board.ts"; +import type { Workspace } from "../model/model.ts"; +import { readOptional, saveDocument } from "./persistence.ts"; + +export const catalogPath = ".runestone/pm/workspace.json"; +export const boardKey = (id: string) => `pm-board:${id}`; +export const isManagedBoard = (path: string) => path.startsWith("pm-board:"); +export interface OriginalFile { + path: string; + source: string; + backup: string; +} +export interface ManagedBoard { + name: string; + value: Board; + archived?: boolean; + original?: OriginalFile; +} +export interface Catalog { + schema: 1; + boards: ManagedBoard[]; + deletedBoardIds?: string[]; + [key: string]: unknown; +} +export function boardMarkdown(value: Board): string { + return `---\n${new Document({ runestone_pm: value }).toString({ lineWidth: 0 })}---\n`; +} +export function validateName(name: string) { + if (!name.trim() || name.trim().length > 100 || /[\x00-\x1f]/.test(name)) + throw new Error("Enter a board name of 1 to 100 characters."); +} +export function parseCatalog(source: string | null): Catalog { + if (source === null) return { schema: 1, boards: [] }; + const data = JSON.parse(source); + if (!data || data.schema !== 1 || !Array.isArray(data.boards)) + throw new Error( + "The Project Management storage format is unsupported. Restore a backup or update Project Management.", + ); + const ids = new Set(); + if ( + data.deletedBoardIds !== undefined && + (!Array.isArray(data.deletedBoardIds) || + data.deletedBoardIds.some((id: unknown) => typeof id !== "string" || !id.trim()) || + new Set(data.deletedBoardIds).size !== data.deletedBoardIds.length) + ) + throw new Error("The deleted board record is invalid."); + for (const board of data.boards) { + if (!board || typeof board.name !== "string") + throw new Error("A saved board has no name."); + validateName(board.name); + parseBoard(boardMarkdown(board.value)); + if (ids.has(board.value.id)) + throw new Error("Project Management storage contains duplicate board IDs."); + ids.add(board.value.id); + if (data.deletedBoardIds?.includes(board.value.id)) + throw new Error("A deleted board still has an active storage entry."); + if (board.archived !== undefined && typeof board.archived !== "boolean") + throw new Error("The board archive state is invalid."); + if ( + board.original && + (typeof board.original.path !== "string" || + typeof board.original.source !== "string" || + typeof board.original.backup !== "string") + ) + throw new Error("The board migration record is invalid."); + } + return data; +} +export async function readCatalog(workspace: Workspace) { + const source = await readOptional(workspace, catalogPath); + return { source, value: parseCatalog(source) }; +} +export async function writeCatalog( + workspace: Workspace, + value: Catalog, + expected: string | null, +) { + if (!workspace.readOptional) + throw new Error("Update RuneStone to use hidden Project Management storage."); + const source = JSON.stringify(value, null, 2) + "\n"; + parseCatalog(source); + await saveDocument(workspace, catalogPath, source, expected); + return source; +} +export function managedDocuments( + value: Catalog, + source: string, +): BoardDocument[] { + return value.boards.map((board) => ({ + id: board.value.id, + path: boardKey(board.value.id), + name: board.name, + value: board.value, + archived: board.archived, + source, + })); +} +export async function createBoard(workspace: Workspace, name: string) { + validateName(name); + const snapshot = await readCatalog(workspace); + if ( + snapshot.value.boards.some( + (board) => + board.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(), + ) + ) + throw new Error("A board with this name already exists."); + const value = defaultBoard(); + snapshot.value.boards.push({ name: name.trim(), value }); + await writeCatalog(workspace, snapshot.value, snapshot.source); + return { id: value.id, path: boardKey(value.id) }; +} +export async function backupFile( + workspace: Workspace, + path: string, + source: string, +): Promise { + if ( + path.startsWith(".") || + path.includes("\\") || + path.split("/").some((part) => !part || part === ".." || part === ".") + ) + throw new Error("The migration source path is invalid."); + const backup = `.runestone/pm/backups/${path}`; + const saved = await readOptional(workspace, backup); + if (saved === null) await saveDocument(workspace, backup, source, null); + else if (saved !== source) + throw new Error( + `The backup differs from ${path}. Preserve both versions before migration.`, + ); + if ((await workspace.read(backup)) !== source) + throw new Error(`Backup check failed for ${path}.`); + return { path, source, backup }; +} diff --git a/src/lib/features/pm/storage/deleted-cards.ts b/src/lib/features/pm/storage/deleted-cards.ts new file mode 100644 index 0000000..62c2ae4 --- /dev/null +++ b/src/lib/features/pm/storage/deleted-cards.ts @@ -0,0 +1,23 @@ +import type { Workspace } from "../model/model.ts"; +import { readOptional, saveDocument } from "./persistence.ts"; + +export const deletedCardsPath = ".runestone/pm/deleted-cards.json"; + +export async function readDeletedCards(workspace: Workspace) { + const source = await readOptional(workspace, deletedCardsPath); + if (source === null) return { source, ids: [] as string[] }; + const value = JSON.parse(source); + if (value?.schema !== 1 || !Array.isArray(value.ids) || + value.ids.some((id: unknown) => typeof id !== "string" || !id.trim()) || + new Set(value.ids).size !== value.ids.length) + throw new Error("The deleted card record is invalid. Restore it before editing cards."); + return { source, ids: value.ids as string[] }; +} + +/** Keep a deletion record so saved legacy notes cannot restore deleted cards. */ +export async function recordCardDeletion(workspace: Workspace, id: string) { + const snapshot = await readDeletedCards(workspace); + if (snapshot.ids.includes(id)) return; + await saveDocument(workspace, deletedCardsPath, + JSON.stringify({ schema: 1, ids: [...snapshot.ids, id] }, null, 2) + "\n", snapshot.source); +} diff --git a/src/lib/features/pm/storage/description-draft.ts b/src/lib/features/pm/storage/description-draft.ts new file mode 100644 index 0000000..faa075c --- /dev/null +++ b/src/lib/features/pm/storage/description-draft.ts @@ -0,0 +1,33 @@ +import type { Workspace } from "../model/model.ts"; +import { readOptional, saveDocument } from "./persistence.ts"; + +/** A draft is separate from the saved card and uses compare-and-write protection. */ +export class DescriptionDraft { + private source: string | null = null; + private queue: Promise = Promise.resolve(); + readonly path: string; + private workspace: Workspace; + constructor(workspace: Workspace, id: string) { + this.workspace = workspace; + const key = Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join(""); + this.path = `.runestone/pm/drafts/${key}.json`; + } + async load(): Promise { + this.source = await readOptional(this.workspace, this.path); + if (this.source === null) return null; + const value = JSON.parse(this.source); + if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string")) + throw new Error("The description draft is invalid. Preserve it before recovery."); + return value.body; + } + save(body: string | null): Promise { + const write = this.queue.then(async () => { + const source = JSON.stringify({ schema: 1, body }) + "\n"; + if (source === this.source || (body === null && this.source === null)) return; + await saveDocument(this.workspace, this.path, source, this.source); + this.source = source; + }); + this.queue = write.catch(() => {}); + return write; + } +} diff --git a/src/lib/features/pm/storage/images.ts b/src/lib/features/pm/storage/images.ts new file mode 100644 index 0000000..2a88dce --- /dev/null +++ b/src/lib/features/pm/storage/images.ts @@ -0,0 +1,69 @@ +import type { Workspace, TaskFields } from "../model/model.ts"; +import { saveDocument, storageRoot } from "./persistence.ts"; + +export const maxImageBytes = 50 * 1024 * 1024; +export const imageTypes = [ + "image/png", + "image/jpeg", + "image/gif", + "image/webp", +]; +const idPattern = + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; +export const imageFolder = `${storageRoot}/images`; +export function imagePath(id: string) { + if (!new RegExp(`^${idPattern}$`).test(id)) + throw new Error("The image ID is invalid."); + return `${imageFolder}/${id}.json`; +} +export function imageReferences(body: string) { + return [ + ...body.matchAll( + new RegExp(`!\\[([^\\]\\r\\n]*)\\]\\(pm-image:(${idPattern})\\)`, "g"), + ), + ].map((match) => ({ + id: match[2], + name: match[1] || "Pasted image", + markdown: match[0], + index: match.index, + })); +} +export function imageMarkdown(name: string, id: string) { + imagePath(id); + return `![${name.replace(/[\[\]\r\n\\]/g, " ").trim() || "Pasted image"}](pm-image:${id})`; +} +export function parseImage(source: string): string { + if (source.length > Math.ceil(maxImageBytes / 3) * 4 + 256) + throw new Error("The saved image exceeds the 50 MiB limit."); + const value = JSON.parse(source); + if (value?.schema !== 1 || typeof value.data !== "string") + throw new Error("The saved image is invalid."); + const match = + /^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec( + value.data, + ); + if ( + !match || + match[2].length % 4 !== 0 || + atob(match[2]).length > maxImageBytes + ) + throw new Error("The saved image is invalid or exceeds 50 MiB."); + return value.data; +} +export async function saveImages( + workspace: Workspace, + body: string, + pending: Map, + attachments: TaskFields["attachments"] = [], +) { + for (const id of new Set([...imageReferences(body), ...attachments].map((image) => image.id))) { + const data = pending.get(id); + if (!data) continue; + const source = JSON.stringify({ schema: 1, data }) + "\n"; + parseImage(source); + const path = imagePath(id); + // Retrying a failed card save reuses its complete image files. + const previous = await workspace.readOptional?.(path); + if (previous !== source) await saveDocument(workspace, path, source, null); + } +} diff --git a/src/lib/features/pm/storage/labels.ts b/src/lib/features/pm/storage/labels.ts new file mode 100644 index 0000000..1c34f03 --- /dev/null +++ b/src/lib/features/pm/storage/labels.ts @@ -0,0 +1,141 @@ +import { cardColors, type Workspace } from "../model/model.ts"; +import { readOptional, saveDocument } from "./persistence.ts"; + +export const labelsPath = ".runestone/pm/labels.json"; +export const legacyLabelsPath = "runestone-pm-labels.json"; +export interface SavedLabel { + id: string; + name: string; + color: keyof typeof cardColors; + archived?: boolean; +} +export interface LabelSnapshot { + source: string | null; + labels: SavedLabel[]; + legacy?: boolean; +} +export function defaultLabels(): SavedLabel[] { + return [ + { id: "bug", name: "Bug", color: "red" }, + { id: "feature", name: "Feature", color: "blue" }, + { id: "improvement", name: "Improvement", color: "green" }, + ]; +} +export function validateLabels( + labels: unknown, +): asserts labels is SavedLabel[] { + if (!Array.isArray(labels)) throw new Error("Saved labels must be a list."); + const ids = new Set(), + names = new Set(); + for (const label of labels) { + if ( + !label || + typeof label !== "object" || + Array.isArray(label) || + typeof label.id !== "string" || + !/^[a-zA-Z0-9_-]{1,100}$/.test(label.id) || + ids.has(label.id) + ) + throw new Error("Each saved label needs a unique ID."); + if ( + typeof label.name !== "string" || + !label.name.trim() || + label.name.trim().length > 80 || + /[\x00-\x1f\x7f]/.test(label.name) + ) + throw new Error("Enter a label name of 1 to 80 characters."); + const name = label.name.trim().toLocaleLowerCase(); + if (names.has(name)) + throw new Error( + "Use a different name for each label, including archived labels.", + ); + if ( + typeof label.color !== "string" || + !Object.hasOwn(cardColors, label.color) + ) + throw new Error("Choose a supported label color."); + if (label.archived !== undefined && typeof label.archived !== "boolean") + throw new Error("Label archive state must be true or false."); + ids.add(label.id); + names.add(name); + } +} +export function parseLabels(source: string | null): LabelSnapshot { + if (source === null) return { source, labels: defaultLabels() }; + let data; + try { + data = JSON.parse(source); + } catch { + throw new Error("Fix the saved labels file before editing labels."); + } + if ( + !data || + typeof data !== "object" || + Array.isArray(data) || + data.schema !== 1 + ) + throw new Error("The saved labels file has an unsupported schema."); + validateLabels(data.labels); + return { source, labels: data.labels }; +} + +export class LabelStore { + value: SavedLabel[] = []; + source: string | null | undefined; + error = ""; + legacy = false; + readonly workspace: Workspace; + constructor(workspace: Workspace) { + this.workspace = workspace; + } + async read(): Promise { + const source = await readOptional(this.workspace, labelsPath); + if (source !== null) return parseLabels(source); + const legacy = await readOptional(this.workspace, legacyLabelsPath); + return { ...parseLabels(legacy), legacy: legacy !== null }; + } + load(snapshot?: LabelSnapshot, error = "") { + this.value = snapshot?.labels ?? []; + this.source = snapshot?.source; + this.error = error; + this.legacy = snapshot?.legacy ?? false; + } + checkSave(labels: SavedLabel[], expected: string | null | undefined): asserts expected is string | null { + if (this.legacy) + throw new Error( + "Use the workspace migration tool before editing legacy labels. See the Project Management development guide.", + ); + if (!this.workspace.readOptional) + throw new Error("Update RuneStone to use hidden Project Management storage."); + if (expected === undefined || this.error) + throw new Error( + "Saved labels are unavailable. Refresh before editing labels.", + ); + validateLabels(labels); + } + async save(labels: SavedLabel[], expected: string | null | undefined, allowDelete = false) { + this.checkSave(labels, expected); + const previous = parseLabels(expected!); + if ( + !allowDelete && previous.labels.some( + (label) => !labels.some((next) => next.id === label.id), + ) + ) + throw new Error("Archive unused labels to preserve existing cards."); + const data = expected === null ? { schema: 1 } : JSON.parse(expected); + const source = + JSON.stringify( + { + ...data, + labels: labels.map((label) => ({ + ...label, + name: label.name.trim(), + })), + }, + null, + 2, + ) + "\n"; + await saveDocument(this.workspace, labelsPath, source, expected); + this.load(parseLabels(source)); + } +} diff --git a/src/lib/features/pm/storage/legacy.ts b/src/lib/features/pm/storage/legacy.ts new file mode 100644 index 0000000..d4ea794 --- /dev/null +++ b/src/lib/features/pm/storage/legacy.ts @@ -0,0 +1,78 @@ +// The legacy format: boards and task notes in visible Markdown files, and the root label file. +// The native feature reads only `.runestone/pm/`. When it opens a workspace that still has data in the legacy format, +// it offers the migration (`migrateStorage` in `migration.ts`), and it migrates only after the user chooses it. +import type { Workspace } from "../model/model.ts"; +import { readCatalog } from "./catalog.ts"; +import { cardPath } from "./cards.ts"; +import { readDeletedCards } from "./deleted-cards.ts"; +import { labelsPath, legacyLabelsPath } from "./labels.ts"; +import { split } from "./notes.ts"; +import { cardsFolder, readOptional } from "./persistence.ts"; +import { markdownPaths, readSources } from "./scan.ts"; + +/** The legacy data that the migration has not copied to `.runestone/pm/` yet. */ +export interface LegacyContent { + /** The paths of board notes. */ + boards: string[]; + /** The paths of task notes. */ + cards: string[]; + /** The paths of notes with invalid Project Management properties. The migration reports them. */ + invalid: string[]; + /** True when `runestone-pm-labels.json` exists and `.runestone/pm/labels.json` does not. */ + labels: boolean; +} + +/** The YAML properties at the start of a note, up to a line that starts with `runestone_pm:`. The closing line stops it. */ +const properties = /^---[ \t]*\r?\n(?:(?!(?:---|\.\.\.)[ \t]*\r?\n)[^\n]*\n)*?runestone_pm[ \t]*:/; + +/** True when the YAML properties of a note can contain Project Management data. It needs no YAML parse. */ +export function mentionsProjectData(source: string): boolean { + return properties.test(source.charCodeAt(0) === 0xfeff ? source.slice(1) : source); +} + +/** + * Find the legacy data of a workspace. Only notes that name `runestone_pm` in their properties get a YAML parse. + * A board or a card that the migration copied, or that the user deleted, does not count. + */ +export async function findLegacy(workspace: Workspace, check: () => void = () => {}): Promise { + const result: LegacyContent = { boards: [], cards: [], invalid: [], labels: false }; + const paths = await markdownPaths(workspace, check); + const found: { path: string; kind: "board" | "task"; id: string }[] = []; + // One batch at a time, so the texts of all notes are never in memory together. + for (let offset = 0; offset < paths.length; offset += 64) { + const sources = await readSources(workspace, paths.slice(offset, offset + 64)); + check(); + for (const [path, file] of sources) { + if (file.source === undefined || !mentionsProjectData(file.source)) continue; + try { + const value = split(file.source).doc.toJS({ maxAliasCount: 50 }).runestone_pm; + if (value === undefined) continue; + if (!value || typeof value.id !== "string" || !value.id.trim() || (value.kind !== "board" && value.kind !== "task")) throw new Error("Invalid data."); + found.push({ path, kind: value.kind, id: value.id }); + } catch { result.invalid.push(path); } + } + } + let saved = new Set(), deletedBoards = new Set(), deletedCards = new Set(); + try { + const catalog = await readCatalog(workspace); + saved = new Set(catalog.value.boards.map(board => board.value.id)); + deletedBoards = new Set(catalog.value.deletedBoardIds ?? []); + } catch { /* The migration reports a damaged catalog. */ } + try { deletedCards = new Set((await readDeletedCards(workspace)).ids); } catch { /* The migration reports it. */ } + let cards = new Set(); + if (found.some(item => item.kind === "task")) { + try { cards = new Set((await workspace.list(cardsFolder)).map(entry => entry.rel_path)); } catch { /* No card folder yet. */ } + } + for (const item of found) { + if (item.kind === "board" && !saved.has(item.id) && !deletedBoards.has(item.id)) result.boards.push(item.path); + if (item.kind === "task" && !cards.has(cardPath(item.id)) && !deletedCards.has(item.id)) result.cards.push(item.path); + } + result.labels = (await readOptional(workspace, legacyLabelsPath)) !== null && (await readOptional(workspace, labelsPath)) === null; + for (const list of [result.boards, result.cards, result.invalid]) list.sort(); + return result; +} + +/** True when the workspace has legacy data to migrate. */ +export function hasLegacy(content: LegacyContent): boolean { + return content.boards.length > 0 || content.cards.length > 0 || content.invalid.length > 0 || content.labels; +} diff --git a/src/lib/features/pm/storage/migration.ts b/src/lib/features/pm/storage/migration.ts new file mode 100644 index 0000000..7cdf3a8 --- /dev/null +++ b/src/lib/features/pm/storage/migration.ts @@ -0,0 +1,152 @@ +import type { Workspace, Task } from "../model/model.ts"; +import { migrateCards, readCards, cardOrigin } from "./cards.ts"; +import type { BoardDocument } from "./board.ts"; +import { + backupFile, + readCatalog, + writeCatalog, + isManagedBoard, + type OriginalFile, +} from "./catalog.ts"; +import { labelsPath, legacyLabelsPath, parseLabels } from "./labels.ts"; +import { + readOptional, + saveDocument, + ensurePrivateStorage, +} from "./persistence.ts"; + +/** Retain originals until the user checks the boards and removes the listed files. */ +export async function migrateStorage( + workspace: Workspace, + boards: BoardDocument[], + cards: Task[] = [], +) { + if (!workspace.readOptional || !workspace.create) + throw new Error("Update RuneStone before migrating Project Management storage."); + const snapshot = await readCatalog(workspace); + const legacy = boards.filter((board) => !isManagedBoard(board.path)); + const legacyLabels = await readOptional(workspace, legacyLabelsPath); + const savedLabels = await readOptional(workspace, labelsPath); + if (legacyLabels !== null) parseLabels(legacyLabels); + if (savedLabels !== null) parseLabels(savedLabels); + // Validate every source before creating backups or publishing any changes. + for (const board of legacy) { + if (snapshot.value.deletedBoardIds?.includes(board.id)) + throw new Error("This board was deleted. Refresh Project Management before migration."); + if ((await workspace.read(board.path)) !== board.source) + throw new Error( + `The board changed: ${board.path}. Refresh before migration.`, + ); + const existing = snapshot.value.boards.find( + (item) => item.value.id === board.id, + ); + if ( + existing && + (existing.original?.path !== board.path || + existing.original.source !== board.source) + ) + throw new Error( + `A different board already uses the ID from ${board.path}.`, + ); + } + if (legacyLabels !== null && savedLabels !== null) { + const original = JSON.parse(savedLabels).original; + if ( + original?.path !== legacyLabelsPath || + original?.source !== legacyLabels + ) + throw new Error( + "Hidden labels and legacy labels both exist. Resolve their differences before migration.", + ); + } + await ensurePrivateStorage(workspace); + let changed = false; + for (const board of legacy) { + if (snapshot.value.boards.some((item) => item.value.id === board.id)) + continue; + const original = await backupFile(workspace, board.path, board.source); + snapshot.value.boards.push({ + name: board.name, + value: board.value, + original, + }); + changed = true; + } + const labelBackup = + legacyLabels !== null && savedLabels === null + ? await backupFile(workspace, legacyLabelsPath, legacyLabels) + : undefined; + for (const board of legacy) + if ((await workspace.read(board.path)) !== board.source) + throw new Error( + `The board changed: ${board.path}. Refresh before migration.`, + ); + if (legacyLabels !== (await readOptional(workspace, legacyLabelsPath))) + throw new Error("Legacy labels changed. Refresh before migration."); + if (changed) await writeCatalog(workspace, snapshot.value, snapshot.source); + if (labelBackup) { + const source = + JSON.stringify( + { ...JSON.parse(legacyLabels!), original: labelBackup }, + null, + 2, + ) + "\n"; + await saveDocument(workspace, labelsPath, source, null); + if ((await workspace.read(labelsPath)) !== source) + throw new Error("The saved label check failed. Retry migration."); + } + const saved = await readCatalog(workspace); + for (const board of legacy) { + const entry = saved.value.boards.find((item) => item.value.id === board.id); + const expected = snapshot.value.boards.find( + (item) => item.value.id === board.id, + ); + if ( + entry?.original?.source !== board.source || + JSON.stringify(entry) !== JSON.stringify(expected) + ) + throw new Error("The saved board check failed. Retry migration."); + } + await migrateCards(workspace, cards); + const files = await migrationFiles(workspace); + for (const file of files) { + if ((await workspace.read(file.backup)) !== file.source) + throw new Error( + `Backup check failed for ${file.path}. Keep the original.`, + ); + const current = await readOptional(workspace, file.path); + if (current !== null && current !== file.source) + throw new Error( + `The original changed: ${file.path}. Keep both versions.`, + ); + } + return files; +} + +export async function migrationFiles( + workspace: Workspace, +): Promise { + const snapshot = await readCatalog(workspace); + const files = snapshot.value.boards.flatMap((board) => + board.original ? [board.original] : [], + ); + const labels = await readOptional(workspace, labelsPath); + if (labels !== null) { + parseLabels(labels); + const original = JSON.parse(labels).original; + if ( + original && + typeof original.path === "string" && + typeof original.source === "string" && + typeof original.backup === "string" + ) + files.push(original); + } + const cards = await readCards(workspace); + if (cards.issues.length) throw new Error(cards.issues.join(" ")); + for (const task of cards.tasks) { + const original = cardOrigin(task.source); + if (original) files.push(original); + } + return files; +} diff --git a/src/lib/features/pm/storage/notes.ts b/src/lib/features/pm/storage/notes.ts new file mode 100644 index 0000000..ba19769 --- /dev/null +++ b/src/lib/features/pm/storage/notes.ts @@ -0,0 +1,211 @@ +import { Document, isMap, parseDocument } from "yaml"; +import { isHiddenCard } from "./persistence.ts"; +import { + validateFields, + type Task, + type TaskFields, + type Status, + type Session, +} from "../model/model.ts"; + +const frontmatter = + /^(\uFEFF?)(---[ \t]*\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$))/; +export function split(source: string) { + const match = frontmatter.exec(source); + if (!match && /^\uFEFF?---[ \t]*\r?\n/.test(source)) + throw new Error( + "Close the YAML properties block before editing this note.", + ); + const doc = match + ? parseDocument(match[3], { uniqueKeys: true, keepSourceTokens: true }) + : new Document({}); + if (doc.errors.length || doc.warnings.length) + throw new Error( + "Fix invalid or unsupported YAML properties before editing this note.", + ); + if (!isMap(doc.contents)) + throw new Error("Note properties must be a YAML mapping."); + return { + match, + doc, + body: match ? source.slice(match[0].length) : source, + newline: source.includes("\r\n") ? "\r\n" : "\n", + }; +} +function record(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +export function readTask(path: string, source: string): Task | null { + const { doc, body } = split(source); + const metadata = doc.toJS({ maxAliasCount: 50 }); + const pm: unknown = metadata.runestone_pm; + if (pm === undefined) return null; + if (record(pm) && pm.kind === "board") return null; + if ( + !record(pm) || + pm.schema !== 1 || + pm.kind !== "task" || + typeof pm.id !== "string" || + !pm.id.trim() + ) { + throw new Error("This note has an unsupported Project Management schema, kind, or ID."); + } + if (pm.archived !== undefined && typeof pm.archived !== "boolean") + throw new Error("Archive state must be true or false."); + if ( + pm.due !== undefined && + (!record(pm.due) || typeof pm.due.date !== "string") + ) + throw new Error("This preview supports date-only deadlines."); + if ( + pm.plan !== undefined && + (!record(pm.plan) || + typeof pm.plan.start !== "string" || + typeof pm.plan.end !== "string") + ) + throw new Error("The plan needs a start and an exclusive end date."); + if ( + pm.sessions !== undefined && + (!Array.isArray(pm.sessions) || + pm.sessions.some( + (value) => + !record(value) || + typeof value.id !== "string" || + typeof value.start !== "string" || + typeof value.end !== "string" || + typeof value.timeZone !== "string", + )) + ) { + throw new Error("Sessions need an ID, start, end, and time zone."); + } + const task: Task = { + id: pm.id, + createdAt: pm.createdAt as string | undefined, + path, + title: + pm.title === undefined + ? (isHiddenCard(path) && + record(metadata.runestone_pm_origin) && + typeof metadata.runestone_pm_origin.path === "string" + ? metadata.runestone_pm_origin.path + : path + ) + .split("/") + .at(-1)! + .replace(/\.(md|markdown|mdown)$/i, "") + : (pm.title as string), + order: pm.order as string | undefined, + body, + source, + status: pm.status as Status, + listId: pm.listId as string | null | undefined, + placements: pm.placements as Task["placements"], + tags: (pm.tags ?? []) as string[], + labels: pm.labels as Task["labels"], + priority: pm.priority as Task["priority"], + coverImage: pm.coverImage as Task["coverImage"], + attachments: pm.attachments as Task["attachments"], + subtasks: pm.subtasks as Task["subtasks"], + links: pm.links as Task["links"], + color: pm.color as Task["color"], + assignees: pm.assignees as Task["assignees"], + customFields: pm.customFields as Task["customFields"], + due: pm.due as Task["due"], + plan: pm.plan as Task["plan"], + sessions: (pm.sessions ?? []) as Session[], + archived: pm.archived === true, + }; + validateFields({ ...task, title: pm.title as string | undefined }); + return task; +} + +// Update individual YAML nodes so unknown keys and comments remain in the document. +export function editTask( + task: Task, + patch: Partial & { body?: string }, +): string { + const fields = { ...task, title: undefined, ...patch }; + if (Object.hasOwn(patch, "createdAt") && patch.createdAt !== task.createdAt) + throw new Error("The card creation timestamp cannot change."); + validateFields(fields); + const { doc, match, newline } = split(task.source); + for (const key of [ + "title", + "order", + "listId", + "placements", + "status", + "tags", + "labels", + "priority", + "coverImage", + "attachments", + "subtasks", + "links", + "color", + "assignees", + "customFields", + "due", + "plan", + "sessions", + "archived", + ] as const) { + if (!Object.hasOwn(patch, key)) continue; + const value = patch[key]; + if (value === undefined) { + doc.deleteIn(["runestone_pm", key]); + continue; + } + if (key === "due" || key === "plan") { + for (const [name, child] of Object.entries(value as object)) + doc.setIn(["runestone_pm", key, name], child); + } else doc.setIn(["runestone_pm", key], value); + } + const bom = match?.[1] ?? ""; + const yaml = doc.toString({ lineWidth: 0 }).replaceAll("\n", newline); + const closing = match?.[4].replace(/^\r?\n/, "") ?? `---${newline}`; + return `${bom}---${newline}${yaml}${closing}${patch.body ?? task.body}`; +} +export function newTask( + title: string, + fields: TaskFields, + body = "", + id: string = crypto.randomUUID(), +): { path: string; source: string } { + title = title.trim(); + if ( + !title || + title.length > 100 || + /[<>:"/\\|?*\x00-\x1f]/.test(title) || + /[. ]$/.test(title) || + /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(title) + ) + throw new Error("Use a valid note name of 1 to 100 characters."); + validateFields(fields); + const doc = new Document({ + runestone_pm: { schema: 1, id, kind: "task", ...fields, createdAt: fields.createdAt ?? new Date().toISOString() }, + }); + return { + path: `Projects/Inbox/${title}.md`, + source: `---\n${doc.toString({ lineWidth: 0 })}---\n${body}`, + }; +} +export function adoptNote(path: string, source: string): string { + if (readTask(path, source)) return source; + const { doc, body, match, newline } = split(source); + if (doc.has("runestone_pm")) + throw new Error( + "This document already contains Project Management data and cannot become a task.", + ); + doc.set("runestone_pm", { + schema: 1, + id: crypto.randomUUID(), + kind: "task", + createdAt: new Date().toISOString(), + status: "todo", + tags: [], + sessions: [], + archived: false, + }); + return `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`; +} diff --git a/src/lib/features/pm/storage/order.ts b/src/lib/features/pm/storage/order.ts new file mode 100644 index 0000000..9c98356 --- /dev/null +++ b/src/lib/features/pm/storage/order.ts @@ -0,0 +1,41 @@ +import type { Task } from "../model/model.ts"; + +const digits = "0123456789abcdefghijklmnopqrstuvwxyz"; +const encode = (text: string) => + text + .split("") + .map((char) => char.charCodeAt(0).toString(16).padStart(4, "0")) + .join(""); + +export function cardOrder(task: Task, boardId?: string): string { + const saved = boardId ? task.placements?.[boardId]?.order : task.order; + // Old notes keep filename order. Title edits do not change their positions. + const position = saved ?? legacyPosition(task.path); + // The ID breaks ties when separate windows choose the same position. + return position + "i" + encode(task.id) + "8"; +} + +export function legacyPosition(path: string): string { + return encode(path.split("/").at(-1)!.toLowerCase()) + "0000" + encode(path); +} + +export function compareCards(a: Task, b: Task, boardId?: string): number { + const left = cardOrder(a, boardId), + right = cardOrder(b, boardId); + return left < right ? -1 : left > right ? 1 : 0; +} + +export function orderBetween(lower?: string, upper?: string): string { + if (lower !== undefined && upper !== undefined && lower >= upper) + throw new Error("The card order changed. Refresh the board."); + let result = ""; + for (let index = 0; ; index++) { + const low = + index < (lower?.length ?? 0) ? digits.indexOf(lower![index]) : 0; + const high = + upper === undefined ? digits.length : digits.indexOf(upper[index]); + if (high - low > 1) return result + digits[Math.floor((low + high) / 2)]; + result += digits[low]; + if (low < high) upper = undefined; + } +} diff --git a/src/lib/features/pm/storage/persistence.ts b/src/lib/features/pm/storage/persistence.ts new file mode 100644 index 0000000..0038101 --- /dev/null +++ b/src/lib/features/pm/storage/persistence.ts @@ -0,0 +1,61 @@ +import type { Workspace } from "../model/model.ts"; + +export const storageRoot = ".runestone/pm"; +export const privateRulesPath = `${storageRoot}/.gitignore`; +export const cardsFolder = `${storageRoot}/cards`; +export const cardsMarker = `${cardsFolder}/.gitignore`; +export const isHiddenCard = (path: string) => + path.startsWith(cardsFolder + "/") && /\.md$/i.test(path); + +/** Install the local exclusion before publishing any private Project Management data. */ +export async function ensurePrivateStorage(workspace: Workspace) { + if (!workspace.readOptional || !workspace.create) + throw new Error("Update RuneStone to use hidden Project Management storage."); + const expected = await workspace.readOptional(privateRulesPath); + const rules = expected + ?.split(/\r?\n/) + .filter((line) => line && !line.startsWith("#")); + if (rules?.at(-1) === "*") return; + const source = + (expected ? expected + (expected.endsWith("\n") ? "" : "\n") : "") + + "# RuneStone Project Management local data\n*\n"; + if (expected === null) { + try { + await workspace.create(privateRulesPath, source); + } catch (error) { + if ((await workspace.readOptional(privateRulesPath)) !== source) + throw error; + } + } else await workspace.write(privateRulesPath, source, expected); + if ((await workspace.readOptional(privateRulesPath)) !== source) + throw new Error( + "The Project Management Git exclusion changed. Retry before saving private data.", + ); +} + +/** Older hosts cannot discover hidden files through the root listing. */ +export async function readOptional( + workspace: Workspace, + path: string, +): Promise { + if (workspace.readOptional) return workspace.readOptional(path); + const entries = await workspace.list(); + if (entries.some((entry) => entry.rel_path === path)) + return workspace.read(path); + return null; +} + +export async function saveDocument( + workspace: Workspace, + path: string, + source: string, + expected: string | null, +) { + if (path.startsWith(storageRoot + "/") && path !== privateRulesPath) + await ensurePrivateStorage(workspace); + if (expected === null) { + if (!workspace.create) + throw new Error("Update RuneStone to create Project Management storage."); + await workspace.create(path, source); + } else await workspace.write(path, source, expected); +} diff --git a/src/lib/features/pm/storage/scan.ts b/src/lib/features/pm/storage/scan.ts new file mode 100644 index 0000000..f17787c --- /dev/null +++ b/src/lib/features/pm/storage/scan.ts @@ -0,0 +1,82 @@ +import type { Workspace } from "../model/model.ts"; + +// Limit concurrent bridge requests, including large workspaces with many notes. +export const scanConcurrency = 8; + +/** Read bounded batches while retaining each file's failure and conflict evidence. */ +export async function readSources(workspace: Workspace, paths: string[]) { + const results = new Map(); + if (workspace.readMany) { + for (let offset = 0; offset < paths.length; offset += 64) { + const batch = paths.slice(offset, offset + 64); + const rows = await workspace.readMany(batch); + for (const path of batch) { + const row = rows.find(row => row.path === path); + results.set(path, row && (typeof row.source === "string" || row.error) ? row : { error: "The batch did not return this file." }); + } + } + } else { + await mapConcurrent(paths, async path => { + try { results.set(path, { source: await workspace.read(path) }); } + catch (error) { results.set(path, { error: error instanceof Error ? error.message : String(error) }); } + }); + } + return results; +} + +export async function mapConcurrent( + items: readonly T[], + visit: (item: T) => Promise, +): Promise { + const results = new Array(items.length); + let next = 0; + const workers = Array.from( + { length: Math.min(scanConcurrency, items.length) }, + async () => { + while (next < items.length) { + const index = next++; + results[index] = await visit(items[index]); + } + }, + ); + // Drain every worker before returning or reporting a failed directory read. + const settled = await Promise.allSettled(workers); + const failed = settled.find((result) => result.status === "rejected"); + if (failed?.status === "rejected") throw failed.reason; + return results; +} + +export async function markdownPaths( + workspace: Workspace, + check: () => void, +): Promise { + check(); + if (workspace.listMarkdown) { + const paths = await workspace.listMarkdown(); + check(); + return paths; + } + const files: string[] = []; + let folders = [""]; + while (folders.length) { + const listings = await mapConcurrent(folders, async (path) => { + check(); + return workspace.list(path); + }); + folders = []; + for (const entries of listings) { + check(); + for (const entry of entries) { + if ( + entry.name.startsWith(".") || + entry.rel_path.startsWith(".runestone/") + ) + continue; + if (entry.kind === "folder") folders.push(entry.rel_path); + else if (/\.(md|markdown|mdown)$/i.test(entry.name)) + files.push(entry.rel_path); + } + } + } + return files; +} diff --git a/src/lib/features/pm/ui/choices-ui.ts b/src/lib/features/pm/ui/choices-ui.ts new file mode 100644 index 0000000..1c310e2 --- /dev/null +++ b/src/lib/features/pm/ui/choices-ui.ts @@ -0,0 +1,62 @@ +import type { MenuHost } from "./host.ts"; + +/** Keep form values native while the host renders every choice menu. */ +export function createSharedChoices(root: HTMLElement, ui: MenuHost) { + const choices = new Map(); + let menu: { close(): void } | undefined; + let owner: HTMLSelectElement | undefined; + const close = () => { menu?.close(); menu = undefined; owner = undefined; }; + const sync = () => { + for (const [select, choice] of choices) { + if (!root.contains(select)) { + if (owner === select) close(); + choices.delete(select); + } else choice.update(); + } + }; + const observer = new MutationObserver(sync); + observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["disabled", "label", "selected"] }); + return { + use(select: HTMLSelectElement) { + const existing = choices.get(select); + if (existing) { existing.update(); return existing.trigger; } + const label = select.getAttribute("aria-label") ?? select.closest("label")?.firstChild?.textContent?.trim() ?? "Choose"; + const trigger = document.createElement("button"); + trigger.type = "button"; + trigger.className = "pm-button pm-choice-button"; + trigger.setAttribute("aria-label", label); + trigger.setAttribute("aria-haspopup", "menu"); + const text = document.createElement("span"); text.className = "pm-choice-label"; + const icon = document.createElement("span"); icon.className = "pm-icon"; + icon.innerHTML = ''; + trigger.append(text, icon); + const update = () => { + const value = select.selectedOptions[0]?.textContent ?? "Choose"; + if (text.textContent !== value) text.textContent = value; + if (trigger.disabled !== select.disabled) trigger.disabled = select.disabled; + }; + trigger.onclick = () => { + close(); update(); trigger.focus({ preventScroll: true }); + const bounds = trigger.getBoundingClientRect(); owner = select; + menu = ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: trigger.closest("dialog, [popover]") ?? undefined, + items: Array.from(select.options).map(option => ({ label: option.textContent ?? "", radio: true, + checked: option.selected, disabled: option.disabled, run: () => { + select.value = option.value; + select.dispatchEvent(new Event("change", { bubbles: true })); + sync(); + } })) }); + }; + trigger.onkeydown = event => { + if (["ArrowDown", "ArrowUp"].includes(event.key)) { event.preventDefault(); trigger.click(); } + }; + select.hidden = true; + select.after(trigger); + select.addEventListener("change", update); + choices.set(select, { trigger, update }); update(); + return trigger; + }, + close, + update(select: HTMLSelectElement) { choices.get(select)?.update(); }, + dispose() { close(); observer.disconnect(); choices.clear(); }, + }; +} diff --git a/src/lib/features/pm/ui/colors.ts b/src/lib/features/pm/ui/colors.ts new file mode 100644 index 0000000..3ce358c --- /dev/null +++ b/src/lib/features/pm/ui/colors.ts @@ -0,0 +1,75 @@ +import { cardColors } from "../model/model.ts"; + +// Labels retain the saved color names and use a vivid palette for recognition. +export const labelColors: Record = { + red: "#ff0000", orange: "#ff8000", amber: "#ffb000", yellow: "#ffe000", + lime: "#99ee00", green: "#00cc66", teal: "#00bfa5", cyan: "#00ccff", + blue: "#0066ff", indigo: "#5533ff", purple: "#aa00ff", magenta: "#ff00cc", + pink: "#ff4080", brown: "#a65316", slate: "#527da3", gray: "#858585", +}; + +export function swatchForeground(hex: string) { + const channels = hex.slice(1).match(/../g)!.map(value => { + const channel = parseInt(value, 16) / 255; + return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4; + }); + const luminance = channels[0] * 0.2126 + channels[1] * 0.7152 + channels[2] * 0.0722; + return (luminance + 0.05) / 0.05 > 1.05 / (luminance + 0.05) ? "#000000" : "#ffffff"; +} + +export function createColorPalette( + name: string, + initial: string, + change: (value: string) => void, + allowNone = false, + palette: Record = cardColors, +) { + const element = document.createElement("fieldset"); + element.className = "pm-color-palette pm-wide"; + element.setAttribute("role", "radiogroup"); + element.setAttribute("aria-label", name); + const legend = document.createElement("legend"); + legend.textContent = name; + const choices = document.createElement("div"); + choices.className = "pm-color-choices"; + const current = document.createElement("span"); + current.className = "pm-color-name"; + current.setAttribute("aria-hidden", "true"); + const group = "pm-colors-" + crypto.randomUUID(); + const inputs: HTMLInputElement[] = []; + const colorName = (value: string) => + value ? value[0].toUpperCase() + value.slice(1) : "None"; + const values = [...(allowNone ? [""] : []), ...Object.keys(cardColors)]; + let selected = initial; + const set = (value: string) => { + selected = value; + for (const input of inputs) input.checked = input.value === value; + current.textContent = colorName(value); + }; + for (const value of values) { + const input = document.createElement("input"); + input.type = "radio"; + input.name = group; + input.value = value; + input.className = "pm-color-swatch"; + input.setAttribute("aria-label", colorName(value)); + input.title = colorName(value); + if (value) { + input.style.setProperty( + "--pm-swatch-color", + palette[value as keyof typeof cardColors], + ); + input.style.setProperty("--pm-swatch-foreground", swatchForeground(palette[value as keyof typeof cardColors])); + } else input.classList.add("pm-no-color"); + input.onchange = () => { + if (!input.checked) return; + set(value); + change(value); + }; + inputs.push(input); + choices.append(input); + } + element.append(legend, choices, current); + set(initial); + return { element, value: () => selected, set }; +} diff --git a/src/lib/features/pm/ui/description-find.ts b/src/lib/features/pm/ui/description-find.ts new file mode 100644 index 0000000..fd92660 --- /dev/null +++ b/src/lib/features/pm/ui/description-find.ts @@ -0,0 +1,132 @@ +import { tooltip } from "./host.ts"; +/** Find within the Markdown field, using the host's shared Find presentation. */ +export function createDescriptionFind(textarea: HTMLTextAreaElement) { + const element = document.createElement("section"); + element.className = "rs-find-bar"; + element.setAttribute("aria-label", "Find in description"); + element.hidden = true; + element.innerHTML = `
+
+
+
`; + const input = element.querySelector("input")!; + const actions = element.querySelector(".rs-find-actions")!; + const options = element.querySelector(".rs-find-options")!; + const status = document.createElement("span"); + status.setAttribute("role", "status"); + status.setAttribute("aria-live", "polite"); + let current = -1; + let matches: { from: number; to: number }[] = []; + let returnStart = 0, returnEnd = 0; + const highlights = document.createElement("div"); + highlights.className = "pm-description-find-highlights"; + highlights.setAttribute("aria-hidden", "true"); highlights.hidden = true; + textarea.parentElement!.append(highlights); + function paint() { + highlights.replaceChildren(); + highlights.hidden = element.hidden || !matches.length; + if (highlights.hidden) return; + const style = getComputedStyle(textarea); + for (const property of ["font", "line-height", "padding", "letter-spacing", "tab-size"]) + highlights.style.setProperty(property, style.getPropertyValue(property)); + let end = 0; + for (const [index, match] of matches.entries()) { + highlights.append(document.createTextNode(textarea.value.slice(end, match.from))); + const mark = document.createElement("mark"); mark.textContent = textarea.value.slice(match.from, match.to); + if (index === current) mark.className = "pm-description-find-current"; + highlights.append(mark); end = match.to; + } + highlights.append(document.createTextNode(textarea.value.slice(end))); + } + function option(label: string) { + const wrapper = document.createElement("label"); + const checkbox = document.createElement("input"); checkbox.type = "checkbox"; + checkbox.onchange = refresh; + wrapper.append(checkbox, document.createTextNode(label)); options.append(wrapper); + return checkbox; + } + const matchCase = option("Match case"); + const wholeWord = option("Whole word"); + const regex = option("Regex"); + options.append(status); + function close() { + hide(); + textarea.focus({ preventScroll: true }); + textarea.setSelectionRange(returnStart, returnEnd); + } + function hide() { element.hidden = highlights.hidden = true; } + function action(label: string, path: string, run: () => void) { + const button = document.createElement("button"); + button.type = "button"; button.className = "rs-find-button pm-icon-button"; + button.setAttribute("aria-label", label); + button.innerHTML = ``; + tooltip(button, label); + button.onclick = run; actions.append(button); + return button; + } + const previous = action("Previous match (Shift+Enter)", "m18 15-6-6-6 6", () => next(true)); + const following = action("Next match (Enter)", "m6 9 6 6 6-6", () => next()); + action("Close find (Escape)", "m6 6 12 12M18 6 6 18", close); + function announce() { + status.textContent = input.value ? (matches.length ? `${current < 0 ? 0 : current + 1} of ${matches.length}` : "No matches") : ""; + } + function refresh() { + current = -1; matches = []; + input.setAttribute("aria-invalid", "false"); status.classList.remove("rs-find-error"); + if (input.value) { + try { + const pattern = regex.checked ? input.value : input.value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const expression = new RegExp(wholeWord.checked ? `\\b(?:${pattern})\\b` : pattern, `gmu${matchCase.checked ? "" : "i"}`); + for (const match of textarea.value.matchAll(expression)) { + if (match[0].length) matches.push({ from: match.index, to: match.index + match[0].length }); + } + } catch { + input.setAttribute("aria-invalid", "true"); status.classList.add("rs-find-error"); + } + } + previous.disabled = following.disabled = !matches.length; + if (input.getAttribute("aria-invalid") === "true") status.textContent = "Invalid expression"; + else announce(); + paint(); + } + function next(backward = false) { + if (!matches.length) return; + current = current < 0 ? (backward ? matches.length - 1 : 0) : (current + (backward ? -1 : 1) + matches.length) % matches.length; + const match = matches[current]; + returnStart = match.from; returnEnd = match.to; + textarea.setSelectionRange(match.from, match.to); + // Reveal the matching line without moving focus out of the Find controls. + const style = getComputedStyle(textarea); + const mirror = document.createElement("div"); + mirror.style.cssText = `position:absolute;visibility:hidden;white-space:pre-wrap;overflow-wrap:break-word;box-sizing:border-box;width:${textarea.clientWidth}px;font:${style.font};line-height:${style.lineHeight};padding:${style.padding}`; + mirror.textContent = textarea.value.slice(0, match.from); + const marker = document.createElement("span"); marker.textContent = textarea.value.slice(match.from, match.to); + mirror.append(marker); document.body.append(mirror); + const dialog = textarea.closest("dialog"); + if (dialog) dialog.scrollTop += textarea.getBoundingClientRect().top + marker.offsetTop - dialog.getBoundingClientRect().top - dialog.clientHeight / 2; + mirror.remove(); announce(); paint(); + } + input.oninput = refresh; + element.addEventListener("keydown", event => { + if (event.key === "Escape" || event.key === "Enter" && event.target === input) { + event.preventDefault(); event.stopPropagation(); + if (event.key === "Escape") close(); else next(event.shiftKey); + } + }); + textarea.addEventListener("input", refresh); + return { + element, + open() { + if (element.hidden) { + returnStart = textarea.selectionStart; returnEnd = textarea.selectionEnd; + const selected = textarea.value.slice(returnStart, returnEnd); + if (selected && !selected.includes("\n")) input.value = selected; + refresh(); + } + element.hidden = false; paint(); element.scrollIntoView({ block: "nearest" }); input.focus(); input.select(); + }, + close, + hide, + dispose() { textarea.removeEventListener("input", refresh); highlights.remove(); }, + }; +} diff --git a/src/lib/features/pm/ui/description-ui.ts b/src/lib/features/pm/ui/description-ui.ts new file mode 100644 index 0000000..e630f27 --- /dev/null +++ b/src/lib/features/pm/ui/description-ui.ts @@ -0,0 +1,250 @@ +import { tooltip } from "./host.ts"; +import type { createCardImages } from "./images-ui.ts"; +import { renderMarkdown } from "../model/markdown.ts"; +import { headingEdit } from "../model/description-format.ts"; +import { createDescriptionFind } from "./description-find.ts"; + +/** Description edits and formatted content share the card detail view. */ +export function createDescriptionEditor( + textarea: HTMLTextAreaElement, + images: ReturnType, + control: (name: string, action: () => void) => HTMLButtonElement, + persistence?: { save(): Promise; cancel(): Promise; }, +) { + const element = document.createElement("section"); + element.className = "pm-description-editor pm-wide"; + element.setAttribute("aria-label", "Description"); + const header = document.createElement("div"); + header.className = "pm-description-heading"; + const heading = document.createElement("h3"); + const toggleSection = document.createElement("button"); + toggleSection.type = "button"; toggleSection.className = "pm-section-toggle"; + toggleSection.innerHTML = 'Description'; + toggleSection.setAttribute("aria-expanded", "true"); heading.append(toggleSection); + const source = document.createElement("label"); + source.className = "pm-field pm-description-source"; + textarea.setAttribute("aria-label", "Details (Markdown)"); + source.append(textarea); + const find = createDescriptionFind(textarea); + const preview = document.createElement("div"); + preview.className = "pm-markdown-preview"; + preview.setAttribute("role", "region"); + preview.setAttribute("aria-label", "Description preview"); + const toolbar = document.createElement("div"); + toolbar.className = "pm-description-toolbar"; + toolbar.setAttribute("role", "group"); + toolbar.setAttribute("aria-label", "Markdown formatting"); + textarea.spellcheck = true; + const resize = () => { + if (source.hidden || !textarea.isConnected) return; + textarea.style.height = "auto"; + textarea.style.height = `${Math.max(150, textarea.scrollHeight + 2)}px`; + }; + let width = 0; + let resizeFrame = 0; + const observer = new ResizeObserver(() => { + if (textarea.clientWidth && textarea.clientWidth !== width) { + width = textarea.clientWidth; + cancelAnimationFrame(resizeFrame); + resizeFrame = requestAnimationFrame(resize); + } + }); + observer.observe(element); + let disposed = false; + let revision = 0; + let editing = !textarea.value.trim(); + let original = textarea.value; + let pending = false; + const unsaved = document.createElement("span"); + unsaved.className = "pm-description-unsaved"; + unsaved.textContent = "Unsaved changes"; + unsaved.hidden = true; + unsaved.setAttribute("aria-live", "polite"); + function insert(before: string, after: string, placeholder: string) { + const start = textarea.selectionStart; + const selection = textarea.value.slice(start, textarea.selectionEnd) || placeholder; + textarea.setRangeText(before + selection + after, start, textarea.selectionEnd, "end"); + textarea.setSelectionRange(start + before.length, start + before.length + selection.length); + textarea.dispatchEvent(new Event("input", { bubbles: true })); + textarea.focus(); + } + const formatting = [ + control("Heading", () => { + const edit = headingEdit(textarea.value, textarea.selectionStart, textarea.selectionEnd); + const direction = textarea.selectionDirection; + textarea.setRangeText(edit.text, edit.start, edit.end, "preserve"); + textarea.setSelectionRange(edit.selectionStart, edit.selectionEnd, direction); + textarea.dispatchEvent(new Event("input", { bubbles: true })); + textarea.focus(); + }), + control("Bold", () => insert("**", "**", "Bold text")), + control("Italic", () => insert("*", "*", "Italic text")), + control("Bullet list", () => insert("\n- ", "\n", "List item")), + control("Link", () => insert("[", "](https://example.com)", "Link text")), + control("Code", () => insert("`", "`", "Code")), + ]; + async function render() { + const current = ++revision; + const body = persistence && !editing ? original : textarea.value; + preview.innerHTML = renderMarkdown(body); + if (!body.trim()) preview.textContent = "Add a description."; + for (const image of preview.querySelectorAll("img[data-pm-image]")) { + const trigger = document.createElement("button"); + trigger.type = "button"; + trigger.className = "pm-image-preview-trigger"; + trigger.setAttribute("aria-label", `View image ${image.alt}`); + image.removeAttribute("title"); + trigger.onclick = () => images.showImage(image, trigger); + image.replaceWith(trigger); + tooltip(trigger, `View image ${image.alt}`); + trigger.append(image); + const fail = (message: string) => trigger.replaceWith(document.createTextNode(message)); + try { + const data = await images.resolveImage(image.dataset.pmImage!); + if (disposed || current !== revision) return; + image.src = data; + image.onerror = () => fail(`Cannot display image: ${image.alt}`); + } catch { + if (!disposed && current === revision) + fail(`Cannot load image: ${image.alt}`); + } + } + } + const edit = control("Edit", () => { + if (!persistence) original = textarea.value; + editing = true; + update(); + textarea.focus(); + resize(); + }); + const toggle = control("Preview", () => { + if (!find.element.hidden) find.close(); + source.hidden = !source.hidden; + preview.hidden = !source.hidden; + images.setEditing(!source.hidden); + toggle.lastChild!.textContent = source.hidden ? "Edit Markdown" : "Preview"; + toggle.setAttribute("aria-pressed", String(source.hidden)); + if (source.hidden) void render(); + updateLoading(); + if (!source.hidden) textarea.focus(); + }); + const actions = document.createElement("div"); + actions.className = "pm-description-actions"; + const finish = async (cancel: boolean) => { + if (images.isLoading() || pending) return; + pending = true; updateLoading(); + try { + if (cancel) { + textarea.value = persistence ? await persistence.cancel() : original; + textarea.dispatchEvent(new Event("input", { bubbles: true })); + } else await persistence?.save(); + original = textarea.value; + unsaved.hidden = true; + editing = false; + pending = false; + update(); + edit.focus(); + } catch { /* The card editor shows the persistence error. */ } + finally { pending = false; updateLoading(); } + }; + const cancel = control("Cancel", () => { void finish(true); }); + const apply = control("Save", () => { void finish(false); }); + actions.append(cancel, apply); + for (const item of [...formatting, images.addControl]) { + const name = item.textContent ?? ""; + item.setAttribute("aria-label", name); + item.removeAttribute("title"); + item.classList.add("pm-icon-button"); + for (const child of [...item.childNodes]) + if (child.nodeType === Node.TEXT_NODE) child.remove(); + tooltip(item, name); + } + toolbar.setAttribute("role", "toolbar"); + toolbar.append(...formatting, images.addControl, toggle); + header.append(heading, unsaved, edit); + const surface = document.createElement("div"); + surface.className = "pm-description-surface"; + surface.append(toolbar, source); + const content = document.createElement("div"); content.id = `pm-description-${crypto.randomUUID()}`; + toggleSection.setAttribute("aria-controls", content.id); + toggleSection.onclick = () => { + content.hidden = !content.hidden; + toggleSection.setAttribute("aria-expanded", String(!content.hidden)); + edit.hidden = content.hidden || editing; + if (!content.hidden) resize(); + }; + content.append(find.element, surface, preview, images.element, actions); + element.append(header, content); + function updateLoading() { + edit.disabled = toggle.disabled = cancel.disabled = apply.disabled = images.isLoading() || pending; + images.addControl.disabled = images.isLoading() || pending || !!source.hidden; + for (const button of formatting) button.disabled = images.isLoading() || pending || !!source.hidden; + } + function update() { + find.hide(); + edit.hidden = editing || content.hidden; + toolbar.hidden = actions.hidden = !editing; + source.hidden = !editing; + images.setEditing(editing); + preview.hidden = editing; + toggle.lastChild!.textContent = "Preview"; + toggle.setAttribute("aria-pressed", "false"); + updateLoading(); + if (!editing) void render(); + else { cancelAnimationFrame(resizeFrame); resizeFrame = requestAnimationFrame(resize); } + } + const onInput = () => { + unsaved.hidden = textarea.value === original; + resize(); + if (document.activeElement === textarea) { + const style = getComputedStyle(textarea); + const mirror = document.createElement("div"); + mirror.style.cssText = `position:fixed;visibility:hidden;pointer-events:none;white-space:pre-wrap;overflow-wrap:break-word;box-sizing:border-box;width:${textarea.clientWidth}px;font:${style.font};line-height:${style.lineHeight};padding:${style.padding}`; + mirror.textContent = textarea.value.slice(0, textarea.selectionEnd); + const marker = document.createElement("span"); marker.textContent = "\u200b"; mirror.append(marker); + document.body.append(mirror); + const caret = textarea.getBoundingClientRect().top + marker.offsetTop + parseFloat(style.lineHeight); + mirror.remove(); + const dialog = textarea.closest("dialog"); + const bottomSpace = parseFloat(style.paddingBottom); + if (dialog && caret + bottomSpace > dialog.getBoundingClientRect().bottom - 50) dialog.scrollTop += caret + bottomSpace - dialog.getBoundingClientRect().bottom + 50; + } + if (!preview.hidden) void render(); + }; + textarea.addEventListener("input", onInput); + element.addEventListener("keydown", (event) => { + if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "f") { + event.preventDefault(); event.stopPropagation(); + content.hidden = false; toggleSection.setAttribute("aria-expanded", "true"); + if (!editing) { editing = true; update(); } + if (source.hidden) toggle.click(); + find.open(); + return; + } + if (event.key === "Escape" && !find.element.hidden) { + event.preventDefault(); event.stopPropagation(); find.close(); return; + } + if (event.key === "Escape" && editing && !element.querySelector("dialog[open], :popover-open")) { + event.preventDefault(); + event.stopPropagation(); + editing = false; + update(); + edit.focus(); + } + }); + update(); + return { + element, + updateLoading, + resize, + restoreDraft(body: string) { + textarea.value = body; + unsaved.hidden = body === original; + // Keep the saved description visible until the user opens the draft. + if (editing) resize(); + }, + saved(body: string) { original = body; unsaved.hidden = textarea.value === body; }, + dispose() { disposed = true; find.dispose(); cancelAnimationFrame(resizeFrame); observer.disconnect(); revision++; textarea.removeEventListener("input", onInput); }, + }; +} + diff --git a/src/lib/features/pm/ui/details-ui.ts b/src/lib/features/pm/ui/details-ui.ts new file mode 100644 index 0000000..167b4bc --- /dev/null +++ b/src/lib/features/pm/ui/details-ui.ts @@ -0,0 +1,130 @@ +/** A searchable field picker. Field forms stay inside the card draft. */ +export function createDetailsPicker(trigger: HTMLButtonElement) { + const panel = document.createElement("div"); + panel.className = "pm-label-options pm-details-picker rs-picker"; + panel.id = `pm-details-${crypto.randomUUID()}`; + panel.popover = "auto"; + panel.setAttribute("role", "dialog"); + panel.setAttribute("aria-label", "Add card details"); + const search = document.createElement("input"); + search.type = "search"; + search.placeholder = "Find a detail"; + search.setAttribute("aria-label", "Find a detail"); + const choices = document.createElement("div"); + choices.className = "pm-detail-choices"; + const empty = document.createElement("p"); + empty.textContent = "No matching details."; + empty.hidden = true; + panel.append(search, choices, empty); + trigger.popoverTargetElement = panel; + trigger.setAttribute("aria-haspopup", "dialog"); + trigger.setAttribute("aria-controls", panel.id); + trigger.setAttribute("aria-expanded", "false"); + const close = () => { + if (panel.matches(":popover-open")) panel.hidePopover(); + }; + const position = () => { + if (!panel.matches(":popover-open")) return; + const anchor = trigger.getBoundingClientRect(); + panel.style.maxHeight = `${window.innerHeight - 24}px`; + const bounds = panel.getBoundingClientRect(); + panel.style.left = `${Math.max(12, Math.min(anchor.left, window.innerWidth - bounds.width - 12))}px`; + panel.style.top = `${Math.max(12, Math.min(anchor.bottom + 6, window.innerHeight - bounds.height - 12))}px`; + }; + const entries: { row: HTMLElement; name: string }[] = []; + function filter() { + for (const entry of entries) + entry.row.hidden = !entry.name + .toLocaleLowerCase() + .includes(search.value.trim().toLocaleLowerCase()); + empty.hidden = entries.some((entry) => !entry.row.hidden); + position(); + } + search.oninput = filter; + panel.onkeydown = (event) => { + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + close(); + trigger.focus(); + } else if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) { + if ( + event.target === search && + (event.key === "Home" || event.key === "End") + ) + return; + const buttons = entries + .filter((entry) => !entry.row.hidden) + .map((entry) => entry.row.querySelector("button")!); + const index = buttons.indexOf( + document.activeElement as HTMLButtonElement, + ); + const next = + event.key === "Home" + ? 0 + : event.key === "End" + ? buttons.length - 1 + : event.key === "ArrowDown" + ? (index + 1) % buttons.length + : index < 0 + ? buttons.length - 1 + : (index + buttons.length - 1) % buttons.length; + event.preventDefault(); + buttons[next]?.focus(); + } else if (event.key === "Enter" && event.target === search) { + event.preventDefault(); + entries + .find((entry) => !entry.row.hidden) + ?.row.querySelector("button") + ?.click(); + } + }; + panel.addEventListener("beforetoggle", (event) => { + if ((event as ToggleEvent).newState === "open") { + search.value = ""; + filter(); + } + }); + panel.addEventListener("toggle", () => { + const open = panel.matches(":popover-open"); + trigger.setAttribute("aria-expanded", String(open)); + if (open) { + position(); + if (!panel.contains(document.activeElement)) search.focus(); + } + }); + window.addEventListener("resize", position); + document.addEventListener("scroll", position, true); + return { + element: panel, + add(button: HTMLButtonElement, detail: string) { + button.className = "rs-picker-row"; + button.querySelector(".pm-icon")?.classList.add("rs-picker-icon"); + const row = document.createElement("div"); + row.className = "pm-detail-choice"; + const hint = document.createElement("span"); + hint.id = `pm-detail-hint-${crypto.randomUUID()}`; + hint.textContent = detail; + hint.className = "pm-detail-hint rs-picker-hint"; + button.setAttribute("aria-describedby", hint.id); + button.setAttribute("aria-label", button.textContent ?? ""); + const action = button.onclick; + button.onclick = (event) => { + close(); + action?.call(button, event); + }; + const text = document.createElement("span"); + for (const child of [...button.childNodes]) if (!(child instanceof Element && child.classList.contains("pm-icon"))) text.append(child); + text.append(hint); + button.append(text); + row.append(button); + choices.append(row); + entries.push({ row, name: button.textContent ?? "" }); + }, + dispose() { + close(); + window.removeEventListener("resize", position); + document.removeEventListener("scroll", position, true); + }, + }; +} diff --git a/src/lib/features/pm/ui/host.ts b/src/lib/features/pm/ui/host.ts new file mode 100644 index 0000000..aa870b7 --- /dev/null +++ b/src/lib/features/pm/ui/host.ts @@ -0,0 +1,56 @@ +// The host layer of the Project Management interface: the shared action menu, the shared tooltip, and the shared action +// icons of RuneStone. The interface builds plain DOM. A Svelte version is a later card. +import { showActionMenu, type MenuOptions } from "../../../ui/managedActionMenu.ts"; +import { attachTooltip } from "../../../ui/tooltip.ts"; +export { actionIcons, type ActionIcon } from "../../../ui/actionIcons.ts"; +export type { ActionMenuItem } from "../../../ui/actionMenu.ts"; + +/** The menus that the interface opens. Tests can give their own. */ +export interface MenuHost { + showActionMenu(options: MenuOptions): { close(): void }; +} + +export const hostMenus: MenuHost = { showActionMenu: options => showActionMenu(options) }; + +/** The attribute that gives a control its tooltip text. */ +export const TOOLTIP = "data-pm-tooltip"; + +/** Give a control the shared tooltip. The text can change later through the attribute. */ +export function tooltip(control: T, text: string): T { + control.setAttribute(TOOLTIP, text); + return control; +} + +/** + * Attach the shared tooltip to each control in `root` with `data-pm-tooltip`, also to controls that a render adds later. + * A removed control loses its tooltip. Returns the function that removes all tooltips. + */ +export function mountTooltips(root: HTMLElement): () => void { + const attached = new Map void>(); + const attach = (node: Node) => { + if (!(node instanceof HTMLElement)) return; + const controls = node.matches(`[${TOOLTIP}]`) ? [node, ...node.querySelectorAll(`[${TOOLTIP}]`)] : node.querySelectorAll(`[${TOOLTIP}]`); + for (const control of controls) { + if (attached.has(control)) continue; + attached.set(control, attachTooltip(control, () => control.getAttribute(TOOLTIP) ?? "")); + } + }; + const sweep = () => { + for (const [control, detach] of attached) { + if (control.isConnected && root.contains(control)) continue; + detach(); + attached.delete(control); + } + }; + const observer = new MutationObserver(records => { + sweep(); + for (const record of records) for (const node of record.addedNodes) attach(node); + }); + observer.observe(root, { childList: true, subtree: true }); + attach(root); + return () => { + observer.disconnect(); + for (const detach of attached.values()) detach(); + attached.clear(); + }; +} diff --git a/src/lib/features/pm/ui/images-ui.ts b/src/lib/features/pm/ui/images-ui.ts new file mode 100644 index 0000000..2ae07e2 --- /dev/null +++ b/src/lib/features/pm/ui/images-ui.ts @@ -0,0 +1,359 @@ +import { tooltip } from "./host.ts"; +import type { Workspace, TaskFields } from "../model/model.ts"; +import { + imageMarkdown, + imagePath, + imageReferences, + imageTypes, + maxImageBytes, + parseImage, + saveImages, +} from "../storage/images.ts"; + +/** Image data stays outside card Markdown and loads only in the open editor. */ +export function createCardImages( + workspace: Workspace, + description: HTMLTextAreaElement, + control: (name: string, action: () => void) => HTMLButtonElement, + removeControl: (name: string, action: () => void) => HTMLButtonElement, + changed: (loading: boolean) => void, + initialAttachments: TaskFields["attachments"] = [], +) { + const attachments = structuredClone(initialAttachments); + const element = document.createElement("div"); + element.className = "pm-card-images pm-wide"; + const hint = document.createElement("p"); + hint.className = "pm-muted"; + hint.id = `pm-image-hint-${crypto.randomUUID()}`; + hint.textContent = + "Paste or drop an image into Details, or choose Add image. PNG, JPEG, GIF, or WebP. Up to 50 MiB each."; + description.setAttribute("aria-describedby", hint.id); + const error = document.createElement("p"); + error.className = "pm-error"; + error.setAttribute("role", "alert"); + const gallery = document.createElement("div"); + gallery.className = "pm-image-gallery"; + gallery.setAttribute("role", "group"); + gallery.setAttribute("aria-label", "Images in card details"); + const input = document.createElement("input"); + input.type = "file"; + input.accept = imageTypes.join(","); + input.multiple = true; + input.hidden = true; + input.setAttribute("aria-label", "Insert images in description"); + const add = control("Add image", () => input.click()); + const attachmentInput = input.cloneNode() as HTMLInputElement; + attachmentInput.setAttribute("aria-label", "Attach images to card"); + const attach = control("Attach image", () => attachmentInput.click()); + const heading = document.createElement("h3"); heading.textContent = "Attachments"; + const header = document.createElement("div"); header.className = "pm-attachment-heading"; + header.append(heading, attach); + const attachmentGallery = document.createElement("div"); attachmentGallery.className = "pm-image-gallery"; + attachmentGallery.setAttribute("role", "group"); attachmentGallery.setAttribute("aria-label", "Image attachments"); + const attachmentsElement = document.createElement("section"); attachmentsElement.className = "pm-attachments pm-wide"; + attachmentsElement.setAttribute("aria-label", "Attachments"); + const attachmentError = document.createElement("p"); attachmentError.className = "pm-error"; attachmentError.setAttribute("role", "alert"); + attachmentsElement.append(header, attachmentInput, attachmentError, attachmentGallery); + element.append(input, hint, error, gallery); + const pending = new Map(); + const loaded = new Map>(); + let viewer: HTMLDialogElement | undefined; + let viewerObserver: ResizeObserver | undefined; + let idleTimer: ReturnType | undefined; + let disposed = false, + loading = false, + saving = false, + revision = 0; + function updateControls() { + description.disabled = add.disabled = attach.disabled = loading || saving; + [...element.querySelectorAll("button"), ...attachmentsElement.querySelectorAll("button")].forEach((button) => { + button.disabled = loading || saving; + }); + } + function showImage(source: HTMLImageElement, trigger: HTMLButtonElement) { + if (viewer || disposed || !source.complete || !source.naturalWidth) return; + const dialog = document.createElement("dialog"); + dialog.className = "pm-image-viewer"; + viewer = dialog; + const header = document.createElement("div"); + header.className = "pm-image-viewer-header"; + const title = document.createElement("h2"); + title.id = `pm-image-title-${crypto.randomUUID()}`; + title.textContent = source.alt; + dialog.setAttribute("aria-labelledby", title.id); + const frame = document.createElement("div"); + frame.className = "pm-image-frame"; + const full = document.createElement("img"); + full.src = source.src; + full.alt = source.alt; + frame.append(full); + const size = control("Actual size", () => { + const actual = frame.classList.toggle("pm-image-actual"); + size.setAttribute("aria-pressed", String(actual)); + placeControls(); + }); + size.setAttribute("aria-pressed", "false"); + const close = removeControl("Close image", () => dialog.close()); + header.append(title, size, close); + dialog.append(header, frame); + const placeControls = () => { + if (!dialog.open) return; + const bounds = full.getBoundingClientRect(); + const actual = frame.classList.contains("pm-image-actual"); + const width = actual ? dialog.clientWidth - 16 : Math.min(dialog.clientWidth - 16, Math.max(320, bounds.width - 16)); + header.style.width = `${width}px`; + header.style.left = `${Math.max(8, (dialog.clientWidth - width) / 2)}px`; + header.style.right = "auto"; + header.style.top = `${actual ? 8 : Math.max(8, bounds.top + 8)}px`; + }; + const observer = new ResizeObserver(placeControls); + viewerObserver = observer; + observer.observe(full); + observer.observe(frame); + full.onload = placeControls; + dialog.onclose = () => { + clearTimeout(idleTimer); + observer.disconnect(); + viewerObserver = undefined; + dialog.remove(); + viewer = undefined; + if (!disposed && trigger.isConnected) trigger.focus({ preventScroll: true }); + }; + // Keep the viewer outside the gallery, which is hidden in description previews. + (description.closest(".pm-editor") ?? element.parentElement ?? element).append(dialog); + const outside = (target: EventTarget | null) => target === dialog || target === frame; + let outsidePointer = false; + dialog.addEventListener("pointerdown", (event) => { + outsidePointer = event.isPrimary && event.button === 0 && outside(event.target); + event.stopPropagation(); + }); + dialog.addEventListener("pointercancel", () => { outsidePointer = false; }); + dialog.addEventListener("click", (event) => { + event.stopPropagation(); + if (outsidePointer && outside(event.target)) dialog.close(); + outsidePointer = false; + }); + dialog.addEventListener("keydown", (event) => { + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + dialog.close(); + } + }); + dialog.addEventListener("cancel", (event) => { + event.preventDefault(); + event.stopPropagation(); + dialog.close(); + }); + dialog.showModal(); + placeControls(); + // Focus the surface first so pointer users can see an unobstructed image. + dialog.tabIndex = -1; + dialog.focus(); + idleTimer = setTimeout(() => dialog.classList.add("pm-image-controls-idle"), 2000); + } + async function render() { + const current = ++revision; + gallery.replaceChildren(); + attachmentGallery.replaceChildren(); + for (const ref of [...imageReferences(description.value), ...attachments]) { + const attached = !("index" in ref); + const figure = document.createElement("figure"); + const caption = document.createElement("figcaption"); + const name = document.createElement("span"); + name.textContent = ref.name; + name.title = ref.name; + caption.append( + name, + removeControl(`Remove image ${ref.name}`, () => { + if (attached) { + attachments.splice(attachments.findIndex(item => item.id === ref.id), 1); + description.dispatchEvent(new Event("input", { bubbles: true })); + return; + } + const references = imageReferences(description.value); + const match = references.find( + (item) => item.id === ref.id && item.index === ref.index, + ); + if (!match) return; + description.setRangeText( + "", + match.index, + match.index + match.markdown.length, + "preserve", + ); + description.dispatchEvent(new Event("input", { bubbles: true })); + description.focus(); + }), + ); + const image = document.createElement("img"); + image.alt = ref.name; + image.loading = "lazy"; + const thumbnail = document.createElement("button"); + thumbnail.type = "button"; + thumbnail.className = "pm-image-thumbnail"; + thumbnail.setAttribute("aria-label", `View image ${ref.name}`); + tooltip(thumbnail, `View image ${ref.name}`); + thumbnail.onclick = () => showImage(image, thumbnail); + thumbnail.append(image); + const failure = document.createElement("p"); + failure.className = "pm-error"; + failure.setAttribute("role", "alert"); + const fail = () => { + thumbnail.remove(); + failure.textContent = `Cannot display ${ref.name}. Restore the image file or remove its reference.`; + }; + image.onerror = fail; + figure.append(thumbnail, caption, failure); + (attached ? attachmentGallery : gallery).append(figure); + updateControls(); + let data = pending.get(ref.id); + try { + if (!data) { + let promise = loaded.get(ref.id); + if (!promise) { + promise = workspace.read(imagePath(ref.id)).then(parseImage); + loaded.set(ref.id, promise); + } + data = await promise; + } + if (disposed || current !== revision) return; + image.src = data; + } catch { + if (!disposed && current === revision) fail(); + } + } + } + async function addFiles(files: File[], attachOnly = false) { + if (disposed || loading || description.disabled || !files.length) return; + loading = true; + updateControls(); + changed(true); + error.textContent = ""; + attachmentError.textContent = ""; + const start = description.selectionStart, + end = description.selectionEnd; + try { + const staged: { id: string; name: string; data: string }[] = []; + for (const file of files) { + if (!imageTypes.includes(file.type)) + throw new Error("Use a PNG, JPEG, GIF, or WebP image."); + if (!file.size || file.size > maxImageBytes) + throw new Error("Use an image between 1 byte and 50 MiB."); + const bytes = new Uint8Array(await file.arrayBuffer()); + let binary = ""; + for (let offset = 0; offset < bytes.length; offset += 8192) + binary += String.fromCharCode( + ...bytes.subarray(offset, offset + 8192), + ); + const data = `data:${file.type};base64,${btoa(binary)}`; + // Decode before inserting a reference, so invalid clipboard files preserve the draft. + const image = new Image(); + image.src = data; + await image.decode().catch(() => { + throw new Error( + "The image cannot be read. Copy it again or choose another file.", + ); + }); + staged.push({ + id: crypto.randomUUID(), + name: (file.name || "Pasted image").slice(0, 255), + data, + }); + } + if (disposed) return; + for (const image of staged) pending.set(image.id, image.data); + if (attachOnly) attachments.push(...staged.map(({ id, name }) => ({ id, name }))); + else { + const markdown = staged.map((image) => imageMarkdown(image.name, image.id)).join("\n"); + description.setRangeText(`\n${markdown}\n`, start, end, "end"); + } + description.dispatchEvent(new Event("input", { bubbles: true })); + } catch (reason) { + if (!disposed) + (attachOnly ? attachmentError : error).textContent = + reason instanceof Error ? reason.message : String(reason); + } finally { + loading = false; + if (!disposed) { + updateControls(); + changed(false); + (attachOnly ? attach : description).focus(); + } + } + } + const paste = (event: ClipboardEvent) => { + const files = Array.from(event.clipboardData?.files ?? []).filter((file) => + file.type.startsWith("image/"), + ); + if (!files.length) return; + event.preventDefault(); + event.stopPropagation(); + void addFiles(files); + }; + const dragOver = (event: DragEvent) => { + if (event.dataTransfer?.types.includes("Files")) { + event.preventDefault(); + event.stopPropagation(); + } + }; + const drop = (event: DragEvent) => { + const files = Array.from(event.dataTransfer?.files ?? []); + if (!files.length) return; + event.preventDefault(); + event.stopPropagation(); + void addFiles(files); + }; + description.addEventListener("dragover", dragOver); + description.addEventListener("drop", drop); + description.addEventListener("paste", paste); + description.addEventListener("input", render); + input.onchange = () => { + void addFiles(Array.from(input.files ?? [])); + input.value = ""; + }; + attachmentInput.onchange = () => { + void addFiles(Array.from(attachmentInput.files ?? []), true); + attachmentInput.value = ""; + }; + void render(); + return { + element, + attachmentsElement, + addControl: add, + value: () => structuredClone(attachments), + references: () => [...imageReferences(description.value), ...attachments], + setEditing(value: boolean) { element.hidden = !value; }, + showImage, + async resolveImage(id: string) { + const data = pending.get(id); + if (data) return data; + let promise = loaded.get(id); + if (!promise) { + promise = workspace.read(imagePath(id)).then(parseImage); + loaded.set(id, promise); + } + return promise; + }, + isLoading: () => loading, + setSaving(value: boolean) { + saving = value; + updateControls(); + }, + save: (body: string) => saveImages(workspace, body, pending, attachments), + dispose() { + disposed = true; + clearTimeout(idleTimer); + viewerObserver?.disconnect(); + viewerObserver = undefined; + viewer?.remove(); viewer = undefined; + revision++; + pending.clear(); + loaded.clear(); + description.removeEventListener("paste", paste); + description.removeEventListener("input", render); + description.removeEventListener("dragover", dragOver); + description.removeEventListener("drop", drop); + }, + }; +} diff --git a/src/lib/features/pm/ui/labels-ui.ts b/src/lib/features/pm/ui/labels-ui.ts new file mode 100644 index 0000000..a8e8873 --- /dev/null +++ b/src/lib/features/pm/ui/labels-ui.ts @@ -0,0 +1,355 @@ +import { type LabelStore, type SavedLabel } from "../storage/labels.ts"; +import { actionIcons, tooltip } from "./host.ts"; +import { createColorPalette, labelColors } from "./colors.ts"; + +function node( + tag: K, + text = "", + className = "", +) { + const element = document.createElement(tag); + element.textContent = text; + element.className = className; + return element; +} +function control(text: string, action: () => void) { + const button = node("button", text, "pm-button"); + button.type = "button"; + button.onclick = action; + return button; +} +export function labelBadge(label?: SavedLabel, id = "") { + const badge = node( + "span", + label?.name ?? "Unavailable label", + "pm-label-badge", + ); + if (label) + badge.style.setProperty("--pm-label-color", labelColors[label.color]); + badge.setAttribute("aria-label", label + ? `${label.name} · ${label.color}${label.archived ? " · Archived" : ""}` + : `Unavailable label: ${id}`); + return badge; +} + +export function createLabelPicker( + catalog: LabelStore, + initial: string[], + manage: () => void, + quickAccess = false, +) { + const element = node("section", "", "pm-label-picker pm-wide"); + element.setAttribute("aria-label", "Card labels"); + const selected = new Set(initial); + const known = new Set(catalog.value.map((label) => label.id)); + const chips = node("div", "", "pm-label-chips"); + chips.setAttribute("role", "group"); + chips.setAttribute("aria-label", "Selected labels"); + const panel = node("div", "", "pm-label-options rs-picker"); + panel.id = "pm-labels-" + crypto.randomUUID(); + panel.popover = "auto"; + panel.setAttribute("role", "dialog"); + panel.setAttribute("aria-label", "Choose labels"); + const toggle = control("", () => {}); + toggle.classList.add("pm-label-add"); + const plus = node("span", "", "pm-icon"); + plus.innerHTML = quickAccess + ? '' + : ``; + const toggleText = node("span", quickAccess ? "Labels" : "Add labels"); + toggle.append(plus, toggleText); + toggle.setAttribute("aria-label", quickAccess ? "Labels" : "Add labels"); + toggle.popoverTargetElement = panel; + toggle.setAttribute("aria-controls", panel.id); + toggle.setAttribute("aria-expanded", "false"); + toggle.setAttribute("aria-haspopup", "dialog"); + const search = node("input"); + search.type = "search"; + search.placeholder = "Find a label"; + search.setAttribute("aria-label", "Find a label"); + const choices = node("div", "", "pm-label-choices"); + choices.setAttribute("role", "group"); + choices.setAttribute("aria-label", "Available labels"); + const hint = node("p", "", "pm-muted"); + const manageButton = control("Manage labels", () => { + close(); + toggle.focus(); + manage(); + }); + manageButton.className = "pm-label-manage rs-picker-row"; + const manageIcon = node("span", "", "pm-icon rs-picker-icon"); + manageIcon.innerHTML = ''; + manageButton.prepend(manageIcon); + panel.append(search, choices, hint, manageButton); + chips.append(toggle); + element.append(chips, panel); + const position = () => { + if (!panel.matches(":popover-open")) return; + const anchor = (quickAccess ? toggle : chips).getBoundingClientRect(); + const gap = 6, + margin = 12; + panel.style.maxHeight = `${window.innerHeight - margin * 2}px`; + const bounds = panel.getBoundingClientRect(); + const below = window.innerHeight - anchor.bottom - margin - gap; + const above = anchor.top - margin - gap; + const useBelow = below >= bounds.height || below >= above; + panel.style.maxHeight = `${Math.max(0, useBelow ? below : above)}px`; + const height = panel.getBoundingClientRect().height; + panel.style.left = `${Math.max(margin, Math.min(anchor.left, window.innerWidth - bounds.width - margin))}px`; + panel.style.top = `${Math.max(margin, useBelow ? anchor.bottom + gap : anchor.top - height - gap)}px`; + }; + const scroll = (event: Event) => { + if (!panel.contains(event.target as Node)) position(); + }; + const stop = () => { + window.removeEventListener("resize", position); + document.removeEventListener("scroll", scroll, true); + }; + function close() { + if (panel.matches(":popover-open")) panel.hidePopover(); + stop(); + } + function open() { + if (panel.matches(":popover-open")) return; + panel.showPopover(); + } + panel.addEventListener("beforetoggle", (event) => { + const expanded = (event as ToggleEvent).newState === "open"; + toggle.setAttribute("aria-expanded", String(expanded)); + if (!expanded) stop(); + }); + panel.addEventListener("toggle", (event) => { + if ( + (event as ToggleEvent).newState !== "open" || + !panel.matches(":popover-open") + ) + return; + position(); + window.addEventListener("resize", position); + document.addEventListener("scroll", scroll, true); + if (!panel.contains(document.activeElement)) + search.focus({ preventScroll: true }); + }); + const drawChoices = () => { + choices.replaceChildren(); + const matches = catalog.value.filter( + (label) => + !label.archived && + !selected.has(label.id) && + label.name + .toLocaleLowerCase() + .includes(search.value.trim().toLocaleLowerCase()), + ); + matches.forEach((label, index) => { + const row = control("", () => { + selected.add(label.id); + drawChips(); + drawChoices(); + const remaining = choices.querySelectorAll("button"); + (remaining[Math.min(index, remaining.length - 1)] ?? search).focus({ + preventScroll: true, + }); + }); + row.className = "pm-label-option rs-picker-row"; + row.setAttribute("aria-label", "Add label " + label.name); + row.append(labelBadge(label)); + choices.append(row); + }); + hint.textContent = + catalog.error || + (matches.length + ? "" + : search.value.trim() + ? "No matching labels." + : "No available labels."); + hint.hidden = !hint.textContent; + manageButton.disabled = catalog.source === undefined; + position(); + }; + function drawChips() { + for (const chip of [...chips.children]) if (chip !== toggle) chip.remove(); + for (const id of selected) { + const label = catalog.value.find((label) => label.id === id); + const chip = labelBadge(label, id); + const remove = control("×", () => { + selected.delete(id); + drawChips(); + drawChoices(); + toggle.focus(); + }); + remove.setAttribute("aria-label", "Remove label " + (label?.name ?? id)); + tooltip(remove, remove.getAttribute("aria-label")!); + chip.append(remove); + chips.insertBefore(chip, toggle.parentElement === chips ? toggle : null); + } + toggleText.hidden = !quickAccess && selected.size > 0; + toggle.classList.toggle("pm-label-add-compact", !quickAccess && selected.size > 0); + position(); + } + search.oninput = drawChoices; + search.onkeydown = (event) => { + if (event.key === "Enter") event.preventDefault(); + if (event.key === "ArrowDown") { + event.preventDefault(); + choices.querySelector("button")?.focus(); + } + }; + choices.onkeydown = (event) => { + if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return; + event.preventDefault(); + const rows = [...choices.querySelectorAll("button")]; + const index = rows.indexOf(event.target as HTMLButtonElement); + rows[ + event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : (index + (event.key === "ArrowDown" ? 1 : rows.length - 1)) % rows.length + ]?.focus(); + }; + element.onkeydown = (event) => { + if (event.key === "Escape" && panel.matches(":popover-open")) { + event.preventDefault(); + event.stopPropagation(); + close(); + toggle.focus(); + } + }; + const refresh = () => { + for (const id of selected) + if (known.has(id) && !catalog.value.some((label) => label.id === id)) selected.delete(id); + catalog.value.forEach((label) => known.add(label.id)); + drawChips(); + drawChoices(); + }; + refresh(); + return { element, trigger: toggle, refresh, open, dispose: close, value: () => [...selected] }; +} + +export function createLabelManager( + catalog: LabelStore, + save: ( + labels: SavedLabel[], + expected: string | null | undefined, + ) => Promise, + close: () => void, +) { + const dialog = node("dialog", "", "pm-editor pm-label-manager"); + dialog.setAttribute("aria-label", "Manage labels"); + const form = node("form"); + const draft = structuredClone(catalog.value); + const expected = catalog.source; + const rows = node("div", "", "pm-label-definitions"); + const error = node("p", catalog.error, "pm-error"); + error.setAttribute("role", "alert"); + let saving = false; + const addRow = (label: SavedLabel) => { + const row = node("fieldset", "", "pm-label-definition"); + row.setAttribute("aria-label", "Label " + (label.name || "New label")); + const legend = node("legend"); + const badge = labelBadge(label); + legend.append(badge); + const fields = node("div", "", "pm-label-definition-fields"); + const nameWrap = node("label", "Name", "pm-field"); + const name = node("input"); + name.value = label.name; + name.required = true; + name.maxLength = 80; + nameWrap.append(name); + const color = createColorPalette("Color", label.color, (value) => { + label.color = value as SavedLabel["color"]; + update(); + }, false, labelColors); + const state = node("span", "", "pm-muted"); + const update = () => { + row.setAttribute("aria-label", "Label " + (label.name || "New label")); + badge.textContent = label.name || "New label"; + badge.style.setProperty("--pm-label-color", labelColors[label.color]); + badge.setAttribute("aria-label", `${label.name || "New label"} · ${label.color}`); + state.textContent = label.archived ? "Archived" : ""; + remove.setAttribute("aria-label", `Delete ${label.name || "new label"}`); + tooltip(remove, `Delete ${label.name || "new label"}`); + }; + name.oninput = () => { + label.name = name.value; + update(); + }; + const remove = control("Delete", () => { + draft.splice(draft.indexOf(label), 1); + row.remove(); + add.focus(); + }); + remove.setAttribute("aria-label", `Delete ${label.name || "new label"}`); + remove.classList.add("pm-icon-button"); + remove.innerHTML = ``; + tooltip(remove, `Delete ${label.name || "new label"}`); + fields.append(nameWrap, remove, color.element); + row.append(legend, fields, state); + rows.append(row); + update(); + return name; + }; + const add = control("New label", () => { + const label: SavedLabel = { + id: crypto.randomUUID(), + name: "", + color: "blue", + }; + draft.push(label); + addRow(label).focus(); + }); + draft.forEach(addRow); + const actions = node("div", "", "pm-editor-actions"); + const cancel = control("Cancel", () => { + if (!saving) dialog.close(); + }); + const submit = control("Save labels", () => {}); + submit.type = "submit"; + submit.classList.add("pm-primary"); + actions.append(cancel, submit); + form.append( + node("h2", "Manage labels"), + node( + "p", + "Labels are shared across all boards in this workspace. Name and color changes apply to every card that uses a label.", + "pm-muted", + ), + rows, + add, + node( + "p", + "Deleting a label removes it from every card when you save.", + "pm-muted", + ), + error, + actions, + ); + dialog.append(form); + form.onsubmit = async (event) => { + event.preventDefault(); + if (saving) return; + saving = true; + const controls = form.querySelectorAll< + HTMLInputElement | HTMLButtonElement | HTMLSelectElement + >("input,button,select"); + controls.forEach((control) => { + control.disabled = true; + }); + try { + await save(draft, expected); + if (dialog.isConnected) dialog.close(); + } catch (reason) { + error.textContent = + reason instanceof Error ? reason.message : String(reason); + } finally { + saving = false; + controls.forEach((control) => { + control.disabled = false; + }); + } + }; + dialog.oncancel = (event) => { + if (saving) event.preventDefault(); + }; + dialog.onclose = () => { + dialog.remove(); + close(); + }; + return dialog; +} diff --git a/src/lib/features/pm/ui/priority-ui.ts b/src/lib/features/pm/ui/priority-ui.ts new file mode 100644 index 0000000..77a2f64 --- /dev/null +++ b/src/lib/features/pm/ui/priority-ui.ts @@ -0,0 +1,47 @@ +import type { MenuHost } from "./host.ts"; +import { availablePriorities, priorityNames, type Priority, type PriorityLevels } from "../model/model.ts"; + +export const priorityIcons: Record = { + highest: '', + high: '', + medium: '', + lowest: '', + low: '', +}; +export function setPriorityAppearance(node: HTMLElement, value: Priority | null) { + node.dataset.priority = value ?? "none"; + const icon = node.querySelector(".pm-icon"); + if (icon) icon.innerHTML = ``; +} + +/** The priority control of card details. The shared host menu shows the choices. */ +export function createPriorityPicker( + trigger: HTMLButtonElement, + initial: Priority | null, + levels: PriorityLevels = 3, + ui: MenuHost, +) { + let value = initial; + let changed = false; + trigger.setAttribute("aria-haspopup", "menu"); + const update = () => { + trigger.lastChild!.textContent = value ? `${priorityNames[value]} priority` : "Priority"; + setPriorityAppearance(trigger, value); + }; + let menu: { close(): void } | undefined; + const open = () => { + menu?.close(); const bounds = trigger.getBoundingClientRect(); + menu = ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: "Choose priority", parent: trigger.closest("dialog") ?? undefined, + items: [...availablePriorities(levels), null].map(priority => ({ label: priority ? `${priorityNames[priority]} priority` : "No priority", checked: value === priority, radio: true, + run: () => { value = priority; changed = true; update(); } })) }); + }; + trigger.onclick = open; + trigger.onkeydown = event => { if (["ArrowDown", "ArrowUp"].includes(event.key)) { event.preventDefault(); open(); } }; + update(); + return { + value: () => value, + changed: () => changed, + open, + dispose() { menu?.close(); }, + }; +} diff --git a/src/lib/features/pm/ui/relations-ui.ts b/src/lib/features/pm/ui/relations-ui.ts new file mode 100644 index 0000000..71228d8 --- /dev/null +++ b/src/lib/features/pm/ui/relations-ui.ts @@ -0,0 +1,180 @@ +import { priorityNames, type Task, type TaskFields } from "../model/model.ts"; +import type { BoardDocument } from "../storage/board.ts"; +import { setPriorityAppearance } from "./priority-ui.ts"; + +export function createRelations( + task: Task | undefined, tasks: Task[], + control: (name: string, action: () => void) => HTMLButtonElement, + removeControl: (name: string, action: () => void) => HTMLButtonElement, + boards: BoardDocument[], + open: (target: { taskId?: string; subtaskId?: string }) => void, + useSharedChoices?: (select: HTMLSelectElement) => void, +) { + const element = document.createElement("section"); element.className = "pm-relations pm-wide"; + const subtasks = structuredClone(task?.subtasks ?? []); + for (const item of subtasks) { + const target = tasks.find(task => task.id === item.taskId); + if (target) { item.title = target.title; item.done = target.status === "done"; } + } + const links = structuredClone(task?.links ?? []); + const removedIncoming = new Map(); + const cardRow = (target: Task | undefined, title: string, action: () => void, relation?: string) => { + const button = document.createElement("button"); button.type = "button"; button.className = "pm-related-card"; + button.setAttribute("aria-label", `Open ${title}`); button.onclick = action; + const name = document.createElement("span"); name.className = "pm-related-title"; + name.textContent = relation ? `${relation}: ${title}` : title; + const metadata = document.createElement("span"); metadata.className = "pm-related-metadata"; + const placement = document.createElement("span"); + const positions = Object.entries(target?.placements ?? {}).map(([boardId, position]) => { + const board = boards.find(board => board.id === boardId); + const list = board?.value.lists.find(list => list.id === position.listId); + return `${board?.name ?? "Unavailable board"}: ${position.listId === null ? "Unlisted" : list?.name ?? "Unavailable list"}`; + }); + placement.textContent = positions.length ? positions.join(" · ") : "Unlisted"; + const priority = document.createElement("span"); priority.className = "pm-related-priority"; + priority.innerHTML = ''; + priority.append(document.createTextNode(target?.priority ? `${priorityNames[target.priority]} priority` : "No priority")); + setPriorityAppearance(priority, target?.priority ?? null); + metadata.append(placement, priority); button.append(name, metadata); + return button; + }; + const section = (name: string) => { + const root = document.createElement("section"); root.className = "pm-relation-section"; + const header = document.createElement("div"); header.className = "pm-relation-heading"; + const heading = document.createElement("h3"); + const toggle = document.createElement("button"); toggle.type = "button"; toggle.className = "pm-section-toggle"; + toggle.innerHTML = ''; + const label = document.createElement("span"); label.textContent = name; toggle.append(label); + toggle.setAttribute("aria-expanded", "true"); + const content = document.createElement("div"); content.id = `pm-relations-${crypto.randomUUID()}`; + toggle.setAttribute("aria-controls", content.id); + toggle.onclick = () => { content.hidden = !content.hidden; toggle.setAttribute("aria-expanded", String(!content.hidden)); }; + heading.append(toggle); header.append(heading); root.append(header, content); element.append(root); + return { header, content, toggle, expand() { content.hidden = false; toggle.setAttribute("aria-expanded", "true"); } }; + }; + const sub = section("Subtasks"); + const rows = document.createElement("div"); rows.className = "pm-subtask-rows"; + const count = document.createElement("span"); count.className = "pm-muted"; sub.header.append(count); + const render = () => { + count.textContent = subtasks.length ? `${subtasks.filter(item => item.done).length}/${subtasks.length}` : ""; + rows.replaceChildren(); + for (const item of subtasks) { + const row = document.createElement("div"); row.className = "pm-relation-row"; + const target = tasks.find(task => task.id === item.taskId); + const done = document.createElement("input"); done.type = "checkbox"; done.checked = target ? target.status === "done" : item.done; + done.disabled = !!item.taskId; + done.setAttribute("aria-label", `Complete ${item.title}`); done.onchange = () => { item.done = done.checked; count.textContent = `${subtasks.filter(item => item.done).length}/${subtasks.length}`; }; + const title = cardRow(target, target?.title ?? item.title, () => open({ subtaskId: item.id })); + row.append(done, title, removeControl(`Delete subtask ${item.title}`, () => { subtasks.splice(subtasks.indexOf(item), 1); render(); })); + rows.append(row); + } + }; + const draft = document.createElement("input"); draft.placeholder = "New subtask"; draft.maxLength = 200; draft.setAttribute("aria-label", "New subtask"); + const addRow = document.createElement("div"); addRow.className = "pm-relation-row"; addRow.hidden = true; + const reveal = control("Add subtask", () => { sub.expand(); addRow.hidden = false; reveal.hidden = true; draft.focus(); }); + const dismiss = () => { draft.value = ""; add.disabled = true; addRow.hidden = true; reveal.hidden = false; reveal.focus(); }; + const add = control("Create subtask", () => { + if (!draft.value.trim()) return; + subtasks.push({ id: crypto.randomUUID(), title: draft.value.trim(), done: false }); render(); dismiss(); + }); + add.disabled = true; + draft.oninput = () => add.disabled = !draft.value.trim(); + draft.onkeydown = event => { + if (event.key === "Enter") { event.preventDefault(); add.click(); } + if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); dismiss(); } + }; + addRow.append(draft, add, removeControl("Cancel subtask", dismiss)); + sub.header.append(reveal); sub.content.append(rows, addRow); + + const linkedSection = section("Linked cards"); + const linked = document.createElement("div"); + const names = { relates: "Relates to", blocks: "Blocks", "blocked-by": "Blocked by" }; + const search = document.createElement("input"); search.type = "search"; search.placeholder = "Find a card"; search.setAttribute("aria-label", "Find a card to link"); + const choices = document.createElement("div"); choices.className = "pm-link-results rs-picker"; + choices.id = "pm-link-results-" + crypto.randomUUID(); + choices.setAttribute("role", "group"); choices.setAttribute("aria-label", "Matching cards"); + search.setAttribute("aria-controls", choices.id); + const resultStatus = document.createElement("p"); resultStatus.className = "rs-picker-hint"; + resultStatus.setAttribute("role", "status"); resultStatus.setAttribute("aria-live", "polite"); + const relation = document.createElement("select"); relation.setAttribute("aria-label", "Relationship"); + for (const [value, name] of Object.entries(names)) { const option = document.createElement("option"); option.value = value; option.textContent = name; relation.append(option); } + const candidates = () => tasks.filter(item => item.id !== task?.id && !item.archived + && !links.some(link => link.taskId === item.id) + && !(item.links?.some(link => link.taskId === task?.id) && !removedIncoming.has(item.id)) + && item.title.toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase())); + const drawChoices = () => { + choices.replaceChildren(); + const matches = candidates(); + for (const item of matches) { + const row = document.createElement("button"); row.type = "button"; row.className = "rs-picker-row"; + row.setAttribute("aria-label", `Link ${item.title}`); + const icon = document.createElement("span"); icon.className = "pm-icon rs-picker-icon"; + icon.innerHTML = ''; + const text = document.createElement("span"); text.className = "pm-link-result-text"; + const title = document.createElement("span"); title.textContent = item.title; + const hint = document.createElement("span"); hint.className = "rs-picker-hint"; + hint.textContent = Object.entries(item.placements ?? {}).map(([id, position]) => { + const board = boards.find(board => board.id === id); + return `${board?.name ?? "Unavailable board"}: ${position.listId === null ? "Unlisted" : board?.value.lists.find(list => list.id === position.listId)?.name ?? "Unavailable list"}`; + }).join(" · ") || "Unlisted"; + text.append(title, hint); row.append(icon, text); + row.onclick = () => { + if (!candidates().some(candidate => candidate.id === item.id)) return; + links.push({ taskId: item.id, relation: relation.value as NonNullable[number]["relation"] }); + drawLinks(); search.focus({ preventScroll: true }); + }; + choices.append(row); + } + resultStatus.textContent = matches.length ? "" : search.value.trim() ? "No matching cards." : "No available cards to link."; + resultStatus.hidden = matches.length > 0; + choices.hidden = matches.length === 0; + }; + const drawLinks = () => { + linked.replaceChildren(); + for (const item of links) { + const row = document.createElement("div"); row.className = "pm-relation-row"; + const target = tasks.find(candidate => candidate.id === item.taskId); + const text = cardRow(target, target?.title ?? "Unavailable card", () => open({ taskId: item.taskId }), names[item.relation]); + text.disabled = !target; + row.append(text, removeControl(`Unlink ${target?.title ?? "card"}`, () => { links.splice(links.indexOf(item), 1); drawLinks(); })); linked.append(row); + } + // Inverse links remain visible without duplicate writes to another card. + for (const source of tasks) for (const link of source.links ?? []) if (link.taskId === task?.id && !removedIncoming.has(source.id) && !links.some(item => item.taskId === source.id)) { + const row = document.createElement("div"); row.className = "pm-relation-row"; + row.append(cardRow(source, source.title, () => open({ taskId: source.id }), link.relation === "blocks" ? "Blocked by" : link.relation === "blocked-by" ? "Blocks" : "Relates to")); + row.append(removeControl(`Unlink ${source.title}`, () => { removedIncoming.set(source.id, source); drawLinks(); })); + linked.append(row); + } + for (const parent of tasks.filter(source => task && source.subtasks?.some(item => item.taskId === task.id))) { + const row = document.createElement("div"); row.className = "pm-relation-row"; + row.append(cardRow(parent, parent.title, () => open({ taskId: parent.id }), "Subtask of")); linked.append(row); + } + drawChoices(); + }; + const linkEditor = document.createElement("div"); linkEditor.className = "pm-link-editor"; linkEditor.hidden = true; + const revealLink = control("Add linked card", () => { linkedSection.expand(); linkEditor.hidden = false; revealLink.hidden = true; search.focus(); }); + const dismissLink = () => { search.value = ""; drawChoices(); linkEditor.hidden = true; revealLink.hidden = false; revealLink.focus(); }; + search.oninput = drawChoices; + search.onkeydown = event => { + if (event.key === "Enter") { event.preventDefault(); choices.querySelector("button")?.click(); } + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + event.preventDefault(); + const rows = choices.querySelectorAll("button"); + rows[event.key === "ArrowDown" ? 0 : rows.length - 1]?.focus(); + } + }; + choices.onkeydown = event => { + if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return; + event.preventDefault(); + const rows = [...choices.querySelectorAll("button")]; + const index = rows.indexOf(event.target as HTMLButtonElement); + if (event.key === "ArrowUp" && index === 0) { search.focus(); return; } + rows[event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : (index + (event.key === "ArrowDown" ? 1 : rows.length - 1)) % rows.length]?.focus(); + }; + linkEditor.addEventListener("keydown", event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); dismissLink(); } }); + const linkRow = document.createElement("div"); linkRow.className = "pm-relation-row"; linkRow.append(search, relation, removeControl("Cancel linked card", dismissLink)); + useSharedChoices?.(relation); + linkEditor.append(linkRow, choices, resultStatus); linkedSection.header.append(revealLink); linkedSection.content.append(linked, linkEditor); + render(); drawLinks(); + return { element, focus: () => sub.toggle.focus(), removedIncoming: () => [...removedIncoming.values()], value: () => ({ subtasks: subtasks.map(item => ({ ...item, title: item.title.trim() })), links }) }; +} diff --git a/src/lib/features/pm/ui/style.css b/src/lib/features/pm/ui/style.css new file mode 100644 index 0000000..32d634f --- /dev/null +++ b/src/lib/features/pm/ui/style.css @@ -0,0 +1,1829 @@ +.rs-pm { + --pm-bg: var(--rs-bg, #141414); + --pm-panel: var(--rs-bg-elevated, #1c1c1c); + --pm-hover: var(--rs-bg-active, #2a2a2a); + --pm-line: var(--rs-border, #2e2e2e); + --pm-text: var(--rs-text, #e6e6e6); + --pm-muted: var(--rs-text-dim, #9a9a9a); + --pm-accent: var(--rs-accent, #82aaff); + --pm-radius: var(--rs-control-radius, 5px); + --pm-draft-bg: #ffcc00; + --pm-draft-text: #141414; + --pm-surface-opacity: var(--rs-workarea-surface-opacity, 100%); + --pm-panel-surface: color-mix(in srgb, var(--pm-panel) var(--pm-surface-opacity), transparent); + --pm-field-surface: color-mix(in srgb, var(--pm-bg) var(--pm-surface-opacity), transparent); + --pm-selection-bg: var( + --rs-item-selection-bg, + color-mix(in srgb, var(--pm-accent) 20%, transparent) + ); + --pm-selection-border: var(--rs-item-selection-border, var(--pm-accent)); + --pm-selection-width: var(--rs-item-selection-width, 2px); + --pm-selection-radius: var(--rs-item-selection-radius, var(--pm-radius)); + min-height: 100%; + display: flex; + flex-direction: column; + min-width: 0; + background: var(--rs-workarea-plugin-bg, var(--pm-bg)); + background-image: none; + background-size: cover; + background-position: center; + color: var(--pm-text); + font: 13px/1.4 var(--rs-font-ui, system-ui, sans-serif); + color-scheme: dark; +} +.rs-pm ::selection { + background: var(--rs-selection, #264f78); + color: var(--rs-selection-text, var(--pm-text)); +} +[data-theme="light"] .rs-pm { + color-scheme: light; +} +.rs-pm * { + box-sizing: border-box; +} +.rs-pm [hidden] { + display: none !important; +} +.rs-pm h2 { + font-size: 13px; + font-weight: 600; + margin: 0; +} +.rs-pm p { + margin: 8px 0; +} +.rs-pm button, +.rs-pm input, +.rs-pm select, +.rs-pm textarea { + font: inherit; + color: inherit; +} +.rs-pm button { + cursor: pointer; +} +.rs-pm button:disabled { + opacity: 0.45; + cursor: default; +} +.rs-pm button:not(.rs-picker-row):not([role^="menuitem"]):focus-visible, +.rs-pm input:not(.rs-find-bar input):focus-visible, +.rs-pm select:focus-visible, +.rs-pm textarea:focus-visible { + outline: 1px solid var(--pm-accent); + outline-offset: 1px; +} +.pm-button, .rs-pm:not(.pm-shared-menus) .rs-picker-row { + display: inline-flex; + gap: 6px; + align-items: center; + justify-content: center; + min-height: 30px; + padding: 4px 10px; + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + background: var(--pm-panel); + white-space: nowrap; +} +.pm-button:hover { + background: var(--pm-hover); +} +.pm-primary { + background: var(--pm-accent); + color: var(--pm-bg) !important; + border-color: var(--pm-accent); +} +.pm-primary:hover { + background: color-mix(in srgb, var(--pm-accent) 85%, var(--pm-bg)); +} +.pm-icon { + display: inline-flex; +} +.pm-icon:not(.rs-picker-icon), .rs-pm:not(.pm-shared-menus) .pm-icon { + width: 16px; + height: 16px; + flex-shrink: 0; +} +.pm-icon svg { + fill: none; + stroke: currentColor; + stroke-width: 1.7; + stroke-linecap: round; + stroke-linejoin: round; + width: 100%; + height: 100%; +} +.pm-icon-button { + position: relative; + padding: 5px; + min-width: 30px; + min-height: 30px; + background: transparent; + border-color: transparent; + color: var(--pm-muted) !important; +} +.pm-icon-button:hover, +.pm-icon-button:focus-visible { + color: var(--pm-text) !important; +} +.pm-toolbar { + position: sticky; + top: 0; + z-index: 5; + flex-shrink: 0; + background: var(--pm-bg); + display: flex; + gap: 12px; + align-items: center; + min-height: 44px; + padding: 6px 12px; + border-bottom: 1px solid var(--pm-line); +} +.pm-tabs { + display: flex; + gap: 2px; +} +.pm-tabs .pm-button { + background: transparent; + border-color: transparent; + color: var(--pm-muted); +} +.pm-title-area { + text-align: center; + flex: 1; + min-width: 0; +} +.pm-board-rename { + position: relative; + max-width: 100%; + background: transparent; + border-color: transparent; +} +.pm-board-rename > .pm-icon { + color: var(--pm-muted); + opacity: 0; + visibility: hidden; + transition: opacity 120ms ease; +} +.pm-board-rename > .pm-icon > svg { + width: 13px; + height: 13px; +} +.pm-board-rename:hover > .pm-icon, +.pm-board-rename:focus-visible > .pm-icon { + opacity: 0.72; + visibility: visible; +} +.pm-board-rename:focus-visible { + background: var(--pm-hover); +} +.pm-view-title { + display: block; + min-width: 0; + font-size: 12px; + color: var(--pm-muted); + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} +.pm-toolbar-actions { + display: flex; + gap: 2px; +} +.pm-search-row { + padding: 10px 16px 0; +} +.pm-search-row input { + width: min(340px, 100%); +} +.rs-pm input:not(.rs-find-bar input), +.rs-pm select, +.rs-pm textarea { + background: var(--pm-field-surface); + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + padding: 6px 8px; + min-height: 30px; +} +.rs-pm input[type="checkbox"]:not(.rs-find-bar input) { + min-height: 0; + width: 16px; + height: 16px; + accent-color: var(--pm-accent); +} +.pm-muted { + color: var(--pm-muted); + font-size: 12px; +} +.pm-error { + color: var(--rs-error, #f44747); +} +.pm-notice { + margin: 10px 16px; +} +.pm-sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} +.pm-board { + position: relative; + flex: 1; + display: flex; + align-items: flex-start; + gap: 12px; + padding: 18px 16px; + overflow-x: auto; + min-height: 235px; +} +.pm-column { + flex: 0 0 280px; + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + background: var(--pm-panel); + overflow: visible; +} +.pm-column-heading { + display: flex; + gap: 2px; + align-items: center; + min-height: 39px; + padding: 3px 6px; + border-bottom: 1px solid var(--pm-line); +} +.pm-column-heading h2 { + flex: 1; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} +.pm-column-heading .pm-icon-button { + min-width: 23px; + min-height: 28px; + padding: 3px; +} +.pm-column-collapsed { + flex-basis: 48px; + min-height: 150px; +} +.pm-column-collapsed .pm-column-heading { + flex-direction: column; + padding: 6px 4px; + border-bottom: 0; +} +.pm-column-collapsed .pm-column-heading h2 { + writing-mode: vertical-rl; + flex: none; + max-height: 240px; + margin: 6px 0; +} +.pm-column-collapsed .pm-list-actions { + display: none; +} +.pm-list-grip { + cursor: grab !important; + opacity: 0.6; +} +.pm-list-grip:active { + cursor: grabbing !important; +} +.rs-pm .pm-icon-button.pm-list-limit-reached { + color: var(--rs-error, #f44747) !important; + outline: 1px solid currentColor; + outline-offset: -3px; +} +.pm-count { + color: var(--pm-muted); + padding: 0 5px; + font-variant-numeric: tabular-nums; +} +.pm-column-board { + padding: 4px 10px; + color: var(--pm-text); + font-size: 12px; + overflow-wrap: anywhere; +} +.pm-card-stack { + padding: 8px 8px 0; + min-height: 77px; +} +.pm-add-card { + display: flex; + width: calc(100% - 16px); + margin: 8px; + color: var(--pm-muted) !important; + font-size: 12px !important; + background: transparent; +} +.pm-card-composer { + margin: 8px; +} +.pm-card-stack:empty:has(+ .pm-card-composer) { + display: none; +} +.rs-pm .pm-card-composer textarea { + display: block; + width: 100%; + min-height: 76px; + resize: vertical; + border-radius: var(--rs-control-radius, var(--pm-radius)); +} +.pm-composer-actions { + display: flex; + align-items: center; + gap: 6px; + margin-top: 8px; +} +.pm-drop-target { + outline: var(--rs-item-selection-width, 2px) solid + var(--rs-item-selection-border, var(--pm-accent)); + outline-offset: -1px; + border-radius: var(--rs-item-selection-radius, var(--pm-radius)); + background: var( + --rs-item-selection-bg, + color-mix(in srgb, var(--pm-accent) 15%, var(--pm-panel)) + ); +} +.pm-list-insertion { + position: absolute; + top: 18px; + width: 3px; + border-radius: var(--pm-radius); + background: var(--rs-item-selection-border, var(--pm-accent)); + pointer-events: none; +} +.pm-card-insertion { + position: absolute; + height: 3px; + border-radius: var(--pm-radius); + background: var(--rs-item-selection-border, var(--pm-accent)); + pointer-events: none; +} +.pm-drag-source { + opacity: 0.4; +} +.pm-drag-preview { + position: fixed; + z-index: 1100; + max-width: calc(100vw - 24px); + border: 1px solid var(--pm-accent); + border-radius: var(--pm-radius); + background: var(--pm-panel); + box-shadow: 0 8px 28px #0006; + opacity: 0.92; + pointer-events: none; + user-select: none; + overflow: hidden; +} +.pm-drag-preview-label { + padding: 5px 10px; + border-bottom: 1px solid var(--pm-line); + color: var(--pm-accent); + font-size: 12px; +} +.pm-drag-preview-content { + max-height: min(260px, 35vh); + overflow: hidden; +} +.pm-drag-preview-content > :is(.pm-column, .pm-card) { + width: 100%; + margin: 0; + border: 0; +} +.pm-drag-preview > canvas { + position: absolute; + width: 1px; + height: 1px; +} +.pm-card { + cursor: pointer; + padding: 8px 9px; + margin: 0 0 7px; + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + background: var(--pm-bg); +} +.pm-colored-card, +.pm-color-sample { + background: color-mix(in srgb, var(--pm-card-color) 14%, var(--pm-bg)); + border-top: 4px solid var(--pm-card-color); +} +.pm-color-sample { + padding: 10px; + border-radius: var(--pm-radius); + color: var(--pm-text); +} +.pm-assignee { + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + padding: 1px 5px; +} +.pm-card-line { + display: flex; + gap: 5px; + align-items: flex-start; +} +.pm-card-title { + flex: 1; + padding: 3px 0; + border: 0; + background: transparent; + text-align: left; + overflow-wrap: anywhere; + font-weight: 400; +} +.pm-complete { + color: var(--pm-muted) !important; + text-decoration: line-through; +} +.pm-card-menu { + margin: -3px -5px -3px 0; + min-width: 26px; + min-height: 26px; + opacity: 0; +} +.pm-card:hover .pm-card-menu, +.pm-card:focus-within .pm-card-menu { + opacity: 1; +} +.pm-badges { + display: flex; + gap: 5px; + flex-wrap: wrap; + margin-top: 5px; + align-items: center; + font-size: 11px; + color: var(--pm-muted); +} +.pm-tag { + padding: 1px 5px; + border-radius: 3px; + background: var(--pm-hover); +} +.pm-due { + padding: 1px 0; + margin-left: auto; +} +.pm-overdue { + color: var(--rs-warn, #cca700); +} +.pm-popup { + position: fixed; + inset: auto; + margin: 0; + color: inherit; + z-index: 100; + width: 280px; + max-width: calc(100vw - 16px); + max-height: calc(100vh - 16px); + overflow: auto; + padding: 12px; + border: 0; + border-radius: var(--pm-radius); + background: var(--pm-panel); + box-shadow: 0 8px 24px #0004; +} + +.pm-popup form > input { + width: 100%; +} +.pm-popup form > input + .pm-field { + margin-top: 12px; +} +.pm-popup-actions { + display: flex; + gap: 7px; + margin-top: 14px; +} +.pm-popup .pm-error:empty { + display: none; +} +.pm-toggle-row { + display: flex; + justify-content: space-between; + align-items: center; + gap: 16px; + margin-top: 16px; + padding-bottom: 12px; + border-bottom: 1px solid var(--pm-line); +} +.pm-toggle-row input[role="switch"] { + appearance: none; + flex-shrink: 0; + width: 30px; + height: 18px; + padding: 0; + border-radius: 12px; + background: var(--pm-hover); + position: relative; + cursor: pointer; +} +.pm-toggle-row input[role="switch"]::before { + content: ""; + position: absolute; + width: 12px; + height: 12px; + top: 2px; + left: 2px; + border-radius: 50%; + background: var(--pm-text); +} +.pm-toggle-row input[role="switch"]:checked { + background: var(--pm-accent); +} +.pm-toggle-row input[role="switch"]:checked::before { + left: 14px; + background: var(--pm-bg); +} +.pm-menu { + width: 235px; + padding: 5px; +} +.pm-menu > .pm-button { + display: flex; + justify-content: flex-start; + width: 100%; + border: 0; + background: transparent; +} +.pm-menu > .pm-button:hover { + background: var(--pm-hover); +} +.pm-menu .pm-field, +.pm-menu > p { + margin: 8px 5px; +} +.pm-field { + display: flex; + flex-direction: column; + gap: 5px; + color: var(--pm-muted); + font-size: 12px; +} +.pm-field input, +.pm-field select, +.pm-field textarea { + color: var(--pm-text); +} +.pm-tag-chips { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-bottom: 8px; +} +.pm-tag-chip { + display: inline-flex; + align-items: center; + gap: 5px; + max-width: 100%; + padding: 2px 4px 2px 8px; + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + background: var(--pm-hover); +} +.pm-tag-chip > span { + overflow-wrap: anywhere; + min-width: 0; +} +.pm-tag-chip button { + flex-shrink: 0; + min-width: 26px; + min-height: 26px; + padding: 0; + border: 0; + background: transparent; +} +.rs-pm:not(.pm-shared-menus) .pm-tag-suggestions { + max-height: 180px; + overflow-y: auto; + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + margin-top: 4px; +} +.rs-pm:not(.pm-shared-menus) .pm-tag-suggestions [role="option"] { + padding: 7px 9px; + cursor: pointer; + overflow-wrap: anywhere; +} +.rs-pm:not(.pm-shared-menus) .pm-tag-suggestions [role="option"]:is(:hover, +[aria-selected="true"]) { + background: var(--pm-hover); +} +.pm-tag-editor > p { + margin: 6px 0 0; + font-size: 11px; +} +.pm-label-picker { + min-width: 0; +} +.pm-label-chips { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} +.pm-label-add { + flex: 0 0 auto; +} +.pm-label-add.pm-label-add-compact { + width: 30px; + padding: 5px; +} +.pm-label-badge { + --pm-label-color: var(--pm-muted); + display: inline-flex; + align-items: center; + gap: 6px; + max-width: 100%; + padding: 2px 7px; + border: 1px solid + color-mix(in srgb, var(--pm-label-color) 65%, var(--pm-line)); + border-radius: var(--pm-radius); + background: color-mix(in srgb, var(--pm-label-color) 16%, var(--pm-panel)); + color: var(--pm-text); + font-size: 12px; + overflow-wrap: anywhere; +} +.pm-label-badge::before { + content: ""; + width: 7px; + height: 7px; + flex-shrink: 0; + border-radius: 50%; + background: var(--pm-label-color); +} +.pm-label-badge .pm-button { + position: relative; + flex-shrink: 0; + min-width: 28px; + min-height: 28px; + padding: 0; + background: transparent; + border: 0; +} +.rs-pm:not(.pm-shared-menus) .pm-label-options { + position: fixed; + inset: auto; + margin: 0; + width: min(210px, calc(100vw - 24px)); + padding: 6px; + overflow: auto; + border: 0; + border-radius: var(--pm-radius); + background: var(--pm-panel); + color: var(--pm-text); + box-shadow: 0 8px 28px #0005; +} +.rs-pm:not(.pm-shared-menus) .pm-label-options > input { + width: 100%; + font-size: 12px; +} +.pm-label-choices { + max-height: 160px; + overflow: auto; + margin-top: 4px; +} +.rs-pm:not(.pm-shared-menus) .pm-label-option { + display: flex; + align-items: center; + width: 100%; + min-height: 30px; + padding: 4px; + border: 0; + border-radius: var(--pm-radius); + background: transparent; + text-align: left; + cursor: pointer; +} +.rs-pm:not(.pm-shared-menus) .pm-label-option:is(:hover, :focus-visible) { + background: var(--pm-hover); +} +.rs-pm:not(.pm-shared-menus) .pm-label-options > .pm-label-manage { + justify-content: flex-start; + width: 100%; + margin-top: 4px; + border: 0; + border-top: 1px solid var(--pm-line); + border-radius: 0; + background: transparent; + font-size: 12px; +} +.rs-pm:not(.pm-shared-menus) .pm-label-options > .pm-label-manage:hover { + background: var(--pm-hover); +} +.pm-label-definitions { + display: grid; + gap: 12px; + margin: 16px 0; +} +.pm-label-definition { + min-width: 0; + margin: 0; + padding: 10px; + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); +} +.pm-label-definition legend { + max-width: 100%; +} +.pm-label-definition-fields { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 8px; + align-items: end; +} +.pm-color-palette { + min-width: 0; + margin: 0; + padding: 0; + border: 0; +} +.pm-color-palette legend { + margin-bottom: 6px; + padding: 0; + color: var(--pm-muted); + font-size: 12px; +} +.pm-color-choices { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 7px; + padding: 3px; + max-width: 295px; +} +.rs-pm input.pm-color-swatch { + appearance: none; + flex: 0 0 30px; + width: 30px; + height: 30px; + min-height: 30px; + margin: 0; + padding: 0; + border: 2px solid transparent; + border-radius: var(--pm-radius); + background: var(--pm-swatch-color, var(--pm-bg)); + color: var(--pm-swatch-foreground, #141414); + cursor: pointer; + display: grid; + place-items: center; +} +.rs-pm input.pm-color-swatch:checked::after { + content: "✓"; + font-size: 18px; + font-weight: 700; +} +.rs-pm input.pm-color-swatch:checked { + border-color: var(--pm-panel); + box-shadow: 0 0 0 1px var(--pm-text); +} +.rs-pm input.pm-color-swatch:focus-visible { + outline: 2px solid var(--pm-accent); + outline-offset: 3px; +} +.rs-pm input.pm-no-color { + border-color: var(--pm-line); + color: var(--pm-text); + background-image: linear-gradient( + 135deg, + transparent 47%, + var(--pm-muted) 48%, + var(--pm-muted) 52%, + transparent 53% + ); +} +.pm-color-name { + display: block; + color: var(--pm-muted); + font-size: 12px; + margin: 4px 0 0 3px; +} +.pm-editor.pm-label-manager { + overflow: hidden; +} +.pm-label-manager form { + display: flex; + flex-direction: column; + max-height: calc(90vh - 42px); +} +.pm-label-manager form > :not(.pm-label-definitions) { + flex-shrink: 0; +} +.pm-label-manager form > .pm-button { + align-self: flex-start; +} +.pm-label-manager .pm-label-definitions { + min-height: 0; + overflow-y: auto; + grid-auto-rows: max-content; +} +.pm-label-manager .pm-editor-actions { + margin-top: 8px; + padding-top: 12px; + border-top: 1px solid var(--pm-line); +} +.pm-editor { + background: var(--pm-panel); + color: var(--pm-text); + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + width: 570px; + max-width: calc(100vw - 32px); + max-height: 90vh; + overflow: auto; + padding: 20px; +} +.pm-editor::backdrop { + background: #0006; +} +.pm-editor h2 { + font-size: 16px; +} +.pm-note-picker { + width: 620px; + max-height: calc(100dvh - 32px); + padding: 20px; + overflow-x: hidden; +} +.pm-note-picker form { + display: flex; + flex-direction: column; + gap: 12px; + min-width: 0; +} +.pm-note-picker .pm-field { + min-width: 0; +} +.pm-note-picker input { + min-height: 36px; +} +.rs-pm .pm-note-summary { + margin: 0; + color: var(--pm-muted); + overflow-wrap: anywhere; +} +.rs-pm:not(.pm-shared-menus) .pm-note-results { + display: flex; + flex-direction: column; + gap: 4px; + max-height: min(280px, 35dvh); + min-height: 48px; + overflow: auto; + padding: 4px; + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); +} +.rs-pm:not(.pm-shared-menus) .pm-note-result { + flex: 0 0 auto; + width: 100%; + min-width: 0; + justify-content: flex-start; + text-align: left; + white-space: normal; + padding: 8px; + border-color: transparent; +} +.rs-pm:not(.pm-shared-menus) .pm-note-result[aria-pressed="true"] { + background: var(--pm-selection-bg); + outline: var(--pm-selection-width) solid var(--pm-selection-border); + outline-offset: calc(-1 * var(--pm-selection-width)); + border-radius: var(--pm-selection-radius); +} +.rs-pm:not(.pm-shared-menus) .pm-note-result-text { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; + overflow-wrap: anywhere; +} +.rs-pm:not(.pm-shared-menus) .pm-note-path { + color: var(--pm-muted); + font-size: 12px; +} +.pm-note-picker .pm-editor-actions { + margin-top: 0; + padding-top: 12px; + border-top: 1px solid var(--pm-line); + flex-wrap: wrap; +} +.pm-form-grid { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 12px; + margin-top: 16px; +} +.pm-optional-fields { + display: grid; + gap: 12px; +} +.pm-optional-fields:empty { + display: none; +} +.pm-optional-group { + border-top: 1px solid var(--pm-line); + padding-top: 8px; + min-width: 0; +} +.pm-optional-heading { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 6px; +} +.pm-optional-heading h3 { + font-size: 12px; + font-weight: 500; + margin: 0; +} +.pm-optional-content { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; +} +.pm-optional-content > :only-child { + grid-column: 1 / -1; +} +.pm-field input, +.pm-field select, +.pm-field textarea { + min-width: 0; + width: 100%; +} +.pm-field-choices { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 8px; +} +.pm-field-choices .pm-button { + font-size: 12px; +} +.pm-details-picker { + width: 320px; +} +.rs-pm:not(.pm-shared-menus) .pm-detail-choices { + display: grid; + gap: 8px; + margin-top: 10px; +} +.rs-pm:not(.pm-shared-menus) .pm-detail-choice { + display: grid; + gap: 3px; +} +.rs-pm:not(.pm-shared-menus) .pm-detail-choice > .rs-picker-row { + justify-content: flex-start; + width: 100%; +} +.rs-pm:not(.pm-shared-menus) .pm-detail-choice > span { + padding-inline: 8px; + color: var(--pm-muted); + font-size: 12px; +} +.pm-description-actions { + display: flex; + justify-content: flex-end; +} +.pm-editor.pm-description-editor { + width: 940px; + max-height: calc(100dvh - 32px); +} +.pm-description-toolbar { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-block: 12px; +} +.pm-description-source textarea { + min-height: min(45vh, 420px); + font-family: var(--rs-font-ui, system-ui, sans-serif); + resize: vertical; +} +.pm-markdown-preview { + min-height: min(45vh, 420px); + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + padding: 14px; + overflow-wrap: anywhere; + overflow: auto; +} +.pm-markdown-preview img { + display: block; + max-width: 100%; + max-height: 460px; + object-fit: contain; +} +.pm-markdown-preview pre { + overflow: auto; + padding: 10px; + background: var(--pm-bg); +} +.pm-markdown-preview table { + border-collapse: collapse; +} +.pm-markdown-preview td, +.pm-markdown-preview th { + border: 1px solid var(--pm-line); + padding: 6px; +} +.pm-markdown-preview a { + color: var(--pm-accent); +} +.pm-priority { + display: inline-flex; + gap: 4px; + align-items: center; + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + padding: 2px 5px; + font-size: 11px; +} +.pm-editor .pm-error:empty { + display: none; +} +.pm-wide { + grid-column: 1/-1; +} +.pm-editor-actions { + display: flex; + justify-content: flex-end; + gap: 7px; + margin-top: 16px; +} +.pm-view { + min-width: 0; + margin: 12px 16px 16px; + padding: 0 12px 12px; + background: var(--pm-panel-surface); + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); +} +.pm-date-nav { + display: flex; + gap: 4px; + align-items: center; + flex-wrap: wrap; + min-height: 48px; + padding: 8px 0; +} +.pm-date-nav .pm-button { + border-color: transparent; + background: transparent; + color: var(--pm-muted); +} +.pm-date-nav input { + margin: 0 9px; + background: transparent; + border-color: transparent; +} +.pm-zone { + margin-left: auto; + color: var(--pm-muted); + font-size: 11px; +} +.pm-view > h2 { + margin: 0 0 12px; +} +.pm-gantt-scroll { + overflow: auto; +} +.pm-gantt { + min-width: 900px; + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + overflow: hidden; +} +.pm-gantt-row { + display: grid; + grid-template-columns: 220px 1fr; + border-bottom: 1px solid var(--pm-line); + min-height: 46px; +} +.pm-gantt-row:last-child { + border-bottom: 0; +} +.pm-gantt-name { + padding: 8px 10px; + background: transparent; + border: 0; + border-right: 1px solid var(--pm-line); + text-align: left; + overflow-wrap: anywhere; +} +.pm-gantt-name small { + display: block; + color: var(--pm-muted); + font-size: 11px; +} +.pm-gantt-dates { + display: grid; + grid-template-columns: repeat(28, 1fr); + align-items: center; + font-size: 11px; + text-align: center; + color: var(--pm-muted); +} +.pm-gantt-track { + position: relative; + background: repeating-linear-gradient( + to right, + transparent 0, + transparent calc(100% / 28 - 1px), + var(--pm-line) calc(100% / 28 - 1px), + var(--pm-line) calc(100% / 28) + ); +} +.pm-gantt-bar { + position: absolute; + top: 11px; + height: 23px; + background: color-mix(in srgb, var(--pm-accent) 24%, var(--pm-panel)); + border: 1px solid color-mix(in srgb, var(--pm-accent) 60%, var(--pm-line)); + border-radius: var(--pm-radius); + font-size: 11px !important; + text-align: left; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + padding: 2px 7px; +} +.pm-status-done { + background: var(--pm-hover); + border-color: var(--pm-muted); + color: var(--pm-muted) !important; +} +.pm-deadline { + position: absolute; + top: 23px; + transform: translateX(-50%); + color: var(--pm-card-color, var(--rs-warn, #cca700)) !important; + background: none; + border: 0; + padding: 0; +} +.pm-today { + background: var(--pm-accent) !important; + color: var(--pm-bg) !important; + border-radius: var(--pm-radius); + padding: 3px; +} +.pm-month { + display: grid; + grid-template-columns: repeat(7, minmax(95px, 1fr)); + border-top: 1px solid var(--pm-line); + border-left: 1px solid var(--pm-line); + overflow: auto; +} +.pm-day-heading, +.pm-month-day { + border-right: 1px solid var(--pm-line); + border-bottom: 1px solid var(--pm-line); + padding: 6px; +} +.pm-day-heading { + color: var(--pm-muted); + text-align: center; + font-size: 11px; +} +.pm-month-day { + min-height: 104px; +} +.pm-month-day > .pm-button { + padding: 1px 6px; + min-height: 24px; + border: 0; + background: transparent; + font-size: 11px; +} +.pm-outside { + background: var(--pm-panel-surface); + color: var(--pm-muted); +} +.pm-calendar-entries { + display: flex; + flex-direction: column; + gap: 3px; + margin-top: 5px; +} +.pm-calendar-event { + border: 1px solid var(--pm-line); + background: color-mix(in srgb, var(--pm-accent) 15%, var(--pm-panel)); + border-radius: var(--pm-radius); + padding: 3px 5px; + text-align: left; + font-size: 11px !important; + overflow-wrap: anywhere; + line-height: 1.35; +} +.pm-deadline-event { + background: var(--pm-panel); + color: var(--pm-muted) !important; +} +.pm-gantt-name.pm-colored-task, +.pm-gantt-bar.pm-colored-task, +.pm-calendar-event.pm-colored-task, +.pm-hour-heading .pm-colored-task { + background: color-mix(in srgb, var(--pm-card-color) 14%, var(--pm-bg)); + border-color: var(--pm-card-color); + border-left: 4px solid var(--pm-card-color); + color: var(--pm-text) !important; +} +.pm-hours-scroll { + overflow: auto; + max-height: calc(100vh - 170px); + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); +} +.pm-hours { + display: grid; + grid-template-columns: 52px repeat(var(--days), minmax(110px, 1fr)); + min-width: 100%; +} +.pm-hour-heading { + height: 65px; + background: var(--pm-field-surface); + border-bottom: 1px solid var(--pm-line); + padding: 6px; + overflow: auto; + font-size: 11px; +} +.pm-hour-heading button { + display: block; + font-size: 10px; + min-height: 20px; + padding: 2px; +} +.pm-hour-label { + height: 52px; + padding: 3px; + color: var(--pm-muted); + font-size: 10px; +} +.pm-hour-day { + border-left: 1px solid var(--pm-line); +} +.pm-hour-grid { + position: relative; + height: 1248px; +} +.pm-hour-slot { + display: block; + width: 100%; + height: 52px; + border: 0; + border-bottom: 1px solid var(--pm-line); + background: transparent; +} +.pm-hour-grid .pm-calendar-entries { + position: absolute; + inset: 0; + margin: 0; + pointer-events: none; +} +.pm-timed-event { + position: absolute; + left: 3px; + right: 5px; + pointer-events: auto; +} +.pm-now { + position: absolute; + left: 0; + right: 0; + height: 1px; + background: var(--rs-error, #f44747); + pointer-events: none; +} +.pm-issues { + border: 1px solid var(--pm-line); + border-radius: var(--pm-radius); + padding: 8px; + margin: 10px 16px; + color: var(--rs-warn, #cca700); +} +.pm-issues p { + font-size: 12px; + overflow-wrap: anywhere; +} +.pm-empty { + margin: 16px !important; +} +.rs-pm + .pm-date-nav + .pm-button:is(:hover, :focus-visible, [aria-pressed="true"]) { + color: var(--pm-text); + background: var(--pm-selection-bg); + border-radius: var(--pm-selection-radius); + box-shadow: inset 0 0 0 var(--pm-selection-width) var(--pm-selection-border); + outline: none; +} +.rs-pm .pm-card:is(:hover, :has(:focus-visible)), +.rs-pm + :is( + button.pm-gantt-name, + .pm-gantt-bar, + .pm-deadline, + .pm-calendar-event, + .pm-hour-heading button, + .pm-hour-slot, + .pm-month-day > .pm-button + ):is(:hover, :focus-visible) { + background-image: linear-gradient( + var(--pm-selection-bg), + var(--pm-selection-bg) + ); + border-radius: var(--pm-selection-radius); + box-shadow: inset 0 0 0 var(--pm-selection-width) var(--pm-selection-border); + outline: none; +} +.rs-pm .pm-card-title:focus-visible { + outline: none; +} +@media (max-width: 720px) { + .pm-view-title { + display: none; + } + .pm-toolbar { + flex-wrap: wrap; + justify-content: space-between; + gap: 5px; + } + .pm-tabs .pm-button { + padding: 4px 7px; + } + .pm-form-grid { + grid-template-columns: 1fr; + } + .pm-optional-content { + grid-template-columns: minmax(0, 1fr); + } + .pm-zone { + display: none; + } +} +.rs-pm .pm-scope { + max-width: 220px; + min-width: 90px; +} + +.pm-card-images > .pm-muted { + margin: 6px 0; +} +.pm-image-gallery { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); + gap: 8px; +} +.pm-image-gallery figure { + margin: 0; + padding: 8px; + border: 1px solid var(--pm-line); + border-radius: var(--rs-control-radius, var(--pm-radius)); + min-width: 0; +} +.pm-image-thumbnail { + position: relative; + display: grid; + place-items: center; + width: 100%; + height: 76px; + padding: 4px; + background: var(--pm-bg); + border: 1px solid transparent; + border-radius: var(--pm-radius); +} +.pm-image-thumbnail > .pm-tooltip { + left: 0; + right: auto; + max-width: 100%; + overflow-wrap: anywhere; +} +.pm-image-thumbnail:hover { + border-color: var(--pm-accent); +} +.pm-image-gallery img { + display: block; + max-width: 100%; + max-height: 66px; + object-fit: contain; + margin: auto; +} +.pm-image-gallery figcaption { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + overflow-wrap: anywhere; +} + +.pm-image-gallery figcaption > span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 11px; +} +.pm-image-gallery .pm-error { + font-size: 11px; +} +/* The modal surface has no chrome. Controls stay above the image while it scrolls. */ +.pm-image-viewer { + position: fixed; + inset: 0; + width: 100vw; + height: 100dvh; + max-width: none; + max-height: none; + margin: 0; + padding: 0; + overflow: hidden; + border: 0; + border-radius: 0; + background: transparent; + color: white; +} +.pm-image-viewer::backdrop { background: #000d; } +.pm-image-viewer-header { + position: absolute; + z-index: 1; + top: 16px; + left: 16px; + right: 16px; + display: flex; + align-items: center; + gap: 8px; + pointer-events: none; +} +.pm-image-viewer-header h2 { + flex: 1; + min-width: 0; + margin: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + text-shadow: 0 1px 3px black, 0 0 6px black; + pointer-events: auto; +} +.rs-pm .pm-image-viewer-header button { + flex: 0 0 auto; + min-height: 36px; + min-width: 36px; + border-color: transparent; + background: transparent; + color: white !important; + text-shadow: 0 1px 3px black, 0 0 6px black; + pointer-events: auto; +} +.pm-image-viewer-header .pm-icon { filter: drop-shadow(0 1px 2px black); } +.rs-pm .pm-image-viewer-header button:hover, +.rs-pm .pm-image-viewer-header button:focus-visible, +.rs-pm .pm-image-viewer-header button[aria-pressed="true"] { + background: #0008; + outline-color: white; +} +.pm-image-frame { + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + padding: 16px; + overflow: auto; + background: transparent; +} +.pm-image-frame img { + display: block; + flex: 0 0 auto; + width: auto; + height: auto; + max-width: 100%; + max-height: 100%; + object-fit: contain; + margin: auto; +} +.pm-image-frame.pm-image-actual { display: block; } +.pm-image-actual img { max-width: none; max-height: none; } +.rs-pm .pm-image-preview-trigger { + position: relative; + display: block; + max-width: 100%; + padding: 0; + border: 1px solid transparent; + border-radius: var(--rs-control-radius, var(--pm-radius)); + background: transparent; + cursor: zoom-in; +} +.rs-pm .pm-image-preview-trigger:hover, +.rs-pm .pm-image-preview-trigger:focus-visible { border-color: var(--pm-accent); } +@media (max-width: 480px) { + .pm-image-viewer-header { top: 8px; left: 8px; right: 8px; gap: 4px; } + .pm-image-viewer-header h2 { font-size: 13px; } + .pm-image-frame { padding: 8px; } +} +.pm-visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} +.pm-card-editor { + width: 640px; + padding: 16px 20px; +} +.pm-card-editor-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 12px; + padding-bottom: 10px; + border-bottom: 1px solid var(--pm-line); +} +.pm-card-editor-header .pm-field { + display: flex; + flex-direction: row; + align-items: center; + gap: 8px; + min-width: 0; + color: var(--pm-muted); +} +.pm-card-editor-header select { + width: auto; + max-width: min(280px, 55vw); + color: var(--pm-text); +} +.pm-card-editor-header .pm-choice-button { min-width: 0; max-width: min(280px, 55vw); color: var(--pm-text); } +.pm-choice-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pm-choice-button { justify-content: space-between; min-width: 0; max-width: 100%; text-align: left; } +.rs-pm .pm-card-context { + font-size: 11px; + margin: 8px 0 0; + overflow-wrap: anywhere; +} +.pm-card-editor .pm-form-grid { + margin-top: 8px; + gap: 10px; +} +.pm-editor-card-title { + font-size: 0; + gap: 0; +} +.rs-pm .pm-editor-card-title input { + font-size: 20px; + font-weight: 600; + background: transparent; + border-color: transparent; + padding: 6px 10px; + margin-inline: -10px; + width: calc(100% + 20px); +} +.pm-editor-card-title input:hover { + border-color: var(--pm-line); +} +.pm-card-editor .pm-field-choices { + margin-top: 0; + gap: 4px; +} +.pm-card-editor .pm-field-choices .pm-button { + min-height: 28px; + padding: 3px 7px; +} +.pm-card-editor .pm-card-images > .pm-muted { + font-size: 11px; +} +.pm-card-editor .pm-editor-actions { + padding: 12px 0 0; + background: transparent; + border-top: 1px solid var(--pm-line); +} +@media (hover: none) { + .pm-card-menu { opacity: 1; } +} + +/* Card details stay above the inline description. */ +.rs-pm:not(.pm-shared-menus) .pm-detail-choice > .rs-picker-row { + display: grid; + grid-template-columns: 16px minmax(0, 1fr); + text-align: left; + column-gap: 8px; + row-gap: 2px; + padding: 7px 9px !important; +} +.rs-pm:not(.pm-shared-menus) .pm-detail-hint { + grid-column: 2; + color: var(--pm-muted); + font-size: 11px; + white-space: normal; +} +.rs-pm:not(.pm-shared-menus) .pm-detail-choices { gap: 4px; } +.pm-description-editor { min-width: 0; } +.pm-description-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 8px; +} +.pm-description-heading h3 { margin: 0; font-size: 14px; } +.pm-description-toolbar { gap: 4px; margin: 8px 0; } +.pm-description-toolbar .pm-button { font-size: 12px; } +.pm-description-source textarea { min-height: 150px; } +.pm-description-actions { gap: 6px; margin-top: 8px; } +.pm-description-editor .pm-markdown-preview { min-height: 72px; } +.pm-description-editor [hidden] { display: none !important; } +.pm-priority-picker { width: 210px; } +.rs-pm:not(.pm-shared-menus) .pm-priority-option { display: flex; width: 100%; justify-content: flex-start; margin: 3px 0; } +[data-priority="high"] { --pm-priority-color: #ff0000; } +[data-priority="medium"] { --pm-priority-color: #ffc400; } +[data-priority="low"] { --pm-priority-color: #009dff; } +[data-priority="none"] { --pm-priority-color: var(--pm-muted); } +[data-priority] > .pm-icon { color: var(--pm-priority-color); opacity: 1; filter: drop-shadow(0 0 0.5px #222); } +.pm-priority[data-priority], +.rs-pm:not(.pm-shared-menus) .pm-priority-option[aria-pressed="true"] { + border-color: color-mix(in srgb, var(--pm-priority-color) 65%, var(--pm-line)); + background: color-mix(in srgb, var(--pm-priority-color) 14%, var(--pm-panel)); +} +.rs-pm:not(.pm-shared-menus) .pm-detail-choice > .rs-picker-row > .pm-icon { grid-row: 1 / span 2; align-self: center; } +.pm-description-surface { border: 1px solid var(--pm-line); border-radius: var(--pm-radius); } +.pm-description-surface:has(.pm-description-toolbar[hidden]) { border: 0; } +.pm-description-surface:focus-within { border-color: var(--pm-accent); } +.pm-description-surface .pm-description-toolbar { + gap: 2px; margin: 0; padding: 5px; border-bottom: 1px solid var(--pm-line); +} +.pm-description-toolbar .pm-button { background: transparent; border-color: transparent; } +.pm-description-toolbar .pm-button:hover { background: var(--pm-hover); } +.pm-description-source { gap: 0; position: relative; } +.pm-description-find-highlights { + position: absolute; + inset: 0; + overflow: hidden; + pointer-events: none; + white-space: pre-wrap; + overflow-wrap: break-word; + color: transparent; +} +.pm-description-find-highlights mark { + background: var(--rs-item-selection-bg, var(--pm-selection-bg)); + color: var(--pm-text); +} +.pm-description-find-highlights .pm-description-find-current { + background: var(--rs-selection, var(--pm-selection-bg)); + color: var(--rs-selection-text, var(--pm-text)); + outline: 1px solid var(--pm-accent); +} +.rs-pm .pm-description-source textarea { + width: 100%; border: 0; border-radius: 0 0 var(--pm-radius) var(--pm-radius); + padding: 12px; outline: none; box-shadow: none; line-height: 1.6; +} +.pm-image-viewer-header > * { transition: opacity 160ms ease; } +.pm-image-controls-idle .pm-image-viewer-header > * { opacity: 0; } +.pm-image-controls-idle .pm-image-viewer-header > :hover, +.pm-image-controls-idle .pm-image-viewer-header > :focus-visible { opacity: 1; } +@media (prefers-reduced-motion: reduce) { + .pm-image-viewer-header > * { transition: none; } +} + +/* Compact ribbon controls keep keyboard focus visible. */ +.pm-toolbar .pm-button { border-color: transparent; background: transparent; } +.pm-toolbar .pm-button[aria-pressed="true"] { border-color: transparent; background: var(--pm-hover); } +.pm-toolbar .pm-button:hover { background: var(--pm-hover); } +.pm-title-area { display: flex; align-items: center; justify-content: center; gap: 2px; } +.pm-title-area .pm-scope { width: min(260px, 100%); min-width: 80px; border-color: transparent; background-color: transparent; } +.pm-title-area .pm-board-rename > .pm-icon { visibility: visible; opacity: .7; } +.pm-toolbar .pm-button:focus-visible { outline: 2px solid var(--pm-accent); outline-offset: 2px; } +.rs-pm .pm-description-source textarea { resize: none; overflow-y: hidden; max-height: none; padding-bottom: 32px; scroll-margin-bottom: 32px; } +.pm-description-unsaved, .pm-card-unsaved { + display: inline-flex; + align-items: center; + gap: 4px; + width: fit-content; + max-width: 100%; + padding: 2px 6px; + border-radius: var(--pm-radius); + background: var(--pm-draft-bg); + color: var(--pm-draft-text); + font-size: 12px; + font-weight: 600; +} +.pm-onboarding { padding: 20px; border: 1px solid var(--pm-border); border-radius: var(--rs-control-radius, 5px); margin: 12px; } +.pm-onboarding h2 { margin: 0; font-size: 18px; } +.pm-created-at { font-size: 12px; margin: 8px 0; } +.pm-relation-row { display: flex; align-items: center; gap: 8px; margin: 6px 0; flex-wrap: wrap; } +.pm-relation-row > input:not([type=checkbox]), .pm-relation-row > select, .pm-relation-row > span { flex: 1; min-width: 120px; } +.pm-relation-row > input[type=checkbox] { width: 18px; height: 18px; } +.pm-related-card { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; padding: 10px 12px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius, 5px); background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; } +.pm-related-card:hover { background: var(--rs-bg-active); } +.pm-related-card:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: 2px; } +.pm-related-title { flex: 1 1 220px; overflow-wrap: anywhere; font-size: 15px; line-height: 1.5; } +.pm-related-metadata { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; font-size: 13px; line-height: 1.5; } +.pm-related-metadata > span { overflow-wrap: anywhere; } +.pm-related-priority { display: inline-flex; align-items: center; gap: 6px; } +.pm-link-editor { min-width: 0; } +.pm-link-results { width: 100%; max-height: min(220px, 30dvh); overflow: auto; } +.pm-link-result-text { min-width: 0; overflow-wrap: anywhere; } +.rs-pm:not(.pm-shared-menus) .pm-link-results { border: 1px solid var(--pm-line); border-radius: var(--pm-radius); padding: 4px; background: var(--pm-panel); } +.rs-pm:not(.pm-shared-menus) .pm-link-results .rs-picker-row { display: flex; width: 100%; text-align: left; } +.rs-pm:not(.pm-shared-menus) .pm-link-results .rs-picker-row:is(:hover, :focus-visible) { background: var(--pm-hover); } +.pm-relations h3 { margin: 12px 0 6px; } +.pm-card-cover-button { display: block; width: 100%; padding: 0; border: 0; border-radius: var(--pm-radius); overflow: hidden; background: var(--pm-panel); cursor: pointer; } +.pm-card-cover { display: block; width: 100%; height: 160px; object-fit: cover; } +/* Nested surfaces share the same tint. Text and focus indicators stay opaque. */ +.rs-pm.pm-has-background { --pm-surface-opacity: var(--rs-surface-opacity, 82%); background-color: var(--pm-bg); } +.rs-pm .pm-column, +.rs-pm .pm-card-editor { + background-color: var(--pm-panel-surface); +} +.rs-pm .pm-card:not(.pm-card-selected) { background-color: var(--pm-field-surface); } +.rs-pm .pm-colored-card:not(.pm-card-selected), +.rs-pm .pm-colored-task:not(.pm-deadline):not(.pm-card-selected) { + background-color: color-mix(in srgb, color-mix(in srgb, var(--pm-card-color) 14%, var(--pm-bg)) var(--pm-surface-opacity), transparent); +} +.rs-pm .pm-card-editor button:not([role^="menuitem"]):not(.rs-picker-row) { + background: transparent; + border-color: transparent; +} +.rs-pm .pm-card-editor .pm-primary { color: var(--pm-text) !important; } +.rs-pm .pm-card-editor button:not([role^="menuitem"]):not(.rs-picker-row):is(:hover, :active, [aria-pressed="true"]):not(:disabled) { + background-color: color-mix(in srgb, var(--pm-hover) var(--pm-surface-opacity), transparent); +} +.pm-label-badge .pm-button:is(:hover, :focus-visible) > .pm-tooltip { + opacity: 1; + visibility: visible; +} +.pm-label-badge .pm-tooltip { white-space: normal; width: max-content; text-align: left; } +.pm-preferences { padding: var(--rs-settings-section-gap, 16px); } +.pm-preferences select { min-height: var(--rs-settings-control-height, 32px); } +[data-priority=highest] { --pm-priority-color: #ff0066; } +[data-priority=lowest] { --pm-priority-color: #0066ff; } + +.rs-pm .pm-tabs .pm-button:is(:hover, [aria-pressed="true"]) { background: var(--pm-hover); box-shadow: none; } +.rs-pm .pm-tabs .pm-button:focus-visible { outline: 2px solid var(--pm-accent); outline-offset: 2px; box-shadow: none; } +.pm-title-area .pm-board-rename { display: inline-flex; align-items: center; justify-content: center; min-width: 28px; min-height: 28px; gap: 0; padding: 4px; } +.pm-title-area .pm-board-rename > .pm-icon { display: flex; align-items: center; justify-content: center; } +.pm-relation-heading, .pm-attachment-heading { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } +.pm-relation-heading h3, .pm-attachment-heading h3 { flex: 1; margin: 8px 0; } +.pm-section-toggle { display: inline-flex; align-items: center; gap: 6px; padding: 4px; color: inherit; background: transparent; border: 0; border-radius: var(--rs-control-radius, 5px); font: inherit; cursor: pointer; } +.pm-section-toggle svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.7; } +.pm-section-toggle[aria-expanded=false] svg { transform: rotate(-90deg); } +.pm-section-toggle:hover { background: var(--pm-hover); } +.pm-section-toggle:focus-visible { outline: 2px solid var(--pm-accent); outline-offset: 2px; } +.pm-scope option { color: var(--pm-text); background: var(--pm-panel); } +.pm-button.pm-scope { display: grid; grid-template-columns: 16px minmax(0, 1fr) 16px; overflow: hidden; text-align: center; } +.pm-scope-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +.pm-selection-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 8px 12px; background: var(--pm-panel); } +.pm-selection-count { min-width: 80px; } +.pm-card-selected { background: var(--pm-selection-bg); outline: var(--pm-selection-width) solid var(--pm-selection-border); outline-offset: calc(-1 * var(--pm-selection-width)); border-radius: var(--pm-selection-radius); } +.pm-card-select { width: 20px; height: 20px; cursor: pointer; } +.pm-card:has(.pm-card-select) { cursor: pointer; } +.pm-card:has(.pm-card-select) .pm-card-menu { display: none; } + +.rs-pm { isolation: isolate; } +.pm-background { position: fixed; z-index: -1; pointer-events: none; background-repeat: no-repeat; } +.pm-background-previous { position: absolute; inset: 0; background-repeat: no-repeat; pointer-events: none; } + +.pm-toolbar { flex-wrap: wrap; } +.pm-title-area { flex: 1 1 140px; } +.pm-toolbar-actions { flex-wrap: wrap; } + +.pm-background-settings { margin-top: var(--rs-settings-gap, 8px); } +.pm-background-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap, 8px); padding: var(--rs-settings-row-padding, 10px) 0; } +.pm-background-row + .pm-background-row { border-top: 1px solid var(--pm-line); } +.pm-background-row .pm-choice-button { min-height: var(--rs-settings-control-height, 28px); max-width: 100%; } +.pm-overlay-controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap, 8px); max-width: 100%; } +.pm-overlay-controls input[type=range] { width: 160px; max-width: 100%; min-width: 0; padding: 0; } +.pm-overlay-value { display: flex; align-items: center; gap: 4px; } +.pm-overlay-value input { width: 64px; min-height: var(--rs-settings-control-height, 28px); } +.pm-auto-scrolling, .pm-auto-scrolling * { cursor: all-scroll !important; } +.pm-autoscroll-marker { position: fixed; z-index: 1000; pointer-events: none; width: 26px; height: 26px; transform: translate(-50%, -50%); display: grid; place-items: center; border: 1px solid var(--pm-line); border-radius: 50%; background: var(--pm-panel); color: var(--pm-text); } +.pm-autoscroll-marker .pm-icon { width: 20px; height: 20px; } + +/* Picker layout only. The host menu stylesheet owns its presentation. */ +.pm-shared-menus .pm-label-options { position: fixed; inset: auto; margin: 0; width: min(248px, calc(100vw - 24px)); max-height: calc(100vh - 24px); overflow: auto; } +.pm-shared-menus .pm-details-picker { width: min(320px, calc(100vw - 24px)); } +.pm-shared-menus .pm-label-options > input { width: 100%; } +.pm-shared-menus .pm-label-choices { max-height: 160px; overflow: auto; } +.pm-shared-menus .pm-note-results { display: flex; flex-direction: column; width: 100%; max-height: min(280px, 35dvh); min-height: 48px; overflow: auto; } +.pm-shared-menus .pm-note-result { flex: 0 0 auto; } +.pm-note-result-text { display: flex; flex-direction: column; min-width: 0; overflow-wrap: anywhere; } +.pm-priority[data-priority] { color: var(--pm-text); border-color: var(--pm-priority-color); border-left-width: 3px; } + +.pm-board-group-heading { + margin: 0 0 8px; + padding: 4px 2px 6px; + border-bottom: 1px solid var(--pm-line); + color: var(--pm-text); + font-size: 12px; + font-weight: 600; + overflow-wrap: anywhere; +} +.pm-board-group + .pm-board-group { + margin-top: 16px; +} diff --git a/src/lib/features/pm/ui/tags.ts b/src/lib/features/pm/ui/tags.ts new file mode 100644 index 0000000..20067b1 --- /dev/null +++ b/src/lib/features/pm/ui/tags.ts @@ -0,0 +1,168 @@ +export function createTagInput(initial: string[], existing: string[]) { + const element = document.createElement("div"); + element.className = "pm-tag-editor pm-wide"; + const chips = document.createElement("div"); + chips.className = "pm-tag-chips"; + chips.setAttribute("role", "list"); + chips.setAttribute("aria-label", "Selected tags"); + const label = document.createElement("label"); + label.className = "pm-field"; + label.textContent = "Add a tag"; + const input = document.createElement("input"); + input.type = "text"; + input.autocomplete = "off"; + input.placeholder = "Type a tag and press Enter"; + input.setAttribute("role", "combobox"); + input.setAttribute("aria-autocomplete", "list"); + input.setAttribute("aria-expanded", "false"); + const suggestions = document.createElement("div"); + suggestions.className = "pm-tag-suggestions rs-picker"; + suggestions.id = "pm-tags-" + crypto.randomUUID(); + suggestions.setAttribute("role", "listbox"); + suggestions.setAttribute("aria-label", "Existing tags"); + suggestions.hidden = true; + input.setAttribute("aria-controls", suggestions.id); + const hint = document.createElement("p"); + hint.className = "pm-muted"; + hint.id = suggestions.id + "-hint"; + hint.textContent = + "Press Enter to add a tag. Use the arrow keys to choose an existing tag."; + input.setAttribute("aria-describedby", hint.id); + label.append(input); + element.append(chips, label, suggestions, hint); + + const normalize = (tag: string) => tag.trim().toLocaleLowerCase(); + const known = new Map(); + for (const tag of [...initial, ...existing]) + if (tag.trim() && !known.has(normalize(tag))) + known.set(normalize(tag), tag.trim()); + let selected = [...new Set(initial.map(normalize).filter(Boolean))].map( + (key) => known.get(key)!, + ); + let matches: string[] = [], + active = -1; + const hide = () => { + suggestions.hidden = true; + input.setAttribute("aria-expanded", "false"); + input.removeAttribute("aria-activedescendant"); + active = -1; + }; + const highlight = () => { + [...suggestions.children].forEach((option, index) => + option.setAttribute("aria-selected", String(index === active)), + ); + if (active >= 0) + input.setAttribute( + "aria-activedescendant", + suggestions.children[active].id, + ); + else input.removeAttribute("aria-activedescendant"); + if (active >= 0) suggestions.children[active].scrollIntoView({ block: "nearest" }); + }; + const add = (value: string) => { + const key = normalize(value); + if (key && !selected.some((tag) => normalize(tag) === key)) { + const tag = known.get(key) ?? value.trim(); + known.set(key, tag); + selected.push(tag); + renderChips(); + } + input.value = ""; + hide(); + }; + const suggest = () => { + const query = normalize(input.value); + matches = query + ? [...known.values()] + .filter( + (tag) => + normalize(tag).includes(query) && + !selected.some((value) => normalize(value) === normalize(tag)), + ) + .sort((a, b) => a.localeCompare(b)) + .slice(0, 8) + : []; + suggestions.replaceChildren(); + active = -1; + matches.forEach((tag, index) => { + const option = document.createElement("div"); + option.textContent = tag; + option.className = "rs-picker-row"; + option.id = suggestions.id + "-" + index; + option.setAttribute("role", "option"); + option.onpointerdown = (event) => event.preventDefault(); + option.onclick = () => { + add(tag); + input.focus(); + }; + suggestions.append(option); + }); + suggestions.hidden = matches.length === 0; + input.setAttribute("aria-expanded", String(!suggestions.hidden)); + highlight(); + }; + function renderChips() { + chips.replaceChildren(); + for (const tag of selected) { + const chip = document.createElement("span"); + chip.className = "pm-tag-chip"; + chip.setAttribute("role", "listitem"); + const text = document.createElement("span"); + text.textContent = tag; + const remove = document.createElement("button"); + remove.type = "button"; + remove.textContent = "×"; + remove.setAttribute("aria-label", "Remove tag " + tag); + remove.onclick = () => { + selected = selected.filter((value) => value !== tag); + renderChips(); + input.focus(); + suggest(); + }; + chip.append(text, remove); + chips.append(chip); + } + } + input.oninput = suggest; + input.onfocus = suggest; + input.onblur = hide; + input.onkeydown = (event) => { + if (event.isComposing || event.keyCode === 229) return; + if (event.key === "Enter") { + event.preventDefault(); + add(active >= 0 && !suggestions.hidden ? matches[active] : input.value); + } else if ( + (event.key === "ArrowDown" || event.key === "ArrowUp") && + matches.length + ) { + event.preventDefault(); + if (suggestions.hidden) suggest(); + if (!matches.length) return; + active = + event.key === "ArrowDown" + ? (active + 1) % matches.length + : (active <= 0 ? matches.length : active) - 1; + highlight(); + } else if (["Home", "End"].includes(event.key) && !suggestions.hidden && active >= 0) { + event.preventDefault(); active = event.key === "Home" ? 0 : matches.length - 1; highlight(); + } else if (event.key === "Escape" && !suggestions.hidden) { + event.preventDefault(); + event.stopPropagation(); + hide(); + } + }; + renderChips(); + return { + element, + value() { + add(input.value); + return [...selected]; + }, + clear() { + selected = []; + input.value = ""; + hide(); + renderChips(); + }, + }; +} diff --git a/src/lib/features/pm/ui/ui.ts b/src/lib/features/pm/ui/ui.ts new file mode 100644 index 0000000..f26d980 --- /dev/null +++ b/src/lib/features/pm/ui/ui.ts @@ -0,0 +1,3160 @@ +import { backgroundPositions, backgroundSizes, parseBackground, backgroundOverlay, type BackgroundAppearance } from "../model/background.ts"; +import { actionIcons, mountTooltips, tooltip, TOOLTIP, type ActionIcon, type ActionMenuItem, type MenuHost } from "./host.ts"; +import { watchBackground, type PMBackgroundApi } from "../model/transient-background.ts"; +import { mount as mountComponent, unmount as unmountComponent } from "svelte"; +import ProjectManagementSettings from "../../ProjectManagementSettings.svelte"; +import type { PriorityLevels } from "../model/model.ts"; +import type { LegacyContent } from "../storage/legacy.ts"; +import type { OriginalFile } from "../storage/catalog.ts"; +import { + addDays, + validDate, + cardColors, + dayDistance, + localDay, + localInstant, + localTime, + statuses, + statusNames, + priorityNames, + type Priority, + type Status, + type Task, + type TaskFields, +} from "../model/model.ts"; +import { imageReferences, imagePath, parseImage, imageTypes, maxImageBytes, saveImages, imageMarkdown } from "../storage/images.ts"; +import { createSharedChoices } from "./choices-ui.ts"; +import { createRelations } from "./relations-ui.ts"; +import { readCatalog, writeCatalog } from "../storage/catalog.ts"; +import { TaskStore } from "../model/store.ts"; +import { compareCards } from "../storage/order.ts"; +import { createTagInput } from "./tags.ts"; +import { createCardImages } from "./images-ui.ts"; +import { createDescriptionEditor } from "./description-ui.ts"; +import { DescriptionDraft } from "../storage/description-draft.ts"; +import { createDetailsPicker } from "./details-ui.ts"; +import { createPriorityPicker, setPriorityAppearance } from "./priority-ui.ts"; +import { createColorPalette } from "./colors.ts"; +import { + createLabelManager, + createLabelPicker, + labelBadge, +} from "./labels-ui.ts"; +import type { BoardList, BoardReference } from "../storage/board.ts"; +import { allTaskColumns, allTaskGroups, type TaskColumn } from "../model/all-tasks.ts"; +import { isManagedBoard } from "../storage/catalog.ts"; +import { isHiddenCard } from "../storage/persistence.ts"; +import { editTask } from "../storage/notes.ts"; +import { markdownPaths } from "../storage/scan.ts"; +import styles from "./style.css?inline"; + +/** The preferences of Settings → Project Management that the boards use. */ +export interface Preferences { + priorityLevels: PriorityLevels; +} + +type View = "kanban" | "gantt" | "calendar"; +const icons = { + limit: '', + warning: '', + scroll: '', + priority: '', + heading: actionIcons.heading, + bold: '', + italic: '', + list: '', + link: '', + code: '', + preview: '', + expand: '', + image: actionIcons.image, + close: '', + tag: '', + rename: '', + person: '', + clock: '', + kanban: actionIcons.kanban, + gantt: '', + calendar: + '', + plus: actionIcons.plus, + refresh: actionIcons.refresh, + left: '', + right: '', + more: '', + search: '', + grip: '', + up: actionIcons.up, + down: '', + circlePlus: '', + note: '', + check: '', + select: '', + archive: actionIcons.archive, + trash: actionIcons.trash, + download: '', + refresh2: actionIcons.refresh, +}; +function el( + tag: K, + text = "", + className = "", +): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + node.textContent = text; + node.className = className; + return node; +} +function button(text: string, action: () => void, icon?: keyof typeof icons) { + const node = el("button", "", "pm-button"); + node.type = "button"; + if (icon) { + node.dataset.icon = icon; + const span = el("span", "", "pm-icon"); + span.innerHTML = ``; + node.append(span); + } + node.append(document.createTextNode(text)); + node.onclick = action; + return node; +} +function applyTaskColor(node: HTMLElement, task: Task) { + if (!task.color) return; + node.style.setProperty( + "--pm-card-color", + cardColors[task.color as keyof typeof cardColors], + ); + node.classList.add("pm-colored-task"); +} +function iconButton( + label: string, + icon: keyof typeof icons, + action: () => void, +) { + const control = button("", action, icon); + control.classList.add("pm-icon-button"); + control.setAttribute("aria-label", label); + return tooltip(control, label); +} +const shortDate = (value: string) => + new Date(`${value}T12:00:00`).toLocaleDateString(undefined, { + month: "short", + day: "numeric", + }); + +export interface PMViewState { + view?: View; period?: "day" | "week" | "month"; anchor?: string; search?: string; + showArchived?: boolean; searchOpen?: boolean; + collapsedLists?: string[]; + boardScroll?: { left: number; top: number }; scrollTop?: number; +} + +export function parseViewState(value: unknown): PMViewState { + if (!value || typeof value !== "object" || Array.isArray(value)) return {}; + const raw = value as PMViewState, state: PMViewState = {}; + if (["kanban", "gantt", "calendar"].includes(raw.view!)) state.view = raw.view; + if (["day", "week", "month"].includes(raw.period!)) state.period = raw.period; + if (Array.isArray(raw.collapsedLists)) state.collapsedLists = raw.collapsedLists.filter((id): id is string => typeof id === "string").slice(0, 10000); + if (validDate(raw.anchor)) state.anchor = raw.anchor; + if (typeof raw.search === "string") state.search = raw.search.slice(0, 1000); + for (const key of ["searchOpen", "showArchived"] as const) if (typeof raw[key] === "boolean") state[key] = raw[key]; + if (typeof raw.scrollTop === "number" && Number.isFinite(raw.scrollTop)) state.scrollTop = Math.max(0, raw.scrollTop); + if (raw.boardScroll && Number.isFinite(raw.boardScroll.left) && Number.isFinite(raw.boardScroll.top)) state.boardScroll = { left: Math.max(0, raw.boardScroll.left), top: Math.max(0, raw.boardScroll.top) }; + return state; +} + +export function mountPM( + container: HTMLElement, + store: TaskStore, + options: { + /** The shared host menus. */ + ui: MenuHost; + backgrounds?: PMBackgroundApi; + state?: PMViewState; + stateChanged?: () => void; + preferences: Preferences; + savePreferences?: (value: Preferences) => Promise; + openBoard?: (path: string, replace?: boolean) => void | Promise; + openAll?: (replace?: boolean) => void | Promise; + renameBoard?: (document: BoardReference, name: string) => Promise; + boardRenamed?: (name: string) => void; + boardDeleted?: () => void | Promise; + /** Run `listener` after each workspace change, with the changed paths when they are known. */ + watch?: (listener: (paths?: readonly string[]) => void) => () => void; + /** Data in the legacy format: the boards offer its migration. */ + legacy?: { + find(): Promise; + has(content: LegacyContent): boolean; + migrate(): Promise; + }; + }, +): () => void { + const root = el("section", "", "rs-pm"); + const disposeTooltips = mountTooltips(root); + let boardMenu: { close(): void } | undefined; + const background = el("div", "", "pm-background"); background.setAttribute("aria-hidden", "true"); + const previousBackground = el("div", "", "pm-background-previous"); + background.append(previousBackground); + let backgroundUrl: string | undefined; + let backgroundFade: Animation | undefined; + const positionBackground = () => { + if (!root.isConnected) return; + const box = container.getBoundingClientRect(); + let top = Math.max(0, box.top + container.clientTop), bottom = Math.min(innerHeight, box.top + container.clientTop + container.clientHeight), left = Math.max(0, box.left + container.clientLeft), right = Math.min(innerWidth, box.left + container.clientLeft + container.clientWidth); + for (let node = container.parentElement; node; node = node.parentElement) { + const css = getComputedStyle(node), rect = node.getBoundingClientRect(); + if (/(auto|scroll|hidden|clip)/.test(css.overflowY)) { top = Math.max(top, rect.top + node.clientTop); bottom = Math.min(bottom, rect.top + node.clientTop + node.clientHeight); } + if (/(auto|scroll|hidden|clip)/.test(css.overflowX)) { left = Math.max(left, rect.left + node.clientLeft); right = Math.min(right, rect.left + node.clientLeft + node.clientWidth); } + } + Object.assign(background.style, { top: `${top}px`, left: `${left}px`, width: `${Math.max(0, right - left)}px`, height: `${Math.max(0, bottom - top)}px` }); + }; + const style = el("style"); + style.textContent = styles; + container.append(style, root); + const state = options.state ?? {}; + const collapsedLists = new Set(state.collapsedLists ?? []); + const pendingCollapsedLists = new Map(); + const preferences = options.preferences; + let view: View = state.view ?? "kanban", + period: "day" | "week" | "month" = state.period ?? "month", + anchor = state.anchor ?? localDay(), + search = state.search ?? "", + showArchived = state.showArchived ?? false, + searchOpen = state.searchOpen ?? false; + let selectionMode = false; + const selectedCards = new Set(); + let restoring = true; + let renderPending = false; + const remember = () => { + Object.assign(state, { view, period, anchor, search, showArchived, searchOpen }); + options.stateChanged?.(); + if (!root.getClientRects().length) return; + const board = root.querySelector(".pm-board"); + if (board) state.boardScroll = { left: board.scrollLeft, top: board.scrollTop }; + const scroller = scrollContainer(); + state.scrollTop = scroller.scrollTop; + }; + const scrollContainer = () => { + for (let node = root.parentElement; node; node = node.parentElement) + if (/(auto|scroll)/.test(getComputedStyle(node).overflowY)) return node; + return document.scrollingElement as HTMLElement; + }; + let closed = false, + busy = false, + message = "", + failed = false, + activeDialog: HTMLDialogElement | undefined; + let restoreFocus: HTMLElement | undefined; + let disposeEditor: (() => void) | undefined; + let closePopup: (() => void) | undefined; + let cardDraft: { listId: string | null; status: Status; title: string } | undefined; + const cardDrafts = new Map>(); + let drag: + | { + kind: "list" | "task"; + id: string; + source: HTMLElement; + preview: HTMLElement; + } + | undefined; + const clearDrag = () => { + drag?.source.classList.remove("pm-drag-source"); + drag?.preview.remove(); + drag = undefined; + root.classList.remove("pm-dragging"); + root + .querySelectorAll(".pm-drop-target") + .forEach((node) => node.classList.remove("pm-drop-target")); + root + .querySelectorAll(".pm-list-insertion,.pm-card-insertion") + .forEach((node) => { + node.hidden = true; + }); + }; + const movePreview = (event: DragEvent) => { + if (!drag) return; + const rect = drag.preview.getBoundingClientRect(); + drag.preview.style.left = + Math.max( + 8, + Math.min(event.clientX + 16, window.innerWidth - rect.width - 8), + ) + "px"; + drag.preview.style.top = + Math.max( + 8, + Math.min(event.clientY + 16, window.innerHeight - rect.height - 8), + ) + "px"; + }; + const beginDrag = ( + event: DragEvent, + kind: "list" | "task", + id: string, + source: HTMLElement, + name: string, + ) => { + if (!event.dataTransfer || busy) { + event.preventDefault(); + return; + } + clearDrag(); + closePopup?.(); + event.stopPropagation(); + event.dataTransfer.setData(`application/x-runestone-pm-${kind}`, id); + event.dataTransfer.effectAllowed = "move"; + const preview = el("div", "", "pm-drag-preview"); + preview.setAttribute("aria-hidden", "true"); + preview.inert = true; + preview.style.width = + Math.min(source.getBoundingClientRect().width, 340) + "px"; + const clone = source.cloneNode(true) as HTMLElement; + clone.removeAttribute("aria-label"); + for (const node of [clone, ...clone.querySelectorAll(`[${TOOLTIP}]`)]) node.removeAttribute(TOOLTIP); + const content = el("div", "", "pm-drag-preview-content"); + content.append(clone); + preview.append(el("div", "Move " + name, "pm-drag-preview-label"), content); + const blank = el("canvas"); + blank.width = blank.height = 1; + preview.append(blank); + root.append(preview); + event.dataTransfer.setDragImage(blank, 0, 0); + drag = { kind, id, source, preview }; + source.classList.add("pm-drag-source"); + root.classList.add("pm-dragging"); + movePreview(event); + }; + document.addEventListener("dragover", movePreview); + document.addEventListener("dragend", clearDrag); + document.addEventListener("drop", clearDrag); + function popup( + trigger: HTMLElement, + name: string, + fill: (panel: HTMLDivElement, close: () => void) => void | (() => void), + ) { + closePopup?.(); + const panel = el("div", "", "pm-popup"); + let disposePanel: (() => void) | undefined; + panel.setAttribute("role", "dialog"); + panel.setAttribute("aria-label", name); + const close = () => { + disposePanel?.(); + sharedChoices.close(); + panel.remove(); + document.removeEventListener("pointerdown", outside, true); + window.removeEventListener("keydown", key, true); + if (closePopup === close) closePopup = undefined; + if (trigger.isConnected) trigger.focus({ preventScroll: true }); + }; + const outside = (event: PointerEvent) => { + if ( + !busy && + !(event.target instanceof Element && event.target.closest(".rs-menu")) && + !panel.contains(event.target as Node) && + !trigger.contains(event.target as Node) + ) + close(); + }; + const key = (event: KeyboardEvent) => { + if (event.key === "Escape" && !busy && !(event.target instanceof Element && event.target.closest(".rs-menu"))) { + event.preventDefault(); + event.stopPropagation(); + close(); + } + }; + disposePanel = fill(panel, close) || undefined; + if (panel.classList.contains("pm-menu")) { + boardMenu?.close(); + trigger.focus({ preventScroll: true }); + const hostIcons: Record = { kanban: "kanban", up: "up", down: "down", rename: "rename", left: "arrow-left", right: "arrow-right", archive: "archive", trash: "trash", image: "image", list: "settings", circlePlus: "kanban", note: "file-plus", link: "link", refresh: "refresh" }; + const items: ActionMenuItem[] = []; + for (const child of panel.children) { + if (child instanceof HTMLButtonElement) items.push({ label: child.textContent ?? "", icon: hostIcons[child.dataset.icon ?? ""], disabled: child.disabled, run: () => child.click() }); + else if (child instanceof HTMLLabelElement) { + const select = child.querySelector("select"); + if (select) items.push({ label: child.firstChild?.textContent ?? "Choose", icon: "kanban", children: Array.from(select.options).map(option => ({ label: option.textContent ?? "", checked: option.selected, radio: true, disabled: option.disabled, + run: () => { select.value = option.value; select.dispatchEvent(new Event("change")); } })) }); + } + } + const bounds = trigger.getBoundingClientRect(); + boardMenu = options.ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: name, items }); + return; + } + for (const select of panel.querySelectorAll("select:not([hidden])")) sharedChoice(select); + panel.setAttribute("popover", "manual"); + root.append(panel); + panel.showPopover(); + const anchor = trigger.getBoundingClientRect(), + bounds = panel.getBoundingClientRect(); + panel.style.left = + Math.max( + 8, + Math.min( + anchor.right - bounds.width, + window.innerWidth - bounds.width - 8, + ), + ) + "px"; + panel.style.top = + Math.max( + 8, + Math.min(anchor.bottom + 6, window.innerHeight - bounds.height - 8), + ) + "px"; + document.addEventListener("pointerdown", outside, true); + window.addEventListener("keydown", key, true); + closePopup = close; + panel.querySelector("input:not([hidden]):not(:disabled),button:not([hidden]):not(:disabled),select:not([hidden]):not(:disabled)")?.focus(); + } + root.classList.add("pm-shared-menus"); + const sharedChoices = createSharedChoices(root, options.ui); + const sharedChoice = sharedChoices.use; + const imageCache = new Map>(); + const loadImage = (id: string) => { + if (!imageCache.has(id)) imageCache.set(id, store.workspace.read(imagePath(id)).then(parseImage)); + return imageCache.get(id)!; + }; + const backgroundWatcher = watchBackground( + store.board.reference ? `pm-board:${store.board.reference.id}` : "pm-all", + options.backgrounds, + async () => { + const saved = store.board.reference ? store.board.value : (await readCatalog(store.workspace)).value; + const id = saved.backgroundImage; + const appearance = parseBackground(saved.backgroundAppearance); + const data = typeof id === "string" ? await loadImage(id) : ""; + return data ? { ...appearance, url: data } : null; + }, + frame => { + const appearance = parseBackground(frame); + const fade = !!backgroundUrl && backgroundUrl !== frame?.url && !!frame?.previous && !!frame.transitionMs && !matchMedia("(prefers-reduced-motion: reduce)").matches; + backgroundFade?.cancel(); + previousBackground.style.backgroundImage = fade ? `${backgroundOverlay(frame!.previous!.overlay)}, url(${JSON.stringify(frame!.previous!.url)})${frame?.previous?.blurredUrl ? `, url(${JSON.stringify(frame.previous.blurredUrl)})` : ""}` : "none"; + previousBackground.style.backgroundPosition = frame?.previous?.blurredUrl ? `center, ${frame.previous.position}, center` : frame?.previous?.position ?? "center"; + previousBackground.style.backgroundSize = `100% 100%, ${frame?.previous?.size ?? "cover"}${frame?.previous?.blurredUrl ? ", cover" : ""}`; + previousBackground.hidden = !fade; + background.style.backgroundImage = frame ? `${backgroundOverlay(appearance.overlay)}, url(${JSON.stringify(frame.url)})${frame.blurredUrl ? `, url(${JSON.stringify(frame.blurredUrl)})` : ""}` : "none"; + background.style.backgroundPosition = frame?.blurredUrl ? `center, ${appearance.position}, center` : appearance.position; + background.style.backgroundSize = `100% 100%, ${appearance.size}${frame?.blurredUrl ? ", cover" : ""}`; + background.style.backgroundRepeat = "no-repeat"; + backgroundUrl = frame?.url; + if (fade) { + backgroundFade = previousBackground.animate([{ opacity: 1 }, { opacity: 0 }], { duration: frame!.transitionMs, fill: "forwards" }); + backgroundFade.onfinish = () => { previousBackground.hidden = true; }; + } + root.classList.toggle("pm-has-background", !!frame); + positionBackground(); + }, + ); + const applyBackground = backgroundWatcher.refresh; + function customizeBackground(trigger: HTMLElement) { + popup(trigger, "Customize background", (panel, close) => { + panel.append(el("h3", "Customize background"), el("p", "Choose a PNG, JPEG, GIF, or WebP image up to 50 MiB.", "pm-muted")); + const file = el("input"); file.type = "file"; file.accept = imageTypes.join(","); file.setAttribute("aria-label", "Background image"); + const saveBackground = async (id: string | null) => { + if (store.board.reference) await store.changeBoard(() => store.board.update(board => { board.backgroundImage = id; })); + else { const catalog = await readCatalog(store.workspace); catalog.value.backgroundImage = id; await writeCatalog(store.workspace, catalog.value, catalog.source); } + }; + file.onchange = () => { + const image = file.files?.[0]; if (!image) return; + void perform(async () => { + if (!imageTypes.includes(image.type) || image.size > maxImageBytes) throw new Error("Choose a supported image no larger than 50 MiB."); + const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result)); reader.onerror = () => reject(new Error("Cannot read this image.")); reader.readAsDataURL(image); }); + const id = crypto.randomUUID(); + await saveImages(store.workspace, imageMarkdown(image.name, id), new Map([[id, data]])); + await saveBackground(id); close(); + }, "Background saved."); + }; + const saveAppearance = async (appearance: BackgroundAppearance) => { + if (store.board.reference) await store.changeBoard(() => store.board.update(board => { board.backgroundAppearance = appearance; })); + else { const catalog = await readCatalog(store.workspace); catalog.value.backgroundAppearance = appearance; await writeCatalog(store.workspace, catalog.value, catalog.source); } + await applyBackground(); + }; + const controls = el("div"); + void (async () => { + await Promise.resolve(); + const saved = store.board.reference ? store.board.value : (await readCatalog(store.workspace)).value; + let appearance = parseBackground(saved.backgroundAppearance); + if (!panel.isConnected) return; + controls.classList.add("pm-background-settings"); + const error = el("p", "", "pm-error"); error.setAttribute("role", "alert"); + let saveQueue = Promise.resolve(); + const save = async (next: BackgroundAppearance) => { appearance = next; error.textContent = ""; try { saveQueue = saveQueue.catch(() => {}).then(() => saveAppearance(next)); await saveQueue; } catch (reason) { error.textContent = reason instanceof Error ? reason.message : String(reason); } }; + const positionRow = el("label", "Image position", "pm-background-row"), position = el("select"); position.setAttribute("aria-label", "Image position"); + const positionLabels = ["Center", "Top left", "Top center", "Top right", "Center left", "Center right", "Bottom left", "Bottom center", "Bottom right"]; + for (const [index, value] of backgroundPositions.entries()) { const option = el("option", positionLabels[index]); option.value = value; position.append(option); } + position.value = appearance.position; position.onchange = () => { void save({ ...appearance, position: position.value as BackgroundAppearance["position"] }); }; + positionRow.append(position); controls.append(positionRow); sharedChoice(position); + const sizeRow = el("label", "Image size", "pm-background-row"), size = el("select"); size.setAttribute("aria-label", "Image size"); + for (const [index, value] of backgroundSizes.entries()) { const option = el("option", ["Fill", "Fit", "Actual size"][index]); option.value = value; size.append(option); } + size.value = appearance.size; size.onchange = () => { void save({ ...appearance, size: size.value as BackgroundAppearance["size"] }); }; + sizeRow.append(size); controls.append(sizeRow); sharedChoice(size); + const overlay = el("input"); overlay.type = "range"; overlay.min = "-100"; overlay.max = "100"; overlay.step = "1"; overlay.value = String(Math.round(appearance.overlay * 100)); overlay.setAttribute("aria-label", "Image overlay"); + const percent = el("input"); percent.type = "number"; percent.min = "-100"; percent.max = "100"; percent.step = "1"; percent.value = overlay.value; percent.setAttribute("aria-label", "Image overlay percentage"); + const changeOverlay = (input: HTMLInputElement) => { + if (!Number.isFinite(input.valueAsNumber)) return; + const value = Math.round(Math.max(-100, Math.min(100, input.valueAsNumber))); + overlay.value = String(value); + if (input === overlay) percent.value = overlay.value; + void save({ ...appearance, overlay: value / 100 }); + }; + overlay.oninput = () => changeOverlay(overlay); percent.oninput = () => changeOverlay(percent); + percent.onblur = () => { percent.value = String(Math.round(appearance.overlay * 100)); }; + const overlayRow = el("div", "", "pm-background-row"), overlayControls = el("div", "", "pm-overlay-controls"), percentLabel = el("label", "", "pm-overlay-value"); + percentLabel.append(percent, el("span", "%")); overlayControls.append(overlay, percentLabel); + overlayRow.append(el("span", "Image overlay"), overlayControls); controls.append(overlayRow, el("p", "Move left to lighten the image or right to darken it.", "pm-muted")); + controls.append(error); + })().catch(reason => { controls.textContent = String(reason); }); + panel.append(file, controls, button("Remove background", () => { void perform(async () => { await saveBackground(null); close(); }, "Background removed."); }, "trash")); + }); + } + root.addEventListener("contextmenu", event => { + const target = event.target as HTMLElement; + if (target.closest(".pm-card,button,input,textarea,select,dialog,.pm-popup,.pm-toolbar")) return; + event.preventDefault(); + const anchor = el("span"); anchor.style.cssText = `position:fixed;left:${event.clientX}px;top:${event.clientY}px;width:1px;height:1px`; + root.append(anchor); + popup(anchor, "Background actions", (panel, close) => { panel.classList.add("pm-menu"); panel.append(button("Customize background", () => { close(); customizeBackground(root.querySelector(".pm-toolbar")!); }, "image")); }); + anchor.remove(); + }); + function renameBoardForm(trigger: HTMLElement, create = false) { + const action = create ? "Create board" : "Rename board"; + popup(trigger, action, (panel, close) => { + const form = el("form"), + label = el("label", "Board name", "pm-field"), + name = el("input"), + error = el("p", "", "pm-error"), + actions = el("div", "", "pm-popup-actions"), + save = button(action, () => {}); + name.value = create ? "" : store.board.name; + name.required = true; + label.append(name); + error.role = "alert"; + save.type = "submit"; + save.classList.add("pm-primary"); + actions.append( + save, + button("Cancel", () => { + if (!busy) close(); + }), + ); + form.append(label, error, actions); + panel.append(form); + name.select(); + form.onsubmit = async (event) => { + event.preventDefault(); + if (busy) return; + save.disabled = true; + const ok = await perform( + async () => { + if (create) { + const reference = await store.createBoard(name.value); + close(); + await options.openBoard?.(reference.path); + } else { + await store.renameBoard(name.value, options.renameBoard); + options.boardRenamed?.(store.board.name); + } + }, + create ? "Board created." : "Board renamed.", + ); + save.disabled = false; + if (ok) { + close(); + render(); + if (!create) + root.querySelector( + trigger.classList.contains("pm-board-rename") + ? ".pm-board-rename" + : '[aria-label="More actions"]', + )?.focus({ preventScroll: true }); + } else error.textContent = message; + }; + }); + } + function deleteBoardForm(trigger: HTMLElement) { + if (activeDialog || busy) return; + closePopup?.(); + const dialog = el("dialog", "", "pm-editor"), + error = el("p", "", "pm-error"), + actions = el("div", "", "pm-editor-actions"), + cancel = button("Cancel", () => { if (!busy) dialog.close(); }), + remove = button("Delete board", () => { void removeBoard(); }, "trash"); + activeDialog = dialog; + dialog.setAttribute("aria-label", "Delete board"); + const description = el("p", "Cards stay in All tasks. Notes, backups, and memberships on other boards stay unchanged. This action has no undo."); + description.id = "pm-delete-board-description"; + dialog.setAttribute("aria-describedby", description.id); + error.role = "alert"; + actions.append(cancel, remove); + dialog.append(el("h2", `Delete “${store.board.name}”?`), description, + el("p", "Original board files stay on disk, but Project Management no longer lists this board."), error, actions); + root.append(dialog); + dialog.oncancel = (event) => { if (busy) event.preventDefault(); }; + dialog.onclose = () => { + activeDialog = undefined; + dialog.remove(); + render(); + if (trigger.isConnected) trigger.focus({ preventScroll: true }); + else root.querySelector('[aria-label="More actions"]')?.focus({ preventScroll: true }); + }; + dialog.showModal(); + cancel.focus(); + async function removeBoard() { + if (busy) return; + remove.disabled = cancel.disabled = true; + const ok = await perform( + () => store.changeBoard(() => store.board.deleteBoard()), + "Board deleted. Cards remain in All tasks.", + ); + remove.disabled = cancel.disabled = false; + if (!ok) { error.textContent = message; return; } + dialog.close(); + await perform(async () => { + await options.openAll?.(true); + await options.boardDeleted?.(); + }, "Board deleted. Cards remain in All tasks."); + } + } + function deleteCardForm(task: Task, trigger: HTMLElement) { + if (activeDialog || busy) return; + closePopup?.(); + const dialog = el("dialog", "", "pm-editor"), + error = el("p", "", "pm-error"), + actions = el("div", "", "pm-editor-actions"), + cancel = button("Cancel", () => { if (!busy) dialog.close(); }), + remove = button("Delete card", () => { void removeCard(); }, "trash"); + activeDialog = dialog; + dialog.setAttribute("aria-label", "Delete card"); + const description = el("p", "This removes the card from all boards, All tasks, and the archive. This action has no undo."); + description.id = `pm-delete-card-${crypto.randomUUID()}`; + dialog.setAttribute("aria-describedby", description.id); + error.role = "alert"; + actions.append(cancel, remove); + dialog.append(el("h2", `Delete “${task.title}”?`), description, + el("p", "Stored notes and images remain on disk for recovery. Linked cards and subtasks remain separate cards."), error, actions); + root.append(dialog); + dialog.oncancel = event => { if (busy) event.preventDefault(); }; + dialog.onclose = () => { + activeDialog = undefined; + dialog.remove(); + render(); + const card = Array.from(root.querySelectorAll(".pm-card-menu")).find(item => item.getAttribute("aria-label") === trigger.getAttribute("aria-label")); + (card ?? root.querySelector('[aria-label="More actions"]'))?.focus({ preventScroll: true }); + }; + dialog.showModal(); + cancel.focus(); + async function removeCard() { + if (busy) return; + remove.disabled = cancel.disabled = true; + const ok = await perform(() => store.deleteCard(task), "Card deleted."); + remove.disabled = cancel.disabled = false; + if (!ok) { error.textContent = message; return; } + dialog.close(); + } + } + function listForm(trigger: HTMLElement, list?: BoardList) { + popup(trigger, list ? "Edit list" : "Add list", (panel, close) => { + const form = el("form"), + name = el("input"); + name.setAttribute("aria-label", "List name"); + name.placeholder = "List name"; + name.required = true; + name.maxLength = 80; + name.value = list?.name ?? ""; + const label = el( + "label", + "Status when a card enters this list", + "pm-field", + ), + status = el("select"); + status.setAttribute("aria-label", "Status on move"); + const unchanged = el("option", "Do not change status"); + unchanged.value = ""; + status.append(unchanged); + for (const value of statuses) { + const option = el("option", statusNames[value]); + option.value = value; + status.append(option); + } + status.value = list?.status ?? ""; + label.append(status); + const error = el("p", "", "pm-error"); + error.role = "alert"; + const add = button(list ? "Save list" : "Add list", () => {}); + add.type = "submit"; + add.classList.add("pm-primary"); + const actions = el("div", "", "pm-popup-actions"); + actions.append( + add, + button("Cancel", () => { + if (!busy) close(); + }), + ); + form.append(name, label, error, actions); + panel.append(form); + sharedChoice(status); + form.onsubmit = async (event) => { + event.preventDefault(); + if (busy) return; + add.disabled = true; + const ok = await perform( + () => + store.changeBoard(() => + list + ? store.board.edit( + list.id, + name.value, + (status.value || null) as Status | null, + ) + : store.board.add( + name.value, + (status.value || null) as Status | null, + ), + ), + list ? "List saved." : "List added.", + ); + add.disabled = false; + if (ok) { + close(); + render(); + } else error.textContent = message; + }; + }); + } + function listLimitForm(trigger: HTMLElement, list: BoardList) { + popup(trigger, "Set list limit", (panel, close) => { + const form = el("form"); + const field = el("label", "Maximum cards", "pm-field"); + const maximum = el("input"); + maximum.type = "number"; + maximum.min = "1"; + maximum.max = String(Number.MAX_SAFE_INTEGER); + maximum.step = "1"; + maximum.placeholder = "No limit"; + maximum.value = list.maxCards === undefined ? "" : String(list.maxCards); + field.append(maximum); + const hint = el("p", "Leave blank for no limit. A warning appears at the maximum. Cards can still enter this list."); + const error = el("p", "", "pm-error"); + error.role = "alert"; + const save = button("Save limit", () => {}, "check"); + save.type = "submit"; + save.classList.add("pm-primary"); + const actions = el("div", "", "pm-popup-actions"); + actions.append(button("Cancel", () => { if (!busy) close(); }), save); + form.append(field, hint, error, actions); + panel.append(form); + form.onsubmit = async event => { + event.preventDefault(); + if (busy) return; + save.disabled = true; + const ok = await perform(() => store.changeBoard(() => store.board.setLimit(list.id, maximum.value === "" ? undefined : Number(maximum.value))), "List limit saved."); + save.disabled = false; + if (ok) { close(); render(); } + else error.textContent = message; + }; + }); + } + function listMenu(trigger: HTMLElement, list: BoardList) { + const fill = (panel: HTMLDivElement, close: () => void) => { + panel.classList.add("pm-menu"); + panel.append( + button("Edit list", () => { + close(); + listForm(trigger, list); + }, "rename"), + button("Set list limit", () => { + close(); + listLimitForm(trigger, list); + }, "limit"), + ); + const index = store.board.value.lists.findIndex( + (item) => item.id === list.id, + ); + for (const [label, delta] of [ + ["Move left", -1], + ["Move right", 1], + ] as const) { + const move = button(label, () => { + close(); + void perform( + () => + store.changeBoard(() => store.board.move(list.id, index + delta)), + "List moved.", + ); + }, delta < 0 ? "left" : "right"); + move.disabled = + index + delta < 0 || index + delta >= store.board.value.lists.length; + panel.append(move); + } + const archive = button("Archive all cards", () => { + close(); + void perform(() => store.archiveList(list.id), "Cards archived."); + }, "archive"); + archive.disabled = !store.cardsInList(list.id).length; + panel.append(archive); + panel.append( + button("Delete list", () => { + close(); + popup(trigger, "Delete list", (confirmation, done) => { + const count = store.tasks.filter( + (task) => store.board.listFor(task)?.id === list.id, + ).length; + confirmation.append( + el("strong", "Delete “" + list.name + "”?"), + el( + "p", + count + ? count + + " cards will move to Unlisted. Their notes and status will stay unchanged." + : "This removes the empty list.", + ), + ); + const error = el("p", "", "pm-error"); + error.role = "alert"; + const actions = el("div", "", "pm-popup-actions"); + actions.append( + button("Cancel", () => { + if (!busy) done(); + }), + button("Delete list", async () => { + const ok = await perform( + () => store.changeBoard(() => store.board.remove(list.id)), + "List deleted. Task notes were kept.", + ); + if (ok) { + done(); + render(); + } else error.textContent = message; + }), + ); + confirmation.append(error, actions); + }); + }, "trash"), + ); + }; + closePopup?.(); + boardMenu?.close(); + trigger.focus({ preventScroll: true }); + const panel = el("div"); + fill(panel, () => { boardMenu?.close(); boardMenu = undefined; }); + const bounds = trigger.getBoundingClientRect(); + const hostIcons = { limit: "settings", kanban: "kanban", up: "up", down: "down", rename: "rename", left: "arrow-left", right: "arrow-right", archive: "archive", trash: "trash" } as const; + boardMenu = options.ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: "List actions", items: Array.from(panel.querySelectorAll(":scope > button")).map(control => ({ + label: control.textContent ?? "", icon: hostIcons[control.dataset.icon as keyof typeof hostIcons], disabled: control.disabled, run: () => control.click(), + })) }); + } + const notify = (text: string, error = false) => { + message = text; + failed = error; + }; + async function perform( + action: () => Promise, + success: string, + ): Promise { + if (busy || closed) return false; + busy = true; + root.setAttribute("aria-busy", "true"); + try { + await action(); + if (!closed) notify(success); + return true; + } catch (error) { + if (!closed) + notify(error instanceof Error ? error.message : String(error), true); + return false; + } finally { + busy = false; + if (!closed) { + root.removeAttribute("aria-busy"); + if (!activeDialog && !closePopup) render(); + } + } + } + const filtered = () => + store.scopedTasks.filter( + (task) => + task.archived === showArchived && + `${task.title} ${task.body} ${task.tags.join(" ")} ${(task.labels ?? []).map((id) => store.labels.value.find((label) => label.id === id)?.name ?? "").join(" ")} ${(task.assignees ?? []).join(" ")} ${(task.customFields ?? []).map((field) => `${field.name} ${field.value}`).join(" ")}` + .toLocaleLowerCase() + .includes(search.toLocaleLowerCase()), + ); + function manageLabels(updated?: () => void) { + if (busy || store.labels.source === undefined) return; + closePopup?.(); + const parent = activeDialog; + const focus = document.activeElement as HTMLElement | null; + const dialog = createLabelManager( + store.labels, + async (labels, expected) => { + const ok = await perform( + () => store.saveLabels(labels, expected), + "Labels saved.", + ); + if (!ok) throw new Error(message); + }, + () => { + activeDialog = parent; + if (closed) return; + render(); + if (focus?.isConnected) focus.focus({ preventScroll: true }); + else + root + .querySelector('[aria-label="Manage labels"]') + ?.focus({ preventScroll: true }); + updated?.(); + }, + ); + activeDialog = dialog; + root.append(dialog); + dialog.showModal(); + } + function openEditor(task?: Task, initial: Partial = {}) { + if (activeDialog || busy) return; + closePopup?.(); + restoreFocus = + document.activeElement instanceof HTMLElement + ? document.activeElement + : undefined; + const restoreTaskId = restoreFocus?.closest(".pm-card")?.dataset.taskId; + const dialog = el("dialog", "", "pm-editor pm-card-editor"); + activeDialog = dialog; + const form = el("form"); + form.method = "dialog"; + const heading = el("h2", task ? task.title : "New card"); + heading.id = "pm-editor-title"; + dialog.setAttribute("aria-labelledby", heading.id); + const intro = el( + "p", + task + ? isHiddenCard(task.path) + ? "Private workspace card" + : `Linked note: ${task.path}` + : "Creates a private workspace card.", + "pm-muted", + ); + heading.classList.add("pm-visually-hidden"); + intro.classList.add("pm-card-context"); + form.append(heading, intro); + const grid = el("div", "", "pm-form-grid"); + form.append(grid); + const field = ( + label: string, + type: string, + value: string, + wide = false, + ) => { + const wrap = el("label", label, wide ? "pm-field pm-wide" : "pm-field"); + const input = el("input"); + input.type = type; + input.value = value; + wrap.append(input); + grid.append(wrap); + return input; + }; + const title = field("Title", "text", task?.title ?? "", true); + title.parentElement!.classList.add("pm-editor-card-title"); + title.placeholder = "Card title"; + title.required = true; + title.maxLength = 100; + const values: TaskFields = task ?? { + status: "todo", + listId: store.board.value.defaults.todo, + tags: [], + archived: false, + sessions: [], + ...initial, + }; + const statusWrap = el("label", "Status", "pm-field pm-wide"), + status = el("select"); + status.setAttribute("aria-label", "Status"); + statuses.forEach((value) => { + const option = el("option", statusNames[value]); + option.value = value; + status.append(option); + }); + status.value = values.status; + statusWrap.append(status); + grid.append(statusWrap); + const listWrap = el("label", "List", "pm-field pm-wide"), + listSelect = el("select"); + const activeBoards = store.boards.filter(board => !board.archived); + let originalBoardId = store.board.reference?.id ?? + (task ? activeBoards.find(board => Object.hasOwn(task?.placements ?? {}, board.id))?.id : undefined) ?? ""; + const editorBoard = activeBoards.find(board => board.id === originalBoardId)?.value ?? store.board.value; + listSelect.setAttribute("aria-label", "List"); + const unlisted = el("option", "Unlisted"); + unlisted.value = ""; + listSelect.append(unlisted); + for (const list of editorBoard.lists) { + const option = el("option", list.name); + option.value = list.id; + listSelect.append(option); + } + let originalListId = originalBoardId && task + ? task.placements?.[originalBoardId]?.listId ?? "" + : store.board.listFor(values)?.id ?? ""; + listSelect.value = originalListId; + if (listSelect.selectedIndex < 0) listSelect.value = ""; + listWrap.append(listSelect); + grid.append(listWrap); + const due = field("Deadline", "date", values.due?.date ?? ""); + const start = field("Planned start", "date", values.plan?.start ?? ""); + const end = field( + "Planned last day", + "date", + values.plan ? addDays(values.plan.end, -1) : "", + ); + const tags = createTagInput( + values.tags, + store.tasks.flatMap((task) => task.tags), + ); + const first = values.sessions[0]; + const sessionStart = field( + "Work session start", + "datetime-local", + first ? localTime(first.start) : "", + ); + const sessionEnd = field( + "Work session end", + "datetime-local", + first ? localTime(first.end) : "", + ); + const sessionHint = el( + "p", + `Session times use ${Intl.DateTimeFormat().resolvedOptions().timeZone}. This editor changes the first session only.`, + "pm-muted pm-wide", + ); + const description = el("textarea"); + description.rows = 3; + description.spellcheck = true; + description.value = task?.body ?? ""; + const labels = createLabelPicker(store.labels, values.labels ?? [], () => + manageLabels(() => { + if (task) { + const current = store.tasks.find((current) => current.id === task!.id); + if (current && current.source === editTask(task, { labels: current.labels })) task = current; + } + labels.refresh(); + labels.open(); + }), + true, + ); + const images = createCardImages( + store.workspace, + description, + (name, action) => button(name, action, name === "Actual size" ? "expand" : "image"), + (name, action) => iconButton(name, "close", action), + (loading) => { save.disabled = loading || busy || !title.value.trim(); descriptionEditor.updateLoading(); }, + task?.attachments, + ); + const formattingIcons: Record = { + Heading: "heading", Bold: "bold", Italic: "italic", "Bullet list": "list", Link: "link", Code: "code", + Preview: "preview", Save: "check", Cancel: "close", + }; + const draft = task ? new DescriptionDraft(store.workspace, task.id) : undefined; + let descriptionSaving = false; + let draftTimer: ReturnType | undefined; + let draftEdited = false; + const draftReady = draft?.load().then(body => { + if (body !== null && !draftEdited && dialog.isConnected) { + descriptionEditor.restoreDraft(body); + updateDescriptionBadge(task!.id, body !== task!.body); + } + }); + const flushDraft = async () => { + clearTimeout(draftTimer); + await draftReady; + if (!draft || !task) return; + await images.save(description.value); + await draft.save(description.value === task.body ? null : description.value); + }; + const reportDraftError = (reason: unknown) => { error.textContent = reason instanceof Error ? reason.message : String(reason); }; + void draftReady?.catch(reportDraftError); + const descriptionEditor = createDescriptionEditor(description, images, + (name, action) => button(name, action, name === "Edit" ? "rename" : formattingIcons[name]), task ? { + async save() { + if (busy) throw new Error("Wait for the card to finish saving."); + descriptionSaving = true; + const body = description.value; + description.readOnly = true; + for (const control of [boardSelect, listSelect, status, save, cancel, closeEditor]) control.disabled = true; + clearTimeout(draftTimer); + try { + await draftReady; + await placementQueue; + await images.save(body); + await store.save(task!, { body, attachments: images.value() }); + task = store.tasks.find(item => item.id === task!.id)!; + await draft!.save(null); + updateDescriptionBadge(task!.id, false); + error.textContent = ""; + } catch (reason) { reportDraftError(reason); throw reason; } + finally { + descriptionSaving = false; description.readOnly = false; + for (const control of [boardSelect, listSelect, status, cancel, closeEditor]) control.disabled = false; + save.disabled = !title.value.trim() || images.isLoading(); + } + }, + async cancel() { + clearTimeout(draftTimer); + try { await draftReady; await draft!.save(null); updateDescriptionBadge(task!.id, false); error.textContent = ""; return task!.body; } + catch (reason) { reportDraftError(reason); throw reason; } + }, + } : undefined); + description.addEventListener("input", () => { + draftEdited = true; + if (task) updateDescriptionBadge(task.id, description.value !== task.body); + clearTimeout(draftTimer); + if (draft && !images.isLoading()) draftTimer = setTimeout(() => { void flushDraft().catch(reportDraftError); }, 300); + }); + const useSharedChoices = sharedChoice; + const updateChoice = sharedChoices.update; + const header = el("div", "", "pm-card-editor-header"); + const closeEditor = iconButton("Close card", "close", () => { + if (!busy) requestClose(); + }); + listWrap.hidden = !originalBoardId; + statusWrap.hidden = !!originalBoardId; + header.append(listWrap); + if (!store.board.reference) header.append(statusWrap); + const boardSelect = el("select"); boardSelect.setAttribute("aria-label", "Board"); + const needsBoard = !task && !store.board.reference; + if (task || needsBoard) { + const boardWrap = el("label", "Board", "pm-field"); + if (!originalBoardId) { const none = el("option", needsBoard ? "Choose a board" : "No active board"); none.value = ""; boardSelect.append(none); } + for (const board of activeBoards) { const option = el("option", board.name); option.value = board.id; boardSelect.append(option); } + boardSelect.value = originalBoardId; + boardSelect.onchange = () => { + const board = store.boards.find(item => item.id === boardSelect.value); + listSelect.replaceChildren(el("option", "Unlisted")); listSelect.options[0].value = ""; + for (const list of (board?.value ?? store.board.value).lists) { const option = el("option", list.name); option.value = list.id; listSelect.append(option); } + const placement = task?.placements?.[boardSelect.value]; + const matchingList = needsBoard ? board?.value.lists.find(list => `list:${list.name.trim().toLowerCase()}` === initial.listId) : undefined; + listSelect.value = placement ? placement.listId ?? "" : matchingList?.id ?? board?.value.defaults[values.status] ?? ""; + if (listSelect.selectedIndex < 0) listSelect.value = ""; + listWrap.hidden = !boardSelect.value; statusWrap.hidden = !!boardSelect.value; + updateChoice(listSelect); + error.textContent = ""; + }; + boardWrap.append(boardSelect); header.prepend(boardWrap); + } + header.append(closeEditor); + for (const select of [status, listSelect, boardSelect]) if (select.isConnected || select.parentElement) useSharedChoices(select); + form.insertBefore(header, heading); + let relatedTarget: { taskId?: string; subtaskId?: string } | undefined; + let nextCard: Task | undefined; + const relations = createRelations(task, store.tasks, (name, action) => button(name, action, "plus"), (name, action) => iconButton(name, "trash", action), store.boards, target => { + if (busy || images.isLoading()) return; + relatedTarget = target; + form.requestSubmit(save); + }, useSharedChoices); + grid.replaceChildren(title.parentElement!, labels.element, descriptionEditor.element); + const optional = el("div", "", "pm-optional-fields pm-wide"); + const choices = el("div", "", "pm-field-choices pm-wide"); + choices.setAttribute("role", "group"); + choices.setAttribute("aria-label", "Card details"); + const addDetails = button("Add details", () => {}, "plus"); + const details = createDetailsPicker(addDetails); + choices.append(addDetails, labels.trigger, details.element); + details.add(button("Subtasks and linked cards", () => { relations.element.hidden = false; relations.focus(); }, "link"), "Track smaller tasks and card dependencies."); + relations.element.hidden = !(task?.links?.length || task?.subtasks?.length || (task && store.tasks.some(item => item.links?.some(link => link.taskId === task?.id) || item.subtasks?.some(subtask => subtask.taskId === task?.id)))); + grid.append(images.attachmentsElement, relations.element); + const coverWrap = el("label", "Card cover", "pm-field pm-wide"); + const cover = el("select"); cover.setAttribute("aria-label", "Card cover"); + let coverInitialized = false; + const drawCovers = () => { + const selected = coverInitialized ? cover.value : task?.coverImage || ""; + coverInitialized = true; + cover.replaceChildren(el("option", "No cover")); cover.options[0].value = ""; + for (const ref of images.references()) { const option = el("option", ref.name); option.value = ref.id; cover.append(option); } + cover.value = [...cover.options].some(item => item.value === selected) ? selected : ""; + }; + drawCovers(); description.addEventListener("input", drawCovers); coverWrap.append(cover); + const coverChoice = useSharedChoices(cover); + coverWrap.hidden = !task?.coverImage; grid.append(coverWrap); + details.add(button("Card cover", () => { drawCovers(); coverWrap.hidden = false; coverChoice.focus(); }, "image"), "Choose an image from this card."); + details.add(button("Labels", () => labels.open(), "tag"), "Organize cards with saved labels."); + disposeEditor = () => { clearTimeout(draftTimer); sharedChoices.close(); descriptionEditor.dispose(); details.dispose(); priority.dispose(); labels.dispose(); images.dispose(); }; + const group = ( + name: string, + icon: keyof typeof icons, + nodes: HTMLElement[], + visible: boolean, + clear?: () => void, + ) => { + const section = el("section", "", "pm-optional-group"); + section.setAttribute("aria-label", name + " fields"); + const header = el("div", "", "pm-optional-heading"); + const content = el("div", "", "pm-optional-content"); + content.append(...nodes); + const show = () => { + section.hidden = false; + section.querySelector("input,select,textarea")?.focus(); + }; + const choice = button( + name, + show, + icon, + ); + const remove = iconButton( + (clear ? "Remove " : "Hide ") + name, + "close", + () => { + clear?.(); + section.hidden = true; + (quickChoice ?? addDetails).focus(); + }, + ); + header.append(el("h3", name), remove); + section.append(header, content); + section.hidden = !visible; + const quickChoice = ["Deadline", "Assignments", "Priority"].includes(name) ? button(name, show, icon) : undefined; + if (quickChoice) choices.append(quickChoice); + details.add(choice, name === "Priority" ? "Set urgency without changing labels." : `Add or edit ${name.toLocaleLowerCase()}.`); + optional.append(section); + }; + group("Deadline", "calendar", [due.parentElement!], !!values.due, () => { + due.value = ""; + }); + group( + "Planned dates", + "gantt", + [start.parentElement!, end.parentElement!], + !!values.plan, + () => { + start.value = end.value = ""; + }, + ); + group("Tags", "tag", [tags.element], !!values.tags.length, tags.clear); + group( + "Work session", + "clock", + [sessionStart.parentElement!, sessionEnd.parentElement!, sessionHint], + !!first, + () => { + sessionStart.value = sessionEnd.value = ""; + }, + ); + const color = createColorPalette( + "Card color", + values.color ?? "", + () => updateColor(), + true, + ); + const colorSample = el("div", "Card preview", "pm-color-sample pm-wide"); + const updateColor = () => { + colorSample.style.setProperty( + "--pm-card-color", + cardColors[color.value() as keyof typeof cardColors] ?? "transparent", + ); + }; + updateColor(); + group("Color", "tag", [color.element, colorSample], !!values.color, () => { + color.set(""); + updateColor(); + }); + const assignees = field( + "Names (comma separated)", + "text", + (values.assignees ?? []).join(", "), + true, + ); + assignees.placeholder = "People, teams, or customers"; + group( + "Assignments", + "person", + [assignees.parentElement!], + !!values.assignees?.length, + () => { + assignees.value = ""; + }, + ); + const priorityTrigger = button("Priority", () => {}, "priority"); + const priority = createPriorityPicker(priorityTrigger, values.priority ?? null, preferences.priorityLevels, options.ui); + choices.append(priorityTrigger); + details.add(button("Priority", () => priority.open(), "priority"), "Set urgency without changing labels."); + const customRows: { name: HTMLInputElement; value: HTMLInputElement }[] = + []; + const addCustomField = (name = "", value = "") => { + const section = el("section", "", "pm-optional-group"); + const header = el("div", "", "pm-optional-heading"); + const content = el("div", "", "pm-optional-content"); + const nameInput = field("Field name", "text", name); + const valueInput = field("Field value", "text", value); + nameInput.required = true; + nameInput.maxLength = 80; + const row = { name: nameInput, value: valueInput }; + customRows.push(row); + header.append( + el("h3", "Custom field"), + iconButton("Remove custom field", "close", () => { + customRows.splice(customRows.indexOf(row), 1); + section.remove(); + addDetails.focus(); + }), + ); + content.append(nameInput.parentElement!, valueInput.parentElement!); + section.append(header, content); + optional.append(section); + return nameInput; + }; + for (const field of values.customFields ?? []) + addCustomField(field.name, field.value); + const customChoice = button( + "Custom field", + () => addCustomField().focus(), + "plus", + ); + details.add(customChoice, "Store a named value on this card."); + grid.insertBefore(choices, labels.element); + grid.insertBefore(optional, descriptionEditor.element); + const placement = store.board.listFor(values)?.name ?? "Unlisted"; + intro.textContent = task + ? isHiddenCard(task.path) + ? "Private workspace card" + : `Linked note: ${task.path}` + : needsBoard ? "Choose a board for this card." : `New card in ${placement}`; + const error = el("p", needsBoard && !activeBoards.length ? "Create a board before adding cards." : "", "pm-error"); + error.setAttribute("role", "alert"); + form.append(error); + if (task) { + const created = el("p", `Created: ${task.createdAt ? new Date(task.createdAt).toLocaleString() : "Unknown"}`, "pm-created-at"); + if (task.createdAt) created.title = task.createdAt; + form.append(created); + } + const actions = el("div", "", "pm-editor-actions"); + const cancel = button("Cancel", () => { if (!busy && !descriptionSaving) void placementQueue.then(flushDraft).then(() => dialog.close()).catch(reportDraftError); }); + const save = button(task ? "Save card" : "Create card", () => {}); + save.type = "submit"; + save.classList.add("pm-primary"); + actions.append(cancel, save); + form.append(actions); + dialog.append(form); + root.append(dialog); + dialog.showModal(); + let titleEntered = !!task; + const titleFirst = () => { + if (title.value.trim()) titleEntered = true; + for (const item of [choices, labels.element, optional, descriptionEditor.element, images.attachmentsElement]) + item.hidden = !titleEntered; + save.disabled = images.isLoading() || !title.value.trim() || (needsBoard && !activeBoards.length); + descriptionEditor.resize(); + }; + title.addEventListener("input", titleFirst); + titleFirst(); + const initialDraft = () => JSON.stringify({ + title: title.value.trim(), body: description.value.trim(), status: status.value, + board: boardSelect.value, list: listSelect.value, due: due.value, start: start.value, end: end.value, + tags: tags.value(), labels: labels.value(), color: color.value(), + priority: priority.value(), cover: cover.value, relations: relations.value(), removedIncoming: relations.removedIncoming().map(task => task.id), assignees: assignees.value.trim(), + attachments: images.value(), + sessionStart: sessionStart.value, sessionEnd: sessionEnd.value, + custom: customRows.map((row) => [row.name.value, row.value.value]), + }); + const emptyDraft = initialDraft(); + let placementQueue: Promise = Promise.resolve(); + const persistPlacement = () => { + if (!task || descriptionSaving) return; + const boardId = boardSelect.value; + const listId = listSelect.value; + const nextStatus = status.value as Status; + placementQueue = placementQueue.catch(() => {}).then(async () => { + try { + if (boardId) await store.saveToBoard(task!, boardId, listId || null, {}); + else await store.save(task!, { status: nextStatus }); + task = store.tasks.find(item => item.id === task!.id)!; + originalBoardId = boardId; + originalListId = listId; + status.value = task.status; + updateChoice(status); + error.textContent = ""; + } catch (reason) { + reportDraftError(reason); + throw reason; + } + }); + void placementQueue.catch(() => {}); + }; + for (const control of [boardSelect, listSelect, status]) control.addEventListener("change", persistPlacement); + title.focus(); + dialog.oncancel = (event) => { + event.preventDefault(); + if (!busy) requestClose(); + }; + dialog.onclose = () => { + activeDialog = undefined; + disposeEditor?.(); + disposeEditor = undefined; + dialog.remove(); + if (nextCard && !closed) { openEditor(nextCard); return; } + if (!closed) { + render(); + const restoredCard = restoreTaskId + ? Array.from(root.querySelectorAll(".pm-card")) + .find((card) => card.dataset.taskId === restoreTaskId) + ?.querySelector(".pm-card-title") + : undefined; + const focus = restoreFocus?.isConnected ? restoreFocus : restoredCard; + if (focus) focus.focus({ preventScroll: true }); + else + root + .querySelector('.pm-tabs [aria-pressed="true"]') + ?.focus({ preventScroll: true }); + } + }; + // A backdrop click must start and end outside the card. Child dialogs and + // popovers consume their own dismissal without saving the parent draft. + let outsidePointer: number | undefined; + let outsideClick = false; + let outsideChildSurface = false; + const onBackdrop = (event: MouseEvent) => { + const target = event.target; + if (!(target instanceof HTMLElement) || + (target !== dialog && !target.matches(":popover-open"))) return false; + const bounds = target.getBoundingClientRect(); + return event.clientX < bounds.left || event.clientX > bounds.right || + event.clientY < bounds.top || event.clientY > bounds.bottom; + }; + const hasChildSurface = () => activeDialog !== dialog || + !!dialog.querySelector('dialog[open], :popover-open'); + dialog.addEventListener("pointerdown", (event) => { + outsideClick = false; + outsideChildSurface = hasChildSurface(); + outsidePointer = event.isPrimary && event.button === 0 && + onBackdrop(event) ? event.pointerId : undefined; + }, true); + dialog.addEventListener("pointerup", (event) => { + outsideClick = outsidePointer === event.pointerId && onBackdrop(event); + outsidePointer = undefined; + }, true); + dialog.addEventListener("pointercancel", () => { + outsidePointer = undefined; + outsideClick = false; + }); + dialog.addEventListener("click", (event) => { + const dismiss = outsideClick && onBackdrop(event); + outsideClick = false; + if (!dismiss || busy || !dialog.open) return; + if (outsideChildSurface || hasChildSurface()) { + for (const panel of dialog.querySelectorAll(":popover-open")) + panel.hidePopover(); + return; + } + requestClose(); + }); + function requestClose() { + if (descriptionSaving) return; + if (images.isLoading()) { + error.textContent = "Wait for images to finish loading, then try again."; + return; + } + if (!task && initialDraft() === emptyDraft) { + dialog.close(); + return; + } + if (!title.value.trim()) { + title.focus(); + error.textContent = "Enter a card title to save this draft."; + return; + } + form.requestSubmit(save); + } + form.addEventListener("invalid", (event) => { + const control = event.target as HTMLInputElement; + error.textContent = control.validationMessage; + }, true); + form.onsubmit = async (event) => { + event.preventDefault(); + if (busy || descriptionSaving || images.isLoading()) return; + error.textContent = ""; + if (needsBoard && !boardSelect.value) { error.textContent = "Choose a board for this card."; sharedChoice(boardSelect).focus(); return; } + try { + await placementQueue; + if (!!start.value !== !!end.value) + throw new Error("Enter both planned dates, or clear both fields."); + if (!!sessionStart.value !== !!sessionEnd.value) + throw new Error("Enter both session times, or clear both fields."); + const sessions = [...values.sessions.slice(1)]; + if (sessionStart.value) + sessions.unshift({ + id: first?.id ?? crypto.randomUUID(), + start: localInstant(sessionStart.value), + end: localInstant(sessionEnd.value), + timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, + }); + const selectedList = (boardSelect.value ? activeBoards.find(board => board.id === boardSelect.value)?.value : store.board.value)?.lists.find( + (list) => list.id === listSelect.value, + ); + const listChanged = listSelect.value !== originalListId; + const fields: TaskFields = { + ...(task && title.value.trim() !== task.title + ? { title: title.value.trim() } + : {}), + color: color.value() || undefined, + coverImage: cover.value || null, + attachments: images.value(), + ...relations.value(), + ...(priority.changed() ? { priority: priority.value() } : {}), + assignees: assignees.value + .split(",") + .map((name) => name.trim()) + .filter(Boolean), + customFields: customRows.map((row) => ({ + name: row.name.value.trim(), + value: row.value.value, + })), + status: boardSelect.value || store.board.reference || needsBoard + ? ((!task || listChanged ? selectedList?.status : null) ?? + task?.status ?? values.status) + : (status.value as Status), + ...((store.board.reference && originalBoardId === store.board.reference.id) || needsBoard + ? { listId: listSelect.value || null } + : {}), + tags: tags.value(), + labels: + labels.value().length || values.labels !== undefined + ? labels.value() + : undefined, + due: due.value ? { date: due.value } : undefined, + plan: start.value + ? { start: start.value, end: addDays(end.value, 1) } + : undefined, + sessions, + archived: values.archived, + }; + save.disabled = cancel.disabled = true; + images.setSaving(true); + const body = task ? task.body : description.value; + const ok = await perform( + async () => { + await flushDraft(); + await images.save(body); + const existingIds = new Set(store.tasks.map(candidate => candidate.id)); + await (task && boardSelect.value && (boardSelect.value !== originalBoardId || (!store.board.reference && listChanged)) + ? store.saveToBoard(task, boardSelect.value, listSelect.value || null, { ...fields, body }) + : task + ? store.save( + task, + { ...fields, body }, + !!store.board.reference && listChanged, + ) + : store.create(title.value, fields, body, needsBoard ? boardSelect.value : undefined)); + task = store.tasks.find(candidate => task ? candidate.id === task.id : !existingIds.has(candidate.id)); + if (!task) throw new Error("The saved card is unavailable. Refresh the board."); + await store.unlinkIncoming(task.id, relations.removedIncoming()); + save.textContent = "Save card"; + if (relatedTarget?.subtaskId) { + nextCard = await store.openSubtask(task.id, relatedTarget.subtaskId); + } else if (relatedTarget?.taskId) { + nextCard = store.tasks.find(candidate => candidate.id === relatedTarget!.taskId); + if (!nextCard) throw new Error("The linked card is unavailable. Refresh the board."); + } + }, + "Card saved.", + ); + if (closed) return; + if (ok) dialog.close(); + else error.textContent = message; + } catch (reason) { + error.textContent = + reason instanceof Error ? reason.message : String(reason); + } finally { + relatedTarget = undefined; + save.disabled = cancel.disabled = false; + images.setSaving(false); + } + }; + } + function transferCard(task: Task) { + if (activeDialog || busy) return; + closePopup?.(); + const dialog = el("dialog", "", "pm-editor"), + form = el("form"), + grid = el("div", "", "pm-form-grid"), + boardLabel = el("label", "Destination board", "pm-field"), + boardSelect = el("select"), + listLabel = el("label", "Destination list", "pm-field"), + listSelect = el("select"), + hint = el("p", "", "pm-muted"), + error = el("p", "", "pm-error"), + actions = el("div", "", "pm-editor-actions"), + cancel = button("Cancel", () => { if (!busy) dialog.close(); }), + move = button("Move card", () => {}, "right"); + activeDialog = dialog; + dialog.setAttribute("aria-label", "Move card to board"); + boardSelect.required = true; + boardLabel.append(boardSelect); + listLabel.append(listSelect); + error.role = "alert"; + move.type = "submit"; + move.classList.add("pm-primary"); + actions.append(cancel, move); + grid.append(boardLabel, listLabel); + form.append(el("h2", `Move “${task.title}”`), + el("p", `Remove this card from ${store.board.name} and place it on the selected board. Card details, status, and other board memberships stay unchanged.`), + grid, hint, error, actions); + dialog.append(form); + root.append(dialog); + const fillLists = (preferred?: string) => { + listSelect.replaceChildren(); + const destination = store.boards.find((board) => board.id === boardSelect.value); + if (destination) { + const unlisted = el("option", "Unlisted"); + unlisted.value = ""; + listSelect.append(unlisted); + for (const list of destination.value.lists) { + const option = el("option", list.name); + option.value = list.id; + listSelect.append(option); + } + const placement = task.placements?.[destination.id]; + listSelect.value = preferred ?? + (placement ? placement.listId : destination.value.defaults[task.status]) ?? ""; + if (listSelect.selectedIndex < 0) listSelect.value = ""; + hint.textContent = placement + ? "This card already belongs to that board. The selected list replaces its current placement." + : "The card will appear at the end of the selected list."; + } + listSelect.disabled = move.disabled = !destination; + }; + const fillBoards = () => { + const previousBoard = boardSelect.value, previousList = listSelect.value; + const boards = store.boards.filter((board) => + board.id !== store.board.reference?.id && !board.archived); + const placeholder = el("option", boards.length ? "Choose a board" : "No other active boards"); + placeholder.value = ""; + boardSelect.replaceChildren(placeholder); + for (const board of boards) { + const option = el("option", board.name); + option.value = board.id; + boardSelect.append(option); + } + boardSelect.value = boards.some((board) => board.id === previousBoard) ? previousBoard : ""; + boardSelect.disabled = !boards.length; + hint.textContent = boards.length ? "Choose the board that should contain this card." : "Create another board before moving this card."; + fillLists(previousList); + }; + fillBoards(); + const boardChoice = sharedChoice(boardSelect); + sharedChoice(listSelect); + boardSelect.onchange = () => fillLists(); + dialog.oncancel = (event) => { if (busy) event.preventDefault(); }; + dialog.onclose = () => { + activeDialog = undefined; + dialog.remove(); + if (closed) return; + render(); + const card = Array.from(root.querySelectorAll(".pm-card")) + .find((item) => item.dataset.taskId === task.id); + (card?.querySelector(".pm-card-menu") ?? + root.querySelector('.pm-tabs [aria-pressed="true"]')) + ?.focus({ preventScroll: true }); + }; + form.onsubmit = async (event) => { + event.preventDefault(); + if (busy || !boardSelect.value) return; + error.textContent = ""; + boardSelect.disabled = listSelect.disabled = move.disabled = cancel.disabled = true; + const ok = await perform( + () => store.transferTask(task, boardSelect.value, listSelect.value || null), + "Card moved to the selected board.", + ); + if (closed) return; + if (ok) dialog.close(); + else { + cancel.disabled = false; + fillBoards(); + error.textContent = message; + } + }; + dialog.showModal(); + (boardSelect.disabled ? cancel : boardChoice).focus(); + } + function updateDescriptionBadge(id: string, dirty: boolean) { + for (const badge of root.querySelectorAll(`.pm-card[data-task-id="${CSS.escape(id)}"] .pm-card-unsaved`)) { + badge.dataset.edited = "true"; + badge.hidden = !dirty; + } + } + function card(task: Task): HTMLElement { + const item = el("article", "", "pm-card"); + const toggleSelection = () => { + if (selectedCards.has(task.id)) selectedCards.delete(task.id); else selectedCards.add(task.id); + render(); root.querySelector(`.pm-card[data-task-id="${CSS.escape(task.id)}"] .pm-card-select`)?.focus(); + }; + if (selectionMode) { + item.classList.toggle("pm-card-selected", selectedCards.has(task.id)); + const checkbox = el("input", "", "pm-card-select"); checkbox.type = "checkbox"; checkbox.checked = selectedCards.has(task.id); checkbox.setAttribute("aria-label", `Select ${task.title}`); checkbox.onchange = toggleSelection; item.append(checkbox); + } + item.dataset.taskId = task.id; + applyTaskColor(item, task); + if (task.coverImage && [...imageReferences(task.body), ...(task.attachments ?? [])].some(ref => ref.id === task.coverImage)) { + const cover = el("img", "", "pm-card-cover"); cover.alt = ""; cover.loading = "lazy"; + const coverButton = button("", () => openEditor(task)); coverButton.className = "pm-card-cover-button"; + coverButton.setAttribute("aria-label", `Open ${task.title}`); coverButton.append(cover); item.append(coverButton); + void loadImage(task.coverImage).then(data => { if (!closed) cover.src = data; }).catch(() => coverButton.remove()); + cover.onerror = () => coverButton.remove(); + } + if (task.color) { + item.classList.add("pm-colored-card"); + item.setAttribute("aria-label", task.title + ", " + task.color); + } + const line = el("div", "", "pm-card-line"), + open = button(task.title, () => openEditor(task)); + open.className = "pm-card-title"; + if (task.status === "done") open.classList.add("pm-complete"); + const menu = iconButton("Actions for " + task.title, "more", () => + popup(menu, "Card actions", (panel, close) => { + panel.classList.add("pm-menu"); + panel.append( + button("Edit card", () => { + close(); + openEditor(task); + }, "rename"), + ); + const label = el("label", "Move to list", "pm-field"), + select = el("select"); + select.setAttribute("aria-label", "Move " + task.title + " to list"); + const unlisted = el("option", "Unlisted"); + unlisted.value = ""; + select.append(unlisted); + for (const list of store.board.value.lists) { + const option = el("option", list.name); + option.value = list.id; + select.append(option); + } + select.value = store.board.listFor(task)?.id ?? ""; + select.onchange = () => { + close(); + void perform( + () => store.moveTask(task, select.value || null), + "Card moved.", + ); + }; + label.append(select); + if (store.board.reference) panel.append(label); + if (store.board.reference) { + const transfer = button("Move to board", () => { + close(); + transferCard(task); + }, "right"); + transfer.disabled = store.board.archived; + panel.append(transfer); + } + if (store.board.reference && !task.archived) { + const listId = store.board.listFor(task)?.id ?? null; + const cards = store.cardsInList(listId); + const index = cards.findIndex((card) => card.id === task.id); + for (const [name, delta] of [ + ["Move up", -1], + ["Move down", 1], + ] as const) { + const move = button(name, () => { + close(); + const beforeId = + delta < 0 + ? cards[index - 1].id + : (cards[index + 2]?.id ?? null); + void perform( + () => store.moveTask(task, listId, beforeId), + "Card moved.", + ); + }, delta < 0 ? "up" : "down"); + move.disabled = index + delta < 0 || index + delta >= cards.length; + panel.append(move); + } + } + if (store.board.reference) + panel.append( + button("Remove from board", () => { + close(); + void perform( + () => store.removeFromBoard(task), + "Card removed from this board. The task note remains.", + ); + }, "kanban"), + ); + panel.append( + button(task.archived ? "Restore" : "Archive", () => { + close(); + void perform( + () => store.save(task, { archived: !task.archived }), + task.archived ? "Task restored." : "Task archived.", + ); + }, "archive"), + button("Delete card", () => { close(); deleteCardForm(task, menu); }, "trash"), + ); + }), + ); + menu.classList.add("pm-card-menu"); + menu.setAttribute("aria-haspopup", "menu"); + menu.onkeydown = event => { if (["ArrowDown", "ArrowUp"].includes(event.key)) { event.preventDefault(); menu.click(); } }; + line.append(open, menu); + item.append(line); + const unsaved = el("span", "Unsaved description", "pm-card-unsaved"); + const draftIcon = el("span", "", "pm-icon"); + draftIcon.innerHTML = ``; + unsaved.prepend(draftIcon); + unsaved.title = "Open this card and save or cancel the description changes."; + unsaved.hidden = true; + item.append(unsaved); + void new DescriptionDraft(store.workspace, task.id).load().then(body => { + if (!closed && !unsaved.dataset.edited) unsaved.hidden = body === null || body === task.body; + }).catch(() => { + if (!closed && !unsaved.dataset.edited) { + unsaved.textContent = "Description draft needs recovery"; + unsaved.hidden = false; + } + }); + if ( + task.tags.length || + task.labels?.length || + task.priority || + task.due || + task.assignees?.length + ) { + const badges = el("div", "", "pm-badges"); + if (task.priority) { + const priority = el("span", `${priorityNames[task.priority]} priority`, "pm-priority"); + const icon = el("span", "", "pm-icon"); + icon.innerHTML = ``; + priority.prepend(icon); + setPriorityAppearance(priority, task.priority); + badges.append(priority); + } + for (const id of task.labels ?? []) + badges.append( + labelBadge( + store.labels.value.find((label) => label.id === id), + id, + ), + ); + for (const tag of task.tags) badges.append(el("span", tag, "pm-tag")); + for (const name of task.assignees ?? []) { + const person = el("span", name, "pm-assignee"); + person.setAttribute("aria-label", "Assigned to " + name); + badges.append(person); + } + if (task.due) + badges.append( + el( + "span", + shortDate(task.due.date), + task.status !== "done" && task.due.date < localDay() + ? "pm-due pm-overdue" + : "pm-due", + ), + ); + item.append(badges); + } + let dragged = false; + item.onpointerdown = () => { dragged = false; }; + item.addEventListener("click", (event) => { + if (selectionMode && event.target instanceof Element && !event.target.closest(".pm-card-select")) { + event.preventDefault(); event.stopImmediatePropagation(); toggleSelection(); return; + } + if (dragged && event.detail !== 0) { + event.preventDefault(); + event.stopImmediatePropagation(); + return; + } + if (event.defaultPrevented || drag || !(event.target instanceof Element)) return; + if (event.target.closest("button,a,input,select,textarea,label,summary,[role=button],[contenteditable=true]")) return; + open.focus({ preventScroll: true }); + openEditor(task); + }, true); + item.draggable = !!store.board.reference && !task.archived && !selectionMode; + item.ondragstart = (event) => { + if (!item.draggable) { event.preventDefault(); return; } + dragged = true; + beginDrag(event, "task", task.id, item, task.title); + }; + return item; + } + function bulkForm(trigger: HTMLElement, action: "delete" | "list" | "board") { + const tasks = filtered().filter(task => selectedCards.has(task.id)); + if (!tasks.length || busy) return; + const title = action === "delete" ? "Delete selected cards" : action === "list" ? "Move selected cards to list" : "Move selected cards to board"; + popup(trigger, title, (panel, close) => { + panel.append(el("h3", title), el("p", `${tasks.length} cards selected.`)); + const boards = el("select"); boards.setAttribute("aria-label", "Destination board"); + const lists = el("select"); lists.setAttribute("aria-label", "Destination list"); + const destinations = store.boards.filter(board => !board.archived && board.id !== store.board.reference?.id); + for (const board of destinations) { const option = el("option", board.name); option.value = board.id; boards.append(option); } + const updateLists = () => { + lists.replaceChildren(); const unlisted = el("option", "Unlisted"); unlisted.value = ""; lists.append(unlisted); + const board = action === "board" ? destinations.find(board => board.id === boards.value)?.value : store.board.value; + for (const list of board?.lists ?? []) { const option = el("option", list.name); option.value = list.id; lists.append(option); } + }; + boards.onchange = updateLists; updateLists(); + if (action === "board") { const field = el("label", "Destination board", "pm-field"); field.append(boards); panel.append(field); } + if (action !== "delete") { const field = el("label", "Destination list", "pm-field"); field.append(lists); panel.append(field); } + else panel.append(el("p", "Delete these cards from all boards. Saved source notes and images remain in the workspace.")); + const error = el("p", "", "pm-error"); error.setAttribute("role", "alert"); panel.append(error); + const actions = el("div", "", "pm-popup-actions"); + const apply = button(action === "delete" ? "Delete cards" : "Move cards", async () => { + let completed = 0; + apply.disabled = true; + const ok = await perform(async () => { + await store.reload(); + for (const task of tasks) if (!store.tasks.some(current => current.id === task.id && current.source === task.source)) + throw new Error("A selected card changed. Refresh and select the cards again."); + for (const task of tasks) { + if (action === "delete") await store.deleteCard(task); + else if (action === "list") await store.moveTask(task, lists.value || null); + else await store.transferTask(task, boards.value, lists.value || null); + selectedCards.delete(task.id); completed++; + } + }, `${tasks.length} cards ${action === "delete" ? "deleted" : "moved"}.`); + apply.disabled = false; + if (ok) { close(); render(); } + else { error.textContent = `${completed} of ${tasks.length} cards changed. ${message}`; apply.disabled = true; } + }, action === "delete" ? "trash" : "right"); + apply.disabled = action === "board" && !destinations.length; + actions.append(button("Cancel", () => { if (!busy) { close(); render(); } }), apply); panel.append(actions); + }); + } + root.addEventListener("keydown", event => { + if (event.key === "Escape" && selectionMode && !activeDialog && !closePopup && !busy) { + event.preventDefault(); selectionMode = false; selectedCards.clear(); render(); root.querySelector(".pm-select-mode")?.focus(); + } + }); + function selectionToolbar() { + const bar = el("div", "", "pm-selection-toolbar"); bar.setAttribute("role", "group"); bar.setAttribute("aria-label", "Selected cards"); + bar.append(el("span", `${selectedCards.size} selected`, "pm-selection-count")); + bar.append(button("Select all cards", () => { for (const task of filtered()) selectedCards.add(task.id); render(); root.querySelector(".pm-selection-toolbar button")?.focus(); }, "check")); + const clear = button("Clear selection", () => { selectedCards.clear(); render(); root.querySelector(".pm-selection-toolbar button")?.focus(); }, "close"); clear.disabled = !selectedCards.size; bar.append(clear); + for (const [label, action, icon] of [["Move to list", "list", "kanban"], ["Move to board", "board", "right"], ["Delete selected", "delete", "trash"]] as const) { + const control = button(label, () => bulkForm(control, action), icon); + control.disabled = !selectedCards.size || (action !== "delete" && (!store.board.editable || !store.board.reference)); bar.append(control); + } + return bar; + } + let autoScroll: { x: number; y: number; pointerX: number; pointerY: number; moved: boolean; frame: number; time: number; marker: HTMLElement } | undefined; + function stopAutoScroll() { + if (!autoScroll) return; + cancelAnimationFrame(autoScroll.frame); autoScroll.marker.remove(); autoScroll = undefined; + root.classList.remove("pm-auto-scrolling"); + } + function autoScrollFrame(time: number) { + const state = autoScroll; + if (!state) return; + const board = root.querySelector(".pm-board"); + if (!board || !root.getClientRects().length || activeDialog || closePopup || closed) { stopAutoScroll(); return; } + const elapsed = Math.min(40, time - state.time || 16) / 16; + state.time = time; + const speed = (distance: number) => Math.abs(distance) <= 8 ? 0 : Math.sign(distance) * Math.min(40, (Math.abs(distance) - 8) / 6); + board.scrollLeft += speed(state.pointerX - state.x) * elapsed; + scrollContainer().scrollTop += speed(state.pointerY - state.y) * elapsed; + state.frame = requestAnimationFrame(autoScrollFrame); + } + function startAutoScroll(event: MouseEvent) { + if (autoScroll) { event.preventDefault(); stopAutoScroll(); return; } + if (event.button !== 1 || activeDialog || closePopup || drag || !root.querySelector(".pm-board") || + !(event.target instanceof Element) || event.target.closest("button,a,input,textarea,select,dialog,.pm-popup,.rs-menu,[contenteditable=true]")) return; + const board = root.querySelector(".pm-board")!, vertical = scrollContainer(); + if (board.scrollWidth <= board.clientWidth && vertical.scrollHeight <= vertical.clientHeight) return; + event.preventDefault(); + const marker = el("div", "", "pm-autoscroll-marker"); marker.setAttribute("aria-hidden", "true"); + const glyph = el("span", "", "pm-icon"); + glyph.innerHTML = ``; + marker.append(glyph); marker.style.left = `${event.clientX}px`; marker.style.top = `${event.clientY}px`; + root.append(marker); root.classList.add("pm-auto-scrolling"); + autoScroll = { x: event.clientX, y: event.clientY, pointerX: event.clientX, pointerY: event.clientY, moved: false, frame: requestAnimationFrame(autoScrollFrame), time: performance.now(), marker }; + } + function moveAutoScroll(event: MouseEvent) { + if (!autoScroll) return; + autoScroll.pointerX = event.clientX; autoScroll.pointerY = event.clientY; + if (Math.hypot(event.clientX - autoScroll.x, event.clientY - autoScroll.y) > 8) autoScroll.moved = true; + } + function releaseAutoScroll(event: MouseEvent) { if (event.button === 1 && autoScroll?.moved) stopAutoScroll(); } + function dismissAutoScroll(event: KeyboardEvent) { if (event.key === "Escape" && autoScroll) { event.preventDefault(); stopAutoScroll(); } } + function outsideAutoScroll(event: MouseEvent) { if (autoScroll && !root.contains(event.target as Node)) { event.preventDefault(); stopAutoScroll(); } } + function preventAutoScrollClick(event: MouseEvent) { if (event.button === 1 && event.target instanceof Element && !event.target.closest("a,button,input")) event.preventDefault(); } + function scrollBoard(event: WheelEvent) { + if ( + activeDialog || + closePopup || + drag || + event.defaultPrevented || + !event.cancelable || + event.ctrlKey || + event.metaKey || + event.shiftKey || + event.altKey || + event.deltaX !== 0 || + event.deltaY === 0 + ) + return; + const board = root.querySelector(".pm-board"); + if ( + !board || + (event.target !== board && + event.target !== root && + event.target !== root.querySelector(".pm-toolbar")) + ) + return; + const unit = + event.deltaMode === WheelEvent.DOM_DELTA_LINE + ? parseFloat(getComputedStyle(board).lineHeight) || 16 + : event.deltaMode === WheelEvent.DOM_DELTA_PAGE + ? board.clientWidth + : 1; + const previous = board.scrollLeft; + board.scrollLeft += event.deltaY * unit; + if (board.scrollLeft !== previous) event.preventDefault(); + } + function kanban(tasks: Task[]) { + const board = el("div", "", "pm-board"); + const insertion = el("div", "", "pm-list-insertion"); + insertion.hidden = true; + insertion.setAttribute("aria-hidden", "true"); + const cardInsertion = el("div", "", "pm-card-insertion"); + cardInsertion.hidden = true; + cardInsertion.setAttribute("aria-hidden", "true"); + const columns: { node: HTMLElement; id: string | null }[] = []; + const targetAt = (x: number) => { + const remaining = columns.filter( + (column) => column.id !== null && column.id !== drag?.id, + ); + const index = remaining.findIndex(({ node }) => { + const rect = node.getBoundingClientRect(); + return x < rect.left + rect.width / 2; + }); + return { remaining, index: index < 0 ? remaining.length : index }; + }; + const cardTarget = (column: (typeof columns)[number], y: number) => { + const cards = [ + ...column.node.querySelectorAll( + ".pm-card-stack > .pm-card", + ), + ].filter((card) => card.dataset.taskId !== drag?.id); + const before = cards.find((card) => { + const rect = card.getBoundingClientRect(); + return y < rect.top + rect.height / 2; + }); + const top = before + ? before.getBoundingClientRect().top - 4 + : cards.length + ? cards.at(-1)!.getBoundingClientRect().bottom + 4 + : column.node + .querySelector(".pm-column-heading")! + .getBoundingClientRect().bottom + 6; + return { beforeId: before?.dataset.taskId ?? null, top }; + }; + const showTarget = (x: number, y: number) => { + columns.forEach(({ node }) => node.classList.remove("pm-drop-target")); + if (drag?.kind === "list") { + const { remaining, index } = targetAt(x); + const target = remaining[index] ?? remaining.at(-1); + if (!target) return; + const rect = target.node.getBoundingClientRect(); + const bounds = board.getBoundingClientRect(); + insertion.hidden = false; + insertion.style.left = + (index < remaining.length ? rect.left - 7 : rect.right + 5) - + bounds.left + + board.scrollLeft + + "px"; + insertion.style.height = Math.max(160, rect.height) + "px"; + } else if (drag?.kind === "task") { + const column = nearestColumn(x); + if (!column) return; + column.node.classList.add("pm-drop-target"); + const target = cardTarget(column, y); + const rect = column.node.getBoundingClientRect(); + const bounds = board.getBoundingClientRect(); + cardInsertion.hidden = false; + cardInsertion.style.left = + rect.left - bounds.left + board.scrollLeft + 8 + "px"; + cardInsertion.style.top = + target.top - bounds.top + board.scrollTop + "px"; + cardInsertion.style.width = rect.width - 16 + "px"; + } + }; + const nearestColumn = (x: number) => + columns.reduce<(typeof columns)[number] | undefined>( + (nearest, column) => { + const distance = (node: HTMLElement) => { + const rect = node.getBoundingClientRect(); + return Math.abs(x - (rect.left + rect.width / 2)); + }; + return !nearest || distance(column.node) < distance(nearest.node) + ? column + : nearest; + }, + undefined, + ); + board.ondragover = (event) => { + if (!store.board.reference || !drag || busy) return; + event.preventDefault(); + if (event.dataTransfer) event.dataTransfer.dropEffect = "move"; + const bounds = board.getBoundingClientRect(); + if (event.clientX < bounds.left + 40) board.scrollLeft -= 24; + else if (event.clientX > bounds.right - 40) board.scrollLeft += 24; + if (event.clientY < bounds.top + 40) board.scrollTop -= 24; + else if (event.clientY > bounds.bottom - 40) board.scrollTop += 24; + showTarget(event.clientX, event.clientY); + }; + board.ondragleave = (event) => { + if (!board.contains(event.relatedTarget as Node)) { + insertion.hidden = true; + cardInsertion.hidden = true; + columns.forEach(({ node }) => node.classList.remove("pm-drop-target")); + } + }; + board.ondrop = (event) => { + if (!store.board.reference || !drag || busy) return; + event.preventDefault(); + const { kind, id } = drag; + if (kind === "list") { + const { index } = targetAt(event.clientX); + const source = store.board.value.lists.findIndex( + (list) => list.id === id, + ); + clearDrag(); + if (source !== index) + void perform( + () => store.changeBoard(() => store.board.move(id, index)), + "List moved.", + ); + } else { + const target = nearestColumn(event.clientX); + const task = store.tasks.find((task) => task.id === id); + const position = target ? cardTarget(target, event.clientY) : undefined; + clearDrag(); + if (task && target && position) + void perform( + () => store.moveTask(task, target.id, position.beforeId), + "Card moved.", + ); + } + }; + const lists: TaskColumn[] = store.board.reference + ? store.board.value.lists.map(list => ({ list, tasks: tasks.filter(task => store.board.listFor(task)?.id === list.id) })) + : allTaskColumns(store.boards, tasks); + if (store.board.reference && tasks.some(task => !store.board.listFor(task))) + lists.push({ tasks: tasks.filter(task => !store.board.listFor(task)) }); + for (const column of lists) { + const data = column.list; + const name = data?.name ?? "Unlisted", + id = data?.id ?? null; + const list = el("section", "", "pm-column"); + list.setAttribute("aria-label", name); + list.dataset.listId = id ?? "unlisted"; + const collapsed = store.board.reference ? pendingCollapsedLists.get(id ?? "unlisted") ?? !!data?.collapsed : collapsedLists.has(id ?? "unlisted"); + list.classList.toggle("pm-column-collapsed", collapsed); + const members = column.tasks.sort((a, b) => compareCards(a, b, store.board.reference?.id)); + const heading = el("div", "", "pm-column-heading"); + if (data && store.board.editable) { + const grip = iconButton("Move list " + name, "grip", () => + listMenu(grip, data), + ); + grip.classList.add("pm-list-grip"); + grip.draggable = true; + grip.ondragstart = (event) => { + beginDrag(event, "list", data.id, list, name); + }; + heading.append(grip); + } + if (!store.board.reference || (data && store.board.editable)) { + const collapse = iconButton( + (collapsed ? "Expand " : "Collapse ") + name, + collapsed ? "right" : "down", + async () => { + if (store.board.reference && data) { + pendingCollapsedLists.set(data.id, !collapsed); + render(); + await perform(() => store.changeBoard(() => store.board.collapse(data.id), false), "List updated."); + pendingCollapsedLists.delete(data.id); + render(); + } else { + const key = id ?? "unlisted"; + if (collapsedLists.has(key)) collapsedLists.delete(key); else collapsedLists.add(key); + state.collapsedLists = [...collapsedLists]; + render(); + } + Array.from(root.querySelectorAll(".pm-column")) + .find(column => column.dataset.listId === (id ?? "unlisted")) + ?.querySelector("[aria-expanded]")?.focus({ preventScroll: true }); + }, + ); + collapse.setAttribute("aria-expanded", String(!collapsed)); + heading.append(collapse); + } + heading.append( + el("h2", name), + ); + const activeCount = store.cardsInList(id).length; + const maximum = data?.maxCards; + const count = el("span", maximum === undefined ? String(members.length) : `${activeCount}/${maximum}`, "pm-count"); + heading.append(count); + if (maximum !== undefined) { + const reached = activeCount >= maximum; + const description = `${activeCount} active cards in ${name}. Maximum is ${maximum}.${reached ? activeCount > maximum ? " Limit exceeded." : " Limit reached." : ""}`; + count.setAttribute("aria-label", description); + const indicator = iconButton(description, reached ? "warning" : "limit", () => { if (data && store.board.editable) listLimitForm(indicator, data); }); + indicator.classList.add("pm-list-limit"); + if (reached) indicator.classList.add("pm-list-limit-reached"); + heading.append(indicator); + } + if (data && store.board.editable) { + const more = iconButton("List actions for " + name, "more", () => + listMenu(more, data), + ); + more.classList.add("pm-list-actions"); + heading.append(more); + } + list.append(heading); + if (!collapsed) { + const cards = el("div", "", "pm-card-stack"); + if (store.board.reference) members.forEach((task) => cards.append(card(task))); + else for (const group of allTaskGroups(store.boards, column)) { + const section = el("section", "", "pm-board-group"); + section.setAttribute("aria-label", group.name); + section.append(el("h3", group.name, "pm-board-group-heading")); + group.tasks.forEach(task => section.append(card(task))); + cards.append(section); + } + list.append(cards); + if ((store.board.reference || store.boards.some(board => !board.archived)) && !showArchived && cardDraft?.listId === id) { + list.append(cardComposer()); + } else if ((store.board.reference || store.boards.some(board => !board.archived)) && !showArchived) { + list.append(addCardButton(id, data?.status ?? "todo")); + } + } + board.append(list); + columns.push({ node: list, id }); + } + if (!lists.length) { + const empty = el("div", "", "pm-board-empty"); + const add = button("Add a list", () => listForm(add), "plus"); + empty.append(add); + board.append(empty); + } + board.append(insertion, cardInsertion); + return board; + } + function addCardButton(listId: string | null, status: Status) { + const add = button("Add a card", () => { + if (!store.board.reference) { openEditor(undefined, { listId, status }); return; } + cardDraft = cardDrafts.get(listId) ?? { listId, status, title: "" }; + cardDraft.status = status; + cardDrafts.set(listId, cardDraft); + render(); + root.querySelector(".pm-card-composer textarea")?.focus({ preventScroll: true }); + }, "plus"); + add.classList.add("pm-add-card"); + return add; + } + function hideCardComposer() { + if (!cardDraft || busy) return; + const draft = cardDraft; + cardDraft = undefined; + // Replace only the composer, so the outside control keeps its focus and click. + root.querySelector(".pm-card-composer")?.replaceWith(addCardButton(draft.listId, draft.status)); + } + function outsideCardComposer(event: Event) { + const form = root.querySelector(".pm-card-composer"); + if (form && event.target instanceof Node && !form.contains(event.target)) hideCardComposer(); + } + function cardComposer() { + const draft = cardDraft!; + const form = el("form", "", "pm-card-composer"); + form.setAttribute("aria-label", "New card"); + const title = el("textarea"); + title.setAttribute("aria-label", "Card title"); + title.placeholder = "Enter a title for this card"; + title.rows = 3; + title.maxLength = 100; + title.required = true; + title.value = draft.title; + const actions = el("div", "", "pm-composer-actions"); + const save = button("Add card", () => {}, "plus"); + save.type = "submit"; + save.classList.add("pm-primary"); + save.disabled = busy || !draft.title.trim(); + const cancel = iconButton("Cancel new card", "close", () => { + if (busy) return; + cardDrafts.delete(draft.listId); + cardDraft = undefined; + render(); + Array.from(root.querySelectorAll(".pm-column")) + .find(column => column.dataset.listId === (draft.listId ?? "unlisted")) + ?.querySelector(".pm-add-card")?.focus({ preventScroll: true }); + }); + cancel.disabled = title.disabled = busy; + title.oninput = () => { + draft.title = title.value; + save.disabled = busy || !draft.title.trim(); + }; + form.onkeydown = event => { + if (event.key === "Escape") { + event.preventDefault(); + cancel.click(); + } else if (event.target === title && event.key === "Enter" && !event.shiftKey && !event.isComposing) { + event.preventDefault(); + if (!save.disabled) form.requestSubmit(); + } + }; + form.onsubmit = async event => { + event.preventDefault(); + if (busy || !draft.title.trim()) return; + save.disabled = cancel.disabled = title.disabled = true; + form.setAttribute("aria-busy", "true"); + await perform(async () => { + await store.createOrLink(draft.title.trim().replace(/\s*\n\s*/g, " "), { + listId: draft.listId, status: draft.status, tags: [], sessions: [], archived: false, + }); + cardDrafts.delete(draft.listId); + cardDraft = undefined; + }, "Card saved."); + if (closed) return; + const column = Array.from(root.querySelectorAll(".pm-column")) + .find(column => column.dataset.listId === (draft.listId ?? "unlisted")); + column?.querySelector(".pm-card-composer textarea, .pm-add-card")?.focus({ preventScroll: true }); + }; + actions.append(save, cancel); + form.append(title, actions); + return form; + } + function dateNav() { + const toolbar = el("div", "", "pm-date-nav"); + const move = (direction: number) => { + if (view === "calendar" && period === "month") { + const date = new Date(`${anchor.slice(0, 7)}-01T12:00:00`); + date.setMonth(date.getMonth() + direction); + anchor = localDay(date); + } else + anchor = addDays( + anchor, + direction * (view === "gantt" ? 14 : period === "week" ? 7 : 1), + ); + render(); + }; + toolbar.append( + iconButton("Previous", "left", () => move(-1)), + button("Today", () => { + anchor = localDay(); + render(); + }), + iconButton("Next", "right", () => move(1)), + ); + const date = el("input"); + date.type = "date"; + date.value = anchor; + date.setAttribute("aria-label", "Visible date"); + date.onchange = () => { + if (date.value) { + anchor = date.value; + render(); + } + }; + toolbar.append(date); + return toolbar; + } + function gantt(tasks: Task[]) { + const wrap = el("div"); + wrap.className = "pm-view"; + wrap.append(dateNav()); + const scroll = el("div", "", "pm-gantt-scroll"), + table = el("div", "", "pm-gantt"); + table.setAttribute("role", "table"); + table.setAttribute("aria-label", "Task timeline"); + const days = 28; + const header = el("div", "", "pm-gantt-row"); + header.setAttribute("role", "row"); + header.append(el("div", "Task / planned range", "pm-gantt-name")); + const dates = el("div", "", "pm-gantt-dates"); + for (let i = 0; i < days; i++) { + const day = addDays(anchor, i); + const cell = el( + "span", + day.slice(-2), + day === localDay() ? "pm-today" : "", + ); + cell.title = day; + dates.append(cell); + } + header.append(dates); + table.append(header); + for (const task of tasks) { + const row = el("div", "", "pm-gantt-row"); + row.setAttribute("role", "row"); + const name = button(task.title, () => openEditor(task)); + name.className = "pm-gantt-name"; + applyTaskColor(name, task); + name.append( + el( + "small", + task.plan + ? `${shortDate(task.plan.start)} – ${shortDate(addDays(task.plan.end, -1))}` + : "Unscheduled", + ), + ); + row.append(name); + const track = el("div", "", "pm-gantt-track"); + if (task.plan) { + const left = Math.max(0, dayDistance(anchor, task.plan.start)), + right = Math.min(days, dayDistance(anchor, task.plan.end)); + if (right > left) { + const bar = button(task.title, () => openEditor(task)); + bar.className = `pm-gantt-bar pm-status-${task.status}`; + applyTaskColor(bar, task); + bar.style.left = `${(left / days) * 100}%`; + bar.style.width = `${((right - left) / days) * 100}%`; + bar.title = `${task.title}: ${task.plan.start} through ${addDays(task.plan.end, -1)}`; + track.append(bar); + } + } + if (task.due) { + const offset = dayDistance(anchor, task.due.date); + if (offset >= 0 && offset < days) { + const marker = button("◆", () => openEditor(task)); + marker.className = "pm-deadline"; + applyTaskColor(marker, task); + marker.style.left = `${((offset + 0.5) / days) * 100}%`; + marker.setAttribute( + "aria-label", + `${task.title}, deadline ${task.due.date}`, + ); + track.append(marker); + } + } + row.append(track); + table.append(row); + } + scroll.append(table); + wrap.append(scroll); + return wrap; + } + function calendar(tasks: Task[]) { + const wrap = el("div"), + toolbar = dateNav(); + for (const value of ["day", "week", "month"] as const) { + const tab = button(value[0].toUpperCase() + value.slice(1), () => { + period = value; + render(); + }); + tab.setAttribute("aria-pressed", String(period === value)); + toolbar.append(tab); + } + wrap.className = "pm-view"; + toolbar.append( + el("span", Intl.DateTimeFormat().resolvedOptions().timeZone, "pm-zone"), + ); + wrap.append(toolbar); + const entries = (day: string, timedOnly = false) => { + const list = el("div", "", "pm-calendar-entries"); + for (const task of tasks) { + if (!timedOnly && task.due?.date === day) { + const event = button(`◆ Due: ${task.title}`, () => openEditor(task)); + event.className = "pm-calendar-event pm-deadline-event"; + applyTaskColor(event, task); + list.append(event); + } + for (const session of task.sessions) { + const start = new Date(session.start), + end = new Date(session.end); + const dayStart = new Date(`${day}T00:00:00`), + dayEnd = new Date(`${addDays(day, 1)}T00:00:00`); + if (start >= dayEnd || end <= dayStart) continue; + const event = button( + `${start.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })} ${task.title}`, + () => openEditor(task), + ); + event.className = "pm-calendar-event"; + applyTaskColor(event, task); + event.title = `${task.title}: ${start.toLocaleString()} – ${end.toLocaleString()}`; + if (timedOnly) { + const clippedStart = start < dayStart ? dayStart : start, + clippedEnd = end > dayEnd ? dayEnd : end; + const minuteStart = + clippedStart.getHours() * 60 + clippedStart.getMinutes(); + const minuteEnd = + clippedEnd.getTime() === dayEnd.getTime() + ? 1440 + : clippedEnd.getHours() * 60 + clippedEnd.getMinutes(); + event.style.top = `${(minuteStart / 60) * 52}px`; + event.style.minHeight = `${Math.max(24, ((minuteEnd - minuteStart) / 60) * 52)}px`; + event.classList.add("pm-timed-event"); + } + list.append(event); + } + } + return list; + }; + if (period === "month") { + const first = `${anchor.slice(0, 7)}-01`, + start = addDays(first, -new Date(`${first}T12:00:00`).getDay()); + wrap.append( + el( + "h2", + new Date(`${first}T12:00:00`).toLocaleDateString(undefined, { + month: "long", + year: "numeric", + }), + ), + ); + const month = el("div", "", "pm-month"); + for (const label of ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]) + month.append(el("div", label, "pm-day-heading")); + for (let i = 0; i < 42; i++) { + const day = addDays(start, i), + cell = el( + "div", + "", + `pm-month-day${day.slice(0, 7) !== anchor.slice(0, 7) ? " pm-outside" : ""}`, + ); + const add = button(day.slice(-2), () => + openEditor(undefined, { due: { date: day } }), + ); + add.title = `Create task due ${day}`; + add.setAttribute("aria-label", add.title); + if (day === localDay()) add.classList.add("pm-today"); + cell.append(add, entries(day)); + month.append(cell); + } + wrap.append(month); + } else { + const count = period === "week" ? 7 : 1, + start = + count === 7 + ? addDays(anchor, -new Date(`${anchor}T12:00:00`).getDay()) + : anchor; + const scroller = el("div", "", "pm-hours-scroll"), + hours = el("div", "", "pm-hours"); + hours.style.setProperty("--days", String(count)); + const labels = el("div", "", "pm-hour-labels"); + labels.append(el("div", "Time", "pm-hour-heading")); + for (let hour = 0; hour < 24; hour++) + labels.append( + el("div", `${String(hour).padStart(2, "0")}:00`, "pm-hour-label"), + ); + hours.append(labels); + for (let i = 0; i < count; i++) { + const day = addDays(start, i), + column = el("div", "", "pm-hour-day"), + heading = el("div", "", "pm-hour-heading"); + heading.append(el("strong", shortDate(day))); + for (const task of tasks.filter((task) => task.due?.date === day)) { + const event = button(`◆ ${task.title}`, () => openEditor(task)); + applyTaskColor(event, task); + heading.append(event); + } + const grid = el("div", "", "pm-hour-grid"); + for (let hour = 0; hour < 24; hour++) { + const slot = button("", () => { + const from = new Date( + `${day}T${String(hour).padStart(2, "0")}:00:00`, + ); + openEditor(undefined, { + sessions: [ + { + id: crypto.randomUUID(), + start: from.toISOString(), + end: new Date(from.getTime() + 3_600_000).toISOString(), + timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, + }, + ], + }); + }); + slot.className = "pm-hour-slot"; + slot.setAttribute("aria-label", `Create session ${day} ${hour}:00`); + grid.append(slot); + } + const events = entries(day, true); + grid.append(events); + if (day === localDay()) { + const now = new Date(), + line = el("div", "", "pm-now"); + line.style.top = `${(now.getHours() + now.getMinutes() / 60) * 52}px`; + grid.append(line); + } + column.append(heading, grid); + hours.append(column); + } + scroller.append(hours); + wrap.append(scroller); + } + return wrap; + } + function addExisting() { + if (activeDialog || busy) return; + closePopup?.(); + const dialog = el("dialog", "", "pm-editor pm-note-picker"); + activeDialog = dialog; + dialog.setAttribute("aria-label", "Add existing note"); + const form = el("form"), + searchLabel = el("label", "Find a note or card", "pm-field"), + searchInput = el("input"), + results = el("div", "", "pm-note-results rs-picker"), + summary = el("p", "Loading notes…", "pm-note-summary"), + label = el("label", "Workspace note path", "pm-field"), + input = el("input"); + searchInput.type = "search"; + searchInput.placeholder = "Search by title or path"; + searchLabel.append(searchInput); + summary.setAttribute("aria-live", "polite"); + results.setAttribute("role", "group"); + results.setAttribute("aria-label", "Matching notes and cards"); + input.placeholder = "Notes/My task.md"; + input.required = true; + label.append(input); + let candidates: { path: string; title: string }[] = []; + let loading = true; + let scanError = ""; + const updateSelection = () => { + submit.disabled = busy || !input.value.trim(); + for (const row of results.querySelectorAll("button")) + { const selected = String(row.dataset.path === input.value.trim()); row.setAttribute("aria-pressed", selected); row.setAttribute("aria-current", selected); } + }; + const showResults = () => { + const query = searchInput.value.trim().toLocaleLowerCase(); + const matches = candidates.filter(({ title, path }) => + `${title} ${path}`.toLocaleLowerCase().includes(query), + ); + results.replaceChildren(); + for (const note of matches.slice(0, 100)) { + const row = button("", () => { + input.value = note.path; + error.textContent = ""; + updateSelection(); + }, "note"); + row.className = "pm-note-result rs-picker-row"; + row.querySelector(".pm-icon")?.classList.add("rs-picker-icon"); + row.disabled = busy; + row.dataset.path = note.path; + const text = el("span", "", "pm-note-result-text"); + text.append(el("span", note.title), el("span", + isHiddenCard(note.path) ? "Private card" : note.path, + "pm-note-path rs-picker-hint")); + row.append(text); + results.append(row); + } + summary.textContent = loading ? "Loading notes…" : scanError || + (matches.length > 100 ? `${matches.length} matches. First 100 shown. Refine your search.` : + matches.length ? `${matches.length} ${matches.length === 1 ? "match" : "matches"}. Choose a note, then select Add note.` : + query ? "No matching notes. Change the search or enter a path below." : + "No notes found. Enter a workspace note path below."); + updateSelection(); + }; + searchInput.oninput = showResults; + input.oninput = () => { error.textContent = ""; updateSelection(); }; + searchInput.onkeydown = (event) => { + if (event.key === "ArrowDown") { + event.preventDefault(); + results.querySelector("button")?.focus(); + } + if (event.key === "Enter") event.preventDefault(); + }; + results.onkeydown = (event) => { + const rows = [...results.querySelectorAll("button")]; + const index = rows.indexOf(document.activeElement as HTMLButtonElement); + if (index < 0) return; + const next = event.key === "ArrowDown" ? Math.min(index + 1, rows.length - 1) : + event.key === "ArrowUp" ? Math.max(index - 1, 0) : + event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : -1; + if (next >= 0) { event.preventDefault(); rows[next].focus(); } + }; + const error = el("p", "", "pm-error"); + error.role = "alert"; + const submit = button("Add note", () => {}, "plus"), + cancel = button("Cancel", () => { if (!busy) dialog.close(); }), + actions = el("div", "", "pm-editor-actions"); + submit.type = "submit"; + submit.classList.add("pm-primary"); + submit.disabled = true; + actions.append(cancel, submit); + form.append( + el("h2", "Add an existing note"), + searchLabel, + summary, + results, + label, + error, + actions, + ); + dialog.append(form); + root.append(dialog); + dialog.showModal(); + searchInput.focus(); + dialog.oncancel = (event) => { + if (busy) event.preventDefault(); + }; + dialog.onclose = () => { + activeDialog = undefined; + dialog.remove(); + render(); + root.querySelector('[aria-label="More actions"]')?.focus({ preventScroll: true }); + }; + void markdownPaths(store.workspace, () => { + if (closed || !dialog.isConnected) throw new Error("The note picker is closed."); + }).then((paths) => { + const tasks = new Map(store.tasks.map((task) => [task.path, task.title])); + const boards = new Set([...store.boards, ...store.legacyBoards].map((board) => board.path)); + candidates = [...new Set([...paths, ...tasks.keys()])] + .filter((path) => !boards.has(path)) + .map((path) => ({ path, title: tasks.get(path) ?? path.split("/").at(-1)!.replace(/\.(md|markdown|mdown)$/i, "") })) + .sort((a, b) => a.title.localeCompare(b.title) || a.path.localeCompare(b.path)); + }).catch(() => { + scanError = "Could not list notes. Enter a workspace note path below."; + }).finally(() => { + loading = false; + if (!closed && dialog.isConnected) showResults(); + }); + form.onsubmit = async (event) => { + event.preventDefault(); + if (busy || !input.value.trim()) return; + error.textContent = ""; + for (const control of form.querySelectorAll("input, button")) control.disabled = true; + form.setAttribute("aria-busy", "true"); + const ok = await perform( + async () => { await store.adopt(input.value.trim()); }, + "Note added.", + ); + if (closed || !dialog.isConnected) return; + form.removeAttribute("aria-busy"); + for (const control of form.querySelectorAll("input, button")) control.disabled = false; + updateSelection(); + if (ok) dialog.close(); + else error.textContent = message; + }; + } + /** The legacy data of the workspace, when the migration has data to copy. */ + let legacyOffer: LegacyContent | undefined; + let legacyDismissed = false; + /** The original files after a migration. The user removes them after a check. */ + let migrated: OriginalFile[] | undefined; + function legacyNotice() { + const section = el("section", "", "pm-onboarding pm-migration"); + if (migrated) { + section.setAttribute("aria-label", "Migration complete"); + section.append(el("h2", "Migration complete"), el("p", migrated.length + ? "Project Management copied the data to hidden storage. The original files stay unchanged. Check the boards, then remove these originals:" + : "Project Management copied the data to hidden storage.")); + if (migrated.length) { + const list = el("ul"); + for (const file of migrated) list.append(el("li", file.path)); + section.append(list); + } + section.append(button("Done", () => { migrated = undefined; legacyOffer = undefined; render(); }, "check")); + return section; + } + const content = legacyOffer!; + const parts = [ + ...content.boards.length ? [content.boards.length === 1 ? "1 board" : `${content.boards.length} boards`] : [], + ...content.cards.length ? [content.cards.length === 1 ? "1 task note" : `${content.cards.length} task notes`] : [], + ...content.labels ? ["the label file runestone-pm-labels.json"] : [], + ]; + section.setAttribute("aria-label", "Migrate Project Management data"); + section.append(el("h2", "Migrate Project Management data"), + el("p", `This workspace has Project Management data in visible files${parts.length ? `: ${parts.join(", ")}` : ""}. Project Management now reads only hidden storage in .runestone/pm. The migration copies the data there with exact backups. The original files stay unchanged.`)); + if (content.invalid.length) + section.append(el("p", `${content.invalid.length === 1 ? "1 note has" : `${content.invalid.length} notes have`} invalid Project Management properties: ${content.invalid.join(", ")}. Repair them before the migration.`)); + const actions = el("div", "", "pm-popup-actions"); + const migrate = button("Migrate", () => { + void perform(async () => { + migrated = await options.legacy!.migrate(); + legacyOffer = undefined; + await store.reload(); + }, "Migration complete."); + }); + migrate.classList.add("pm-primary"); + actions.append(migrate, button("Not now", () => { legacyDismissed = true; render(); })); + section.append(actions); + return section; + } + function render() { + Object.assign(state, { view, period, anchor, search, showArchived, searchOpen }); + options.stateChanged?.(); + if (closed || activeDialog || closePopup) return; + stopAutoScroll(); + // Host tabs retain their mounts while hidden. Replacing hidden scroll nodes loses their position. + if (!root.getClientRects().length) { + renderPending = true; + return; + } + renderPending = false; + const focusedDraft = document.activeElement instanceof HTMLTextAreaElement && + document.activeElement.closest(".pm-card-composer")?.parentElement?.closest(".rs-pm") === root + ? { start: document.activeElement.selectionStart, end: document.activeElement.selectionEnd } + : undefined; + const previousBoard = + view === "kanban" ? root.querySelector(".pm-board") : null; + const boardScroll = previousBoard + ? { left: previousBoard.scrollLeft, top: previousBoard.scrollTop } + : undefined; + const scrollParents: { node: HTMLElement; left: number; top: number }[] = + []; + if (boardScroll) + for (let node: HTMLElement | null = root; node; node = node.parentElement) + scrollParents.push({ + node, + left: node.scrollLeft, + top: node.scrollTop, + }); + const visibleIds = new Set(filtered().map(task => task.id)); + for (const id of selectedCards) if (!visibleIds.has(id)) selectedCards.delete(id); + root.replaceChildren(background); + const header = el("header", "", "pm-toolbar"), + tabs = el("nav", "", "pm-tabs"); + tabs.setAttribute("aria-label", "Project Management views"); + for (const tab of ["kanban", "gantt", "calendar"] as const) { + const control = iconButton( + tab[0].toUpperCase() + tab.slice(1), tab, + () => { + if (view !== tab) { + cardDraft = undefined; + cardDrafts.clear(); + } + selectionMode = false; selectedCards.clear(); + view = tab; + remember(); + render(); + }, + ); + control.setAttribute("aria-pressed", String(view === tab)); + tabs.append(control); + } + header.append(tabs); + const canRenameBoard = store.board.editable && + Boolean(options.renameBoard || isManagedBoard(store.board.reference!.path)); + const titleArea = el("div", "", "pm-title-area"); + const title = el( + "span", + store.board.name + (showArchived ? " · Archived" : ""), + "pm-view-title", + ); + if (canRenameBoard) { + const rename = button("", () => renameBoardForm(rename), "rename"); + rename.classList.add("pm-board-rename"); + rename.setAttribute("aria-label", `Rename board: ${store.board.name}`); + rename.setAttribute("aria-haspopup", "dialog"); + tooltip(rename, "Rename board"); + if (!options.openBoard && !options.openAll) rename.prepend(title); + titleArea.append(rename); + } else if (!options.openBoard && !options.openAll) titleArea.append(title); + header.append(titleArea); + if (options.openBoard || options.openAll) { + const scope = button("", () => { + boardMenu?.close(); + const bounds = scope.getBoundingClientRect(); + const open = (path: string) => void perform(async () => { + if (path) await options.openBoard?.(path, true); + else await options.openAll?.(true); + }, "View opened."); + boardMenu = options.ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: "Board scope", items: [ + { label: "All tasks", checked: !store.board.reference, radio: true, run: () => open("") }, + ...store.boards.map(board => ({ label: board.name + (board.archived ? " (archived)" : "") + (isManagedBoard(board.path) ? "" : " · " + board.path), checked: board.path === store.board.reference?.path, radio: true, run: () => open(board.path) })), + ] }); + }, "down"); + scope.classList.add("pm-scope"); + scope.append(el("span", store.board.name, "pm-scope-label")); + scope.setAttribute("aria-label", `Board scope: ${store.board.name}`); + scope.setAttribute("aria-haspopup", "menu"); + scope.onkeydown = event => { if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); scope.click(); } }; + titleArea.prepend(scope); + } + const actions = el("div", "", "pm-toolbar-actions"); + if (view === "kanban") { + const select = iconButton(selectionMode ? "Finish selection" : "Select cards", "select", () => { selectionMode = !selectionMode; selectedCards.clear(); render(); root.querySelector(".pm-select-mode")?.focus(); }); + select.classList.add("pm-select-mode"); select.setAttribute("aria-pressed", String(selectionMode)); actions.append(select); + } + const labels = iconButton("Manage labels", "tag", () => manageLabels()); + labels.disabled = store.labels.source === undefined; + actions.append(labels); + if (view === "kanban" && store.board.editable) { + const add = iconButton("Add a list", "circlePlus", () => listForm(add)); + actions.append(add); + } else if (view !== "kanban") + actions.append(iconButton("New card", "note", () => openEditor())); + const searchButton = iconButton("Search tasks", "search", () => { + searchOpen = !searchOpen; + render(); + if (searchOpen) + root.querySelector("input[type=search]")?.focus(); + }); + searchButton.setAttribute("aria-pressed", String(searchOpen)); + actions.append(searchButton); + const more = iconButton("More actions", "more", () => + popup(more, "More actions", (panel, close) => { + panel.classList.add("pm-menu"); + if (options.openBoard && store.workspace.create) + panel.append( + button("New board", () => { + close(); + renameBoardForm(more, true); + }, "circlePlus"), + ); + if ( + store.board.reference && + isManagedBoard(store.board.reference.path) && + store.board.available + ) + panel.append( + button( + store.board.archived ? "Restore board" : "Archive board", + () => { + close(); + void perform( + () => + store.changeBoard(() => + store.board.manage({ archived: !store.board.archived }), + ), + "Board archive state saved.", + ); + }, + "archive", + ), + ); + if (store.board.reference && store.board.available) + panel.append( + button("Delete board", () => { + close(); + deleteBoardForm(more); + }, "trash"), + ); + if (canRenameBoard) + panel.append( + button("Rename board", () => { + close(); + renameBoardForm(more); + }, "rename"), + ); + panel.append( + button("New card", () => { + close(); + openEditor(); + }, "note"), + button("Add existing note", () => { + close(); + addExisting(); + }, "link"), + button(showArchived ? "Show active" : "Show archived", () => { + close(); + showArchived = !showArchived; + render(); + }, "archive"), + button("Refresh", () => { + close(); + void perform(() => store.reload(), "Tasks reloaded."); + }, "refresh"), + ); + panel.append(button("Customize background", () => { close(); customizeBackground(more); }, "image")); + panel.append(button("Project Management settings", () => { + close(); popup(more, "Project Management settings", panel => { + // The same component as Settings → Project Management. + panel.classList.add("pm-settings-popup"); + const component = mountComponent(ProjectManagementSettings, { target: panel, props: { compact: true } }); + return () => { void unmountComponent(component); }; + }); + }, "list")); + }), + ); + actions.append(more); + header.append(actions); + root.append(header); + if (!store.board.reference && !store.boards.some(board => !board.archived) && options.openBoard && store.workspace.create) { + const welcome = el("section", "", "pm-onboarding"); + welcome.setAttribute("aria-label", "Create your first board"); + const create = button("Create your first board", () => renameBoardForm(create, true), "circlePlus"); + welcome.append(el("h2", "Create your first board"), el("p", "Use a board to organize cards and move them between lists."), create); + root.append(welcome); + } + if (migrated || (legacyOffer && !legacyDismissed)) root.append(legacyNotice()); + if (selectionMode) root.append(selectionToolbar()); + if (searchOpen || search) { + const field = el("div", "", "pm-search-row"), + find = el("input"); + find.type = "search"; + find.placeholder = "Search tasks, labels, and tags"; + find.setAttribute("aria-label", "Search tasks"); + find.value = search; + find.oninput = () => { + search = find.value; + render(); + root.querySelector("input[type=search]")?.focus(); + }; + field.append(find); + root.append(field); + } + const notice = el( + "div", + message, + failed ? "pm-error pm-notice" : "pm-sr-only", + ); + notice.setAttribute("role", failed ? "alert" : "status"); + root.append(notice); + if (store.issues.length) { + const details = el("details", "", "pm-issues"); + details.append( + el("summary", store.issues.length + " notes need attention"), + ); + for (const issue of store.issues) details.append(el("p", issue)); + root.append(details); + } + void applyBackground(); + const tasks = filtered(); + if (search && !tasks.length) + root.append(el("p", "No tasks match this search.", "pm-muted pm-empty")); + root.append( + view === "kanban" + ? kanban(tasks) + : view === "gantt" + ? gantt(tasks) + : calendar(tasks), + ); + if (restoring && message === "Workspace loaded.") { + restoring = false; + root.querySelector(".pm-board")?.scrollTo({ ...state.boardScroll, behavior: "instant" }); + scrollContainer().scrollTop = state.scrollTop ?? 0; + } else if (boardScroll) { + root.querySelector(".pm-board")?.scrollTo({ + ...boardScroll, + behavior: "instant", + }); + for (const { node, left, top } of scrollParents) + node.scrollTo({ left, top, behavior: "instant" }); + } + if (focusedDraft) { + const title = root.querySelector(".pm-card-composer textarea"); + title?.focus({ preventScroll: true }); + title?.setSelectionRange(focusedDraft.start, focusedDraft.end); + } + } + root.addEventListener("mousedown", startAutoScroll); + root.addEventListener("auxclick", preventAutoScrollClick); + document.addEventListener("mousedown", outsideAutoScroll); + document.addEventListener("mousemove", moveAutoScroll); + document.addEventListener("mouseup", releaseAutoScroll); + window.addEventListener("keydown", dismissAutoScroll); + window.addEventListener("blur", stopAutoScroll); + root.addEventListener("wheel", scrollBoard, { passive: false }); + root.addEventListener("scroll", remember, true); + document.addEventListener("pointerdown", outsideCardComposer, true); + document.addEventListener("focusin", outsideCardComposer); + window.addEventListener("blur", hideCardComposer); + let composerFocusTimer: ReturnType | undefined; + const composerFocusOut = (event: FocusEvent) => { + if (event.relatedTarget) return; + clearTimeout(composerFocusTimer); + // Wait for the full focus transition, including controls inside the form. + composerFocusTimer = setTimeout(() => { + const form = root.querySelector(".pm-card-composer"); + if (!closed && form && !form.contains(document.activeElement)) hideCardComposer(); + }, 0); + }; + root.addEventListener("focusout", composerFocusOut); + const visibilityObserver = new ResizeObserver(() => { + positionBackground(); + if (!root.getClientRects().length) hideCardComposer(); + if (renderPending && root.getClientRects().length) render(); + }); + visibilityObserver.observe(root); + visibilityObserver.observe(container); + document.addEventListener("scroll", positionBackground, true); + window.addEventListener("resize", positionBackground); + render(); + void perform(() => store.reload(), "Workspace loaded."); + // Offer the migration when the workspace still has data in the legacy format. Nothing migrates without a choice. + void options.legacy?.find().then(content => { + if (closed || !options.legacy!.has(content)) return; + legacyOffer = content; + if (!busy) render(); + }, () => undefined); + let refreshTimer: ReturnType | undefined; + let refreshing = false; + const sameDocuments = ( + before: { path: string; source: string }[], + after: { path: string; source: string }[], + ) => + before.length === after.length && + before.every( + (document, index) => + document.path === after[index].path && + document.source === after[index].source, + ); + /** The changed paths since the last refresh. Null when a change had no paths, so everything reads again. */ + let pendingPaths: Set | null = new Set(); + const refresh = (paths?: readonly string[]) => { + if (!paths) pendingPaths = null; + else if (pendingPaths) for (const path of paths) pendingPaths.add(path); + clearTimeout(refreshTimer); + refreshTimer = setTimeout(async () => { + if (closed) return; + if (busy || refreshing || activeDialog || closePopup || drag) { + refresh([]); + return; + } + const changedPaths = pendingPaths; + pendingPaths = new Set(); + refreshing = true; + const before = { + tasks: store.tasks, + boards: store.boards, + issues: store.issues, + labels: store.labels.source, + labelError: store.labels.error, + boardAvailable: store.board.available, + }; + let changed = false; + try { + await store.reloadPaths(changedPaths ? [...changedPaths] : undefined); + changed = + !sameDocuments(before.tasks, store.tasks) || + !sameDocuments(before.boards, store.boards) || + before.labels !== store.labels.source || + before.labelError !== store.labels.error || + before.boardAvailable !== store.board.available || + before.issues.length !== store.issues.length || + before.issues.some((issue, index) => issue !== store.issues[index]); + } catch (error) { + changed = true; + if (!closed) + notify(error instanceof Error ? error.message : String(error), true); + } finally { + refreshing = false; + if (changed && !busy && !drag) render(); + } + }, 150); + }; + // The host watcher reports the changed files of `.runestone/pm/`, also from other windows and programs. + const unsubscribe = options.watch ? options.watch(refresh) : store.workspace.subscribe?.(() => refresh()); + return () => { + if (closed) return; + remember(); + closed = true; + disposeTooltips(); + backgroundWatcher.dispose(); + backgroundFade?.cancel(); + clearTimeout(refreshTimer); + clearTimeout(composerFocusTimer); + unsubscribe?.(); + window.removeEventListener("blur", hideCardComposer); + document.removeEventListener("pointerdown", outsideCardComposer, true); + document.removeEventListener("focusin", outsideCardComposer); + root.removeEventListener("focusout", composerFocusOut); + visibilityObserver.disconnect(); + document.removeEventListener("scroll", positionBackground, true); + window.removeEventListener("resize", positionBackground); + root.removeEventListener("scroll", remember, true); + stopAutoScroll(); + root.removeEventListener("mousedown", startAutoScroll); + root.removeEventListener("auxclick", preventAutoScrollClick); + document.removeEventListener("mousedown", outsideAutoScroll); + document.removeEventListener("mousemove", moveAutoScroll); + document.removeEventListener("mouseup", releaseAutoScroll); + window.removeEventListener("keydown", dismissAutoScroll); + window.removeEventListener("blur", stopAutoScroll); + root.removeEventListener("wheel", scrollBoard); + clearDrag(); + document.removeEventListener("dragover", movePreview); + document.removeEventListener("dragend", clearDrag); + document.removeEventListener("drop", clearDrag); + closePopup?.(); + boardMenu?.close(); + sharedChoices.dispose(); + disposeEditor?.(); + store.dispose(); + activeDialog?.remove(); + root.remove(); + style.remove(); + }; +} diff --git a/src/lib/features/pm/views.ts b/src/lib/features/pm/views.ts new file mode 100644 index 0000000..5c8afc7 --- /dev/null +++ b/src/lib/features/pm/views.ts @@ -0,0 +1,21 @@ +// The view IDs of Project Management. They are the same as in the plugin, so saved tab states and tab transfers between +// the plugin and the feature keep their boards. The catalog (`../catalog.ts`) has the same board pattern. + +/** All tasks, or the default board when the ribbon button opens it. */ +export const PLANNING = "planning"; +const BOARD_VIEW = /^board-((?:[0-9a-f]{2})+)$/; + +/** The view ID of a board: `board-` and the UTF-8 bytes of the board ID in hexadecimal. */ +export function boardViewId(id: string): string { + return "board-" + Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join(""); +} + +/** The board ID of a board view ID, or null for another view. */ +export function boardOfView(view: string): string | null { + const hex = BOARD_VIEW.exec(view)?.[1]; + if (!hex) return null; + try { + const id = new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(hex.match(/../g)!, pair => parseInt(pair, 16))); + return id.trim() && boardViewId(id) === view ? id : null; + } catch { return null; } +} diff --git a/src/lib/features/pm/workspace.ts b/src/lib/features/pm/workspace.ts new file mode 100644 index 0000000..171c358 --- /dev/null +++ b/src/lib/features/pm/workspace.ts @@ -0,0 +1,27 @@ +// The workspace of the storage code (`model/model.ts`), on the host workspace commands of this window. +// Writes and creations tell the other views of this window at once. The file watcher reports the same paths later, +// also for changes from other windows and programs. +import { invoke } from "@tauri-apps/api/core"; +import { workspaceList, workspaceRead, workspaceReadMany, workspaceWrite } from "../../workspace/api.ts"; +import { notifyPluginWorkspace } from "../../plugins/external.ts"; +import type { Workspace } from "./model/model.ts"; + +/** A workspace with a subscription that reports the changed paths. */ +export interface FeatureWorkspace extends Workspace { + /** Run `listener` after each change. `paths` is undefined when the change is unknown. */ + watch(listener: (paths?: readonly string[]) => void): () => void; +} + +export function hostWorkspace(onChange: (listener: (paths?: readonly string[]) => void) => () => void): FeatureWorkspace { + return { + list: path => workspaceList(path ?? ""), + listMarkdown: () => invoke("workspace_list_markdown"), + read: workspaceRead, + readMany: workspaceReadMany, + readOptional: path => invoke("workspace_read", { rel: path, missingOk: true }), + write: async (path, contents, expected) => { await workspaceWrite(path, contents, expected); notifyPluginWorkspace([path]); }, + create: async (path, contents) => { await invoke("workspace_create", { rel: path, kind: "file", contents }); notifyPluginWorkspace([path]); }, + subscribe: listener => onChange(() => listener()), + watch: onChange, + }; +} diff --git a/src/lib/features/pmBoards.ts b/src/lib/features/pmBoards.ts new file mode 100644 index 0000000..663cafb --- /dev/null +++ b/src/lib/features/pmBoards.ts @@ -0,0 +1,72 @@ +// The board list of Project Management, read from `.runestone/pm/workspace.json` without the feature code. +// Appearance → Background lists the boards for its targets, and Settings → Project Management chooses the default board. +// It reads JSON only. The feature code (`src/lib/features/pm/storage/catalog.ts`) owns the full format and validation. +import { invoke } from "@tauri-apps/api/core"; +import { workspaceWrite } from "../workspace/api.ts"; + +export const BOARD_CATALOG_PATH = ".runestone/pm/workspace.json"; + +export interface BoardSummary { + id: string; + name: string; + archived: boolean; +} + +export interface BoardCatalog { + /** The boards in the order of the file. */ + boards: BoardSummary[]; + /** The board that opens first, or null for All tasks. */ + defaultBoardId: string | null; + /** The file text, or null when the file does not exist. */ + source: string | null; +} + +/** Reads one workspace file, or gives null when the file does not exist. */ +export type ReadOptional = (path: string) => Promise; +/** Replaces one workspace file when its text is still `expected`. */ +export type WriteExpected = (path: string, contents: string, expected: string) => Promise; + +const desktopRead: ReadOptional = path => invoke("workspace_read", { rel: path, missingOk: true }); +const desktopWrite: WriteExpected = (path, contents, expected) => workspaceWrite(path, contents, expected); + +function record(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : null; +} + +/** The boards of the file text. A missing file has no boards. A damaged file throws. */ +export function parseBoardCatalog(source: string | null): BoardCatalog { + if (source === null) return { boards: [], defaultBoardId: null, source }; + const data = record(JSON.parse(source)); + if (!data || data.schema !== 1 || !Array.isArray(data.boards)) throw new Error("The Project Management storage format is unsupported."); + const boards: BoardSummary[] = []; + for (const row of data.boards) { + const board = record(row), value = record(board?.value); + if (!board || !value || typeof value.id !== "string" || !value.id.trim() || typeof board.name !== "string") continue; + if (boards.some(item => item.id === value.id)) continue; + boards.push({ id: value.id, name: board.name.trim() || value.id, archived: board.archived === true }); + } + return { boards, defaultBoardId: typeof data.defaultBoardId === "string" ? data.defaultBoardId : null, source }; +} + +/** Read the board list of the workspace of this window. */ +export async function readBoardCatalog(read: ReadOptional = desktopRead): Promise { + return parseBoardCatalog(await read(BOARD_CATALOG_PATH)); +} + +/** + * Save the default board of the workspace: a board ID, or null for All tasks. Other keys of the file stay. + * The write fails when another window changed the file after the read. + */ +export async function writeDefaultBoard(id: string | null, read: ReadOptional = desktopRead, write: WriteExpected = desktopWrite): Promise { + const source = await read(BOARD_CATALOG_PATH); + const catalog = parseBoardCatalog(source); + if (source === null) { + if (id === null) return; + throw new Error("This board is unavailable. Refresh Project Management."); + } + if (id !== null && !catalog.boards.some(board => board.id === id)) throw new Error("This board is unavailable. Refresh Project Management."); + const data = JSON.parse(source) as Record; + data.defaultBoardId = id; + data.defaultBoardPath = id === null ? null : `pm-board:${id}`; + await write(BOARD_CATALOG_PATH, JSON.stringify(data, null, 2) + "\n", source); +} diff --git a/src/lib/features/pmSettings.ts b/src/lib/features/pmSettings.ts new file mode 100644 index 0000000..a29c4bd --- /dev/null +++ b/src/lib/features/pmSettings.ts @@ -0,0 +1,81 @@ +// The settings of the Project Management feature: the `projectManagement` section of the settings file, and the view +// state of each Project Management tab in localStorage. +// This file is in the main bundle, because Settings → Project Management and the first-start migration need it +// without the board interface code. +import { onSettingsChange, readSection, writeSection } from "../settings/store.ts"; +import type { LegacyPlugin } from "./migration.ts"; + +export type PriorityLevels = 2 | 3 | 5; +export const PRIORITY_LEVELS: readonly PriorityLevels[] = [2, 3, 5]; + +export interface ProjectManagementSettings { + /** The priority choices of a card: 2 (High and Low), 3 (High, Medium, and Low), or 5 (Highest through Lowest). */ + priorityLevels: PriorityLevels; +} + +export const DEFAULT_PROJECT_MANAGEMENT: Readonly = Object.freeze({ priorityLevels: 3 }); +/** + * The view state of each tab: the view, the period, the search, collapsed lists, and scroll positions. + * The keys are the view IDs, `planning` for All tasks and `board-` for a board. RuneStone can lose these values without harm. + */ +export const VIEW_STATES_KEY = "runestone.pm.viewStates"; + +function record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} + +/** Valid settings from any value. Invalid fields take the defaults. */ +export function normalizeProjectManagement(value: unknown): ProjectManagementSettings { + const levels = record(value).priorityLevels; + return { priorityLevels: levels === 2 || levels === 5 ? levels : 3 }; +} + +export function readProjectManagement(): ProjectManagementSettings { + return normalizeProjectManagement(readSection("projectManagement")); +} + +/** Save the settings. Keys of a newer version stay. */ +export function writeProjectManagement(next: ProjectManagementSettings): Promise { + return writeSection("projectManagement", { ...record(readSection("projectManagement")), ...normalizeProjectManagement(next) }); +} + +/** Run `listener` after each change of the settings in any window. Returns the function that stops it. */ +export function onProjectManagementChange(listener: () => void): () => void { + return onSettingsChange("projectManagement", listener); +} + +/** The saved view states. An unreadable value gives none. */ +export function readViewStates(storage: Pick = localStorage): Record { + try { return record(JSON.parse(storage.getItem(VIEW_STATES_KEY) ?? "null")); } catch { return {}; } +} + +/** Save the view states of some tabs. The other tabs keep their states. */ +export function writeViewStates(changes: Record, storage: Pick = localStorage): void { + try { storage.setItem(VIEW_STATES_KEY, JSON.stringify({ ...readViewStates(storage), ...changes })); } + catch { /* View state is harmless to lose. */ } +} + +/** The host side of the first-start migration of the `projectManagement` section and the view states. */ +export interface ProjectManagementMigrationHost { + /** True when the settings file has no `projectManagement` section. */ + missing(): boolean; + write(value: ProjectManagementSettings): Promise; + storage: Pick; +} + +/** + * Make the `projectManagement` section from the kept settings of the Project Management plugin + * (`plugin-data/runestone.pm/settings.json`), and copy its view states to localStorage when localStorage has none. + * The plugin files stay unchanged. Without a section to make, nothing is written. + */ +export async function migrateProjectManagement(legacy: LegacyPlugin | undefined, host: ProjectManagementMigrationHost): Promise { + if (!host.missing()) return null; + const kept = record(legacy?.settings); + const views = record(kept.viewStates); + try { + if (Object.keys(views).length && host.storage.getItem(VIEW_STATES_KEY) === null) host.storage.setItem(VIEW_STATES_KEY, JSON.stringify(views)); + } catch (reason) { console.error("RuneStone could not copy the Project Management view states.", reason); } + const value = normalizeProjectManagement(kept); + await host.write(value); + return value; +} diff --git a/src/lib/features/session.ts b/src/lib/features/session.ts index becd417..40df9bd 100644 --- a/src/lib/features/session.ts +++ b/src/lib/features/session.ts @@ -1,6 +1,7 @@ // A feature in the workbench of one window. Its views, commands, and document types come from the static catalog, so the // navigation buttons, the command palette, and the file tree show them without the feature code. The first mount, // restore, or action command loads the feature module and starts one instance for this window. +// A view pattern of the catalog makes a view for each matching ID on request (`patternView`), also before the module loads. // A launch rule (`launch.ts`) can also start the instance at once. import { tr } from "../i18n/index.ts"; import type { Dispose, PluginCommand, PluginDocumentContext, PluginDocumentType, PluginView } from "../plugins/sdk.ts"; @@ -18,6 +19,8 @@ export class FeatureSession { private load: () => Promise; private instance?: Promise; private ready?: FeatureInstance; + /** The IDs of the views that a view pattern made. Only these take a title from the feature. */ + private patterned = new Set(); constructor(entry: FeatureEntry, context: FeatureContext, load: () => Promise = () => loadFeature(entry.id)) { this.entry = entry; @@ -30,6 +33,10 @@ export class FeatureSession { mount: element => this.mountView(info.id, element), saveTabState: () => this.ready?.saveTabState?.(info.id), restoreTabState: async state => { await (await this.running()).restoreTabState?.(info.id, state); }, + ...info.launch ? { launch: async () => { + const instance = await this.running(); + if (instance.launch) await instance.launch(info.id); else context.openView(info.id); + } } : {}, }); } for (const info of entry.documentTypes) { @@ -46,6 +53,34 @@ export class FeatureSession { } } + /** + * The view with this ID: a catalog view, or a new editor view when a view pattern of the catalog matches the ID. + * A new view keeps the title of the pattern until the feature gives one. + */ + patternView(id: string): PluginView | undefined { + const existing = this.views.get(id); + if (existing || this.controller.signal.aborted) return existing; + const pattern = this.entry.viewPatterns?.find(item => item.match.test(id)); + if (!pattern) return undefined; + const view: PluginView = { + id, title: pattern.title(), placement: "editor", icon: pattern.icon, navigation: false, launcher: false, + mount: element => this.mountView(id, element), + saveTabState: () => this.ready?.saveTabState?.(id), + restoreTabState: async state => { await (await this.running()).restoreTabState?.(id, state); }, + }; + this.views.set(id, view); + this.patterned.add(id); + return view; + } + + /** Give a view of a view pattern its title. Returns true when the title changed. */ + setViewTitle(id: string, title: string): boolean { + const view = this.patterned.has(id) ? this.views.get(id) : this.patternView(id); + if (!view || !this.patterned.has(id) || !title.trim() || view.title === title) return false; + view.title = title; + return true; + } + /** The instance of this window. A failed load leaves no instance, so a later call tries again. */ private running(): Promise { if (this.controller.signal.aborted) return Promise.reject(new Error(tr("This feature is off."))); @@ -68,7 +103,7 @@ export class FeatureSession { /** Mount a view, or with `document`, a document of the document type `id`. */ async mount(id: string, element: HTMLElement, document?: PluginDocumentContext): Promise { - const view = document ? this.documentTypes.get(id) : this.views.get(id); + const view = document ? this.documentTypes.get(id) : this.patternView(id); if (!view) throw new Error(tr("This view is unavailable.")); const dispose = document ? await (view as PluginDocumentType).mount(element, document) : await (view as PluginView).mount(element, { surface: "view" }); return async () => { @@ -77,7 +112,11 @@ export class FeatureSession { }; } - async launch(id: string) { this.context.openView(id); } + async launch(id: string) { + const view = this.views.get(id); + if (view?.launch) await view.launch(); + else this.context.openView(id); + } /** Load the module and start the instance now, without a view. Later calls use the same instance. */ async start(): Promise { await this.running(); } diff --git a/src/lib/features/types.ts b/src/lib/features/types.ts index d4476a8..282aafc 100644 --- a/src/lib/features/types.ts +++ b/src/lib/features/types.ts @@ -6,8 +6,17 @@ export interface FeatureContext { openView(id: string): void; /** Open a workspace file in the editor. */ openFile(path: string): Promise; - /** Run `listener` after each change in the workspace. Returns the function that stops it. */ - onWorkspaceChange(listener: () => void): () => void; + /** + * Run `listener` after each change in the workspace. `paths` lists the changed workspace paths, also in `.runestone/`. + * Without `paths`, the change is unknown, and the feature reads its data again. Returns the function that stops it. + */ + onWorkspaceChange(listener: (paths?: readonly string[]) => void): () => void; + /** Give a view of a view pattern its title, for example the name of a board. Its tabs show the title. */ + setViewTitle(id: string, title: string): void; + /** Close the tabs of a view. */ + closeView(id: string): void; + /** Show the view `next` in the tab of the view `current`. The tab keeps its place and its pin. */ + replaceView(current: string, next: string): void; } /** One running copy of a feature in one window. */ @@ -18,6 +27,8 @@ export interface FeatureInstance { * The returned function removes the document and stops its work, for example a worker. */ mountDocument?(type: string, element: HTMLElement, document: PluginDocumentContext): Dispose | Promise; + /** Open a view with `launch` in the catalog. The feature chooses the view, for example the default board. */ + launch?(view: string): void | Promise; /** Run a command of the catalog that has no view. */ run?(command: string): void | Promise; /** The state of a tab for a transfer to another window. */ diff --git a/src/lib/i18n/messages.ts b/src/lib/i18n/messages.ts index 8858ed6..34dcffb 100644 --- a/src/lib/i18n/messages.ts +++ b/src/lib/i18n/messages.ts @@ -3681,6 +3681,9 @@ export const messageRows: [string, string, string, string][] = [ ["Cannot display this PDF. {reason}", "Impossible d’afficher ce PDF. {reason}", "この PDF を表示できません。{reason}", "无法显示此 PDF。{reason}"], // The native features without the desktop host. ["This feature needs the desktop app.", "Cette fonctionnalité nécessite l’application de bureau.", "この機能にはデスクトップアプリが必要です。", "此功能需要桌面应用。"], + // Project Management (src/lib/features/catalog.ts, PluginRibbon.svelte, SettingsDialog.svelte). Part B of stage 7-5 translates the board interface. + ["Project Management", "Project Management", "Project Management", "Project Management"], + ["Plan work on Kanban boards, in All tasks, and on Gantt and calendar views. The cards stay in the workspace.", "Planifiez le travail sur des tableaux Kanban, dans Toutes les tâches, et dans les vues Gantt et calendrier. Les cartes restent dans l’espace de travail.", "Kanban ボード、すべてのタスク、ガントビューとカレンダービューで作業を計画します。カードはワークスペースに保存されます。", "在看板、所有任务以及甘特图和日历视图中规划工作。卡片保存在工作区中。"], ]; export const catalogs: Record, Record> = { fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])), diff --git a/src/lib/layout/PluginRibbon.svelte b/src/lib/layout/PluginRibbon.svelte index 1e23ddc..539b836 100644 --- a/src/lib/layout/PluginRibbon.svelte +++ b/src/lib/layout/PluginRibbon.svelte @@ -1,11 +1,17 @@ \n\n[x](javascript:alert(1))\n\n![remote](https://example.com/tracker.png)\n\n![image](pm-image:12345678-1234-1234-1234-123456789abc)\n\n[safe](https://example.com)", + ); + assert.match(result, /

Heading<\/h1>/); + assert.match(result, /Bold<\/strong>/); + assert.doesNotMatch(result, / { + const coverImage = "12345678-1234-1234-1234-123456789abc"; + const subtasks = [{ id: "subtask", title: "Check the change", done: true }]; + const links = [{ taskId: "dependency", relation: "blocked-by" as const }]; + const note = newTask("Relationships", { ...fields, coverImage, subtasks, links }); + const task = readTask(note.path, note.source)!; + assert.deepEqual(task.subtasks, subtasks); assert.deepEqual(task.links, links); assert.equal(task.coverImage, coverImage); + const edited = readTask(note.path, editTask(task, { body: "Revised", priority: "lowest" }))!; + assert.deepEqual(edited.subtasks, subtasks); assert.deepEqual(edited.links, links); assert.equal(edited.coverImage, coverImage); + assert.throws(() => editTask(task, { coverImage: "../outside.png" }), /image/); + assert.throws(() => editTask(task, { subtasks: [...subtasks, ...subtasks] }), /unique ID/); + assert.throws(() => editTask(task, { links: [...links, ...links] }), /once/); +}); + +test("attachments round-trip independently of description edits and reject duplicate or invalid IDs", () => { + const attachments = [{ id: "12345678-1234-1234-1234-123456789abc", name: "Screenshot.png" }]; + const note = newTask("Attached image", { ...fields, attachments }, "Description"); + const task = readTask(note.path, note.source)!; + assert.deepEqual(task.attachments, attachments); + const changed = readTask(note.path, editTask(task, { body: "", status: "doing" }))!; + assert.deepEqual(changed.attachments, attachments); + assert.equal(changed.body, ""); + assert.deepEqual(readTask(note.path, editTask(changed, { attachments: [] }))!.attachments, []); + assert.throws(() => editTask(task, { attachments: [...attachments, ...attachments] }), /unique image ID/); + assert.throws(() => editTask(task, { attachments: [{ id: "../outside", name: "Image" }] }), /unique image ID/); +}); diff --git a/tests/unit/features/pm/card-fields.spec.ts b/tests/unit/features/pm/card-fields.spec.ts new file mode 100644 index 0000000..2748230 --- /dev/null +++ b/tests/unit/features/pm/card-fields.spec.ts @@ -0,0 +1,69 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts"; +import { validateFields, type TaskFields } from "../../../../src/lib/features/pm/model/model.ts"; + +const fields: TaskFields = { + status: "todo", + tags: [], + sessions: [], + archived: false, +}; + +test("optional card fields survive moves and can be removed without changing other note data", () => { + const note = newTask( + "Customer work", + { + ...fields, + color: "purple", + assignees: ["Alex", "Northwind"], + customFields: [ + { name: "Customer ID", value: "0012" }, + { name: "Contact", value: "hello@example.test" }, + ], + }, + "Keep **these details**.\n", + ); + const source = note.source.replace( + " schema: 1", + " extra: keep-me # future property\n schema: 1", + ); + const task = readTask(note.path, source)!; + assert.equal(task.color, "purple"); + assert.deepEqual(task.assignees, ["Alex", "Northwind"]); + assert.equal(task.customFields?.[0].value, "0012"); + const moved = readTask( + note.path, + editTask(task, { status: "done", listId: "done" }), + )!; + assert.deepEqual(moved.customFields, task.customFields); + assert.equal(moved.color, "purple"); + const cleared = editTask(moved, { + color: undefined, + assignees: [], + customFields: [], + }); + assert.ok(cleared.includes("extra: keep-me # future property")); + assert.equal(readTask(note.path, cleared)!.body, task.body); + assert.equal(readTask(note.path, cleared)!.color, undefined); + assert.deepEqual(readTask(note.path, cleared)!.customFields, []); +}); + +test("invalid optional fields and duplicate names cannot enter saved notes", () => { + for (const patch of [ + { color: "url(bad)" }, + { assignees: "Alex" }, + { assignees: [1] }, + { customFields: [null] }, + { customFields: [{ name: "", value: "x" }] }, + { + customFields: [ + { name: "ID", value: "1" }, + { name: " id ", value: "2" }, + ], + }, + ]) + assert.throws(() => validateFields({ ...fields, ...patch } as TaskFields)); + const old = newTask("Basic", fields); + assert.equal(readTask(old.path, old.source)!.color, undefined); +}); diff --git a/tests/unit/features/pm/card-workflow.spec.ts b/tests/unit/features/pm/card-workflow.spec.ts new file mode 100644 index 0000000..c785283 --- /dev/null +++ b/tests/unit/features/pm/card-workflow.spec.ts @@ -0,0 +1,296 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts"; +import { adoptNote, editTask, newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts"; +import { cardOrder, orderBetween } from "../../../../src/lib/features/pm/storage/order.ts"; +import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts"; +import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts"; +import type { TaskFields, Workspace } from "../../../../src/lib/features/pm/model/model.ts"; + +const fields: TaskFields = { + status: "todo", + tags: [], + sessions: [], + archived: false, +}; +function fixture() { + const board = newBoardSource(); + const files = new Map([["Board.md", board]]); + const reads: string[] = [], + lists: string[] = [], + writes: string[] = []; + const workspace: Workspace = { + async readOptional(path) { + return files.get(path) ?? null; + }, + async list(parent = "") { + lists.push(parent); + const entries = new Map(); + for (const path of files.keys()) { + const prefix = parent ? parent + "/" : ""; + if (!path.startsWith(prefix)) continue; + const parts = path.slice(prefix.length).split("/"); + entries.set(parts[0], { + name: parts[0], + rel_path: prefix + parts[0], + kind: parts.length > 1 ? "folder" : "file", + }); + } + return [...entries.values()]; + }, + async read(path) { + reads.push(path); + if (!files.has(path)) throw new Error("Missing note"); + return files.get(path)!; + }, + async write(path, source, expected) { + assert.equal(files.get(path), expected); + writes.push(path); + files.set(path, source); + }, + async create(path, source) { + if (files.has(path)) throw new Error("Exists"); + files.set(path, source); + }, + }; + const reference = { id: parseBoard(board).id, path: "Board.md" }; + return { + files, + reads, + lists, + writes, + workspace, + reference, + store: new TaskStore(workspace, reference), + }; +} + +test("card creation reads one board and does not scan unrelated notes after loading", async () => { + const { store, files, lists, reads } = fixture(); + for (let index = 0; index < 300; index++) + files.set(`Archive/Note ${index}.md`, "Plain note"); + await store.reload(); + lists.length = reads.length = 0; + await store.create("New card", fields, "Details"); + assert.deepEqual(lists, []); + assert.deepEqual(reads, ["Board.md"]); + assert.equal(store.scopedTasks[0].title, "New card"); + assert.equal(store.scopedTasks[0].body, "Details"); + await store.create("New card", fields, "Second"); + assert.equal(store.scopedTasks.length, 2); + assert.equal(store.scopedTasks[0].body, "Details"); +}); + +test("creation checks the current list before writing a card", async () => { + const { store, files } = fixture(); + await store.reload(); + await store.board.remove("todo"); + const snapshot = new Map(files); + await assert.rejects( + store.create("Missing list", { ...fields, listId: "todo" }, ""), + /list no longer exists/, + ); + assert.deepEqual(files, snapshot); + assert.equal(store.tasks.length, 0); +}); + +test("a background scan cannot replace a newly created card with an older snapshot", async () => { + const { store, workspace } = fixture(); + await store.reload(); + const list = workspace.list; + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + workspace.list = async (path) => { + const snapshot = await list(path); + await gate; + return snapshot; + }; + const pending = store.reload(); + await store.create("Keep new card", fields, ""); + release(); + await pending; + assert.deepEqual( + store.scopedTasks.map((task) => task.title), + ["Keep new card"], + ); +}); + +test("title edits preserve the filename, identity, metadata, and body", async () => { + const { store, files } = fixture(); + await store.create("Original", fields, "Keep **Markdown**.\n"); + const original = store.tasks[0]; + files.set( + original.path, + original.source.replace("---\n", "---\nowner: Ada # keep\n"), + ); + await store.reload(); + await store.save(store.tasks[0], { title: "Edited: title / shared" }); + const updated = store.tasks[0]; + assert.equal(updated.title, "Edited: title / shared"); + assert.equal(updated.id, original.id); + assert.equal(updated.path, original.path); + assert.equal(updated.body, original.body); + assert.match(updated.source, /owner: Ada # keep/); + assert.equal([...files.keys()].filter(isHiddenCard).length, 1); + await store.reload(); + assert.equal(store.tasks[0].title, updated.title); + await assert.rejects(store.save(original, { title: "Stale" }), /changed/); + await assert.rejects( + store.save(store.tasks[0], { title: " " }), + /card title/, + ); + assert.equal(readTask(original.path, original.source)!.title, "Original"); +}); + +test("legacy notes with long filenames remain editable before a card title is set", () => { + const path = "Long existing note ".repeat(8).trim() + ".md"; + const source = adoptNote(path, "Existing description"); + const task = readTask(path, source)!; + assert.equal(task.title, path.slice(0, -3)); + const edited = readTask(path, editTask(task, { status: "doing" }))!; + assert.equal(edited.title, task.title); + assert.equal(edited.status, "doing"); +}); + +test("cards retain insertion order and can move before, between, and after other cards", async () => { + const { store, workspace, reference, writes } = fixture(); + for (const name of ["Zulu", "Alpha", "Middle"]) + await store.create(name, fields, ""); + const names = () => store.cardsInList("todo").map((task) => task.title); + const task = (title: string) => + store.tasks.find((task) => task.title === title)!; + assert.deepEqual(names(), ["Zulu", "Alpha", "Middle"]); + await store.save(task("Middle"), { status: "done" }); + const middle = task("Middle"); + writes.length = 0; + await store.moveTask(middle, "todo", task("Zulu").id); + assert.deepEqual(writes, [middle.path]); + assert.equal(task("Middle").status, "done"); + assert.deepEqual(names(), ["Middle", "Zulu", "Alpha"]); + await store.moveTask(task("Alpha"), "todo", task("Zulu").id); + assert.deepEqual(names(), ["Middle", "Alpha", "Zulu"]); + await store.moveTask(task("Middle"), "todo", null); + assert.deepEqual(names(), ["Alpha", "Zulu", "Middle"]); + await store.save(task("Zulu"), { + title: "A renamed card", + listId: "todo", + tags: ["release"], + }); + const reopened = new TaskStore(workspace, reference); + await reopened.reload(); + assert.deepEqual( + reopened.cardsInList("todo").map((task) => task.title), + ["Alpha", "A renamed card", "Middle"], + ); +}); + +test("card order stays independent in each board and All tasks", async () => { + const { store, files, workspace, reference } = fixture(); + const secondSource = newBoardSource(); + files.set("Second.md", secondSource); + const second = new TaskStore(workspace, { + id: parseBoard(secondSource).id, + path: "Second.md", + }); + for (const name of ["Alpha", "Beta", "Gamma"]) { + await store.create( + name, + { ...fields, due: { date: "2026-10-08" } }, + "Shared details", + ); + await second.adopt(store.tasks.find((task) => task.title === name)!.path); + } + await store.reload(); + const gamma = store.tasks.find((task) => task.title === "Gamma")!; + const secondPlacement = gamma.placements![second.board.reference!.id]; + await store.moveTask( + gamma, + "todo", + store.tasks.find((task) => task.title === "Alpha")!.id, + ); + await second.reload(); + assert.deepEqual( + second.cardsInList("todo").map((task) => task.title), + ["Alpha", "Beta", "Gamma"], + ); + assert.deepEqual( + second.tasks.find((task) => task.id === gamma.id)!.placements![ + second.board.reference!.id + ], + secondPlacement, + ); + const all = new TaskStore(workspace); + await all.reload(); + await all.moveTask(all.tasks[1], "todo", all.tasks[0].id); + assert.deepEqual( + all.cardsInList("todo").map((task) => task.title), + ["Beta", "Alpha", "Gamma"], + ); + await store.reload(); + assert.deepEqual( + store.cardsInList("todo").map((task) => task.title), + ["Gamma", "Alpha", "Beta"], + ); + await store.moveTask(store.cardsInList("todo")[0], "done", null); + const moved = store.cardsInList("done")[0]; + assert.equal(moved.status, "done"); + assert.deepEqual(moved.due, { date: "2026-10-08" }); + assert.equal(moved.body, "Shared details"); + assert.equal(moved.placements![reference.id].listId, "done"); +}); + +test("failed or stale order writes keep card data intact", async () => { + const { store, workspace, files } = fixture(); + await store.create("Alpha", fields, ""); + await store.create("Beta", fields, ""); + const [alpha, beta] = store.cardsInList("todo"); + const snapshot = new Map(files); + workspace.write = async () => { + throw new Error("Disk failure"); + }; + await assert.rejects(store.moveTask(beta, "todo", alpha.id), /Disk failure/); + assert.deepEqual(files, snapshot); + assert.deepEqual( + store.cardsInList("todo").map((task) => task.title), + ["Alpha", "Beta"], + ); + await assert.rejects( + store.moveTask(beta, "todo", "missing"), + /target card moved/, + ); + files.set(beta.path, editTask(beta, { body: "External change" })); + await assert.rejects(store.moveTask(beta, "todo", alpha.id), /changed/); +}); + +test("ordering handles repeated narrow gaps, legacy notes, and matching saved ranks", () => { + let upper = "j"; + for (let index = 0; index < 1200; index++) { + const rank = orderBetween("i", upper); + assert.ok("i" < rank && rank < upper); + assert.match(rank, /^[0-9a-z]*[1-9a-z]$/); + upper = rank; + } + const alphaNote = newTask( + "Alpha", + fields, + "", + "00000000-0000-4000-8000-000000000001", + ); + const betaNote = newTask( + "Beta", + fields, + "", + "00000000-0000-4000-8000-000000000002", + ); + const alpha = readTask(alphaNote.path, alphaNote.source)!; + const beta = readTask(betaNote.path, betaNote.source)!; + assert.ok(cardOrder(alpha) < cardOrder(beta)); + assert.equal(cardOrder(alpha), cardOrder({ ...alpha, title: "Zulu" })); + alpha.order = beta.order = "i"; + const between = orderBetween(cardOrder(alpha), cardOrder(beta)); + const inserted = cardOrder({ ...alpha, id: "new", order: between }); + assert.ok(cardOrder(alpha) < inserted && inserted < cardOrder(beta)); + assert.throws(() => editTask(alpha, { order: "invalid!" }), /order/); +}); diff --git a/tests/unit/features/pm/core.spec.ts b/tests/unit/features/pm/core.spec.ts new file mode 100644 index 0000000..f598a64 --- /dev/null +++ b/tests/unit/features/pm/core.spec.ts @@ -0,0 +1,198 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readTask, editTask, newTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts"; +import { + addDays, + dayDistance, + validDate, + type Workspace, + type TaskFields, +} from "../../../../src/lib/features/pm/model/model.ts"; +import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts"; +import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts"; + +const fields: TaskFields = { + status: "todo", + tags: [], + sessions: [], + archived: false, +}; +function memory(initial: Record = {}) { + const files = new Map(Object.entries(initial)); + const workspace: Workspace = { + async readOptional(path) { + return files.get(path) ?? null; + }, + async list(parent = "") { + const entries = new Map(); + for (const path of files.keys()) { + const prefix = parent ? `${parent}/` : ""; + if (!path.startsWith(prefix)) continue; + const parts = path.slice(prefix.length).split("/"); + entries.set(parts[0], { + name: parts[0], + rel_path: `${prefix}${parts[0]}`, + kind: parts.length > 1 ? "folder" : "file", + }); + } + return [...entries.values()]; + }, + async read(path) { + const text = files.get(path); + if (text === undefined) throw Error("Missing file"); + return text; + }, + async write(path, text, expected) { + assert.equal(files.get(path), expected, "Changed on disk"); + files.set(path, text); + }, + async create(path, text) { + if (files.has(path)) throw Error("Exists"); + files.set(path, text); + }, + }; + return { workspace, files }; +} + +test("tasks round trip with a stable ID, description, deadline, plan, and sessions", () => { + const note = newTask( + "Launch", + { + ...fields, + due: { date: "2026-10-30" }, + plan: { start: "2026-10-05", end: "2026-10-31" }, + sessions: [ + { + id: "session-1", + start: "2026-10-08T16:00:00Z", + end: "2026-10-08T17:00:00Z", + timeZone: "America/Vancouver", + }, + ], + }, + "Keep **Markdown**.\n", + ); + const task = readTask(note.path, note.source)!; + const moved = readTask(note.path, editTask(task, { status: "doing" }))!; + assert.equal(moved.id, task.id); + assert.equal(moved.body, task.body); + assert.deepEqual(moved.plan, task.plan); + assert.deepEqual(moved.sessions, task.sessions); + assert.deepEqual(moved.due, task.due); + assert.equal(moved.status, "doing"); +}); +test("metadata edits preserve unknown properties, comments, and the exact body", () => { + const source = + '\uFEFF---\r\nowner: Ada # keep this\r\nrunestone_pm:\r\n schema: 1\r\n id: stable\r\n kind: task\r\n status: todo # workflow\r\n future: {value: 12}\r\n plan:\r\n start: "2026-10-04"\r\n end: "2026-10-08"\r\n custom: untouched\r\n---\r\n# Body\r\n\r\n- [ ] Keep spacing \r\n'; + const original = readTask("Note.md", source)!; + const next = editTask(original, { + status: "doing", + plan: { start: "2026-10-05", end: "2026-10-09" }, + }); + assert.equal(readTask("Note.md", next)!.body, original.body); + assert.match(next, /owner: Ada # keep this/); + assert.match(next, /# workflow/); + assert.match(next, /future:/); + assert.match(next, /custom: untouched/); + assert.ok(next.startsWith("\uFEFF")); + assert.ok(!/(? { + const source = "---\ncategory: reference\n---\nOriginal body\n"; + const adopted = adoptNote("Existing.md", source), + task = readTask("Existing.md", adopted)!; + assert.equal(task.body, "Original body\n"); + assert.match(adopted, /category: reference/); + assert.equal(adoptNote("Existing.md", adopted), adopted); +}); +test("unsupported metadata and invalid dates are rejected without rewriting a note", () => { + const note = newTask("Task", fields); + assert.throws( + () => readTask(note.path, note.source.replace("schema: 1", "schema: 2")), + /unsupported/, + ); + assert.throws( + () => + readTask( + note.path, + note.source.replace("status: todo", "status: unknown"), + ), + /status/, + ); + assert.throws( + () => + editTask(readTask(note.path, note.source)!, { + due: { date: "2026-02-30" }, + }), + /deadline/, + ); + assert.throws( + () => adoptNote("Bad.md", "---\nkey: 1\nkey: 2\n---\nBody"), + /YAML/, + ); + assert.throws(() => newTask("../escape", fields), /name/); + assert.throws(() => newTask("CON", fields), /name/); + assert.throws( + () => + newTask("Task", { + ...fields, + plan: { start: "2026-10-10", end: "2026-10-09" }, + }), + /end/, + ); +}); +test("date arithmetic preserves whole dates over leap years and daylight-saving boundaries", () => { + assert.equal(addDays("2024-02-28", 1), "2024-02-29"); + assert.equal(addDays("2026-12-31", 1), "2027-01-01"); + assert.equal(dayDistance("2026-03-07", "2026-03-09"), 2); + assert.equal(dayDistance("2026-10-31", "2026-11-02"), 2); + assert.equal(validDate("2026-02-29"), false); +}); +test("save and reload use one note, and archive retains its file", async () => { + const { files, workspace } = memory(); + const store = new TaskStore(workspace); + await store.create("Launch", fields, "Description"); + assert.equal([...files.keys()].filter(isHiddenCard).length, 1); + const original = store.tasks[0]; + await store.save(original, { status: "done", archived: true }); + const reopened = new TaskStore(workspace); + await reopened.reload(); + assert.equal(reopened.tasks[0].id, original.id); + assert.equal(reopened.tasks[0].status, "done"); + assert.equal(reopened.tasks[0].archived, true); + assert.equal([...files.keys()].filter(isHiddenCard).length, 1); +}); +test("stale edits cannot overwrite external changes", async () => { + const { workspace, files } = memory(); + const store = new TaskStore(workspace); + await store.create("Task", fields, "Original"); + const original = store.tasks[0]; + const external = editTask(original, { body: "External change" }); + files.set(original.path, external); + await assert.rejects(store.save(original, { status: "done" }), /changed/); + assert.equal(files.get(original.path), external); +}); +test("duplicate identities are excluded and blocked even when introduced after reload", async () => { + const note = newTask("Task", fields); + const { workspace, files } = memory({ [note.path]: note.source }); + const store = new TaskStore(workspace); + await store.reload(); + const original = store.tasks[0]; + files.set("Copy.md", note.source); + await assert.rejects(store.save(original, { status: "done" }), /duplicate/); + assert.equal(store.tasks.length, 0); + assert.match(store.issues[0], /Duplicate/); + assert.equal(files.get(note.path), note.source); +}); +test("duplicate card titles preserve both cards and disposal blocks new writes", async () => { + const { workspace, files } = memory(); + const store = new TaskStore(workspace); + await store.create("Task", fields, "Original"); + const first = store.tasks[0]; + await store.create("Task", fields, "Second card"); + assert.equal(store.tasks.length, 2); + assert.equal(files.get(first.path), first.source); + assert.equal(new Set(store.tasks.map((task) => task.id)).size, 2); + store.dispose(); + await assert.rejects(store.create("Later", fields, ""), /closed/); +}); diff --git a/tests/unit/features/pm/deleted-cards.spec.ts b/tests/unit/features/pm/deleted-cards.spec.ts new file mode 100644 index 0000000..d836816 --- /dev/null +++ b/tests/unit/features/pm/deleted-cards.spec.ts @@ -0,0 +1,63 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts"; +import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts"; +import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts"; +import { migrateCards } from "../../../../src/lib/features/pm/storage/cards.ts"; +import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts"; + +function fixture() { + const note = newTask("Delete me", { status: "todo", tags: [], sessions: [], archived: false, + placements: { first: { listId: "todo" }, second: { listId: "doing" } } }, "Keep this source"); + const task = readTask("Delete me.md", note.source)!; + const parent = newTask("Related", { status: "todo", tags: [], sessions: [], archived: false, + links: [{ taskId: task.id, relation: "relates" }], subtasks: [{ id: "sub", taskId: task.id, title: task.title, done: false }] }, ""); + const files = new Map([[task.path, note.source], ["Related.md", parent.source]]); + let fail = false; + const workspace: Workspace = { + async list(folder = "") { return [...files.keys()].filter(path => folder ? path.startsWith(`${folder}/`) : !path.startsWith(".")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); }, + async read(path) { if (!files.has(path)) throw Error("Missing"); return files.get(path)!; }, + async readOptional(path) { return files.get(path) ?? null; }, + async create(path, source) { if (fail || files.has(path)) throw Error("Write failed"); files.set(path, source); }, + async write(path, source, expected) { if (fail) throw Error("Write failed"); assert.equal(files.get(path), expected); files.set(path, source); }, + }; + return { task, files, workspace, setFailure() { fail = true; } }; +} + +test("confirmed deletion removes legacy and migrated cards from all scopes and retains source records", async () => { + for (const migrate of [false, true]) { + const { workspace, files, task } = fixture(); + if (migrate) await migrateCards(workspace, [task]); + const store = new TaskStore(workspace); await store.reload(); + const before = new Map(files); + await store.deleteCard(store.tasks.find(item => item.id === task.id)!); + assert.deepEqual(store.tasks.map(item => item.title), ["Related"]); + for (const [path, source] of before) assert.equal(files.get(path), source); + assert.deepEqual(JSON.parse(files.get(deletedCardsPath)!).ids, [task.id]); + const fresh = new TaskStore(workspace); await fresh.reload(); + assert.equal(fresh.tasks.some(item => item.id === task.id), false); + await assert.rejects(fresh.openSubtask(fresh.tasks[0].id, "sub"), /unavailable/); + assert.equal(fresh.tasks[0].links![0].taskId, task.id); + await assert.rejects(fresh.save(task, { archived: false }), /changed|duplicate/); + } +}); + +test("stale cards and failed deletion writes preserve the card", async () => { + const stale = fixture(); const store = new TaskStore(stale.workspace); await store.reload(); + stale.files.set(stale.task.path, stale.task.source + "External edit\n"); + await assert.rejects(store.deleteCard(stale.task), /changed/); + assert.equal(stale.files.has(deletedCardsPath), false); + const failed = fixture(); const next = new TaskStore(failed.workspace); await next.reload(); + failed.setFailure(); await assert.rejects(next.deleteCard(failed.task), /Write failed/); + await next.reload(); assert.equal(next.tasks.length, 2); +}); + +test("damaged deletion records block card access instead of restoring deleted cards", async () => { + const { workspace, files } = fixture(); + for (const source of ['{', '{"schema":2,"ids":[]}', '{"schema":1,"ids":[4]}']) { + files.set(deletedCardsPath, source); + const store = new TaskStore(workspace); await store.reload(); + assert.equal(store.tasks.length, 0); + assert.ok(store.issues.some(issue => issue.startsWith("Deleted cards:"))); + } +}); diff --git a/tests/unit/features/pm/description-format.spec.ts b/tests/unit/features/pm/description-format.spec.ts new file mode 100644 index 0000000..17d8322 --- /dev/null +++ b/tests/unit/features/pm/description-format.spec.ts @@ -0,0 +1,31 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { headingEdit } from "../../../../src/lib/features/pm/model/description-format.ts"; + +function apply(value: string, start: number, end = start) { + const edit = headingEdit(value, start, end); + return { value: value.slice(0, edit.start) + edit.text + value.slice(edit.end), start: edit.selectionStart, end: edit.selectionEnd }; +} + +test("Heading formats the caret line and preserves the caret inside its text", () => { + assert.deepEqual(apply("Before\nTyped text\nAfter", 12), { value: "Before\n## Typed text\nAfter", start: 15, end: 15 }); + assert.deepEqual(apply("Typed text", 0), { value: "## Typed text", start: 3, end: 3 }); + assert.deepEqual(apply("Typed text", 10), { value: "## Typed text", start: 13, end: 13 }); +}); + +test("Heading preserves selected text and formats all selected lines", () => { + assert.deepEqual(apply("One line\nTwo lines\nLast", 2, 12), { value: "## One line\n## Two lines\nLast", start: 5, end: 18 }); + assert.deepEqual(apply("One\nTwo", 0, 4), { value: "## One\nTwo", start: 3, end: 7 }); +}); + +test("Heading changes an existing heading without duplicate markers", () => { + assert.deepEqual(apply("# Title", 7), { value: "## Title", start: 8, end: 8 }); + assert.deepEqual(apply("## Title", 5), { value: "## Title", start: 5, end: 5 }); + assert.deepEqual(apply("### Title", 1), { value: "## Title", start: 3, end: 3 }); +}); + +test("Heading leaves the caret after the marker on empty lines", () => { + assert.deepEqual(apply("", 0), { value: "## ", start: 3, end: 3 }); + assert.deepEqual(apply("Text\n", 5), { value: "Text\n## ", start: 8, end: 8 }); + assert.deepEqual(apply("\nText", 0), { value: "## \nText", start: 3, end: 3 }); +}); diff --git a/tests/unit/features/pm/images.spec.ts b/tests/unit/features/pm/images.spec.ts new file mode 100644 index 0000000..17f3ee5 --- /dev/null +++ b/tests/unit/features/pm/images.spec.ts @@ -0,0 +1,107 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + imageMarkdown, + imageReferences, + imagePath, + parseImage, + saveImages, + maxImageBytes, +} from "../../../../src/lib/features/pm/storage/images.ts"; +import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts"; +const id = "12345678-1234-1234-1234-123456789abc"; +const data = "data:image/png;base64,aGVsbG8="; + +test("image references preserve surrounding text and restrict private paths", () => { + const markdown = imageMarkdown("shot [one]\n\\test.png", id); + assert.equal(markdown, `![shot one test.png](pm-image:${id})`); + const body = `Before\n${markdown}\nAfter`; + assert.deepEqual(imageReferences(body), [ + { id, name: "shot one test.png", markdown, index: 7 }, + ]); + assert.deepEqual( + imageReferences( + "![remote](https://example.com/a.png) ![bad](pm-image:../../secret)", + ), + [], + ); + assert.throws(() => imagePath("../../secret"), /invalid/); +}); +test("saved image data rejects unsupported and executable sources", () => { + assert.equal(parseImage(JSON.stringify({ schema: 1, data })), data); + for (const value of [ + null, + {}, + { schema: 1, data: "https://example.com/image.png" }, + { schema: 1, data: "data:image/svg+xml;base64,PHN2Zz4=" }, + { schema: 1, data: "data:image/png;base64,***=" }, + ]) + assert.throws(() => parseImage(JSON.stringify(value))); + assert.throws( + () => parseImage("x".repeat(Math.ceil(maxImageBytes / 3) * 4 + 257)), + /50 MiB/, + ); +}); +test("save writes only referenced images, protects existing files, and permits retry", async () => { + const files = new Map(); + const writes: string[] = []; + const workspace: Workspace = { + async list() { + return []; + }, + async read(path) { + return files.get(path)!; + }, + async readOptional(path) { + return files.get(path) ?? null; + }, + async create(path, source) { + if (files.has(path)) throw new Error("Already exists"); + files.set(path, source); + writes.push(path); + }, + async write() { + throw new Error("Unexpected overwrite"); + }, + }; + const pending = new Map([ + [id, data], + ["87654321-1234-1234-1234-123456789abc", data], + ]); + const body = imageMarkdown("Screenshot", id); + await saveImages(workspace, body, pending); + assert.deepEqual(writes, [".runestone/pm/.gitignore", imagePath(id)]); + await saveImages(workspace, body, pending); + assert.equal(writes.length, 2); + files.set(imagePath(id), "other image"); + await assert.rejects(saveImages(workspace, body, pending), /Already exists/); + assert.equal(files.get(imagePath(id)), "other image"); +}); + +test("attachment metadata saves staged images without description references", async () => { + const files = new Map(); + const workspace: Workspace = { + async list() { return []; }, + async read(path) { return files.get(path)!; }, + async readOptional(path) { return files.get(path) ?? null; }, + async create(path, source) { files.set(path, source); }, + async write() { throw new Error("Unexpected overwrite"); }, + }; + await saveImages(workspace, "", new Map([[id, data]]), [{ id, name: "Attachment.png" }]); + assert.equal(parseImage(files.get(imagePath(id))!), data); +}); + +test("image storage accepts exactly 50 MiB and rejects one extra byte", async () => { + assert.equal(maxImageBytes, 50 * 1024 * 1024); + const data = `data:image/png;base64,${Buffer.alloc(maxImageBytes).toString("base64")}`; + const files = new Map(); + const workspace: Workspace = { + async list() { return []; }, async read(path) { return files.get(path)!; }, async readOptional(path) { return files.get(path) ?? null; }, + async write() { throw new Error("Unexpected overwrite"); }, + async create(path, source) { files.set(path, source); }, + }; + await saveImages(workspace, "", new Map([[id, data]]), [{ id, name: "large.png" }]); + assert.equal(parseImage(files.get(imagePath(id))!), data); + const tooLarge = `data:image/png;base64,${Buffer.alloc(maxImageBytes + 1).toString("base64")}`; + assert.throws(() => parseImage(JSON.stringify({ schema: 1, data: tooLarge })), /50 MiB/); +}); diff --git a/tests/unit/features/pm/labels.spec.ts b/tests/unit/features/pm/labels.spec.ts new file mode 100644 index 0000000..5fc6be2 --- /dev/null +++ b/tests/unit/features/pm/labels.spec.ts @@ -0,0 +1,364 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + defaultLabels, + labelsPath, + parseLabels, + validateLabels, +} from "../../../../src/lib/features/pm/storage/labels.ts"; +import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts"; +import { editTask, newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts"; +import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts"; +import { + validateFields, + type TaskFields, + type Workspace, +} from "../../../../src/lib/features/pm/model/model.ts"; + +const fields: TaskFields = { + status: "todo", + tags: [], + sessions: [], + archived: false, +}; +function fixture() { + const files = new Map(); + const writes: string[] = []; + const workspace: Workspace = { + async list() { + return [...files.keys()].map((path) => ({ + name: path.split("/").at(-1)!, + rel_path: path, + kind: "file", + })); + }, + async read(path) { + if (!files.has(path)) throw new Error("Missing file"); + return files.get(path)!; + }, + async readOptional(path) { + return files.get(path) ?? null; + }, + async create(path, source) { + if (files.has(path)) throw new Error("File already exists"); + files.set(path, source); + writes.push(path); + }, + async write(path, source, expected) { + if (files.get(path) !== expected) throw new Error("File changed"); + files.set(path, source); + writes.push(path); + }, + }; + return { files, writes, workspace, store: new TaskStore(workspace) }; +} + +test("old notes and custom tags remain independent of saved labels", () => { + const note = newTask( + "Task", + { ...fields, tags: ["customer, success"], color: "pink" }, + "Keep **details**.\n", + ); + const source = note.source.replace("---\n", "---\nowner: Ada # keep\n"); + const old = readTask(note.path, source)!; + assert.equal(old.labels, undefined); + const labeled = readTask( + note.path, + editTask(old, { labels: ["bug", "feature", "missing-label"] }), + )!; + assert.deepEqual(labeled.labels, ["bug", "feature", "missing-label"]); + const moved = readTask(note.path, editTask(labeled, { status: "doing" }))!; + assert.deepEqual(moved.labels, labeled.labels); + const cleared = readTask(note.path, editTask(moved, { labels: [] }))!; + assert.deepEqual(cleared.labels, []); + assert.deepEqual(cleared.tags, old.tags); + assert.equal(cleared.color, old.color); + assert.equal(cleared.body, old.body); + assert.match(cleared.source, /owner: Ada # keep/); + for (const labels of [null, "bug", [1], [""], ["bug", "bug"], ["bad id"]]) + assert.throws( + () => validateFields({ ...fields, labels } as TaskFields), + /label IDs/, + ); +}); + +test("one catalog serves every board and renames leave task files unchanged", async () => { + const { files, workspace, writes } = fixture(); + const first = newBoardSource(), + second = newBoardSource(); + files.set("First.md", first); + files.set("Second.md", second); + const a = new TaskStore(workspace, { + id: parseBoard(first).id, + path: "First.md", + }); + const b = new TaskStore(workspace, { + id: parseBoard(second).id, + path: "Second.md", + }); + await a.reload(); + assert.deepEqual(a.labels.value, defaultLabels()); + assert.equal(files.has(labelsPath), false); + await a.create( + "Shared label", + { ...fields, labels: ["bug"] }, + "Keep details.", + ); + const task = a.tasks[0]; + await a.saveLabels( + [ + ...a.labels.value, + { id: "review", name: " Needs review ", color: "purple" }, + ], + a.labels.source, + ); + await b.reload(); + assert.equal(b.labels.value.at(-1)!.name, "Needs review"); + assert.deepEqual(b.tasks[0].labels, ["bug"]); + const changed = b.labels.value.map((label) => + label.id === "bug" + ? { ...label, name: "Defect", color: "orange" as const, archived: true } + : label, + ); + writes.length = 0; + await b.saveLabels(changed, b.labels.source); + await a.reload(); + assert.deepEqual(writes, [labelsPath]); + assert.equal(a.labels.value[0].name, "Defect"); + assert.equal(a.labels.value[0].color, "orange"); + assert.equal(a.labels.value[0].archived, true); + assert.equal(files.get(task.path), task.source); +}); + +test("expanded palette colors persist in cards and shared labels", async () => { + const { store, workspace } = fixture(); + const colors = [ + "amber", + "lime", + "teal", + "cyan", + "indigo", + "magenta", + "brown", + "slate", + "gray", + ] as const; + await store.reload(); + await store.saveLabels( + [ + ...defaultLabels(), + ...colors.map((color) => ({ id: color, name: color, color })), + ], + store.labels.source, + ); + for (const color of colors) + await store.create( + `Palette ${color}`, + { ...fields, color, labels: [color] }, + "Keep these details.", + ); + const reopened = new TaskStore(workspace); + await reopened.reload(); + for (const color of colors) { + const task = reopened.tasks.find( + (task) => task.title === `Palette ${color}`, + )!; + assert.equal(task.color, color); + assert.deepEqual(task.labels, [color]); + assert.equal(task.body, "Keep these details."); + assert.equal( + reopened.labels.value.find((label) => label.id === color)!.color, + color, + ); + } +}); + +test("catalog validation blocks duplicate names, bad colors, IDs, and archive states", () => { + for (const labels of [ + null, + {}, + [null], + [{ id: "bug", name: "Bug", color: "url(bad)" }], + [{ id: "bug", name: "\nBug", color: "red" }], + [{ id: "bug", name: " ", color: "red" }], + [{ id: "bug", name: "Bug", color: "red", archived: "yes" }], + [ + ...defaultLabels(), + { id: "other", name: " BUG ", color: "blue", archived: true }, + ], + [...defaultLabels(), { id: "bug", name: "Another", color: "blue" }], + ]) + assert.throws(() => validateLabels(labels)); + assert.throws(() => parseLabels('{"schema":2,"labels":[]}'), /schema/); + assert.throws(() => parseLabels("broken json"), /saved labels file/); + assert.deepEqual(parseLabels('{"schema":1,"labels":[]}').labels, []); +}); + +test("concurrent catalog creation and stale edits cannot replace newer labels", async () => { + const { store, workspace, files } = fixture(); + const other = new TaskStore(workspace); + await store.reload(); + await other.reload(); + await store.saveLabels(defaultLabels(), store.labels.source); + const created = files.get(labelsPath); + await assert.rejects( + other.saveLabels(defaultLabels(), other.labels.source), + /already exists/, + ); + assert.equal(files.get(labelsPath), created); + await other.reload(); + const expected = other.labels.source; + await store.saveLabels( + store.labels.value.map((label) => ({ ...label, archived: true })), + store.labels.source, + ); + const updated = files.get(labelsPath); + await assert.rejects(other.saveLabels(defaultLabels(), expected), /changed/); + assert.equal(files.get(labelsPath), updated); + await store.reload(); + await store.saveLabels([], store.labels.source); + assert.deepEqual(store.labels.value, []); +}); + +test("catalog read failures and invalid files leave task editing available without overwriting the catalog", async () => { + const { store, files, workspace } = fixture(); + const task = newTask("Keep task", { ...fields, labels: ["unknown"] }); + files.set(task.path, task.source); + files.set(labelsPath, "invalid json"); + await store.reload(); + assert.equal(store.tasks.length, 1); + assert.match(store.issues.join(" "), /Saved labels/); + assert.equal(store.labels.source, undefined); + await assert.rejects(store.saveLabels(defaultLabels(), null), /unavailable/); + await store.save(store.tasks[0], { status: "done" }); + assert.equal(files.get(labelsPath), "invalid json"); + assert.deepEqual(store.tasks[0].labels, ["unknown"]); + workspace.readOptional = async () => { + throw new Error("Permission denied"); + }; + await store.reload(); + assert.match(store.issues.join(" "), /Permission denied/); + await assert.rejects(store.saveLabels(defaultLabels(), null), /unavailable/); +}); + +test("catalog writes preserve unknown metadata and propagate filesystem errors", async () => { + const { store, files, workspace } = fixture(); + const source = JSON.stringify({ + schema: 1, + future: { keep: true }, + labels: defaultLabels().map((label) => ({ ...label, extra: "keep" })), + }); + files.set(labelsPath, source); + await store.reload(); + await store.saveLabels(store.labels.value, store.labels.source); + const data = JSON.parse(files.get(labelsPath)!); + assert.deepEqual(data.future, { keep: true }); + assert.equal(data.labels[0].extra, "keep"); + const before = files.get(labelsPath); + workspace.write = async () => { + throw new Error("Disk full"); + }; + await assert.rejects( + store.saveLabels(defaultLabels(), store.labels.source), + /Disk full/, + ); + assert.equal(store.labels.source, before); + assert.equal(files.get(labelsPath), before); +}); + +test("a pending scan cannot replace saved label edits", async () => { + const { store, workspace } = fixture(); + await store.reload(); + let release!: () => void, entered!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const started = new Promise((resolve) => { + entered = resolve; + }); + const read = workspace.readOptional!; + let blocked = false; + workspace.readOptional = async (path) => { + if (path !== labelsPath || blocked) return read(path); + blocked = true; + const source = await read(path); + entered(); + await gate; + return source; + }; + const pending = store.reload(); + await started; + await store.saveLabels( + [...defaultLabels(), { id: "new", name: "New label", color: "pink" }], + null, + ); + release(); + await pending; + assert.equal(store.labels.value.at(-1)!.id, "new"); + assert.notEqual(store.labels.source, null); +}); + +test("older workspaces can read catalogs through listing but cannot create without create support", async () => { + const { store, workspace, files } = fixture(); + delete workspace.readOptional; + delete workspace.create; + await store.reload(); + await assert.rejects( + store.saveLabels(defaultLabels(), null), + /Update RuneStone/, + ); + files.set(labelsPath, JSON.stringify({ schema: 1, labels: defaultLabels() })); + await store.reload(); + assert.deepEqual(store.labels.value, defaultLabels()); + store.dispose(); + await assert.rejects( + store.saveLabels(defaultLabels(), store.labels.source), + /closed/, + ); +}); + +test("deleting labels clears active, archived, unlisted, and shared cards while preserving unrelated data", async () => { + const { store, files, workspace } = fixture(); + for (let index = 0; index < 4; index++) { + const task = newTask(`Card ${index}`, { + ...fields, archived: index === 1, labels: ["bug", "feature", "unknown"], tags: ["bug"], + placements: index === 2 ? {} : { a: { listId: "todo", order: "m" }, b: { listId: null } }, + }, "Keep **body**."); + files.set(task.path, task.source); + } + await store.reload(); + await store.saveLabels(store.labels.value.filter(label => label.id !== "bug"), store.labels.source); + const reopened = new TaskStore(workspace); + await reopened.reload(); + assert.equal(reopened.tasks.length, 4); + for (const task of reopened.tasks) { + assert.deepEqual(task.labels, ["feature", "unknown"]); + assert.deepEqual(task.tags, ["bug"]); + assert.equal(task.body, "Keep **body**."); + } + assert.equal(reopened.tasks[1].archived, true); + assert.deepEqual(reopened.tasks[0].placements, { a: { listId: "todo", order: "m" }, b: { listId: null } }); + assert.equal(reopened.labels.value.some(label => label.id === "bug"), false); +}); + +test("failed label deletion keeps definitions and allows guarded retry", async () => { + const { store, files, workspace } = fixture(); + for (const name of ["A", "B"]) { + const task = newTask(name, { ...fields, labels: ["bug"] }, "Keep body"); + files.set(task.path, task.source); + } + await store.reload(); + const next = store.labels.value.filter(label => label.id !== "bug"); + const write = workspace.write; + workspace.write = async (path, source, expected) => { + if (path === store.tasks.find(task => task.title === "B")!.path) throw new Error("Disk full"); + return write(path, source, expected); + }; + await assert.rejects(store.saveLabels(next, store.labels.source), /Disk full/); + assert.equal(store.labels.value.some(label => label.id === "bug"), true); + assert.deepEqual(store.tasks.find(task => task.title === "B")!.labels, ["bug"]); + workspace.write = write; + await store.saveLabels(next, store.labels.source); + await store.reload(); + assert.equal(store.tasks.every(task => !task.labels?.includes("bug")), true); +}); diff --git a/tests/unit/features/pm/legacy-offer.spec.ts b/tests/unit/features/pm/legacy-offer.spec.ts new file mode 100644 index 0000000..e4b73b9 --- /dev/null +++ b/tests/unit/features/pm/legacy-offer.spec.ts @@ -0,0 +1,118 @@ +// The legacy format: the native feature finds visible boards, task notes, and the root label file, and offers the +// migration. The migration of the offer is the migration of the plugin, with its backups. +import test from "node:test"; +import assert from "node:assert/strict"; +import { findLegacy, hasLegacy, mentionsProjectData } from "../../../../src/lib/features/pm/storage/legacy.ts"; +import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts"; +import { boardMarkdown, catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts"; +import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts"; +import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts"; +import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts"; +import { labelsPath, legacyLabelsPath } from "../../../../src/lib/features/pm/storage/labels.ts"; +import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts"; +import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts"; +import { fields, hiddenWorkspace, memoryWorkspace } from "./_memory.ts"; + +const labels = JSON.stringify({ schema: 1, labels: [{ id: "bug", name: "Bug", color: "red" }] }); + +test("only notes that name runestone_pm in their properties count as Project Management data", () => { + assert.equal(mentionsProjectData("---\nrunestone_pm:\n kind: task\n---\n"), true); + assert.equal(mentionsProjectData(String.fromCharCode(0xfeff) + "---\r\ntitle: x\r\nrunestone_pm: {}\r\n---\r\n"), true); + assert.equal(mentionsProjectData("# Plan\nrunestone_pm: in the body\n"), false); + assert.equal(mentionsProjectData("---\ntitle: x\n---\nrunestone_pm: in the body\n"), false); + assert.equal(mentionsProjectData("---\nother_runestone_pm: x\n---\n"), false); +}); + +test("an empty workspace or a migrated workspace has nothing to offer", async () => { + assert.equal(hasLegacy(await findLegacy(memoryWorkspace({ "Notes/Plain.md": "# Plain\n" }))), false); + const workspace = hiddenWorkspace([{ id: "hidden", title: "Hidden" }]); + assert.deepEqual(await findLegacy(workspace), { boards: [], cards: [], invalid: [], labels: false }); +}); + +test("visible boards, task notes, and the root label file are found without a parse of plain notes", async () => { + const board = defaultBoard("visible-board"); + const workspace = memoryWorkspace({ + "Boards/Plan.md": boardMarkdown(board), + "Tasks/Write.md": newTask("Write", fields(), "Body", "write").source, + "Notes/Plain.md": "---\ntitle: [broken yaml\n---\nPlain note.\n", + "Notes/Broken.md": "---\nrunestone_pm: [\n---\n", + [legacyLabelsPath]: labels, + }); + const content = await findLegacy(workspace); + assert.deepEqual(content, { boards: ["Boards/Plan.md"], cards: ["Tasks/Write.md"], invalid: ["Notes/Broken.md"], labels: true }); + assert.equal(hasLegacy(content), true); +}); + +test("migrated, deleted, and already saved data does not count again", async () => { + const board = defaultBoard("old-board"); + const workspace = hiddenWorkspace([{ id: "copied", title: "Copied" }], { + "Old.md": boardMarkdown(board), + "Gone.md": boardMarkdown(defaultBoard("gone-board")), + "Copied.md": newTask("Copied", fields(), "", "copied").source, + "Deleted.md": newTask("Deleted", fields(), "", "deleted").source, + [deletedCardsPath]: JSON.stringify({ schema: 1, ids: ["deleted"] }), + [legacyLabelsPath]: labels, + [labelsPath]: labels, + }); + const catalog = JSON.parse(workspace.files.get(catalogPath)!); + catalog.boards.push({ name: "Old", value: board }); + catalog.deletedBoardIds = ["gone-board"]; + workspace.files.set(catalogPath, JSON.stringify(catalog)); + assert.deepEqual(await findLegacy(workspace), { boards: [], cards: [], invalid: [], labels: false }); +}); + +test("the offer migrates every legacy board, task note, and the label file with backups, and changes no original", async () => { + const board = defaultBoard("visible-board"); + const originals = { + "Boards/Plan.md": boardMarkdown(board), + "Tasks/Write.md": newTask("Write", fields({ placements: { "visible-board": { listId: "todo" } } }), "Body", "write").source, + "Tasks/Read.md": newTask("Read", fields(), "", "read").source, + [legacyLabelsPath]: labels, + }; + const workspace = memoryWorkspace(originals); + // The native view sees nothing before the migration. + const hidden = new TaskStore(workspace, undefined, { legacy: false }); + await hidden.reload(); + assert.equal(hidden.tasks.length, 0); + assert.equal(hidden.boards.length, 0); + // The offer: a legacy store migrates all boards, the labels, and every visible task note. + const legacy = new TaskStore(workspace, undefined, { legacy: true }); + await legacy.reload(); + const files = await legacy.migrateStorage(legacy.tasks.filter(task => !isHiddenCard(task.path)).map(task => task.id)); + legacy.dispose(); + assert.deepEqual(files.map(file => file.path).sort(), ["Boards/Plan.md", "Tasks/Read.md", "Tasks/Write.md", legacyLabelsPath].sort()); + for (const file of files) assert.equal(workspace.files.get(file.backup), file.source); + for (const [path, source] of Object.entries(originals)) assert.equal(workspace.files.get(path), source, path); + assert.equal(hasLegacy(await findLegacy(workspace)), false); + await hidden.reload(); + assert.deepEqual(hidden.tasks.map(task => task.id).sort(), ["read", "write"]); + assert.deepEqual(hidden.boards.map(item => [item.id, item.name]), [["visible-board", "Plan"]]); + assert.deepEqual(hidden.labels.value.map(label => label.id), ["bug"]); +}); + +test("Add existing note copies a plain note into a private card and leaves the note unchanged", async () => { + const note = "---\ntags: [keep]\n---\n# Research\nDetails.\n"; + const workspace = hiddenWorkspace([], { "Notes/Research.md": note }); + const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false }); + await store.reload(); + const card = await store.adopt("Notes/Research.md"); + assert.equal(workspace.files.get("Notes/Research.md"), note); + assert.equal(card.path, cardPath(card.id)); + assert.equal(card.title, "Research"); + assert.equal(card.body, "# Research\nDetails.\n"); + assert.equal(card.placements?.board.listId, "todo"); + assert.match(workspace.files.get(card.path)!, /^tags: \[ keep \]$/m); + assert.deepEqual(store.tasks.map(task => task.id), [card.id]); + // A legacy task note migrates with a backup and keeps its ID. + const legacyNote = newTask("Legacy", fields(), "Old body", "legacy-id").source; + workspace.files.set("Notes/Legacy.md", legacyNote); + const migrated = await store.adopt("Notes/Legacy.md"); + assert.equal(migrated.id, "legacy-id"); + assert.equal(migrated.path, cardPath("legacy-id")); + assert.equal(workspace.files.get("Notes/Legacy.md"), legacyNote); + assert.equal(workspace.files.get(".runestone/pm/backups/Notes/Legacy.md"), legacyNote); + assert.equal(readTask(migrated.path, workspace.files.get(migrated.path)!)!.placements?.board.listId, "todo"); + // A second add of the same note finds the same card. + assert.equal((await store.adopt("Notes/Legacy.md")).path, migrated.path); + assert.equal(store.tasks.length, 2); +}); diff --git a/tests/unit/features/pm/multiple-boards.spec.ts b/tests/unit/features/pm/multiple-boards.spec.ts new file mode 100644 index 0000000..2fcdd51 --- /dev/null +++ b/tests/unit/features/pm/multiple-boards.spec.ts @@ -0,0 +1,514 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { newBoardSource, parseBoard, boardDocument } from "../../../../src/lib/features/pm/storage/board.ts"; +import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts"; +import { newTask, readTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts"; +import type { Workspace, TaskFields } from "../../../../src/lib/features/pm/model/model.ts"; + +const fields: TaskFields = { + status: "todo", + tags: ["shared"], + sessions: [ + { + id: "session", + start: "2026-10-08T16:00:00Z", + end: "2026-10-08T17:00:00Z", + timeZone: "America/Vancouver", + }, + ], + due: { date: "2026-10-30" }, + plan: { start: "2026-10-05", end: "2026-10-31" }, + archived: false, +}; +function fixture() { + const first = newBoardSource(), + second = newBoardSource(); + const files = new Map([ + ["Project/Launch.md", first], + ["Project/Personal.md", second], + ["Task.md", newTask("Task", fields, "Keep this description.").source], + ]); + let fail = false; + const writes: string[] = []; + const workspace: Workspace = { + async readOptional(path) { + return files.get(path) ?? null; + }, + async list(parent = "") { + const entries = new Map(); + for (const path of files.keys()) { + const prefix = parent ? parent + "/" : ""; + if (!path.startsWith(prefix)) continue; + const parts = path.slice(prefix.length).split("/"); + entries.set(parts[0], { + name: parts[0], + rel_path: prefix + parts[0], + kind: parts.length > 1 ? "folder" : "file", + }); + } + return [...entries.values()]; + }, + async read(path) { + const source = files.get(path); + if (source === undefined) throw Error("Missing"); + return source; + }, + async write(path, source, expected) { + if (fail) throw Error("Disk failure"); + assert.equal(files.get(path), expected); + writes.push(path); + files.set(path, source); + }, + async create(path, source) { + if (files.has(path)) throw Error("Exists"); + files.set(path, source); + }, + }; + const a = new TaskStore(workspace, { + id: parseBoard(first).id, + path: "Project/Launch.md", + }); + const b = new TaskStore(workspace, { + id: parseBoard(second).id, + path: "Project/Personal.md", + }); + const all = new TaskStore(workspace); + return { + files, + workspace, + a, + b, + all, + writes, + failWrites() { + fail = true; + }, + }; +} + +test("a shared task synchronizes status lists and keeps one schedule", async () => { + const { a, b, all, files, writes } = fixture(); + await a.adopt("Task.md"); + await b.adopt("Task.md"); + await a.reload(); + const original = a.tasks[0]; + writes.length = 0; + await a.moveTask(original, "done"); + await b.reload(); + await all.reload(); + assert.deepEqual(writes, ["Task.md"]); + assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "done"); + assert.equal(b.board.listFor(b.scopedTasks[0])?.id, "done"); + assert.equal(b.scopedTasks[0].status, "done"); + assert.equal(all.scopedTasks.length, 1); + assert.equal(all.scopedTasks[0].id, original.id); + assert.deepEqual(all.scopedTasks[0].plan, fields.plan); + assert.deepEqual(all.scopedTasks[0].sessions, fields.sessions); + assert.deepEqual(all.scopedTasks[0].due, fields.due); + assert.equal(all.scopedTasks[0].body, original.body); + assert.equal(files.size, 3); + await b.save(b.scopedTasks[0], { due: { date: "2026-11-01" } }); + await a.reload(); + assert.equal(a.scopedTasks[0].due?.date, "2026-11-01"); +}); + +test("leaving a Done list reopens completion and removal affects only one board", async () => { + const { a, b, all } = fixture(); + await a.adopt("Task.md"); + await b.adopt("Task.md"); + await a.reload(); + await a.moveTask(a.tasks[0], "done"); + await a.changeBoard(() => a.board.add("This week", null)); + await a.moveTask(a.tasks[0], a.board.value.lists.at(-1)!.id); + assert.equal(a.tasks[0].status, "todo"); + await a.removeFromBoard(a.tasks[0]); + assert.equal(a.scopedTasks.length, 0); + await b.reload(); + await all.reload(); + assert.equal(b.scopedTasks.length, 1); + assert.equal(all.scopedTasks.length, 1); + assert.equal(all.scopedTasks[0].archived, false); +}); + +test("All tasks moves synchronize memberships in one write and append to destination lists", async () => { + const { a, b, all, writes } = fixture(); + await a.adopt("Task.md"); + await b.adopt("Task.md"); + await a.create("Existing done", { ...fields, status: "done" }, ""); + await all.reload(); + const task = all.tasks.find((task) => task.title === "Task")!; + writes.length = 0; + await all.moveTask(task, "done"); + assert.deepEqual(writes, ["Task.md"]); + for (const board of [a, b]) { + await board.reload(); + const saved = board.scopedTasks.find((item) => item.id === task.id)!; + assert.equal(saved.status, "done"); + assert.equal(board.board.listFor(saved)?.id, "done"); + assert.deepEqual(saved.sessions, task.sessions); + assert.deepEqual(saved.plan, task.plan); + assert.deepEqual(saved.due, task.due); + assert.equal(saved.body, task.body); + } + assert.deepEqual( + a.cardsInList("done").map((task) => task.title), + ["Existing done", "Task"], + ); + assert.deepEqual( + b.scopedTasks.map((task) => task.title), + ["Task"], + ); +}); + +test("status changes use each board's designated list and preserve unmatched placements", async () => { + const { a, b, all } = fixture(); + await a.adopt("Task.md"); + await b.adopt("Task.md"); + await a.changeBoard(() => a.board.add("Released", "done")); + const destination = a.board.value.lists.at(-1)!.id; + await a.changeBoard(() => + a.board.update((board) => { + board.defaults.done = destination; + }), + ); + await b.changeBoard(() => b.board.remove("done")); + await all.reload(); + const previous = all.tasks[0].placements![b.board.reference!.id]; + await all.save(all.tasks[0], { status: "done" }); + await a.reload(); + await b.reload(); + assert.equal(a.board.listFor(a.tasks[0])?.id, destination); + assert.deepEqual(b.tasks[0].placements![b.board.reference!.id], previous); + assert.equal(b.tasks[0].status, "done"); +}); + +test("status changes preserve absent memberships and unavailable board placements", async () => { + const { a, b, all, files } = fixture(); + await a.adopt("Task.md"); + await all.reload(); + await all.moveTask(all.tasks[0], "doing"); + assert.equal( + Object.hasOwn(all.tasks[0].placements!, b.board.reference!.id), + false, + ); + await a.reload(); + const previous = a.tasks[0].placements![a.board.reference!.id]; + files.delete("Project/Launch.md"); + await all.moveTask(all.tasks[0], "done"); + assert.deepEqual(all.tasks[0].placements![a.board.reference!.id], previous); +}); + +test("failed All tasks moves preserve every placement and the shared status", async () => { + const { a, b, all, files, failWrites } = fixture(); + await a.adopt("Task.md"); + await b.adopt("Task.md"); + await all.reload(); + const before = all.tasks[0]; + failWrites(); + await assert.rejects(all.moveTask(before, "done"), /Disk failure/); + assert.equal(files.get("Task.md"), before.source); + assert.deepEqual(all.tasks[0], before); +}); + +test("board creation does not collect every workspace task", async () => { + const { a, b } = fixture(); + await a.reload(); + await b.reload(); + assert.equal(a.scopedTasks.length, 0); + await a.create("New", fields, ""); + await b.reload(); + assert.equal(a.scopedTasks.length, 1); + assert.equal(b.scopedTasks.length, 0); + assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "todo"); +}); + +test("moving or deleting a board never moves or deletes its tasks", async () => { + const { a, all, files } = fixture(); + await a.adopt("Task.md"); + const taskSource = files.get("Task.md"); + files.set("Elsewhere/Renamed.md", files.get("Project/Launch.md")!); + files.delete("Project/Launch.md"); + await a.reload(); + assert.equal(a.board.reference?.path, "Elsewhere/Renamed.md"); + assert.equal(a.board.name, "Renamed"); + assert.equal(a.scopedTasks.length, 1); + files.delete("Elsewhere/Renamed.md"); + await a.reload(); + await all.reload(); + assert.equal(a.board.available, false); + assert.equal(all.scopedTasks.length, 1); + assert.equal(files.get("Task.md"), taskSource); + await assert.rejects(a.create("Lost", fields, ""), /unavailable/); +}); + +test("invalid and duplicate boards do not block the workspace schedule", async () => { + const { a, all, files } = fixture(); + files.set("Copy.md", files.get("Project/Launch.md")!); + files.set( + "Project/Personal.md", + files.get("Project/Personal.md")!.replace("schema: 1", "schema: 99"), + ); + await all.reload(); + await a.reload(); + assert.equal(all.tasks.length, 1); + assert.equal(all.boards.length, 0); + assert.equal(a.board.available, false); + assert.ok(all.issues.some((issue) => issue.includes("Duplicate board ID"))); + assert.ok(all.issues.some((issue) => issue.includes("unsupported format"))); +}); + +test("failed placement writes preserve both membership and status", async () => { + const { a, files, failWrites } = fixture(); + await a.adopt("Task.md"); + const source = files.get("Task.md"); + failWrites(); + await assert.rejects(a.moveTask(a.tasks[0], "done"), /Disk failure/); + assert.equal(files.get("Task.md"), source); + assert.equal(a.tasks[0].status, "todo"); + assert.equal(a.board.listFor(a.tasks[0])?.id, "todo"); +}); + +test("an open stale card cannot overwrite another board's edit", async () => { + const { a, b, files } = fixture(); + await a.adopt("Task.md"); + await b.adopt("Task.md"); + await a.reload(); + const stale = a.tasks[0]; + await b.moveTask(b.tasks[0], "doing"); + const source = files.get("Task.md"); + await assert.rejects(a.moveTask(stale, "done"), /task changed/); + assert.equal(files.get("Task.md"), source); +}); + +test("board properties and prose survive edits and boards cannot become task notes", async () => { + const { a, files } = fixture(); + const source = + files + .get("Project/Launch.md")! + .replace("runestone_pm:", "owner: Ada # keep\nrunestone_pm:") + + "Board description.\n"; + files.set("Project/Launch.md", source); + await a.reload(); + await a.changeBoard(() => a.board.add("Review", null)); + const saved = files.get("Project/Launch.md")!; + assert.ok(saved.includes("owner: Ada # keep")); + assert.ok(saved.endsWith("Board description.\n")); + assert.equal(readTask("Board.md", saved), null); + assert.throws(() => adoptNote("Board.md", saved), /already contains Project Management data/); + assert.equal(boardDocument("# A normal note", "Board.md"), null); +}); + +test("renaming a board resolves its current path and preserves shared tasks and lists", async () => { + const { a, b, all, files, writes } = fixture(); + await a.adopt("Task.md"); + await b.adopt("Task.md"); + await a.changeBoard(() => a.board.add("Review", null)); + const source = files.get("Project/Launch.md")!; + const taskSource = files.get("Task.md"); + files.set("Moved/Launch.md", source); + files.delete("Project/Launch.md"); + writes.length = 0; + await a.renameBoard(" Release 1.2 ", async (document, name) => { + assert.equal(document.path, "Moved/Launch.md"); + assert.equal(document.id, parseBoard(source).id); + assert.equal(name, "Release 1.2"); + files.set("Moved/Release 1.2.md", files.get(document.path)!); + files.delete(document.path); + return "Moved/Release 1.2.md"; + }); + assert.equal(a.board.name, "Release 1.2"); + assert.equal(a.board.reference?.path, "Moved/Release 1.2.md"); + assert.equal(a.board.value.lists.at(-1)?.name, "Review"); + assert.equal(files.get("Moved/Release 1.2.md"), source); + assert.equal(files.get("Task.md"), taskSource); + assert.deepEqual(writes, []); + await b.reload(); + await all.reload(); + assert.equal(a.scopedTasks.length, 1); + assert.equal(b.scopedTasks.length, 1); + assert.equal(all.scopedTasks.length, 1); + await a.changeBoard(() => a.board.add("After rename", null)); + await a.moveTask(a.scopedTasks[0], "doing"); + assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "doing"); +}); + +test("failed renames and unavailable boards preserve workspace files", async () => { + const { a, all, files } = fixture(); + await a.reload(); + const before = [...files]; + await assert.rejects( + a.renameBoard("Personal", async () => { + throw Error("Exists"); + }), + /Exists/, + ); + assert.equal(a.board.reference?.path, "Project/Launch.md"); + assert.deepEqual([...files], before); + const rename = async () => { + assert.fail("Rename must not run"); + return ""; + }; + await assert.rejects(all.renameBoard("All", rename), /available board/); + files.set("Copy.md", files.get("Project/Launch.md")!); + await assert.rejects(a.renameBoard("Duplicate", rename), /available board/); + files.delete("Copy.md"); + files.delete("Project/Launch.md"); + await assert.rejects(a.renameBoard("Missing", rename), /available board/); +}); + +test("board transfers preserve metadata and other memberships in one card write", async () => { + const { a, b, all, files, workspace, writes } = fixture(); + await a.adopt("Task.md"); + await b.adopt("Task.md"); + const destination = await a.createBoard("Destination"); + const target = new TaskStore(workspace, destination); + await target.reload(); + await target.create("Already there", { ...fields, status: "doing" }, ""); + await a.reload(); + await a.save(a.tasks.find((task) => task.title === "Task")!, { + priority: "high", color: "pink", labels: ["bug"], assignees: ["Ada"], + customFields: [{ name: "Customer", value: "Keep" }], + }); + files.set("Task.md", files.get("Task.md")!.replace("runestone_pm:", "owner: Ada # keep\nrunestone_pm:")); + await a.reload(); + const before = a.tasks.find((task) => task.title === "Task")!; + writes.length = 0; + await a.transferTask(before, destination.id, "doing"); + assert.deepEqual(writes, [before.path]); + assert.equal(a.scopedTasks.length, 0); + await target.reload(); + await b.reload(); + await all.reload(); + const saved = target.tasks.find((task) => task.id === before.id)!; + const { placements: _oldPlacements, source: _oldSource, ...oldDetails } = before; + const { placements: _newPlacements, source: _newSource, ...newDetails } = saved; + assert.deepEqual(newDetails, oldDetails); + assert.deepEqual(saved.placements![b.board.reference!.id], before.placements![b.board.reference!.id]); + assert.equal(Object.hasOwn(saved.placements!, a.board.reference!.id), false); + assert.equal(saved.placements![destination.id].listId, "doing"); + assert.ok(saved.source.includes("owner: Ada # keep")); + assert.deepEqual(target.cardsInList("doing").map((task) => task.title), ["Already there", "Task"]); + assert.equal(b.scopedTasks.length, 1); + assert.equal(all.tasks.filter((task) => task.id === before.id).length, 1); +}); + +test("hidden cards transfer to existing memberships, custom lists, and Unlisted without copies", async () => { + const { a, b, workspace, files } = fixture(); + await a.reload(); + await a.create("Private", fields, "![Keep image](runestone-pm-image:asset-id)"); + const privateCard = a.scopedTasks[0]; + assert.ok(privateCard.path.startsWith(".runestone/pm/cards/")); + await a.save(privateCard, { placements: { + ...privateCard.placements, + [b.board.reference!.id]: { listId: "todo", order: "a" }, + } }); + await b.reload(); + await b.changeBoard(() => b.board.add("Review", null)); + const reviewId = b.board.value.lists.at(-1)!.id; + const before = a.tasks.find((task) => task.id === privateCard.id)!; + const paths = [...files.keys()]; + await a.transferTask(before, b.board.reference!.id, reviewId); + await b.reload(); + assert.equal(b.scopedTasks.length, 1); + assert.equal(b.board.listFor(b.scopedTasks[0])?.id, reviewId); + assert.equal(b.scopedTasks[0].body, privateCard.body); + assert.deepEqual([...files.keys()], paths); + const managed = await b.createBoard("Unlisted destination"); + await b.transferTask(b.scopedTasks[0], managed.id, null); + const target = new TaskStore(workspace, managed); + await target.reload(); + assert.equal(target.scopedTasks.length, 1); + assert.equal(target.scopedTasks[0].placements![managed.id].listId, null); + assert.equal(target.scopedTasks[0].status, "todo"); +}); + +test("transfers reject missing, duplicated, deleted, and archived destinations without card changes", async () => { + for (const condition of ["missing", "duplicate", "deleted", "archived", "list"] as const) { + const { a, b, files, workspace, writes } = fixture(); + await a.adopt("Task.md"); + const before = a.scopedTasks[0]; + let destination = b.board.reference!; + if (condition === "missing") files.delete(destination.path); + if (condition === "duplicate") files.set("Copy.md", files.get(destination.path)!); + if (condition === "deleted") { + await b.reload(); + await b.changeBoard(() => b.board.deleteBoard()); + } + if (condition === "archived") { + destination = await a.createBoard("Archived"); + const target = new TaskStore(workspace, destination); + await target.reload(); + await target.changeBoard(() => target.board.manage({ archived: true })); + } + if (condition === "list") { + await b.reload(); + await b.changeBoard(() => b.board.remove("doing")); + } + writes.length = 0; + await assert.rejects(a.transferTask(before, destination.id, "doing"), /destination/); + assert.equal(files.get(before.path), before.source, condition); + assert.deepEqual(writes, [], condition); + assert.deepEqual(a.scopedTasks[0], before, condition); + } +}); + +test("transfers require a current source membership and active source board", async () => { + const { a, b, all, files } = fixture(); + await all.reload(); + await assert.rejects(all.transferTask(all.tasks[0], b.board.reference!.id, "todo"), /active board/); + await a.reload(); + await assert.rejects(a.transferTask(a.tasks[0], b.board.reference!.id, "todo"), /no longer belongs/); + await a.adopt("Task.md"); + const before = a.scopedTasks[0]; + await assert.rejects(a.transferTask(before, a.board.reference!.id, "todo"), /different destination/); + files.delete(a.board.reference!.path); + await assert.rejects(a.transferTask(before, b.board.reference!.id, "todo"), /active board/); + assert.equal(files.get(before.path), before.source); +}); + +test("stale cards and failed transfer writes preserve every membership", async () => { + const { a, b, files, failWrites, writes } = fixture(); + await a.adopt("Task.md"); + const stale = a.scopedTasks[0]; + await b.reload(); + await b.save(b.tasks[0], { body: "An external edit." }); + const external = files.get(stale.path); + await assert.rejects(a.transferTask(stale, b.board.reference!.id, "done"), /card changed/); + assert.equal(files.get(stale.path), external); + const current = a.scopedTasks[0]; + writes.length = 0; + failWrites(); + await assert.rejects(a.transferTask(current, b.board.reference!.id, "done"), /Disk failure/); + assert.equal(files.get(current.path), current.source); + assert.deepEqual(a.scopedTasks[0], current); + assert.deepEqual(writes, []); +}); + +test("detail board changes save draft fields and membership atomically with stale-write protection", async () => { + const { a, b, files, writes, failWrites } = fixture(); + await a.reload(); await a.adopt("Task.md"); await b.reload(); + const task = a.tasks[0]; const original = files.get(task.path); + writes.length = 0; + await a.saveToBoard(task, b.board.reference!.id, "doing", { body: "Draft preserved", priority: "highest" }); + assert.equal(writes.length, 1); + const changed = readTask(task.path, files.get(task.path)!)!; + assert.equal(changed.body, "Draft preserved"); assert.equal(changed.priority, "highest"); + assert.equal(changed.status, "doing"); assert.equal(changed.placements?.[a.board.reference!.id], undefined); + assert.equal(changed.placements?.[b.board.reference!.id]?.listId, "doing"); + await assert.rejects(a.saveToBoard(task, b.board.reference!.id, "todo", { body: "Stale draft" }), /changed/); + const saved = files.get(task.path); failWrites(); + await assert.rejects(b.saveToBoard(changed, a.board.reference!.id, "todo", { body: "Failed draft" }), /Disk failure/); + assert.equal(files.get(task.path), saved); assert.notEqual(saved, original); +}); + +test("pasted relative paths reuse one card and reject paths outside the workspace", async () => { + const { a, files } = fixture(); await a.reload(); + const original = readTask("Task.md", files.get("Task.md")!)!; + await a.createOrLink("./Task.md", { ...fields, listId: "doing" }); + assert.equal(a.tasks.length, 1); assert.equal(a.tasks[0].id, original.id); + assert.equal(a.tasks[0].placements?.[a.board.reference!.id]?.listId, "doing"); + const before = new Map(files); + for (const path of ["../Task.md", "D:/Task.md", "/Task.md", "https://example.com/Task.md"]) + await assert.rejects(a.createOrLink(path, fields), /relative Markdown path/); + assert.deepEqual(files, before); +}); diff --git a/tests/unit/features/pm/native.spec.ts b/tests/unit/features/pm/native.spec.ts new file mode 100644 index 0000000..450414d --- /dev/null +++ b/tests/unit/features/pm/native.spec.ts @@ -0,0 +1,187 @@ +// The main-bundle parts of the native Project Management feature: the catalog entry, the board view pattern of the +// session, the settings and their first-start migration, and the board reader of Background and Settings. +import test from "node:test"; +import assert from "node:assert/strict"; +import { featureEntry, featureOfOwner } from "../../../../src/lib/features/catalog.ts"; +import { FeatureSession } from "../../../../src/lib/features/session.ts"; +import { migrateFeatures, type LegacyPlugin } from "../../../../src/lib/features/migration.ts"; +import type { FeatureContext, FeatureInstance } from "../../../../src/lib/features/types.ts"; +import { boardOfView, boardViewId, PLANNING } from "../../../../src/lib/features/pm/views.ts"; +import { DEFAULT_PROJECT_MANAGEMENT, migrateProjectManagement, normalizeProjectManagement, readViewStates, VIEW_STATES_KEY, writeViewStates, type ProjectManagementMigrationHost, type ProjectManagementSettings } from "../../../../src/lib/features/pmSettings.ts"; +import { BOARD_CATALOG_PATH, parseBoardCatalog, readBoardCatalog, writeDefaultBoard } from "../../../../src/lib/features/pmBoards.ts"; +import { SETTINGS_SECTIONS, LEGACY_KEYS } from "../../../../src/lib/settings/store.ts"; +import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts"; +import { parseCatalog } from "../../../../src/lib/features/pm/storage/catalog.ts"; + +function memoryStorage(initial: Record = {}) { + const values = new Map(Object.entries(initial)); + return { values, getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } }; +} + +function context(log: string[] = []): FeatureContext { + return { + openView: id => { log.push(`open ${id}`); }, openFile: async () => {}, onWorkspaceChange: () => () => {}, + setViewTitle: (id, title) => { log.push(`title ${id} ${title}`); }, closeView: id => { log.push(`close ${id}`); }, + replaceView: (current, next) => { log.push(`replace ${current} ${next}`); }, + }; +} + +test("Project Management keeps the plugin ID, is on by default, and follows its package", () => { + const pm = featureEntry("pm"); + assert.equal(pm.owner, "runestone.pm"); + assert.equal(featureOfOwner("runestone.pm")?.id, "pm"); + assert.equal(pm.defaultOn, true); + assert.equal(pm.followsPackage, true); + assert.deepEqual(pm.views.map(view => [view.id, view.placement, view.launch]), [["planning", "editor", true]]); + assert.deepEqual(pm.documentTypes, [], "The file tree reads no Markdown file for Project Management."); + assert.equal((SETTINGS_SECTIONS as readonly string[]).includes("projectManagement"), true); + assert.equal(LEGACY_KEYS.projectManagement, "runestone.project-management"); +}); + +test("board view IDs are the plugin IDs, and only valid board IDs match", () => { + const id = "0c18bcdc-f41e-4a31-87f4-87c369f398c1"; + const view = boardViewId(id); + assert.equal(view, "board-" + Buffer.from(id).toString("hex")); + assert.equal(boardOfView(view), id); + assert.equal(boardOfView(boardViewId("Plan ✓")), "Plan ✓"); + for (const other of [PLANNING, "board-", "board-6", "board-zz", "board-ff", "board-41-42", "graph"]) assert.equal(boardOfView(other), null, other); + const pattern = featureEntry("pm").viewPatterns![0].match; + assert.equal(pattern.test(view), true); + assert.equal(pattern.test(PLANNING), false); + assert.equal(pattern.test(view + "x"), false); +}); + +test("the session answers for board views before the module loads, and gives them the board name later", async () => { + let loads = 0; + const log: string[] = []; + const restored: [string, unknown][] = []; + const mounted: string[] = []; + const instance: FeatureInstance = { + mount: view => { mounted.push(view); return () => {}; }, + launch: view => { log.push(`launch ${view}`); }, + restoreTabState: (view, state) => { restored.push([view, state]); }, + saveTabState: view => ({ view }), + dispose() {}, + }; + const session = new FeatureSession(featureEntry("pm"), context(log), async () => { loads++; return { start: () => instance }; }); + const view = boardViewId("board-a"); + assert.equal(session.views.has(view), false); + const pattern = session.patternView(view)!; + assert.equal(pattern.placement, "editor"); + assert.equal(pattern.title, "Project Management"); + assert.equal(pattern.navigation, false); + assert.equal(pattern.launcher, false); + assert.equal(session.patternView(view), pattern, "One view for each ID"); + assert.equal(session.patternView("board-zz"), undefined); + assert.equal(loads, 0, "No module load for a pattern view"); + assert.equal(session.setViewTitle(view, "Roadmap"), true); + assert.equal(session.setViewTitle(view, "Roadmap"), false); + assert.equal(session.setViewTitle("planning", "Other"), false, "A catalog view keeps its title"); + assert.equal(pattern.title, "Roadmap"); + // A tab transfer restores the state, which loads the module. + await pattern.restoreTabState!({ search: "x" }); + assert.deepEqual(restored, [[view, { search: "x" }]]); + assert.equal(loads, 1); + assert.deepEqual(pattern.saveTabState!(), { view }); + const element = { replaceChildren() {} } as unknown as HTMLElement; + const dispose = await session.mount(boardViewId("board-b"), element); + assert.deepEqual(mounted, [boardViewId("board-b")]); + await dispose(); + // The ribbon button launches `planning` through the feature, which chooses the default board. + await session.launch("planning"); + assert.deepEqual(log, ["launch planning"]); + await session.stop(); + assert.equal(session.patternView(boardViewId("board-c")), undefined, "An off feature makes no views"); +}); + +test("the settings keep 2, 3, or 5 priority levels", () => { + assert.deepEqual(normalizeProjectManagement(undefined), DEFAULT_PROJECT_MANAGEMENT); + assert.deepEqual(normalizeProjectManagement({ priorityLevels: 5, other: 1 }), { priorityLevels: 5 }); + assert.deepEqual(normalizeProjectManagement({ priorityLevels: 2 }), { priorityLevels: 2 }); + for (const value of [4, "5", null, 0]) assert.deepEqual(normalizeProjectManagement({ priorityLevels: value }), { priorityLevels: 3 }); +}); + +test("view states stay in localStorage, and a write keeps the states of other tabs", () => { + const storage = memoryStorage({ [VIEW_STATES_KEY]: JSON.stringify({ planning: { view: "gantt" } }) }); + writeViewStates({ "board-61": { search: "bug" } }, storage); + assert.deepEqual(readViewStates(storage), { planning: { view: "gantt" }, "board-61": { search: "bug" } }); + assert.deepEqual(readViewStates(memoryStorage({ [VIEW_STATES_KEY]: "not json" })), {}); +}); + +function pmHost(missing: boolean, storage = memoryStorage()) { + const written: ProjectManagementSettings[] = []; + const host: ProjectManagementMigrationHost & { written: ProjectManagementSettings[] } = { + written, missing: () => missing, storage, write: async value => { written.push(value); }, + }; + return host; +} + +test("the first start makes the section and the view states from the kept plugin settings", async () => { + const legacy: LegacyPlugin = { id: "runestone.pm", installed: true, enabled: true, settings: { priorityLevels: 5, viewStates: { planning: { view: "calendar" } }, other: true } }; + const host = pmHost(true); + assert.deepEqual(await migrateProjectManagement(legacy, host), { priorityLevels: 5 }); + assert.deepEqual(host.written, [{ priorityLevels: 5 }]); + assert.deepEqual(JSON.parse(host.storage.getItem(VIEW_STATES_KEY)!), { planning: { view: "calendar" } }); + // Existing view states in localStorage stay. + const kept = pmHost(true, memoryStorage({ [VIEW_STATES_KEY]: "{\"planning\":{}}" })); + await migrateProjectManagement(legacy, kept); + assert.equal(kept.storage.getItem(VIEW_STATES_KEY), "{\"planning\":{}}"); + // Without plugin settings, the defaults apply. A present section stays. + const fresh = pmHost(true); + assert.deepEqual(await migrateProjectManagement(undefined, fresh), DEFAULT_PROJECT_MANAGEMENT); + assert.equal(fresh.storage.getItem(VIEW_STATES_KEY), null); + const present = pmHost(false); + assert.equal(await migrateProjectManagement(legacy, present), null); + assert.deepEqual(present.written, []); +}); + +test("the feature migration asks for the Project Management package when the section is missing", async () => { + const asked: string[][] = []; + const switches: unknown[] = []; + const host = { read: () => ({ git: true, background: true, terminal: true, pdf: true }), write: async (value: unknown) => { switches.push(value); }, + legacy: async (ids: string[]) => { asked.push(ids); return ids.map(id => ({ id, installed: true, enabled: false, settings: { priorityLevels: 2 } })); } }; + const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} }; + const terminal = { missing: () => false, legacy: () => null, write: async () => {} }; + const pm = pmHost(true); + assert.deepEqual(await migrateFeatures(host, background, terminal, pm), ["pm"]); + assert.deepEqual(asked, [["runestone.pm"]]); + assert.deepEqual(switches, [{ git: true, background: true, terminal: true, pdf: true, pm: false }], "The switch follows the disabled package."); + assert.deepEqual(pm.written, [{ priorityLevels: 2 }]); +}); + +test("the board reader lists the boards of workspace.json without the feature code", async () => { + const value = { + schema: 1, defaultBoardId: "b", defaultBoardPath: "pm-board:b", future: { keep: true }, + boards: [{ name: "Roadmap", value: defaultBoard("a") }, { name: "Bugs", value: defaultBoard("b"), archived: true }, { name: "Copy", value: defaultBoard("a") }, { name: "No value" }], + }; + const source = JSON.stringify(value); + assert.deepEqual(parseBoardCatalog(source), { source, defaultBoardId: "b", boards: [{ id: "a", name: "Roadmap", archived: false }, { id: "b", name: "Bugs", archived: true }] }); + assert.deepEqual(parseBoardCatalog(null), { boards: [], defaultBoardId: null, source: null }); + assert.throws(() => parseBoardCatalog("{\"schema\":2,\"boards\":[]}"), /unsupported/); + const reads: string[] = []; + const catalog = await readBoardCatalog(async path => { reads.push(path); return source; }); + assert.deepEqual(reads, [BOARD_CATALOG_PATH]); + assert.deepEqual(catalog.boards.map(board => board.id), ["a", "b"]); +}); + +test("Settings saves the default board with a guarded write and keeps the other keys", async () => { + const files = new Map([[BOARD_CATALOG_PATH, JSON.stringify({ schema: 1, boards: [{ name: "Roadmap", value: defaultBoard("a") }], future: 1 }, null, 2) + "\n"]]); + const read = async (path: string) => files.get(path) ?? null; + const write = async (path: string, contents: string, expected: string) => { + if (files.get(path) !== expected) throw new Error("The file changed."); + files.set(path, contents); + }; + await writeDefaultBoard("a", read, write); + const saved = JSON.parse(files.get(BOARD_CATALOG_PATH)!); + assert.equal(saved.defaultBoardId, "a"); + assert.equal(saved.defaultBoardPath, "pm-board:a"); + assert.equal(saved.future, 1); + // The feature code accepts the file. + assert.equal(parseCatalog(files.get(BOARD_CATALOG_PATH)!).defaultBoardId, "a"); + await writeDefaultBoard(null, read, write); + assert.equal(JSON.parse(files.get(BOARD_CATALOG_PATH)!).defaultBoardId, null); + await assert.rejects(writeDefaultBoard("missing", read, write), /unavailable/); + await assert.rejects(writeDefaultBoard("a", read, async () => { throw new Error("The file changed."); }), /changed/); + // Without a catalog, All tasks needs no write. + await writeDefaultBoard(null, async () => null, async () => { throw new Error("no write"); }); +}); diff --git a/tests/unit/features/pm/october-cards.spec.ts b/tests/unit/features/pm/october-cards.spec.ts new file mode 100644 index 0000000..6f029da --- /dev/null +++ b/tests/unit/features/pm/october-cards.spec.ts @@ -0,0 +1,63 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { newTask, readTask, editTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts"; +import { DescriptionDraft } from "../../../../src/lib/features/pm/storage/description-draft.ts"; +import { defaultBoardPath } from "../../../../src/lib/features/pm/model/workspace-default.ts"; +import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts"; +import { catalogPath, boardMarkdown } from "../../../../src/lib/features/pm/storage/catalog.ts"; +import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts"; + +function fixture() { + const files = new Map(); + const workspace: Workspace = { + async list() { throw new Error("No task scan expected"); }, + async read(path) { if (!files.has(path)) throw new Error("Missing"); return files.get(path)!; }, + async readOptional(path) { return files.get(path) ?? null; }, + async create(path, source) { if (files.has(path)) throw new Error("Exists"); files.set(path, source); }, + async write(path, source, expected) { if (files.get(path) !== expected) throw new Error("Conflict"); files.set(path, source); }, + }; + return { files, workspace }; +} +const fields = { status: "todo" as const, tags: [], sessions: [], archived: false }; +test("new captures record immutable timestamps and existing legacy cards keep an unknown date", () => { + const before = Date.now(); + const note = newTask("Timestamp", fields); + const task = readTask(note.path, note.source)!; + assert.ok(Date.parse(task.createdAt!) >= before && Date.parse(task.createdAt!) <= Date.now()); + const edited = readTask(task.path, editTask(task, { body: "Updated", status: "done", placements: { next: { listId: "done" } } }))!; + assert.equal(edited.createdAt, task.createdAt); + assert.throws(() => editTask(task, { createdAt: undefined }), /cannot change/); + assert.throws(() => editTask(task, { createdAt: "2026-01-01T00:00:00Z" }), /cannot change/); + assert.ok(Date.parse(readTask("Old.md", adoptNote("Old.md", "Original note"))!.createdAt!) >= before); + const legacy = readTask(note.path, note.source.replace(/^ createdAt:.*\n/m, ""))!; + assert.equal(readTask(legacy.path, editTask(legacy, { title: "Legacy edit" }))!.createdAt, undefined); + assert.equal(adoptNote(legacy.path, legacy.source), legacy.source); +}); +test("description drafts persist separately, cancel clears them, and stale writers cannot overwrite drafts", async () => { + const { files, workspace } = fixture(); + const draft = new DescriptionDraft(workspace, "task"); + assert.equal(await draft.load(), null); + await draft.save("Uncommitted text"); + const other = new DescriptionDraft(workspace, "task"); + assert.equal(await other.load(), "Uncommitted text"); + await draft.save("Newer draft"); + await assert.rejects(other.save("Stale draft"), /Conflict/); + await draft.save(null); + assert.equal(await new DescriptionDraft(workspace, "task").load(), null); + assert.ok([...files.keys()].every(path => !path.includes("/cards/"))); +}); +test("default board resolves without scanning cards and keeps unavailable selections fixed", async () => { + const { files, workspace } = fixture(); + const board = defaultBoard("chosen"); + const catalog = { schema: 1, boards: [{ name: "Chosen", value: board }], defaultBoardId: "chosen", unknown: "keep" }; + files.set(catalogPath, JSON.stringify(catalog)); + assert.equal(await defaultBoardPath(workspace), "pm-board:chosen"); + files.set(catalogPath, JSON.stringify({ ...catalog, boards: [] })); + assert.equal(await defaultBoardPath(workspace), undefined); + assert.equal(JSON.parse(files.get(catalogPath)!).defaultBoardId, "chosen"); + files.set("Legacy.md", boardMarkdown(board)); + files.set(catalogPath, JSON.stringify({ ...catalog, boards: [], defaultBoardPath: "Legacy.md" })); + assert.equal(await defaultBoardPath(workspace), "Legacy.md"); + files.set(catalogPath, JSON.stringify({ ...catalog, boards: [], defaultBoardPath: "Legacy.md", deletedBoardIds: ["chosen"] })); + assert.equal(await defaultBoardPath(workspace), undefined); +}); diff --git a/tests/unit/features/pm/partial-reload.spec.ts b/tests/unit/features/pm/partial-reload.spec.ts new file mode 100644 index 0000000..02dc887 --- /dev/null +++ b/tests/unit/features/pm/partial-reload.spec.ts @@ -0,0 +1,142 @@ +// The hidden mode of the store (`legacy: false`): it reads only `.runestone/pm/`, and a save, a delete, a move, +// or a watcher event reads only the changed files again. +import test from "node:test"; +import assert from "node:assert/strict"; +import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts"; +import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts"; +import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts"; +import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts"; +import { labelsPath } from "../../../../src/lib/features/pm/storage/labels.ts"; +import { editTask, newTask } from "../../../../src/lib/features/pm/storage/notes.ts"; +import { newBoardSource } from "../../../../src/lib/features/pm/storage/board.ts"; +import { privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts"; +import { fields, hiddenWorkspace } from "./_memory.ts"; + +const cards = [{ id: "a", title: "Card A" }, { id: "b", title: "Card B" }, { id: "c", title: "Card C" }]; + +test("the hidden mode reads only .runestone/pm and never a visible Markdown note", async () => { + const workspace = hiddenWorkspace(cards, { + "Notes/Task.md": newTask("Task", fields(), "", "visible").source, + "Board.md": newBoardSource(), + }); + const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false }); + await store.reload(); + assert.equal(store.legacy, false); + assert.deepEqual(store.issues, []); + assert.deepEqual(store.tasks.map(task => task.id), ["a", "b", "c"]); + assert.deepEqual(store.boards.map(board => board.id), ["board"]); + assert.equal(workspace.markdownLists, 0); + assert.ok(workspace.reads.every(path => path.startsWith(".runestone/pm/") || path === "runestone-pm-labels.json"), workspace.reads.join(", ")); + assert.equal(workspace.reads.some(path => path.endsWith(".md") && !path.startsWith(".runestone/")), false); + // The legacy mode, for the migration and the skill helper, still reads the visible notes. + const legacy = new TaskStore(workspace); + await legacy.reload(); + assert.equal(legacy.legacy, true); + assert.ok(legacy.tasks.some(task => task.id === "visible")); +}); + +test("a save, a move, and a delete read only the changed card again", async () => { + const workspace = hiddenWorkspace(cards); + const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false }); + await store.reload(); + const card = (id: string) => store.tasks.find(task => task.id === id)!; + // Each write also checks the Git exclusion file of `.runestone/pm/`. It is not a reload. + const reads = () => workspace.reads.filter(path => path !== privateRulesPath); + + workspace.reads.length = 0; + await store.save(card("a"), { body: "Changed" }); + assert.deepEqual(reads(), [cardPath("a")]); + assert.equal(card("a").body, "Changed"); + + workspace.reads.length = 0; + await store.moveTask(card("b"), "doing"); + assert.deepEqual(reads(), [cardPath("b")]); + assert.equal(card("b").placements!.board.listId, "doing"); + assert.equal(card("b").status, "doing"); + + workspace.reads.length = 0; + await store.deleteCard(card("c")); + assert.deepEqual(reads().filter(path => path !== deletedCardsPath), [cardPath("c")]); + assert.deepEqual(store.tasks.map(task => task.id), ["a", "b"]); + assert.match(workspace.files.get(deletedCardsPath)!, /"c"/); +}); + +test("a save still stops when another window changed the card", async () => { + const workspace = hiddenWorkspace(cards); + const store = new TaskStore(workspace, undefined, { legacy: false }); + await store.reload(); + const card = store.tasks.find(task => task.id === "a")!; + workspace.files.set(cardPath("a"), editTask(card, { body: "Other window" })); + await assert.rejects(store.save(card, { body: "This window" }), /changed/); + assert.equal(store.tasks.find(task => task.id === "a")!.body, "Other window"); +}); + +test("watcher paths read only the changed files of .runestone/pm", async () => { + const workspace = hiddenWorkspace(cards); + const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false }); + await store.reload(); + + // A change outside `.runestone/pm/`, or of images and drafts, reads nothing. + workspace.reads.length = 0; workspace.lists.length = 0; + await store.reloadPaths(["Notes/Plan.md", ".runestone/pm/images/x.json", ".runestone/pm/drafts/61.json", ".runestone/tabs.json"]); + assert.deepEqual(workspace.reads, []); + assert.deepEqual(workspace.lists, []); + + // A new card from another window. + workspace.files.set(cardPath("d"), newTask("Card D", fields({ title: "Card D", placements: { board: { listId: "done" } } }), "", "d").source); + workspace.reads.length = 0; + await store.reloadPaths([cardPath("d")]); + assert.deepEqual(workspace.reads, [cardPath("d")]); + assert.deepEqual(store.tasks.map(task => task.id), ["a", "b", "c", "d"]); + + // A deleted card file. + workspace.files.delete(cardPath("b")); + workspace.reads.length = 0; + await store.reloadPaths([cardPath("b")]); + assert.deepEqual(workspace.reads, [cardPath("b"), cardPath("b")]); + assert.deepEqual(store.tasks.map(task => task.id), ["a", "c", "d"]); + + // A renamed board reads only the catalog. + const catalog = JSON.parse(workspace.files.get(catalogPath)!); + catalog.boards[0].name = "Renamed"; + workspace.files.set(catalogPath, JSON.stringify(catalog)); + workspace.reads.length = 0; + await store.reloadPaths([catalogPath]); + assert.deepEqual(workspace.reads, [catalogPath]); + assert.equal(store.board.name, "Renamed"); + + // Labels and deleted cards each read their own file. + workspace.files.set(labelsPath, JSON.stringify({ schema: 1, labels: [{ id: "x", name: "X", color: "red" }] })); + workspace.files.set(deletedCardsPath, JSON.stringify({ schema: 1, ids: ["d"] })); + workspace.reads.length = 0; + await store.reloadPaths([labelsPath, deletedCardsPath]); + assert.deepEqual(workspace.reads.sort(), [deletedCardsPath, labelsPath].sort()); + assert.deepEqual(store.labels.value.map(label => label.id), ["x"]); + assert.deepEqual(store.tasks.map(task => task.id), ["a", "c"]); +}); + +test("an invalid card from a watcher event hides all cards until it is valid again", async () => { + const workspace = hiddenWorkspace(cards); + const store = new TaskStore(workspace, undefined, { legacy: false }); + await store.reload(); + const valid = workspace.files.get(cardPath("a"))!; + workspace.files.set(cardPath("a"), "---\nrunestone_pm: [\n---\n"); + await store.reloadPaths([cardPath("a")]); + assert.deepEqual(store.tasks, []); + assert.match(store.issues.join(" "), /\.runestone\/pm\/cards\/61\.md/); + workspace.files.set(cardPath("a"), valid); + await store.reloadPaths([cardPath("a")]); + assert.deepEqual(store.issues, []); + assert.equal(store.tasks.length, 3); +}); + +test("a folder change, a marker change, or an unknown change reads everything again", async () => { + const workspace = hiddenWorkspace(cards); + const store = new TaskStore(workspace, undefined, { legacy: false }); + await store.reload(); + for (const paths of [[".runestone/pm/cards"], [".runestone/pm/cards/.gitignore"], [".runestone"], undefined]) { + workspace.lists.length = 0; + await store.reloadPaths(paths); + assert.deepEqual(workspace.lists, [".runestone/pm/cards"], String(paths)); + } +}); diff --git a/tests/unit/features/pm/private-cards.spec.ts b/tests/unit/features/pm/private-cards.spec.ts new file mode 100644 index 0000000..8988f2f --- /dev/null +++ b/tests/unit/features/pm/private-cards.spec.ts @@ -0,0 +1,278 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + mkdtemp, + readFile, + writeFile, + mkdir, + readdir, + rm, +} from "node:fs/promises"; +import { execFileSync } from "node:child_process"; +import { tmpdir } from "node:os"; +import { resolve, join, dirname } from "node:path"; +import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts"; +import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts"; +import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts"; +import { cardOrder } from "../../../../src/lib/features/pm/storage/order.ts"; +import { + privateRulesPath, + cardsMarker, + isHiddenCard, +} from "../../../../src/lib/features/pm/storage/persistence.ts"; +import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts"; +import { defaultLabels, labelsPath } from "../../../../src/lib/features/pm/storage/labels.ts"; +import type { Workspace, TaskFields } from "../../../../src/lib/features/pm/model/model.ts"; + +const fields: TaskFields = { + status: "todo", + tags: ["keep"], + labels: ["bug"], + archived: false, + sessions: [], + due: { date: "2026-10-30" }, + plan: { start: "2026-10-07", end: "2026-10-10" }, + placements: { board: { listId: "todo" } }, +}; +async function fixture(t: test.TestContext) { + const root = await mkdtemp(join(tmpdir(), "runestone-pm-private-")); + t.after(async () => { + assert.ok( + resolve(root).startsWith(resolve(tmpdir(), "runestone-pm-private-")), + ); + await rm(root, { recursive: true, force: true }); + }); + const file = (path: string) => { + const absolute = resolve(root, path); + assert.ok( + absolute === root || + absolute.startsWith(root + "/") || + absolute.startsWith(root + "\\"), + ); + return absolute; + }; + const workspace: Workspace = { + async readOptional(path) { + try { + return await readFile(file(path), "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } + }, + async read(path) { + return readFile(file(path), "utf8"); + }, + async list(path = "") { + return (await readdir(file(path), { withFileTypes: true })) + .filter((entry) => ![".git", ".runestone"].includes(entry.name)) + .map((entry) => ({ + name: entry.name, + rel_path: (path ? path + "/" : "") + entry.name, + kind: entry.isDirectory() ? "folder" : "file", + })); + }, + async create(path, source) { + await mkdir(dirname(file(path)), { recursive: true }); + await writeFile(file(path), source, { flag: "wx" }); + }, + async write(path, source, expected) { + assert.equal(await workspace.read(path), expected, "Changed on disk"); + await writeFile(file(path), source); + }, + }; + const git = (...args: string[]) => + execFileSync("git", args, { + cwd: root, + encoding: "utf8", + windowsHide: true, + }).trim(); + return { root, file, workspace, git, store: new TaskStore(workspace) }; +} + +test("new cards and other Project Management data stay outside navigation and normal Git staging", async (t) => { + const { store, workspace, git } = await fixture(t); + git("init", "--quiet"); + await workspace.create!("README.md", "Shared project\n"); + await store.createBoard("Board"); + await store.create("Card: / duplicate?", fields, "Private details"); + await store.create("Card: / duplicate?", fields, "Second card"); + await store.saveLabels(defaultLabels(), store.labels.source); + await store.reload(); + assert.equal(store.tasks.length, 2); + assert.equal(new Set(store.tasks.map((task) => task.id)).size, 2); + assert.ok(store.tasks.every((task) => isHiddenCard(task.path))); + assert.deepEqual( + (await workspace.list()).map((entry) => entry.name), + ["README.md"], + ); + assert.equal(await workspace.readOptional!(".gitignore"), null); + for (const path of [ + catalogPath, + labelsPath, + privateRulesPath, + cardsMarker, + ...store.tasks.map((task) => task.path), + ]) + assert.equal(git("check-ignore", "--", path), path); + git("add", "."); + assert.equal(git("ls-files"), "README.md"); +}); + +test("Git protection is installed before data writes and failures preserve privacy", async (t) => { + const { store, workspace } = await fixture(t); + const create = workspace.create!; + const writes: string[] = []; + workspace.create = async (path, source) => { + writes.push(path); + if (path === privateRulesPath) + throw new Error("Cannot create Git exclusion"); + await create(path, source); + }; + await assert.rejects(store.create("Private", fields, ""), /Git exclusion/); + assert.deepEqual(writes, [privateRulesPath]); + workspace.create = async (path, source) => { + writes.push(path); + await create(path, source); + }; + writes.length = 0; + await store.create("Private", fields, ""); + assert.deepEqual(writes, [ + privateRulesPath, + cardsMarker, + store.tasks[0].path, + ]); +}); + +test("selected legacy cards migrate with exact backups, stable order, and no changes to linked notes", async (t) => { + const { store, workspace, file, git } = await fixture(t); + git("init", "--quiet"); + const original = newTask("Existing", fields, "Preserve **body**.\n"); + const source = original.source.replace("---\n", "---\nowner: Ada # retain\n"); + await workspace.create!(original.path, source); + const linked = newTask("Shared", fields, "Keep as a note"); + await workspace.create!("Docs/Shared.md", linked.source); + git("add", "."); + await store.reload(); + const before = store.tasks.find((task) => task.title === "Existing")!; + const stale = new TaskStore(workspace); + await stale.reload(); + const report = await store.migrateStorage([before.id]); + assert.equal(report.length, 1); + const current = store.tasks.find((task) => task.id === before.id)!; + assert.equal(current.path, cardPath(before.id)); + assert.equal(current.title, before.title); + assert.equal(current.body, before.body); + for (const key of [ + "status", + "tags", + "labels", + "due", + "plan", + "sessions", + "archived", + ] as const) + assert.deepEqual(current[key], before[key]); + assert.equal(cardOrder(current, "board"), cardOrder(before, "board")); + assert.equal(cardOrder(current), cardOrder(before)); + assert.equal(await workspace.read(original.path), source); + assert.equal(await workspace.read(report[0].backup), source); + assert.equal(await workspace.read("Docs/Shared.md"), linked.source); + assert.match(current.source, /owner: Ada # retain/); + await assert.rejects(stale.save(before, { status: "done" }), /changed/); + await store.save(current, { title: "Private: edited", status: "doing" }); + await store.migrateStorage([before.id]); + assert.equal( + store.tasks.find((task) => task.id === before.id)!.title, + "Private: edited", + ); + await rm(file(original.path)); + await store.reload(); + assert.equal(store.tasks.length, 2); + assert.equal( + store.tasks.find((task) => task.id === before.id)!.status, + "doing", + ); + git("add", "-A"); + assert.equal(git("ls-files"), "Docs/Shared.md"); +}); + +test("partial card migration resumes without replacing newer hidden edits", async (t) => { + const { workspace, store } = await fixture(t); + for (const title of ["A", "B"]) { + const note = newTask(title, fields); + await workspace.create!(note.path, note.source); + } + await store.reload(); + const ids = store.tasks.map((task) => task.id); + const blocked = cardPath(ids[1]); + const create = workspace.create!; + workspace.create = async (path, source) => { + if (path === blocked) throw new Error("Disk full"); + await create(path, source); + }; + await assert.rejects(store.migrateStorage(ids), /Disk full/); + await store.reload(); + assert.equal(store.tasks.length, 2); + const first = store.tasks.find((task) => task.id === ids[0])!; + await store.save(first, { body: "Later edit" }); + workspace.create = create; + await store.migrateStorage(ids); + assert.ok(store.tasks.every((task) => isHiddenCard(task.path))); + assert.equal( + store.tasks.find((task) => task.id === ids[0])!.body, + "Later edit", + ); +}); + +test("changed originals block further migration and stale saves without losing either version", async (t) => { + const { workspace, store } = await fixture(t); + const note = newTask("A", fields); + await workspace.create!(note.path, note.source); + await store.reload(); + const id = store.tasks[0].id; + await store.migrateStorage([id]); + const hidden = store.tasks[0]; + await workspace.write( + note.path, + editTask(readTask(note.path, note.source)!, { body: "Outside edit" }), + note.source, + ); + await assert.rejects(store.save(hidden, { status: "done" }), /changed/); + await assert.rejects(store.migrateStorage(), /issues/); + assert.equal(await workspace.read(hidden.path), hidden.source); +}); + +test("migration retains long filename titles and an existing Project Management ignore file", async (t) => { + const { workspace, store } = await fixture(t); + const note = newTask("A", fields); + const path = "Legacy/" + "a".repeat(130) + ".md"; + await workspace.create!(path, note.source); + await workspace.create!( + privateRulesPath, + "# Personal rules\ncache/\n!keep.json\n", + ); + await store.reload(); + await store.migrateStorage([store.tasks[0].id]); + assert.equal(store.tasks[0].title, "a".repeat(130)); + assert.equal( + await workspace.read(privateRulesPath), + "# Personal rules\ncache/\n!keep.json\n# RuneStone Project Management local data\n*\n", + ); +}); + +test("an invalid hidden card cannot fall back to editing its old visible note", async (t) => { + const { workspace, store } = await fixture(t); + const note = newTask("A", fields); + await workspace.create!(note.path, note.source); + await store.reload(); + const legacy = store.tasks[0]; + await store.migrateStorage([legacy.id]); + const hidden = store.tasks[0]; + await workspace.write(hidden.path, "broken data", hidden.source); + await store.reload(); + assert.equal(store.tasks.length, 0); + assert.match(store.issues.join(" "), /hidden card ID/); + await assert.rejects(store.save(legacy, { status: "done" }), /changed/); + assert.equal(await workspace.read(note.path), note.source); +}); diff --git a/tests/unit/features/pm/scan-performance.spec.ts b/tests/unit/features/pm/scan-performance.spec.ts new file mode 100644 index 0000000..6304aff --- /dev/null +++ b/tests/unit/features/pm/scan-performance.spec.ts @@ -0,0 +1,195 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { setTimeout as delay } from "node:timers/promises"; +import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts"; +import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts"; +import { newTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts"; +import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts"; +import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts"; +import { mapConcurrent, scanConcurrency } from "../../../../src/lib/features/pm/storage/scan.ts"; +import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts"; + +test("native discovery avoids directory bridge calls and retains save conflicts", async () => { + const boardSource = newBoardSource(); + const boardId = parseBoard(boardSource).id; + const id = crypto.randomUUID(); + const taskPath = cardPath(id); + const original = newTask(id, { + title: "Latency card", status: "todo", tags: [], sessions: [], archived: false, + placements: { [boardId]: { listId: "todo" } }, + }, "Original details", id).source; + const files = new Map([["Board.md", boardSource], [taskPath, original], [cardsMarker, "*\n"], [privateRulesPath, "*\n"]]); + let scans = 0, lists = 0, writes = 0; + let scanFailure = false; + const workspace: Workspace = { + async listMarkdown() { + scans++; + if (scanFailure) throw new Error("Directory unavailable"); + return [...files.keys()].filter(path => !path.startsWith(".") && path.endsWith(".md")); + }, + async list(path) { + lists++; + assert.equal(path, ".runestone/pm/cards", "Visible folders must use the native listing"); + return [{ name: taskPath.split("/").at(-1)!, rel_path: taskPath, kind: "file" }]; + }, + async read(path) { const value = files.get(path); assert.notEqual(value, undefined); return value!; }, + async readOptional(path) { return files.get(path) ?? null; }, + async create() { throw new Error("Unexpected create"); }, + async write(path, source, expected) { assert.equal(files.get(path), expected); writes++; files.set(path, source); }, + }; + const store = new TaskStore(workspace, { id: boardId, path: "Board.md" }); + await store.reload(); + await store.moveTask(store.tasks[0], "doing"); + await store.save(store.tasks[0], { body: "Updated details" }); + assert.equal(scans, 3); + assert.equal(lists, 3); + assert.equal(writes, 2); + const stale = store.tasks[0]; + const external = editTask(stale, { body: "External details" }); + files.set(taskPath, external); + await assert.rejects(store.save(stale, { body: "Stale details" }), /changed/); + const current = store.tasks[0]; + files.set("Copy.md", current.source); + await assert.rejects(store.moveTask(current, "done"), /duplicate/); + files.delete("Copy.md"); + await store.reload(); + scanFailure = true; + await assert.rejects(store.save(store.tasks[0], { body: "Blocked details" }), /Directory unavailable/); + assert.equal(files.get(taskPath), external); + assert.equal(writes, 2); +}); + +test("load, move, and detail saves overlap bounded reads without weakening conflict checks", async (t) => { + const source = newBoardSource(); + const boardId = parseBoard(source).id; + const files = new Map([ + ["Board.md", source], + [cardsMarker, "*\n"], + [privateRulesPath, "*\n"], + ]); + for (let index = 0; index < 32; index++) { + files.set(`Notes${index % 4}/Note${index}.md`, "An ordinary note."); + const id = crypto.randomUUID(); + files.set( + cardPath(id), + newTask( + id, + { + title: `Card ${index}`, + status: "todo", + tags: [], + sessions: [], + archived: false, + placements: { [boardId]: { listId: "todo" } }, + }, + "Original details", + id, + ).source, + ); + } + let active = 0, + peak = 0, + reads = 0; + const readDelay = 15; + const workspace: Workspace = { + async list(parent = "") { + const entries = new Map(); + const prefix = parent ? `${parent}/` : ""; + for (const path of files.keys()) { + if (!path.startsWith(prefix)) continue; + const parts = path.slice(prefix.length).split("/"); + entries.set(parts[0], { + name: parts[0], + rel_path: prefix + parts[0], + kind: parts.length > 1 ? "folder" : "file", + }); + } + return [...entries.values()]; + }, + async read(path) { + reads++; + peak = Math.max(peak, ++active); + try { + await delay(readDelay); + const value = files.get(path); + if (value === undefined) throw new Error("Missing note"); + return value; + } finally { + active--; + } + }, + async readOptional(path) { + return files.get(path) ?? null; + }, + async write(path, source, expected) { + assert.equal(files.get(path), expected); + files.set(path, source); + }, + async create(path, source) { + assert.equal(files.has(path), false); + files.set(path, source); + }, + }; + const store = new TaskStore(workspace, { id: boardId, path: "Board.md" }); + for (const [name, action] of [ + ["load", () => store.reload()], + ["move", () => store.moveTask(store.tasks[0], "doing")], + ["edit", () => store.save(store.tasks[0], { body: "Updated details" })], + ] as const) { + peak = reads = 0; + const started = performance.now(); + await action(); + const elapsed = performance.now() - started; + assert.equal(reads, 65); + assert.equal(peak, scanConcurrency); + assert.equal(active, 0); + // The serial delay alone is 975 ms. Keep generous headroom for busy runners. + assert.ok(elapsed < reads * readDelay * 0.75, `${name} took ${elapsed} ms`); + t.diagnostic( + `${name}: ${reads} reads, peak ${peak}, ${Math.round(elapsed)} ms (serial delay ${reads * readDelay} ms)`, + ); + } + assert.equal(store.tasks[0].body, "Updated details"); + assert.equal(store.tasks[0].status, "doing"); + const cached = store.tasks[1]; + await store.reload(); + assert.equal( + store.tasks.find((task) => task.id === cached.id), + cached, + ); + + const stale = store.tasks[0]; + const external = editTask(stale, { body: "External details" }); + files.set(stale.path, external); + await assert.rejects(store.save(stale, { body: "Stale details" }), /changed/); + assert.equal(files.get(stale.path), external); + const current = store.tasks.find((task) => task.id === stale.id)!; + files.set("Notes0/Copied card.md", current.source); + await assert.rejects(store.moveTask(current, "done"), /duplicate/); + assert.equal(files.get(current.path), external); +}); + +test("parallel scanning retains input order and drains pending work on failure", async () => { + let active = 0; + await assert.rejects( + mapConcurrent([0, 1, 2, 3], async (value) => { + active++; + try { + await delay(value === 0 ? 1 : 20); + if (value === 0) throw new Error("Directory unavailable"); + return value; + } finally { + active--; + } + }), + /Directory unavailable/, + ); + assert.equal(active, 0); + assert.deepEqual( + await mapConcurrent([0, 1, 2, 3], async (value) => { + await delay(4 - value); + return value; + }), + [0, 1, 2, 3], + ); +}); diff --git a/tests/unit/features/pm/storage-migration.spec.ts b/tests/unit/features/pm/storage-migration.spec.ts new file mode 100644 index 0000000..3b90b31 --- /dev/null +++ b/tests/unit/features/pm/storage-migration.spec.ts @@ -0,0 +1,330 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts"; +import { newBoardSource, parseBoard, BoardStore } from "../../../../src/lib/features/pm/storage/board.ts"; +import { + catalogPath, + createBoard, + readCatalog, + boardKey, + parseCatalog, +} from "../../../../src/lib/features/pm/storage/catalog.ts"; +import { migrateStorage } from "../../../../src/lib/features/pm/storage/migration.ts"; +import { labelsPath, legacyLabelsPath } from "../../../../src/lib/features/pm/storage/labels.ts"; +import { newTask } from "../../../../src/lib/features/pm/storage/notes.ts"; +import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts"; + +function fixture() { + const source = newBoardSource() + "Keep the board description.\n"; + const id = parseBoard(source).id; + const task = newTask( + "Keep task", + { + status: "doing", + tags: ["tag"], + labels: ["bug"], + archived: false, + sessions: [], + placements: { [id]: { listId: "doing", order: "a" } }, + }, + "Keep task body.", + ); + const files = new Map([ + ["Project/Launch.md", source], + [task.path, task.source], + [ + legacyLabelsPath, + JSON.stringify({ + schema: 1, + extra: "keep", + labels: [{ id: "bug", name: "Defect", color: "red" }], + }), + ], + ]); + let fail = ""; + const workspace: Workspace = { + async readOptional(path) { + return files.get(path) ?? null; + }, + async read(path) { + if (!files.has(path)) throw new Error("Missing file"); + return files.get(path)!; + }, + async list(parent = "") { + const entries = new Map(); + for (const path of files.keys()) { + const prefix = parent ? parent + "/" : ""; + if (!path.startsWith(prefix) || path.startsWith(".")) continue; + const parts = path.slice(prefix.length).split("/"); + entries.set(parts[0], { + name: parts[0], + rel_path: prefix + parts[0], + kind: parts.length > 1 ? "folder" : "file", + }); + } + return [...entries.values()]; + }, + async create(path, source) { + if (path === fail) throw new Error("Disk failure"); + if (files.has(path)) throw new Error("Exists"); + files.set(path, source); + }, + async write(path, source, expected) { + if (path === fail) throw new Error("Disk failure"); + if (files.get(path) !== expected) throw new Error("Conflict"); + files.set(path, source); + }, + }; + return { + files, + workspace, + id, + task, + source, + setFailure(path: string) { + fail = path; + }, + }; +} + +test("migration backs up exact originals, preserves cards and survives removal of visible metadata", async () => { + const { files, workspace, id, task, source } = fixture(); + const originalLabels = files.get(legacyLabelsPath)!; + const store = new TaskStore(workspace, { id, path: "Project/Launch.md" }); + const report = await store.migrateStorage(); + assert.equal(report.length, 2); + for (const file of report) + assert.equal(files.get(file.backup), files.get(file.path)); + assert.equal(files.get("Project/Launch.md"), source); + assert.equal(files.get(task.path), task.source); + assert.equal(store.board.reference?.path, boardKey(id)); + assert.equal(store.scopedTasks.length, 1); + assert.equal(store.scopedTasks[0].placements?.[id].order, "a"); + assert.equal(store.labels.value[0].name, "Defect"); + await store.board.edit("doing", "Building", "doing"); + await store.reload(); + await store.saveLabels( + [{ id: "bug", name: "Issue", color: "blue" }], + store.labels.source, + ); + await store.migrateStorage(); + assert.equal(store.board.value.lists[1].name, "Building"); + assert.equal(store.labels.value[0].name, "Issue"); + assert.equal(files.get(legacyLabelsPath), originalLabels); + files.delete("Project/Launch.md"); + files.delete(legacyLabelsPath); + const reopened = new TaskStore(workspace, { id, path: boardKey(id) }); + await reopened.reload(); + assert.equal(reopened.scopedTasks[0].id, store.tasks[0].id); + assert.equal(reopened.labels.value[0].name, "Issue"); + assert.equal(reopened.board.value.lists[1].name, "Building"); + assert.equal(reopened.issues.length, 0); +}); + +test("a label write failure can resume after boards commit without duplicating data", async () => { + const { files, workspace, setFailure } = fixture(); + const store = new TaskStore(workspace); + setFailure(labelsPath); + await assert.rejects(store.migrateStorage(), /Disk failure/); + assert.equal((await readCatalog(workspace)).value.boards.length, 1); + assert.ok(files.has(legacyLabelsPath)); + setFailure(""); + await store.migrateStorage(); + assert.equal((await readCatalog(workspace)).value.boards.length, 1); + assert.ok(files.has(labelsPath)); +}); + +test("backup failure prevents migration publication", async () => { + const { files, workspace, setFailure } = fixture(); + setFailure(".runestone/pm/backups/Project/Launch.md"); + await assert.rejects( + new TaskStore(workspace).migrateStorage(), + /Disk failure/, + ); + assert.equal(files.has(catalogPath), false); + assert.equal(files.has(labelsPath), false); +}); + +test("a legacy editor cannot write its original board after another view migrates it", async () => { + const { files, workspace, id, source } = fixture(); + const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" }); + await stale.reload(); + await new TaskStore(workspace).migrateStorage(); + await assert.rejects(stale.add("Old edit", null), /hidden storage/); + assert.equal(files.get("Project/Launch.md"), source); + await stale.reload(); + assert.equal(stale.reference?.path, boardKey(id)); + await stale.add("New edit", null); + assert.equal( + (await readCatalog(workspace)).value.boards[0].value.lists.at(-1)?.name, + "New edit", + ); +}); + +test("invalid or duplicate originals and conflicting labels block migration without writes", async () => { + for (const kind of [ + "duplicate", + "invalid-labels", + "hidden-labels", + "future", + ]) { + const { files, workspace, source } = fixture(); + if (kind === "duplicate") files.set("Duplicate.md", source); + if (kind === "invalid-labels") files.set(legacyLabelsPath, "broken"); + if (kind === "hidden-labels") + files.set(labelsPath, files.get(legacyLabelsPath)!); + if (kind === "future") files.set(catalogPath, '{"schema":99,"boards":[]}'); + const before = new Map(files); + await assert.rejects(new TaskStore(workspace).migrateStorage()); + assert.deepEqual(files, before); + } +}); + +test("changed legacy files or damaged backups never receive a successful migration check", async () => { + for (const path of [ + "Project/Launch.md", + ".runestone/pm/backups/Project/Launch.md", + legacyLabelsPath, + ]) { + const { files, workspace } = fixture(); + const store = new TaskStore(workspace); + await store.migrateStorage(); + files.set(path, files.get(path)! + "\n"); + const before = new Map(files); + await assert.rejects(store.migrateStorage()); + assert.deepEqual(files, before); + } +}); + +test("hidden boards rename, archive, restore, and reject stale writes without changing task notes", async () => { + const { files, workspace, task } = fixture(); + const reference = await createBoard(workspace, "New board"); + const store = new TaskStore(workspace, reference); + await store.reload(); + await store.renameBoard("Release"); + const stale = new BoardStore(workspace, reference); + await stale.reload(); + await store.board.manage({ archived: true }); + await assert.rejects(stale.add("Review", null), /changed/); + await store.reload(); + assert.equal(store.board.editable, false); + await assert.rejects( + store.create( + "No card", + { status: "todo", tags: [], sessions: [], archived: false }, + "", + ), + /Restore/, + ); + await store.board.manage({ archived: false }); + await store.reload(); + assert.equal(store.board.name, "Release"); + assert.equal(store.board.editable, true); + assert.equal(files.get(task.path), task.source); + await assert.rejects(createBoard(workspace, "release"), /already exists/); +}); + +test("hidden data is isolated by workspace and unknown catalog fields survive edits", async () => { + const a = fixture(), + b = fixture(); + const reference = await createBoard(a.workspace, "Private"); + const value = JSON.parse(a.files.get(catalogPath)!); + value.futureMapping = { externalId: "remote-1" }; + a.files.set(catalogPath, JSON.stringify(value)); + const board = new BoardStore(a.workspace, reference); + await board.reload(); + await board.add("Review", null); + assert.deepEqual( + JSON.parse(a.files.get(catalogPath)!).futureMapping, + value.futureMapping, + ); + assert.equal((await readCatalog(b.workspace)).value.boards.length, 0); +}); + +test("deleting a board preserves cards, other boards, and unknown catalog fields", async () => { + for (const archived of [false, true]) { + const { files, workspace, task, id } = fixture(); + const reference = await createBoard(workspace, "Accidental board"); + const initial = JSON.parse(files.get(catalogPath)!); + initial.futureMapping = { keep: "value" }; + initial.boards[0].archived = archived; + files.set(catalogPath, JSON.stringify(initial)); + const store = new TaskStore(workspace, reference); + await store.reload(); + await store.changeBoard(() => store.board.deleteBoard()); + assert.equal(store.board.available, false); + assert.equal(store.board.editable, false); + assert.equal(files.get(task.path), task.source); + const all = new TaskStore(workspace); + await all.reload(); + assert.deepEqual(all.boards.map((board) => board.id), [id]); + assert.equal(all.tasks[0].placements?.[id].listId, "doing"); + const catalog = (await readCatalog(workspace)).value; + assert.deepEqual(catalog.boards, []); + assert.deepEqual(catalog.deletedBoardIds, [reference.id]); + assert.deepEqual(catalog.futureMapping, initial.futureMapping); + await assert.rejects(store.board.deleteBoard(), /available/); + } +}); + +test("deleted legacy and migrated boards stay deleted after reload and migration", async () => { + for (const migrated of [false, true]) { + const { files, workspace, id, source, task } = fixture(); + const store = new TaskStore(workspace, { id, path: "Project/Launch.md" }); + await store.reload(); + const original = store.boards[0]; + const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" }); + await stale.reload(); + if (migrated) await store.migrateStorage(); + await store.changeBoard(() => store.board.deleteBoard()); + assert.equal(files.get("Project/Launch.md"), source); + assert.equal(files.get(task.path), task.source); + if (migrated) assert.equal(files.get(".runestone/pm/backups/Project/Launch.md"), source); + await assert.rejects(stale.add("Stale list", null), /deleted/); + await assert.rejects(stale.reload(), /deleted/); + assert.equal(stale.available, false); + await assert.rejects(migrateStorage(workspace, [original]), /deleted/); + const all = new TaskStore(workspace); + await all.reload(); + assert.equal(all.boards.length, 0); + assert.equal(all.legacyBoards.length, 0); + assert.equal(all.tasks.length, 1); + await all.migrateStorage(); + await all.reload(); + assert.equal(all.boards.length, 0); + assert.equal(all.issues.length, 0); + } +}); + +test("changed boards and failed catalog writes block deletion", async () => { + for (const managed of [false, true]) { + const { files, workspace, id, setFailure } = fixture(); + const reference = managed ? await createBoard(workspace, "New") : { id, path: "Project/Launch.md" }; + const board = new BoardStore(workspace, reference); + await board.reload(); + const path = managed ? catalogPath : reference.path; + files.set(path, files.get(path)! + "\n"); + const before = new Map(files); + await assert.rejects(board.deleteBoard(), /changed/); + assert.deepEqual(files, before); + await board.reload(); + setFailure(catalogPath); + await assert.rejects(board.deleteBoard(), /Disk failure/); + assert.equal(board.available, true); + assert.equal((await readCatalog(workspace)).value.deletedBoardIds, undefined); + } +}); + +test("a legacy board cannot be deleted from a stale view after migration", async () => { + const { workspace, id } = fixture(); + const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" }); + await stale.reload(); + await new TaskStore(workspace).migrateStorage(); + await assert.rejects(stale.deleteBoard(), /hidden storage/); + assert.equal((await readCatalog(workspace)).value.boards.length, 1); +}); + +test("invalid deletion records fail closed", () => { + for (const deletedBoardIds of ["id", [null], [""], ["id", "id"]]) + assert.throws(() => parseCatalog(JSON.stringify({ schema: 1, boards: [], deletedBoardIds })), /deleted board/); +}); diff --git a/tests/unit/features/pm/subtask-cards.spec.ts b/tests/unit/features/pm/subtask-cards.spec.ts new file mode 100644 index 0000000..e4684d2 --- /dev/null +++ b/tests/unit/features/pm/subtask-cards.spec.ts @@ -0,0 +1,32 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts"; +import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts"; +import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts"; + +test("subtask promotion retains checklist data and retries without duplicate cards", async () => { + const parent = newTask("Parent", { status: "todo", tags: [], sessions: [], archived: false, + subtasks: [{ id: "child", title: "Child", done: true }], priority: "high" }, "Keep the description"); + const files = new Map([["Parent.md", parent.source]]); + const parentId = readTask("Parent.md", parent.source)!.id; + let fail = true; + const workspace: Workspace = { + async list(folder = "") { return [...files.keys()].filter(path => folder ? path.startsWith(`${folder}/`) : !path.startsWith(".")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); }, + async read(path) { if (!files.has(path)) throw Error("Missing"); return files.get(path)!; }, + async readOptional(path) { return files.get(path) ?? null; }, + async create(path, source) { if (files.has(path)) throw Error("Exists"); files.set(path, source); }, + async write(path, source, expected) { if (fail) throw Error("Write failed"); assert.equal(files.get(path), expected); files.set(path, source); }, + }; + const store = new TaskStore(workspace); + await store.reload(); + await assert.rejects(store.openSubtask(parentId, "child"), /Write failed/); + fail = false; + const child = await store.openSubtask(parentId, "child"); + assert.equal(child.title, "Child"); assert.equal(child.status, "done"); assert.equal(child.priority, undefined); + assert.equal(store.tasks.length, 2); + const saved = readTask("Parent.md", files.get("Parent.md")!)!; + assert.equal(saved.subtasks![0].taskId, child.id); + assert.equal(saved.body, "Keep the description"); assert.equal(saved.priority, "high"); + assert.equal((await store.openSubtask(parentId, "child")).id, child.id); + assert.equal(store.tasks.length, 2); +}); diff --git a/tests/unit/features/pm/transient-background.spec.ts b/tests/unit/features/pm/transient-background.spec.ts new file mode 100644 index 0000000..cf29fab --- /dev/null +++ b/tests/unit/features/pm/transient-background.spec.ts @@ -0,0 +1,149 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { watchBackground, type BackgroundFrame, type PMBackgroundApi } from "../../../../src/lib/features/pm/model/transient-background.ts"; + +const frame = (url: string): BackgroundFrame => ({ url, overlay: 0, position: "center", size: "cover" }); +function fixture() { + const frames = new Map(); + const listeners = new Set<(target: string) => void>(); + // The shape of `backgroundHub` in `src/lib/plugins/backgrounds.ts`. + const api: PMBackgroundApi = { + get: target => frames.get(target) ?? null, + subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, + }; + const set = (target: string, value: BackgroundFrame | null) => { + if (value) frames.set(target, value); else frames.delete(target); + for (const listener of listeners) listener(target); + }; + return { api, set, listeners }; +} + +test("slides override saved images and removal restores them without writes", async () => { + const { api, set, listeners } = fixture(); + const seen: (BackgroundFrame | null)[] = []; + let savedReads = 0; + const watcher = watchBackground("pm-board:one", api, async () => { savedReads++; return frame("saved"); }, value => seen.push(value)); + await watcher.refresh(); + set("pm-board:one", frame("slide")); + assert.equal(seen.at(-1)?.url, "slide"); + assert.equal(savedReads, 1); + set("pm-board:one", null); + await Promise.resolve(); + assert.equal(seen.at(-1)?.url, "saved"); + watcher.dispose(); + watcher.dispose(); + assert.equal(listeners.size, 0); +}); + +test("pending saved reads cannot replace a new slide or change a closed mount", async () => { + const { api, set } = fixture(); + let resolve!: (value: BackgroundFrame) => void; + const pending = new Promise(done => { resolve = done; }); + const seen: (BackgroundFrame | null)[] = []; + const watcher = watchBackground("pm-all", api, () => pending, value => seen.push(value)); + const refresh = watcher.refresh(); + set("pm-all", frame("slide")); + resolve(frame("stale")); + await refresh; + assert.deepEqual(seen.map(value => value?.url), ["slide"]); + set("pm-all", null); + watcher.dispose(); + await Promise.resolve(); + await watcher.refresh(); + assert.equal(seen.length, 1); +}); + +test("late failures cannot clear a slide", async () => { + const { api, set } = fixture(); + let reject!: (error: Error) => void; + const pending = new Promise( (_resolve, fail) => { reject = fail; }); + const seen: (BackgroundFrame | null)[] = []; + const watcher = watchBackground("pm-all", api, () => pending, value => seen.push(value)); + const refresh = watcher.refresh(); + set("pm-all", frame("slide")); + reject(new Error("Missing image")); + await refresh; + assert.deepEqual(seen.map(value => value?.url), ["slide"]); + watcher.dispose(); +}); + +test("split mounts subscribe separately and filter board and all-task targets", async () => { + const { api, set, listeners } = fixture(); + const seen = [[], [], []] as (BackgroundFrame | null)[][]; + const mounts = ["pm-board:one", "pm-board:two", "pm-all"].map((target, index) => + watchBackground(target, api, async () => null, value => seen[index].push(value))); + set("pm-board:one", frame("one")); + assert.deepEqual(seen.map(values => values.length), [1, 0, 0]); + mounts[0].dispose(); + set("pm-board:two", frame("two")); + set("pm-all", frame("all")); + assert.deepEqual(seen.map(values => values.at(-1)?.url), ["one", "two", "all"]); + mounts[1].dispose(); mounts[2].dispose(); + assert.equal(listeners.size, 0); +}); + +test("all-board slides override saved boards and specific slides retain priority", async () => { + const { api, set } = fixture(); + const seen: (BackgroundFrame | null)[] = []; + const watcher = watchBackground("pm-board:one", api, async () => frame("saved"), value => seen.push(value)); + await watcher.refresh(); + set("pm-all", frame("all")); + assert.equal(seen.at(-1)?.url, "all"); + set("pm-board:one", frame("specific")); + set("pm-all", frame("next-all")); + assert.equal(seen.at(-1)?.url, "specific"); + set("pm-board:one", null); + assert.equal(seen.at(-1)?.url, "next-all"); + set("pm-all", null); + await Promise.resolve(); + assert.equal(seen.at(-1)?.url, "saved"); + watcher.dispose(); +}); + +test("older hosts use saved images and failures clear the background", async () => { + const seen: (BackgroundFrame | null)[] = []; + let fails = false; + const watcher = watchBackground("pm-all", undefined, async () => { + if (fails) throw new Error("Missing image"); + return frame("saved"); + }, value => seen.push(value)); + await watcher.refresh(); fails = true; await watcher.refresh(); + assert.deepEqual(seen.map(value => value?.url ?? null), ["saved", null]); + watcher.dispose(); +}); + +test("shared app slides use one host layer and react to either target changing", async () => { + const { api, set } = fixture(); + const seen: (BackgroundFrame | null)[] = []; + const watcher = watchBackground("pm-board:one", api, async () => frame("saved"), value => seen.push(value)); + set("pm-all", frame("shared")); + assert.equal(seen.at(-1)?.url, "shared"); + set("app", frame("shared")); + assert.equal(seen.at(-1), null); + set("app", frame("next")); + assert.equal(seen.at(-1)?.url, "shared"); + set("pm-all", frame("next")); + assert.equal(seen.at(-1), null); + set("pm-board:one", frame("specific")); + assert.equal(seen.at(-1)?.url, "specific"); + set("pm-board:one", null); + assert.equal(seen.at(-1), null); + set("app", null); + assert.equal(seen.at(-1)?.url, "next"); + watcher.dispose(); +}); + +test("different image appearance and transitions keep an independent PM layer", () => { + const { api, set } = fixture(); + const seen: (BackgroundFrame | null)[] = []; + const watcher = watchBackground("pm-all", api, async () => null, value => seen.push(value)); + set("app", frame("same")); + for (const difference of [{ blurredUrl: "blob:blur" }, { overlay: 0.4 }, { size: "contain" as const }, { position: "top left" as const }, + { previous: frame("old"), transitionMs: 500 }]) { + set("pm-all", { ...frame("same"), ...difference }); + assert.equal(seen.at(-1)?.url, "same"); + } + set("app", { ...frame("same"), previous: frame("old"), transitionMs: 500 }); + assert.equal(seen.at(-1), null); + watcher.dispose(); +}); diff --git a/tests/unit/features/terminal.spec.ts b/tests/unit/features/terminal.spec.ts index fa523ff..9eee149 100644 --- a/tests/unit/features/terminal.spec.ts +++ b/tests/unit/features/terminal.spec.ts @@ -11,6 +11,12 @@ import { TerminalSessions, type PtyRequest, type PtyTransport } from "../../../s import { SELECTION_ALPHA, TERMINAL_TOKENS, terminalColors } from "../../../src/lib/features/terminal/theme.ts"; import { ANSI_COLORS } from "../../../src/lib/theme/roles.ts"; import { SETTINGS_SECTIONS, LEGACY_KEYS } from "../../../src/lib/settings/store.ts"; +import type { ProjectManagementMigrationHost } from "../../../src/lib/features/pmSettings.ts"; + +/** A Project Management host with a section already present. */ +function presentProjectManagement(): ProjectManagementMigrationHost { + return { missing: () => false, write: async () => { throw new Error("not asked"); }, storage: { getItem: () => null, setItem: () => {} } }; +} test("Terminal keeps the ID of the Terminal plugin and follows its package", () => { const terminal = featureEntry("terminal"); @@ -254,16 +260,16 @@ test("the feature migration copies the terminal settings also when the package r const terminal = terminalHost(true, JSON.stringify({ fontSize: 20 })); const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} }; const host = { read: () => undefined, write: async () => { throw new Error("not asked"); }, legacy: async () => { throw new Error("no host"); } }; - assert.deepEqual(await migrateFeatures(host, background, terminal), []); + assert.deepEqual(await migrateFeatures(host, background, terminal, presentProjectManagement()), []); assert.deepEqual(terminal.written, [{ ...DEFAULT_TERMINAL, fontSize: 20 }]); } finally { console.error = error; } }); test("the terminal switch follows the enabled state of an installed Terminal plugin", async () => { const writes: unknown[] = []; - const host = { read: () => ({ git: true, background: true, pdf: true }), write: async (value: unknown) => { writes.push(value); }, + const host = { read: () => ({ git: true, background: true, pdf: true, pm: true }), write: async (value: unknown) => { writes.push(value); }, legacy: async (ids: string[]) => ids.map(id => ({ id, installed: true, enabled: false, settings: null })) }; const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} }; - assert.deepEqual(await migrateFeatures(host, background, terminalHost(false, null)), ["terminal"]); - assert.deepEqual(writes, [{ git: true, background: true, pdf: true, terminal: false }]); + assert.deepEqual(await migrateFeatures(host, background, terminalHost(false, null), presentProjectManagement()), ["terminal"]); + assert.deepEqual(writes, [{ git: true, background: true, pdf: true, pm: true, terminal: false }]); }); diff --git a/tests/unit/sdk/features.spec.ts b/tests/unit/sdk/features.spec.ts index 205c1e6..8314016 100644 --- a/tests/unit/sdk/features.spec.ts +++ b/tests/unit/sdk/features.spec.ts @@ -45,11 +45,13 @@ test("feature checks find optional members, and missing members give an update m assert.throws(() => requireFeature(api, "files"), (error: unknown) => error instanceof MissingFeatureError && error.name === "MissingFeatureError" && error.features.length === 1 && error.features[0] === "files" && error.message === "This plugin needs the folder grant API (api.files). Update RuneStone to a version that has this feature."); - assert.throws(() => requireFeatures(api, ["files", "backgrounds", "workspace.readBytes"]), { - message: "This plugin needs the folder grant API (api.files) and the background API (api.backgrounds). Update RuneStone to a version that has these features.", + assert.throws(() => requireFeatures(api, ["files", "workspace.readBytes", "openFile"]), { + message: "This plugin needs the folder grant API (api.files) and opening files in the RuneStone editor (api.openFile). Update RuneStone to a version that has these features.", }); - // The terminal API (api.pty) left the SDK when Terminal became a native feature. + // The terminal API (api.pty) left the SDK when Terminal became a native feature, and the background API + // (api.backgrounds) when Project Management became one. assert.throws(() => hasFeature(api, "pty" as never), TypeError); + assert.throws(() => hasFeature(api, "backgrounds" as never), TypeError); assert.doesNotThrow(() => requireFeatures(api, ["services", "workspace.readBytes"])); assert.throws(() => hasFeature(api, "workspace.read" as never), TypeError); assert.equal(describeFeature("ui.showActionMenu"), "the shared action menu (api.ui.showActionMenu)"); @@ -66,7 +68,7 @@ test("a required function stays bound to its parent object", async () => { test("the current host gives every SDK feature when all services are present", async () => { const files = { chooseFolder: async () => null, pictureFolder: async () => ({ id: "g", path: "p", name: "n" }), grants: async () => [], revoke: async () => false, list: async () => [], readBytes: async () => new Uint8Array(), readSidecar: async () => null, writeSidecar: async () => {} }; const { api, session } = await hostApi({ - files, backgrounds: true, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {}, + files, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {}, workspace: { ...base.workspace, listMarkdown: async () => [], readMany: async () => [], readBytes: async () => new Uint8Array(), readOptional: async () => null, create: async () => {}, subscribe: () => () => {} }, settings: { ...base.settings, subscribe: () => () => {} }, }, true); @@ -77,7 +79,7 @@ test("the current host gives every SDK feature when all services are present", a test("the host without optional services lacks only the features that depend on them", async () => { const { api, session } = await hostApi({}); assert.deepEqual(missingFeatures(api, pluginFeatures).sort(), [ - "backgrounds", "closeView", "completion.transport", "files", + "closeView", "completion.transport", "files", "openFile", "renameDocument", "replaceDocumentWithView", "replaceView", "settings.subscribe", "workspace.create", "workspace.listMarkdown", "workspace.readBytes", "workspace.readMany", "workspace.readOptional", "workspace.subscribe", ]); diff --git a/tests/unit/settings/migration.spec.ts b/tests/unit/settings/migration.spec.ts index bf0eda1..d9e7ad4 100644 --- a/tests/unit/settings/migration.spec.ts +++ b/tests/unit/settings/migration.spec.ts @@ -67,5 +67,6 @@ test('Migration keeps renamed theme IDs and a background image data URL', () => test('Every section has one old key', () => { // `runestone.features` and `runestone.background` came after the settings file. Only the browser preview uses them. // `runestone.terminal` is the key of the Terminal plugin. The first start of the Terminal feature copies it into the file. - assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.background', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.settings', 'runestone.terminal']); + // `runestone.project-management` came with the Project Management feature. Only the browser preview uses it. + assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.background', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.project-management', 'runestone.settings', 'runestone.terminal']); }); diff --git a/tests/unit/theme/backgrounds.spec.ts b/tests/unit/theme/backgrounds.spec.ts index f347811..4b033e9 100644 --- a/tests/unit/theme/backgrounds.spec.ts +++ b/tests/unit/theme/backgrounds.spec.ts @@ -3,7 +3,8 @@ import { readFileSync } from 'node:fs'; import assert from 'node:assert/strict'; import { BackgroundHub, backgroundHub } from '../../../src/lib/plugins/backgrounds.ts'; import { ExternalSession } from '../../../src/lib/plugins/externalSession.ts'; -import type { BackgroundFrame, PluginApi } from '../../../src/lib/plugins/sdk.ts'; +import type { PluginApi } from '../../../src/lib/plugins/sdk.ts'; +import type { BackgroundFrame } from '../../../src/lib/plugins/backgroundContracts.ts'; const frame: BackgroundFrame = { url: 'blob:http://localhost/example', overlay: 0.3, position: 'center', size: 'cover' }; @@ -103,36 +104,23 @@ test('subscriber errors do not prevent frame cleanup or remaining notifications' assert.equal(hub.get('pm-all'), null); }); -test('disable removes frames and subscriptions before cleanup', async () => { +test('plugins get no background API, and the frames stay with the host', async () => { let api!: PluginApi; const session = new ExternalSession('org.test.backgrounds', { workspace: { list: async () => [], read: async () => '', write: async () => {} }, settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() }, - backgrounds: true, }, () => {}, () => {}); - let notifications = 0; - await session.start({ activate(value) { - api = value; - api.backgrounds!.subscribe(() => { notifications++; }); - api.backgrounds!.set('app', frame); - api.backgrounds!.set('pm-all', frame); - api.onDispose(() => { - assert.equal(backgroundHub.get('app'), null); - assert.equal(backgroundHub.get('pm-all'), null); - assert.throws(() => api.backgrounds!.get('app'), /disabled/); - }); - } }); - // The deprecated folder methods are gone. Plugins use the folder grants of `api.files`. - for (const name of ['chooseFolder', 'defaultFolder', 'list', 'read', 'readImageSettings', 'writeImageSettings']) assert.equal(name in api.backgrounds!, false, name); + await session.start({ activate(value) { api = value; } }); + // Project Management was the last plugin user of `api.backgrounds`. It reads `backgroundHub` as a native feature. + assert.equal('backgrounds' in api, false); + const owner = Symbol(); + backgroundHub.set(owner, 'pm-all', frame); await session.stop(); - assert.equal(notifications, 2); - assert.throws(() => api.backgrounds!.set('app', frame), /disabled/); - assert.throws(() => api.backgrounds!.subscribe(() => {}), /disabled/); - assert.equal(backgroundHub.get('app'), null); + assert.deepEqual(backgroundHub.get('pm-all'), frame); + backgroundHub.removeOwner(owner); }); - test('the Background commands are allowed in the windows that use them, and the old plugin commands are gone', () => { const build = readFileSync(new URL('../../../src-tauri/build.rs', import.meta.url), 'utf8'); const all = ['background_choose_folder', 'background_folder', 'background_clear_folder', 'background_list', 'background_read', 'background_read_sidecar', 'background_write_sidecar', 'background_migrate'];