Make Project Management a native feature
- 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-<hex> 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.
This commit is contained in:
@@ -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/`) |
|
| `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/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 |
|
| `@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
|
## 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
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## yaml
|
||||||
|
|
||||||
|
From `yaml/LICENSE`.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Copyright Eemeli Aro <[email protected]>
|
||||||
|
|
||||||
|
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.
|
||||||
|
```
|
||||||
|
|||||||
+73
-101
@@ -1,9 +1,7 @@
|
|||||||
{
|
{
|
||||||
"date": "2026-10-15",
|
"date": "2026-10-29",
|
||||||
"scope": [
|
"scope": [
|
||||||
"RuneStone",
|
"RuneStone",
|
||||||
"RuneStone_Project_Management",
|
|
||||||
"RuneStone_Background_Slideshow",
|
|
||||||
"RuneStone_Local_Autocomplete",
|
"RuneStone_Local_Autocomplete",
|
||||||
"RuneStone_CSV_Viewer"
|
"RuneStone_CSV_Viewer"
|
||||||
],
|
],
|
||||||
@@ -172,97 +170,6 @@
|
|||||||
"design": "Shared action menu",
|
"design": "Shared action menu",
|
||||||
"check": "tests/smoke/menus/consistency.smoke.mjs"
|
"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": {
|
"RuneStone_Local_Autocomplete/src/main.mjs": {
|
||||||
"counts": {
|
"counts": {
|
||||||
"action": 1,
|
"action": 1,
|
||||||
@@ -288,13 +195,6 @@
|
|||||||
"design": "Shared action menu for interface language; settings retain ordinary controls",
|
"design": "Shared action menu for interface language; settings retain ordinary controls",
|
||||||
"check": "tests/smoke/settings/displayLanguage.smoke.mjs; tests/smoke/menus/consistency.smoke.mjs"
|
"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": {
|
"RuneStone/src/lib/features/background/BackgroundSettings.svelte": {
|
||||||
"counts": {
|
"counts": {
|
||||||
"action": 1,
|
"action": 1,
|
||||||
@@ -334,6 +234,78 @@
|
|||||||
},
|
},
|
||||||
"design": "Shared action menu for the default profile in Settings → Terminal",
|
"design": "Shared action menu for the default profile in Settings → Terminal",
|
||||||
"check": "tests/smoke/features/terminal.smoke.mjs"
|
"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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -58,7 +58,8 @@
|
|||||||
"@xterm/xterm": "6.0.0",
|
"@xterm/xterm": "6.0.0",
|
||||||
"markdown-it": "^15.0.2",
|
"markdown-it": "^15.0.2",
|
||||||
"mermaid": "^12.0.0",
|
"mermaid": "^12.0.0",
|
||||||
"pdfjs-dist": "6.4.299"
|
"pdfjs-dist": "6.4.299",
|
||||||
|
"yaml": "2.9.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@sveltejs/adapter-static": "^3.0.10",
|
"@sveltejs/adapter-static": "^3.0.10",
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import type { BackgroundApi } from "./backgrounds.ts";
|
|
||||||
import type { CompletionApi } from "./completion.ts";
|
import type { CompletionApi } from "./completion.ts";
|
||||||
import type { Contributions } from "./contributions.ts";
|
import type { Contributions } from "./contributions.ts";
|
||||||
import type { ActionIcon } from "./icons.ts";
|
import type { ActionIcon } from "./icons.ts";
|
||||||
@@ -63,7 +62,6 @@ export interface UiApi { showActionMenu(options: ActionMenuOptions): { close():
|
|||||||
export interface PluginApi {
|
export interface PluginApi {
|
||||||
files?: FilesApi;
|
files?: FilesApi;
|
||||||
services?: ServicesApi;
|
services?: ServicesApi;
|
||||||
backgrounds?: BackgroundApi;
|
|
||||||
ui?: UiApi;
|
ui?: UiApi;
|
||||||
completion?: CompletionApi;
|
completion?: CompletionApi;
|
||||||
readonly id: string;
|
readonly id: string;
|
||||||
|
|||||||
@@ -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<BackgroundFrame, 'previous' | 'transitionMs'>;
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import type { FilesApi, PluginApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts";
|
import type { FilesApi, PluginApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts";
|
||||||
import type { BackgroundApi } from "./backgrounds.ts";
|
|
||||||
import type { CompletionApi } from "./completion.ts";
|
import type { CompletionApi } from "./completion.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -9,7 +8,6 @@ import type { CompletionApi } from "./completion.ts";
|
|||||||
export interface PluginFeatures {
|
export interface PluginFeatures {
|
||||||
files: FilesApi;
|
files: FilesApi;
|
||||||
services: ServicesApi;
|
services: ServicesApi;
|
||||||
backgrounds: BackgroundApi;
|
|
||||||
completion: CompletionApi;
|
completion: CompletionApi;
|
||||||
"completion.transport": NonNullable<CompletionApi["transport"]>;
|
"completion.transport": NonNullable<CompletionApi["transport"]>;
|
||||||
"ui.showActionMenu": UiApi["showActionMenu"];
|
"ui.showActionMenu": UiApi["showActionMenu"];
|
||||||
@@ -34,7 +32,6 @@ export type PluginFeature = keyof PluginFeatures;
|
|||||||
const descriptions: { [K in PluginFeature]: string } = {
|
const descriptions: { [K in PluginFeature]: string } = {
|
||||||
files: "the folder grant API",
|
files: "the folder grant API",
|
||||||
services: "the plugin service API",
|
services: "the plugin service API",
|
||||||
backgrounds: "the background API",
|
|
||||||
completion: "the completion API",
|
completion: "the completion API",
|
||||||
"completion.transport": "the completion model transport",
|
"completion.transport": "the completion model transport",
|
||||||
"ui.showActionMenu": "the shared action menu",
|
"ui.showActionMenu": "the shared action menu",
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
// The public types and helpers of the RuneStone plugin API.
|
// 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".
|
// 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 "./api.ts";
|
||||||
export type * from "./backgrounds.ts";
|
|
||||||
export type * from "./completion.ts";
|
export type * from "./completion.ts";
|
||||||
export type * from "./contributions.ts";
|
export type * from "./contributions.ts";
|
||||||
export type * from "./menu.ts";
|
export type * from "./menu.ts";
|
||||||
|
|||||||
Generated
+26
-15
@@ -104,16 +104,19 @@ importers:
|
|||||||
pdfjs-dist:
|
pdfjs-dist:
|
||||||
specifier: 6.4.299
|
specifier: 6.4.299
|
||||||
version: 6.4.299
|
version: 6.4.299
|
||||||
|
yaml:
|
||||||
|
specifier: 2.9.1
|
||||||
|
version: 2.9.1
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@sveltejs/adapter-static':
|
'@sveltejs/adapter-static':
|
||||||
specifier: ^3.0.10
|
specifier: ^3.0.10
|
||||||
version: 3.0.10(@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected])))
|
version: 3.0.10(@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected])))
|
||||||
'@sveltejs/kit':
|
'@sveltejs/kit':
|
||||||
specifier: ^2.65.1
|
specifier: ^2.65.1
|
||||||
version: 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected]))
|
version: 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected]))
|
||||||
'@sveltejs/vite-plugin-svelte':
|
'@sveltejs/vite-plugin-svelte':
|
||||||
specifier: ^7.1.2
|
specifier: ^7.1.2
|
||||||
version: 7.3.0([email protected])([email protected](@types/[email protected]))
|
version: 7.3.0([email protected])([email protected](@types/[email protected])([email protected]))
|
||||||
'@tauri-apps/cli':
|
'@tauri-apps/cli':
|
||||||
specifier: ^2
|
specifier: ^2
|
||||||
version: 2.11.4
|
version: 2.11.4
|
||||||
@@ -134,7 +137,7 @@ importers:
|
|||||||
version: 6.0.3
|
version: 6.0.3
|
||||||
vite:
|
vite:
|
||||||
specifier: ^8.0.16
|
specifier: ^8.0.16
|
||||||
version: 8.3.0(@types/[email protected])
|
version: 8.3.0(@types/[email protected])([email protected])
|
||||||
|
|
||||||
packages:
|
packages:
|
||||||
|
|
||||||
@@ -1489,6 +1492,11 @@ packages:
|
|||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
|
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
|
||||||
|
|
||||||
|
[email protected]:
|
||||||
|
resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==}
|
||||||
|
engines: {node: '>= 14.6'}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==}
|
resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==}
|
||||||
|
|
||||||
@@ -1860,15 +1868,15 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
acorn: 8.18.0
|
acorn: 8.18.0
|
||||||
|
|
||||||
'@sveltejs/[email protected](@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected])))':
|
'@sveltejs/[email protected](@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected])))':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@sveltejs/kit': 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected]))
|
'@sveltejs/kit': 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected]))
|
||||||
|
|
||||||
'@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected]))':
|
'@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected]))':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@standard-schema/spec': 1.1.0
|
'@standard-schema/spec': 1.1.0
|
||||||
'@sveltejs/acorn-typescript': 1.0.13([email protected])
|
'@sveltejs/acorn-typescript': 1.0.13([email protected])
|
||||||
'@sveltejs/vite-plugin-svelte': 7.3.0([email protected])([email protected](@types/[email protected]))
|
'@sveltejs/vite-plugin-svelte': 7.3.0([email protected])([email protected](@types/[email protected])([email protected]))
|
||||||
'@types/cookie': 0.6.0
|
'@types/cookie': 0.6.0
|
||||||
acorn: 8.18.0
|
acorn: 8.18.0
|
||||||
cookie: 0.6.0
|
cookie: 0.6.0
|
||||||
@@ -1880,20 +1888,20 @@ snapshots:
|
|||||||
set-cookie-parser: 3.1.2
|
set-cookie-parser: 3.1.2
|
||||||
sirv: 3.0.2
|
sirv: 3.0.2
|
||||||
svelte: 5.57.1
|
svelte: 5.57.1
|
||||||
vite: 8.3.0(@types/[email protected])
|
vite: 8.3.0(@types/[email protected])([email protected])
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
typescript: 6.0.3
|
typescript: 6.0.3
|
||||||
|
|
||||||
'@sveltejs/[email protected]': {}
|
'@sveltejs/[email protected]': {}
|
||||||
|
|
||||||
'@sveltejs/[email protected]([email protected])([email protected](@types/[email protected]))':
|
'@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected]))':
|
||||||
dependencies:
|
dependencies:
|
||||||
deepmerge: 4.3.1
|
deepmerge: 4.3.1
|
||||||
magic-string: 1.4.1
|
magic-string: 1.4.1
|
||||||
obug: 2.2.1
|
obug: 2.2.1
|
||||||
svelte: 5.57.1
|
svelte: 5.57.1
|
||||||
vite: 8.3.0(@types/[email protected])
|
vite: 8.3.0(@types/[email protected])([email protected])
|
||||||
vitefu: 1.1.3([email protected](@types/[email protected]))
|
vitefu: 1.1.3([email protected](@types/[email protected])([email protected]))
|
||||||
|
|
||||||
'@tauri-apps/[email protected]': {}
|
'@tauri-apps/[email protected]': {}
|
||||||
|
|
||||||
@@ -2860,7 +2868,7 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected](@types/[email protected]):
|
[email protected](@types/[email protected])([email protected]):
|
||||||
dependencies:
|
dependencies:
|
||||||
lightningcss: 1.33.0
|
lightningcss: 1.33.0
|
||||||
picomatch: 4.0.7
|
picomatch: 4.0.7
|
||||||
@@ -2870,11 +2878,14 @@ snapshots:
|
|||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/node': 24.19.2
|
'@types/node': 24.19.2
|
||||||
fsevents: 2.3.3
|
fsevents: 2.3.3
|
||||||
|
yaml: 2.9.1
|
||||||
|
|
||||||
[email protected]([email protected](@types/[email protected])):
|
[email protected]([email protected](@types/[email protected])([email protected])):
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
vite: 8.3.0(@types/[email protected])
|
vite: 8.3.0(@types/[email protected])([email protected])
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import path from "node:path";
|
|||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
/** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */
|
/** 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. */
|
/** Libraries that only features need. */
|
||||||
export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"];
|
export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"];
|
||||||
|
|
||||||
|
|||||||
@@ -71,8 +71,11 @@ export const TABLE = {
|
|||||||
pm: {
|
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` },
|
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",
|
nativeKey: "pm",
|
||||||
/** Where the view opens: `palette`, or `menu:<ribbon menu name>`. */
|
/**
|
||||||
openIn: { plugin: "menu:Plug-in views", native: "menu:Plug-in views" },
|
* Where the view opens: `palette`, `menu:<ribbon menu name>`, or `ribbon:<ribbon button name>`. 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",
|
title: "Project Management",
|
||||||
card: { plugin: ".pm-card", native: ".pm-card" },
|
card: { plugin: ".pm-card", native: ".pm-card" },
|
||||||
minCards: 50,
|
minCards: 50,
|
||||||
@@ -101,9 +104,14 @@ export async function runPaletteCommand(page, title) {
|
|||||||
await input.press("Enter");
|
await input.press("Enter");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Run a command from the palette or from a ribbon menu. `where` is `palette` or `menu:<menu name>`. */
|
/**
|
||||||
|
* Run a command from the palette, from a ribbon menu, or from a ribbon button.
|
||||||
|
* `where` is `palette`, `menu:<menu name>`, or `ribbon:<button name>`.
|
||||||
|
*/
|
||||||
export async function runCommand(page, where, title) {
|
export async function runCommand(page, where, title) {
|
||||||
if (where === "palette") return runPaletteCommand(page, title);
|
if (where === "palette") return runPaletteCommand(page, title);
|
||||||
|
const button = /^ribbon:(.+)$/.exec(where)?.[1];
|
||||||
|
if (button) return page.locator(".plugin-ribbon").getByRole("button", { name: button, exact: true }).click();
|
||||||
const menu = /^menu:(.+)$/.exec(where)?.[1];
|
const menu = /^menu:(.+)$/.exec(where)?.[1];
|
||||||
if (!menu) throw new Error(`Unknown command place ${where}.`);
|
if (!menu) throw new Error(`Unknown command place ${where}.`);
|
||||||
await page.locator(".plugin-ribbon").getByRole("button", { name: menu, exact: true }).click();
|
await page.locator(".plugin-ribbon").getByRole("button", { name: menu, exact: true }).click();
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
|
|||||||
|
|
||||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||||
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..');
|
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..');
|
||||||
export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_CSV_Viewer'];
|
export const projects = ['RuneStone', 'RuneStone_Local_Autocomplete', 'RuneStone_CSV_Viewer'];
|
||||||
const patterns = {
|
const patterns = {
|
||||||
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
|
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
|
||||||
svelteMenu: /<ContextMenu\b/g,
|
svelteMenu: /<ContextMenu\b/g,
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use crate::error::{Error, Result};
|
|||||||
use crate::plugins::{legacy_packages, LegacyPackage};
|
use crate::plugins::{legacy_packages, LegacyPackage};
|
||||||
|
|
||||||
/// The packages that native features replace. A request for another ID fails.
|
/// The packages that native features replace. A request for another ID fails.
|
||||||
pub const LEGACY_PACKAGES: [&str; 4] = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer"];
|
pub const LEGACY_PACKAGES: [&str; 5] = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm"];
|
||||||
|
|
||||||
fn check(ids: &[String]) -> Result<()> {
|
fn check(ids: &[String]) -> Result<()> {
|
||||||
if ids.len() > LEGACY_PACKAGES.len() {
|
if ids.len() > LEGACY_PACKAGES.len() {
|
||||||
@@ -36,12 +36,13 @@ mod tests {
|
|||||||
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok());
|
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok());
|
||||||
assert!(check(&["runestone.terminal".into()]).is_ok());
|
assert!(check(&["runestone.terminal".into()]).is_ok());
|
||||||
assert!(check(&["runestone.pdf-viewer".into()]).is_ok());
|
assert!(check(&["runestone.pdf-viewer".into()]).is_ok());
|
||||||
|
assert!(check(&["runestone.pm".into()]).is_ok());
|
||||||
assert!(check(&LEGACY_PACKAGES.map(String::from)).is_ok());
|
assert!(check(&LEGACY_PACKAGES.map(String::from)).is_ok());
|
||||||
assert!(check(&[]).is_ok());
|
assert!(check(&[]).is_ok());
|
||||||
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
|
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
|
||||||
assert!(check(&[id.into()]).is_err(), "{id}");
|
assert!(check(&[id.into()]).is_err(), "{id}");
|
||||||
}
|
}
|
||||||
let too_many = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.git"].map(String::from);
|
let too_many = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm", "runestone.git"].map(String::from);
|
||||||
assert!(too_many.len() > LEGACY_PACKAGES.len());
|
assert!(too_many.len() > LEGACY_PACKAGES.len());
|
||||||
assert!(check(&too_many).is_err());
|
assert!(check(&too_many).is_err());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ pub const FILE_NAME: &str = "settings.json";
|
|||||||
pub const SCHEMA: u64 = 1;
|
pub const SCHEMA: u64 = 1;
|
||||||
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
|
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
|
||||||
/// `features` holds the switches of the native features. `background` and `terminal` hold the settings of the Background and Terminal features.
|
/// `features` holds the switches of the native features. `background` and `terminal` hold the settings of the Background and Terminal features.
|
||||||
pub const SECTIONS: [&str; 8] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal"];
|
pub const SECTIONS: [&str; 9] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal", "projectManagement"];
|
||||||
/// The appearance section can hold an image data URL of up to 3,000,000 characters.
|
/// The appearance section can hold an image data URL of up to 3,000,000 characters.
|
||||||
pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
|
pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
|
||||||
pub const CHANGED_EVENT: &str = "settings-changed";
|
pub const CHANGED_EVENT: &str = "settings-changed";
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
<!--
|
||||||
|
Settings → Project Management, and the Project Management settings of the board menu. It is in the main bundle and
|
||||||
|
loads no feature code: the priority levels are in the `projectManagement` settings section (`pmSettings.ts`), and
|
||||||
|
the default board is in `.runestone/pm/workspace.json` of the workspace (`pmBoards.ts`). It shows only while
|
||||||
|
Project Management is on. Each change saves at once.
|
||||||
|
-->
|
||||||
|
<script lang="ts">
|
||||||
|
import { onDestroy, onMount } from "svelte";
|
||||||
|
import { t } from "$lib/i18n";
|
||||||
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
|
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||||
|
import { PRIORITY_LEVELS, onProjectManagementChange, readProjectManagement, writeProjectManagement, type PriorityLevels, type ProjectManagementSettings } from "./pmSettings";
|
||||||
|
import { readBoardCatalog, writeDefaultBoard, type BoardSummary } from "./pmBoards";
|
||||||
|
|
||||||
|
let { compact = false }: { compact?: boolean } = $props();
|
||||||
|
|
||||||
|
const levelNames: Record<PriorityLevels, string> = { 2: "2 — High and Low", 3: "3 — High, Medium, and Low", 5: "5 — Highest through Lowest" };
|
||||||
|
let settings = $state<ProjectManagementSettings>(readProjectManagement());
|
||||||
|
let boards = $state<BoardSummary[]>([]);
|
||||||
|
let defaultBoard = $state("");
|
||||||
|
let boardsReady = $state(false);
|
||||||
|
let boardNote = $state("");
|
||||||
|
let saving = $state(false);
|
||||||
|
let message = $state("");
|
||||||
|
let error = $state("");
|
||||||
|
let closeMenu = () => {};
|
||||||
|
let disposed = false;
|
||||||
|
const active = $derived(boards.filter(board => !board.archived));
|
||||||
|
const boardName = $derived(defaultBoard ? active.find(board => board.id === defaultBoard)?.name ?? "Unavailable board (opens All tasks)" : "All tasks");
|
||||||
|
|
||||||
|
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
|
||||||
|
closeMenu();
|
||||||
|
const anchor = event.currentTarget as HTMLButtonElement;
|
||||||
|
const bounds = anchor.getBoundingClientRect();
|
||||||
|
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
|
||||||
|
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveLevels(priorityLevels: PriorityLevels) {
|
||||||
|
error = "";
|
||||||
|
settings = { ...settings, priorityLevels };
|
||||||
|
writeProjectManagement(settings).then(() => { message = $t("Changes saved."); })
|
||||||
|
.catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; settings = readProjectManagement(); });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveDefault(id: string) {
|
||||||
|
const previous = defaultBoard;
|
||||||
|
error = ""; saving = true; defaultBoard = id;
|
||||||
|
try { await writeDefaultBoard(id || null); if (!disposed) message = $t("Changes saved."); }
|
||||||
|
catch (reason) { if (!disposed) { defaultBoard = previous; message = ""; error = reason instanceof Error ? reason.message : String(reason); } }
|
||||||
|
finally { saving = false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readBoards() {
|
||||||
|
try {
|
||||||
|
const catalog = await readBoardCatalog();
|
||||||
|
if (disposed) return;
|
||||||
|
boards = catalog.boards;
|
||||||
|
defaultBoard = catalog.defaultBoardId ?? "";
|
||||||
|
boardsReady = true;
|
||||||
|
boardNote = "";
|
||||||
|
} catch (reason) {
|
||||||
|
if (!disposed) boardNote = /no workspace/i.test(String(reason)) ? "Open a workspace to choose its default board." : reason instanceof Error ? reason.message : String(reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
void readBoards();
|
||||||
|
return onProjectManagementChange(() => { settings = readProjectManagement(); });
|
||||||
|
});
|
||||||
|
onDestroy(() => { disposed = true; closeMenu(); });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="pm-settings">
|
||||||
|
{#if !compact}
|
||||||
|
<h2>{$t("Project Management")}</h2>
|
||||||
|
<p class="intro">The boards of each workspace stay in .runestone/pm in the workspace.</p>
|
||||||
|
{/if}
|
||||||
|
<div class="card">
|
||||||
|
<div class="setting-row">
|
||||||
|
<div><span class="name" id="pm-priority-label">Priority levels</span><p id="pm-priority-description">Existing card priorities stay unchanged when you change this setting.</p></div>
|
||||||
|
<button class="picker" type="button" aria-label="Priority levels" aria-describedby="pm-priority-description" aria-haspopup="menu"
|
||||||
|
onclick={event => picker(event, "Priority levels", PRIORITY_LEVELS.map(levels => ({ label: levelNames[levels], checked: settings.priorityLevels === levels, run: () => saveLevels(levels) })))}>
|
||||||
|
{levelNames[settings.priorityLevels]}<Icon icon="chevron-down" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<div><span class="name" id="pm-default-label">Default board</span><p id="pm-default-description">{boardNote || "Choose the board that opens in this workspace. Restored tabs keep their board."}</p></div>
|
||||||
|
<button class="picker" type="button" aria-label="Default board" aria-describedby="pm-default-description" aria-haspopup="menu" disabled={!boardsReady || saving}
|
||||||
|
onclick={event => picker(event, "Default board", [
|
||||||
|
{ label: "All tasks", checked: !defaultBoard, run: () => void saveDefault("") },
|
||||||
|
...active.map(board => ({ label: board.name, checked: defaultBoard === board.id, run: () => void saveDefault(board.id) })),
|
||||||
|
])}>
|
||||||
|
{boardName}<Icon icon="chevron-down" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||||
|
<p class="saved" role="status">{message}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.pm-settings { min-width: 0; }
|
||||||
|
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
|
||||||
|
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
|
||||||
|
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
|
||||||
|
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||||
|
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
|
||||||
|
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
|
||||||
|
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
||||||
|
.name { font-weight: 500; color: var(--rs-text); }
|
||||||
|
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
|
||||||
|
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); box-sizing: border-box; max-width: 100%; min-width: 160px; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: left; cursor: pointer; }
|
||||||
|
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
|
||||||
|
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
|
||||||
|
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||||
|
.picker:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||||
|
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
|
||||||
|
.error { color: var(--rs-error); margin-top: 10px; }
|
||||||
|
</style>
|
||||||
@@ -9,7 +9,8 @@
|
|||||||
import Icon from "$lib/ui/Icon.svelte";
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||||
import { onSettingsChange } from "$lib/settings/store";
|
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 { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, saveAppearance, type Appearance } from "$lib/theme/appearance";
|
||||||
import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages";
|
import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages";
|
||||||
import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings";
|
import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings";
|
||||||
@@ -17,8 +18,7 @@
|
|||||||
import { imageNames } from "./imageSettings";
|
import { imageNames } from "./imageSettings";
|
||||||
import ImageEditor from "./ImageEditor.svelte";
|
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. */
|
/** The background targets of single boards need a UUID board ID. */
|
||||||
const BOARD_SERVICE = ["runestone.pm", "boards"] as const;
|
|
||||||
const boardId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
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<BackgroundSettings>(readBackground());
|
let settings = $state<BackgroundSettings>(readBackground());
|
||||||
@@ -148,20 +148,17 @@
|
|||||||
save({ ...settings, targets: on ? [...new Set([...settings.targets, id])] : settings.targets.filter(target => target !== id) });
|
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 revision = ++boardRevision;
|
||||||
const service = serviceHub.get(...BOARD_SERVICE, () => !disposed);
|
if (!on) {
|
||||||
if (!service || typeof service.list !== "function") {
|
|
||||||
boards = []; boardsNote = tr("Turn on Project Management to show the background on one board.");
|
boards = []; boardsNote = tr("Turn on Project Management to show the background on one board.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const rows = await service.list();
|
const catalog = await readBoardCatalog();
|
||||||
if (disposed || revision !== boardRevision) return;
|
if (disposed || revision !== boardRevision) return;
|
||||||
boards = (Array.isArray(rows) ? rows : []).flatMap((row: unknown) => {
|
boards = catalog.boards.filter(board => !board.archived && boardId.test(board.id)).map(board => ({ id: board.id, name: board.name }));
|
||||||
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);
|
|
||||||
boardsNote = boards.length ? "" : tr("The workspace has no boards.");
|
boardsNote = boards.length ? "" : tr("The workspace has no boards.");
|
||||||
} catch (reason) {
|
} catch (reason) {
|
||||||
if (!disposed && revision === boardRevision) boardsNote = tr("Could not read the workspace boards: {error}", { error: reason instanceof Error ? reason.message : String(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(() => {
|
onMount(() => {
|
||||||
const read = () => { settings = readBackground(); appearance = readAppearance(); };
|
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 folderHost.current().then(value => { if (!disposed) { folder = value; void inspectFolder(); } }, () => { folder = null; });
|
||||||
void discoverBoards();
|
|
||||||
return () => stops.forEach(stop => stop());
|
return () => stops.forEach(stop => stop());
|
||||||
});
|
});
|
||||||
onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); });
|
onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); });
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { message, tr } from "../i18n/index.ts";
|
|||||||
import type { PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
|
import type { PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
|
||||||
import { identifyPdf } from "./pdfDocument.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. */
|
/** 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 {
|
export interface FeatureViewInfo {
|
||||||
@@ -16,6 +16,21 @@ export interface FeatureViewInfo {
|
|||||||
icon?: PluginView["icon"];
|
icon?: PluginView["icon"];
|
||||||
/** Show a navigation button for the view. */
|
/** Show a navigation button for the view. */
|
||||||
navigation?: boolean;
|
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. */
|
/** 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`. */
|
/** True when the first start gives the switch the state of the old package. False when every user gets `defaultOn`. */
|
||||||
followsPackage: boolean;
|
followsPackage: boolean;
|
||||||
views: readonly FeatureViewInfo[];
|
views: readonly FeatureViewInfo[];
|
||||||
|
/** Editor views with IDs that follow a pattern. */
|
||||||
|
viewPatterns?: readonly FeatureViewPattern[];
|
||||||
commands: readonly FeatureCommandInfo[];
|
commands: readonly FeatureCommandInfo[];
|
||||||
documentTypes: readonly FeatureDocumentInfo[];
|
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 },
|
{ 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-<hex of the board ID>`, 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 {
|
export function featureEntry(id: FeatureId): FeatureEntry {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
|
|||||||
background: () => import("./background/index.ts"),
|
background: () => import("./background/index.ts"),
|
||||||
terminal: () => import("./terminal/index.ts"),
|
terminal: () => import("./terminal/index.ts"),
|
||||||
pdf: () => import("./pdf/index.ts"),
|
pdf: () => import("./pdf/index.ts"),
|
||||||
|
pm: () => import("./pm/index.ts"),
|
||||||
};
|
};
|
||||||
|
|
||||||
const modules = new Map<FeatureId, Promise<FeatureModule>>();
|
const modules = new Map<FeatureId, Promise<FeatureModule>>();
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
// or the default of the feature when the feature does not follow its package (`followsPackage`).
|
// 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.
|
// `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`),
|
// 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 { invoke, isTauri } from "@tauri-apps/api/core";
|
||||||
import { readSection, writeSection } from "../settings/store.ts";
|
import { readSection, writeSection } from "../settings/store.ts";
|
||||||
import { readAppearance } from "../theme/appearance.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 { storedSwitches } from "./state.ts";
|
||||||
import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts";
|
import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts";
|
||||||
import { LEGACY_TERMINAL_KEY, migrateTerminal, writeTerminal, type TerminalMigrationHost } from "./terminalSettings.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. */
|
/** What the host reports about one old plugin package. */
|
||||||
export interface LegacyPlugin {
|
export interface LegacyPlugin {
|
||||||
@@ -44,6 +46,12 @@ const desktopBackground: BackgroundMigrationHost = {
|
|||||||
write: writeBackground,
|
write: writeBackground,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const desktopProjectManagement: ProjectManagementMigrationHost = {
|
||||||
|
missing: () => readSection("projectManagement") === undefined,
|
||||||
|
write: writeProjectManagement,
|
||||||
|
get storage() { return localStorage; },
|
||||||
|
};
|
||||||
|
|
||||||
const desktopTerminal: TerminalMigrationHost = {
|
const desktopTerminal: TerminalMigrationHost = {
|
||||||
missing: () => readSection("terminal") === undefined,
|
missing: () => readSection("terminal") === undefined,
|
||||||
legacy: () => localStorage.getItem(LEGACY_TERMINAL_KEY),
|
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.
|
* 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.
|
* The `terminal` section needs no package report, so it migrates also then.
|
||||||
*/
|
*/
|
||||||
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground,
|
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground,
|
||||||
terminal: TerminalMigrationHost = desktopTerminal): Promise<FeatureId[]> {
|
terminal: TerminalMigrationHost = desktopTerminal, projectManagement: ProjectManagementMigrationHost = desktopProjectManagement): Promise<FeatureId[]> {
|
||||||
try { await migrateTerminal(terminal); }
|
try { await migrateTerminal(terminal); }
|
||||||
catch (reason) { console.error("RuneStone could not copy the old terminal settings.", reason); }
|
catch (reason) { console.error("RuneStone could not copy the old terminal settings.", reason); }
|
||||||
const current = host.read();
|
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 missing = FEATURES.filter(entry => stored[entry.id] === undefined);
|
||||||
const backgroundOwner = featureEntry("background").owner;
|
const backgroundOwner = featureEntry("background").owner;
|
||||||
const backgroundMissing = background.missing();
|
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 [];
|
if (!owners.length) return [];
|
||||||
let legacy: LegacyPlugin[];
|
let legacy: LegacyPlugin[];
|
||||||
try { legacy = await host.legacy(owners); }
|
try { legacy = await host.legacy(owners); }
|
||||||
@@ -78,6 +89,7 @@ export async function migrateFeatures(host: MigrationHost = desktopHost, backgro
|
|||||||
await host.write(next);
|
await host.write(next);
|
||||||
}
|
}
|
||||||
if (backgroundMissing) await migrateBackground(legacy.find(item => item.id === backgroundOwner), background);
|
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);
|
return missing.map(entry => entry.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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-<hex of the board ID>`.
|
||||||
|
// 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<string, PMViewState>(Object.entries(readViewStates()).map(([key, value]) => [key, parseViewState(value)]));
|
||||||
|
const dirty = new Set<string>();
|
||||||
|
let saveTimer: ReturnType<typeof setTimeout> | 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<string, Promise<LegacyContent>>();
|
||||||
|
|
||||||
|
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<string | null>("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();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<string, TaskColumn>();
|
||||||
|
const assigned = new Set<string>();
|
||||||
|
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<string, TaskBoardGroup>();
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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<BackgroundAppearance> | 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})`;
|
||||||
|
}
|
||||||
@@ -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) };
|
||||||
|
}
|
||||||
@@ -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 `<img data-pm-image="${id}" alt="${name}">`;
|
||||||
|
} catch {
|
||||||
|
return `<span class="pm-muted">Image: ${name} (use Add image to import)</span>`;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export function renderMarkdown(source: string): string {
|
||||||
|
return markdown.render(source);
|
||||||
|
}
|
||||||
@@ -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<Priority, string> = { highest: "Highest", high: "High", medium: "Medium", low: "Low", lowest: "Lowest" };
|
||||||
|
export const statusNames: Record<Status, string> = {
|
||||||
|
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<string, { listId: string | null; order?: string }>;
|
||||||
|
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<Entry[]>;
|
||||||
|
listMarkdown?(): Promise<string[]>;
|
||||||
|
read(path: string): Promise<string>;
|
||||||
|
readMany?(paths: string[]): Promise<{ path: string; source?: string; error?: string }[]>;
|
||||||
|
readOptional?(path: string): Promise<string | null>;
|
||||||
|
write(path: string, contents: string, expected: string): Promise<void>;
|
||||||
|
create?(path: string, contents: string): Promise<void>;
|
||||||
|
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<string>();
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<Workspace, Task[]>();
|
||||||
|
|
||||||
|
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<string, Task>;
|
||||||
|
cardIssues: Map<string, string>;
|
||||||
|
cardsError: string;
|
||||||
|
catalog: { source: string | null; boards: BoardDocument[]; error: string };
|
||||||
|
labels: { snapshot?: LabelSnapshot; error: string };
|
||||||
|
deleted: { ids: Set<string>; error: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TaskStore {
|
||||||
|
tasks: Task[] = [];
|
||||||
|
boards: BoardDocument[] = [];
|
||||||
|
legacyBoards: BoardDocument[] = [];
|
||||||
|
issues: string[] = [];
|
||||||
|
private queue: Promise<unknown> = 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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<void>[] = [];
|
||||||
|
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<void> {
|
||||||
|
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<string, number>();
|
||||||
|
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<string>();
|
||||||
|
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<string, number>();
|
||||||
|
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<T>(action: () => Promise<T>): Promise<T> {
|
||||||
|
const result = this.queue.then(() => {
|
||||||
|
this.check();
|
||||||
|
return action();
|
||||||
|
});
|
||||||
|
this.queue = result.catch(() => {});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
save(
|
||||||
|
task: Task,
|
||||||
|
patch: Partial<TaskFields> & { body?: string },
|
||||||
|
applyListStatus = false,
|
||||||
|
): Promise<void> {
|
||||||
|
return this.run(() => this.saveTask(task, patch, applyListStatus));
|
||||||
|
}
|
||||||
|
deleteCard(task: Task): Promise<void> {
|
||||||
|
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<void> {
|
||||||
|
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<TaskFields> & { body?: string },
|
||||||
|
applyListStatus: boolean,
|
||||||
|
beforeId?: string | null,
|
||||||
|
reloaded = false,
|
||||||
|
placementBoardId = this.board.reference?.id,
|
||||||
|
): Promise<void> {
|
||||||
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<Task> {
|
||||||
|
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<void> {
|
||||||
|
return this.run(() => this.saveTask(task, { listId }, true, beforeId));
|
||||||
|
}
|
||||||
|
removeFromBoard(task: Task): Promise<void> {
|
||||||
|
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<TaskFields> & { body?: string }): Promise<void> {
|
||||||
|
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<void> {
|
||||||
|
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<void>, reload = true): Promise<void> {
|
||||||
|
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<void> {
|
||||||
|
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<string>,
|
||||||
|
): Promise<void> {
|
||||||
|
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<Task> {
|
||||||
|
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<Task> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<BackgroundFrame | null>,
|
||||||
|
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?.();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<string | undefined> {
|
||||||
|
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; }
|
||||||
|
}
|
||||||
@@ -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<Status, string | null>;
|
||||||
|
}
|
||||||
|
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<string>();
|
||||||
|
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<Task, "listId" | "status" | "placements">,
|
||||||
|
): 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.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<string, Task> = 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.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<string>();
|
||||||
|
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<OriginalFile> {
|
||||||
|
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 };
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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<unknown> = 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<string | null> {
|
||||||
|
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<void> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<string, string>,
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<string>(),
|
||||||
|
names = new Set<string>();
|
||||||
|
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<LabelSnapshot> {
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<LegacyContent> {
|
||||||
|
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<string>(), deletedBoards = new Set<string>(), deletedCards = new Set<string>();
|
||||||
|
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<string>();
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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<OriginalFile[]> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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<string, unknown> {
|
||||||
|
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<TaskFields> & { 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}`;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<string | null> {
|
||||||
|
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);
|
||||||
|
}
|
||||||
@@ -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<string, { source?: string; error?: string }>();
|
||||||
|
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<T, R>(
|
||||||
|
items: readonly T[],
|
||||||
|
visit: (item: T) => Promise<R>,
|
||||||
|
): Promise<R[]> {
|
||||||
|
const results = new Array<R>(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<string[]> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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<HTMLSelectElement, { trigger: HTMLButtonElement; update(): void }>();
|
||||||
|
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 = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>';
|
||||||
|
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<HTMLElement>("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(); },
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<keyof typeof cardColors, string> = {
|
||||||
|
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<keyof typeof cardColors, string> = 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 };
|
||||||
|
}
|
||||||
@@ -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 = `<div class="rs-find-row">
|
||||||
|
<div class="rs-find-field"><span class="pm-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="10" cy="10" r="7"/><path d="m15 15 6 6"/></svg></span><input type="text" name="search" autocomplete="off" aria-label="Find in description" placeholder="Find in description"></div>
|
||||||
|
<div class="rs-find-actions"></div>
|
||||||
|
</div><div class="rs-find-options"></div>`;
|
||||||
|
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 = `<span class="pm-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="${path}"/></svg></span>`;
|
||||||
|
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(); },
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<typeof createCardImages>,
|
||||||
|
control: (name: string, action: () => void) => HTMLButtonElement,
|
||||||
|
persistence?: { save(): Promise<void>; cancel(): Promise<string>; },
|
||||||
|
) {
|
||||||
|
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 = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg><span>Description</span>';
|
||||||
|
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<HTMLImageElement>("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); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
@@ -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);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<T extends HTMLElement>(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<HTMLElement, () => void>();
|
||||||
|
const attach = (node: Node) => {
|
||||||
|
if (!(node instanceof HTMLElement)) return;
|
||||||
|
const controls = node.matches(`[${TOOLTIP}]`) ? [node, ...node.querySelectorAll<HTMLElement>(`[${TOOLTIP}]`)] : node.querySelectorAll<HTMLElement>(`[${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();
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<string, string>();
|
||||||
|
const loaded = new Map<string, Promise<string>>();
|
||||||
|
let viewer: HTMLDialogElement | undefined;
|
||||||
|
let viewerObserver: ResizeObserver | undefined;
|
||||||
|
let idleTimer: ReturnType<typeof setTimeout> | 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);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<K extends keyof HTMLElementTagNameMap>(
|
||||||
|
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
|
||||||
|
? '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 3h8l10 10-8 8L3 11z"/><circle cx="7.5" cy="7.5" r="1"/></svg>'
|
||||||
|
: `<svg viewBox="0 0 24 24" aria-hidden="true">${actionIcons.plus}</svg>`;
|
||||||
|
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 = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 3h8l10 10-8 8L3 11z"/><circle cx="7.5" cy="7.5" r="1"/></svg>';
|
||||||
|
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<HTMLButtonElement>("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<HTMLButtonElement>("button")?.focus();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
choices.onkeydown = (event) => {
|
||||||
|
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
|
||||||
|
event.preventDefault();
|
||||||
|
const rows = [...choices.querySelectorAll<HTMLButtonElement>("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<void>,
|
||||||
|
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 = `<span class="pm-icon"><svg viewBox="0 0 24 24" aria-hidden="true">${actionIcons.trash}</svg></span>`;
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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<Priority, string> = {
|
||||||
|
highest: '<path d="m6 9 6-6 6 6M6 15l6-6 6 6M6 21l6-6 6 6"/>',
|
||||||
|
high: '<path d="m6 11 6-6 6 6M6 19l6-6 6 6"/>',
|
||||||
|
medium: '<path d="M5 9h14M5 15h14"/>',
|
||||||
|
lowest: '<path d="m6 3 6 6 6-6M6 9l6 6 6-6M6 15l6 6 6-6"/>',
|
||||||
|
low: '<path d="m6 5 6 6 6-6M6 13l6 6 6-6"/>',
|
||||||
|
};
|
||||||
|
export function setPriorityAppearance(node: HTMLElement, value: Priority | null) {
|
||||||
|
node.dataset.priority = value ?? "none";
|
||||||
|
const icon = node.querySelector(".pm-icon");
|
||||||
|
if (icon) icon.innerHTML = `<svg viewBox="0 0 24 24" aria-hidden="true">${value ? priorityIcons[value] : '<path d="M6 21V3M6 4h13l-3 5 3 5H6"/>'}</svg>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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(); },
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<string, Task>();
|
||||||
|
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 = '<span class="pm-icon"></span>';
|
||||||
|
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 = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>';
|
||||||
|
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 = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m10 13 4-4M8 16l-1 1a4 4 0 0 1-6-6l4-4a4 4 0 0 1 6 0m2 1 1-1a4 4 0 0 1 6 6l-4 4a4 4 0 0 1-6 0"/></svg>';
|
||||||
|
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<TaskFields["links"]>[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<HTMLButtonElement>("button")?.click(); }
|
||||||
|
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||||
|
event.preventDefault();
|
||||||
|
const rows = choices.querySelectorAll<HTMLButtonElement>("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<HTMLButtonElement>("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 }) };
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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<string, string>();
|
||||||
|
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();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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; }
|
||||||
|
}
|
||||||
@@ -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<string[]>("workspace_list_markdown"),
|
||||||
|
read: workspaceRead,
|
||||||
|
readMany: workspaceReadMany,
|
||||||
|
readOptional: path => invoke<string | null>("workspace_read", { rel: path, missingOk: true }),
|
||||||
|
write: async (path, contents, expected) => { await workspaceWrite(path, contents, expected); notifyPluginWorkspace([path]); },
|
||||||
|
create: async (path, contents) => { await invoke<void>("workspace_create", { rel: path, kind: "file", contents }); notifyPluginWorkspace([path]); },
|
||||||
|
subscribe: listener => onChange(() => listener()),
|
||||||
|
watch: onChange,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<string | null>;
|
||||||
|
/** Replaces one workspace file when its text is still `expected`. */
|
||||||
|
export type WriteExpected = (path: string, contents: string, expected: string) => Promise<void>;
|
||||||
|
|
||||||
|
const desktopRead: ReadOptional = path => invoke<string | null>("workspace_read", { rel: path, missingOk: true });
|
||||||
|
const desktopWrite: WriteExpected = (path, contents, expected) => workspaceWrite(path, contents, expected);
|
||||||
|
|
||||||
|
function record(value: unknown): Record<string, unknown> | null {
|
||||||
|
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : 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<BoardCatalog> {
|
||||||
|
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<void> {
|
||||||
|
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<string, unknown>;
|
||||||
|
data.defaultBoardId = id;
|
||||||
|
data.defaultBoardPath = id === null ? null : `pm-board:${id}`;
|
||||||
|
await write(BOARD_CATALOG_PATH, JSON.stringify(data, null, 2) + "\n", source);
|
||||||
|
}
|
||||||
@@ -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<ProjectManagementSettings> = 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-<hex>` for a board. RuneStone can lose these values without harm.
|
||||||
|
*/
|
||||||
|
export const VIEW_STATES_KEY = "runestone.pm.viewStates";
|
||||||
|
|
||||||
|
function record(value: unknown): Record<string, unknown> {
|
||||||
|
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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<void> {
|
||||||
|
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<Storage, "getItem"> = localStorage): Record<string, unknown> {
|
||||||
|
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<string, unknown>, storage: Pick<Storage, "getItem" | "setItem"> = 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<void>;
|
||||||
|
storage: Pick<Storage, "getItem" | "setItem">;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<ProjectManagementSettings | null> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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
|
// 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,
|
// 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.
|
// 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.
|
// A launch rule (`launch.ts`) can also start the instance at once.
|
||||||
import { tr } from "../i18n/index.ts";
|
import { tr } from "../i18n/index.ts";
|
||||||
import type { Dispose, PluginCommand, PluginDocumentContext, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
|
import type { Dispose, PluginCommand, PluginDocumentContext, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
|
||||||
@@ -18,6 +19,8 @@ export class FeatureSession {
|
|||||||
private load: () => Promise<FeatureModule>;
|
private load: () => Promise<FeatureModule>;
|
||||||
private instance?: Promise<FeatureInstance>;
|
private instance?: Promise<FeatureInstance>;
|
||||||
private ready?: FeatureInstance;
|
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<string>();
|
||||||
|
|
||||||
constructor(entry: FeatureEntry, context: FeatureContext, load: () => Promise<FeatureModule> = () => loadFeature(entry.id)) {
|
constructor(entry: FeatureEntry, context: FeatureContext, load: () => Promise<FeatureModule> = () => loadFeature(entry.id)) {
|
||||||
this.entry = entry;
|
this.entry = entry;
|
||||||
@@ -30,6 +33,10 @@ export class FeatureSession {
|
|||||||
mount: element => this.mountView(info.id, element),
|
mount: element => this.mountView(info.id, element),
|
||||||
saveTabState: () => this.ready?.saveTabState?.(info.id),
|
saveTabState: () => this.ready?.saveTabState?.(info.id),
|
||||||
restoreTabState: async state => { await (await this.running()).restoreTabState?.(info.id, state); },
|
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) {
|
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. */
|
/** The instance of this window. A failed load leaves no instance, so a later call tries again. */
|
||||||
private running(): Promise<FeatureInstance> {
|
private running(): Promise<FeatureInstance> {
|
||||||
if (this.controller.signal.aborted) return Promise.reject(new Error(tr("This feature is off.")));
|
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`. */
|
/** Mount a view, or with `document`, a document of the document type `id`. */
|
||||||
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<Dispose> {
|
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<Dispose> {
|
||||||
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."));
|
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" });
|
const dispose = document ? await (view as PluginDocumentType).mount(element, document) : await (view as PluginView).mount(element, { surface: "view" });
|
||||||
return async () => {
|
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. */
|
/** Load the module and start the instance now, without a view. Later calls use the same instance. */
|
||||||
async start(): Promise<void> { await this.running(); }
|
async start(): Promise<void> { await this.running(); }
|
||||||
|
|||||||
@@ -6,8 +6,17 @@ export interface FeatureContext {
|
|||||||
openView(id: string): void;
|
openView(id: string): void;
|
||||||
/** Open a workspace file in the editor. */
|
/** Open a workspace file in the editor. */
|
||||||
openFile(path: string): Promise<void>;
|
openFile(path: string): Promise<void>;
|
||||||
/** 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. */
|
/** 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.
|
* The returned function removes the document and stops its work, for example a worker.
|
||||||
*/
|
*/
|
||||||
mountDocument?(type: string, element: HTMLElement, document: PluginDocumentContext): Dispose | Promise<Dispose>;
|
mountDocument?(type: string, element: HTMLElement, document: PluginDocumentContext): Dispose | Promise<Dispose>;
|
||||||
|
/** Open a view with `launch` in the catalog. The feature chooses the view, for example the default board. */
|
||||||
|
launch?(view: string): void | Promise<void>;
|
||||||
/** Run a command of the catalog that has no view. */
|
/** Run a command of the catalog that has no view. */
|
||||||
run?(command: string): void | Promise<void>;
|
run?(command: string): void | Promise<void>;
|
||||||
/** The state of a tab for a transfer to another window. */
|
/** The state of a tab for a transfer to another window. */
|
||||||
|
|||||||
@@ -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}"],
|
["Cannot display this PDF. {reason}", "Impossible d’afficher ce PDF. {reason}", "この PDF を表示できません。{reason}", "无法显示此 PDF。{reason}"],
|
||||||
// The native features without the desktop host.
|
// The native features without the desktop host.
|
||||||
["This feature needs the desktop app.", "Cette fonctionnalité nécessite l’application de bureau.", "この機能にはデスクトップアプリが必要です。", "此功能需要桌面应用。"],
|
["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<Exclude<Locale, 'en'>, Record<string, string>> = {
|
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
|
||||||
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
|
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
// The left ribbon: the app tools (new browser tab, terminal, plug-in views, commands), then the plugin view shortcuts.
|
// The left ribbon: the app tools (new browser tab, terminal, Project Management, plug-in views, commands), then the
|
||||||
|
// plugin view shortcuts.
|
||||||
// While the side pane is closed, the workspace switcher, Help, and Settings
|
// While the side pane is closed, the workspace switcher, Help, and Settings
|
||||||
// move from the bar at the bottom of the pane (LeftPane.svelte) to the bottom of the ribbon, so they stay reachable.
|
// move from the bar at the bottom of the pane (LeftPane.svelte) to the bottom of the ribbon, so they stay reachable.
|
||||||
import { t } from "$lib/i18n";
|
import { t } from "$lib/i18n";
|
||||||
import IconButton from "$lib/ui/IconButton.svelte";
|
import IconButton from "$lib/ui/IconButton.svelte";
|
||||||
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
|
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
|
||||||
import { openPluginView, pluginEditorActive, pluginSidebar, pluginView } from "$lib/plugins/external";
|
import { openPluginView, pluginEditorActive, pluginSidebar, pluginView } from "$lib/plugins/external";
|
||||||
|
import { featureEntry } from "$lib/features/catalog";
|
||||||
|
import { featureSwitches } from "$lib/features/state";
|
||||||
|
|
||||||
|
/** Project Management is a native feature. Its button opens the default board of the workspace, or All tasks. */
|
||||||
|
const pm = featureEntry("pm").owner;
|
||||||
import { commandShortcut } from "./workbenchKeys";
|
import { commandShortcut } from "./workbenchKeys";
|
||||||
|
|
||||||
let { items, actions, workspaceAnchor = $bindable(), onChooseWorkspace, onHelp, onSettings,
|
let { items, actions, workspaceAnchor = $bindable(), onChooseWorkspace, onHelp, onSettings,
|
||||||
@@ -30,6 +36,7 @@
|
|||||||
<div class="ribbon-tools">
|
<div class="ribbon-tools">
|
||||||
{#if canOpenBrowser}<IconButton icon="globe" label={$t("New browser tab")} side="right" disabled={browserOpening} onclick={onOpenBrowser} />{/if}
|
{#if canOpenBrowser}<IconButton icon="globe" label={$t("New browser tab")} side="right" disabled={browserOpening} onclick={onOpenBrowser} />{/if}
|
||||||
{#if terminalEnabled}<IconButton icon="terminal" label={$t("Terminal")} side="right" active={terminalOpen} onclick={onToggleTerminal} />{/if}
|
{#if terminalEnabled}<IconButton icon="terminal" label={$t("Terminal")} side="right" active={terminalOpen} onclick={onToggleTerminal} />{/if}
|
||||||
|
{#if $featureSwitches.pm}<IconButton icon="kanban" label={$t("Project Management")} side="right" active={$pluginEditorActive && $pluginView?.owner === pm && !$pluginView?.document} onclick={() => openPluginView(pm, "planning")} />{/if}
|
||||||
<PluginAccessMenu surface="open" compact side="right" />
|
<PluginAccessMenu surface="open" compact side="right" />
|
||||||
<PluginAccessMenu surface="commands" compact side="right" />
|
<PluginAccessMenu surface="commands" compact side="right" />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
import { featureErrors } from "$lib/features/loader";
|
import { featureErrors } from "$lib/features/loader";
|
||||||
import { TERMINAL_SHORTCUTS } from "$lib/features/terminalKeys";
|
import { TERMINAL_SHORTCUTS } from "$lib/features/terminalKeys";
|
||||||
import TerminalSettings from "$lib/features/TerminalSettings.svelte";
|
import TerminalSettings from "$lib/features/TerminalSettings.svelte";
|
||||||
|
import ProjectManagementSettings from "$lib/features/ProjectManagementSettings.svelte";
|
||||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||||
import { confirm } from "@tauri-apps/plugin-dialog";
|
import { confirm } from "@tauri-apps/plugin-dialog";
|
||||||
import { onMount, untrack, type Snippet } from "svelte";
|
import { onMount, untrack, type Snippet } from "svelte";
|
||||||
@@ -77,7 +78,8 @@
|
|||||||
keywords: `${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner} settings configuration`,
|
keywords: `${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner} settings configuration`,
|
||||||
})));
|
})));
|
||||||
const terminalSection = $derived($featureSwitches.terminal ? [{ id: "terminal" as const, label: $t("Terminal"), icon: "terminal" as const, keywords: "terminal shell profile default font size scrollback lines cursor blink powershell bash cmd" }] : []);
|
const terminalSection = $derived($featureSwitches.terminal ? [{ id: "terminal" as const, label: $t("Terminal"), icon: "terminal" as const, keywords: "terminal shell profile default font size scrollback lines cursor blink powershell bash cmd" }] : []);
|
||||||
const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: $t("Browser"), icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...terminalSection, ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
|
const pmSection = $derived($featureSwitches.pm ? [{ id: "project-management" as const, label: $t("Project Management"), icon: "kanban" as const, keywords: "project management kanban board priority levels default board" }] : []);
|
||||||
|
const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: $t("Browser"), icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...terminalSection, ...pmSection, ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
|
||||||
const selected = $derived(matches.find(item => item.id === section) ?? matches[0]);
|
const selected = $derived(matches.find(item => item.id === section) ?? matches[0]);
|
||||||
const selectedPlugin = $derived(pluginSections.find(item => item.id === selected?.id));
|
const selectedPlugin = $derived(pluginSections.find(item => item.id === selected?.id));
|
||||||
|
|
||||||
@@ -235,6 +237,8 @@
|
|||||||
<BrowserSlot kind="settings" />
|
<BrowserSlot kind="settings" />
|
||||||
{:else if selected.id === "terminal"}
|
{:else if selected.id === "terminal"}
|
||||||
<TerminalSettings />
|
<TerminalSettings />
|
||||||
|
{:else if selected.id === "project-management"}
|
||||||
|
<ProjectManagementSettings />
|
||||||
{:else if selectedPlugin}
|
{:else if selectedPlugin}
|
||||||
{#key selectedPlugin.id}<PluginSettings owner={selectedPlugin.owner} id={selectedPlugin.view} />{/key}
|
{#key selectedPlugin.id}<PluginSettings owner={selectedPlugin.owner} id={selectedPlugin.view} />{/key}
|
||||||
{:else}
|
{:else}
|
||||||
|
|||||||
@@ -128,11 +128,11 @@
|
|||||||
} else if (change.type === "deleted") {
|
} else if (change.type === "deleted") {
|
||||||
removePluginDocuments(change.path);
|
removePluginDocuments(change.path);
|
||||||
void documents?.refresh();
|
void documents?.refresh();
|
||||||
notifyPluginWorkspace();
|
notifyPluginWorkspace([change.path]);
|
||||||
} else if (change.type === "changed") {
|
} else if (change.type === "changed") {
|
||||||
void documents?.refresh();
|
void documents?.refresh();
|
||||||
notifyPluginWorkspace();
|
notifyPluginWorkspace(change.paths);
|
||||||
} else if (change.type === "internal") notifyPluginWorkspace();
|
} else if (change.type === "internal") notifyPluginWorkspace(change.paths);
|
||||||
}));
|
}));
|
||||||
|
|
||||||
async function openBacklink(entry: Backlink) {
|
async function openBacklink(entry: Backlink) {
|
||||||
|
|||||||
@@ -1,2 +1,14 @@
|
|||||||
// The public background types are in the plugin SDK (packages/plugin-sdk/src/backgrounds.ts).
|
/**
|
||||||
export type { BackgroundApi, BackgroundFrame } from "./sdk.ts";
|
* One background frame of a target: the workspace (`app`), all Project Management boards (`pm-all`), or one board
|
||||||
|
* (`pm-board:<board ID>`). The Background feature sets the frames in `backgroundHub` (`backgrounds.ts`). The workarea and
|
||||||
|
* Project Management read them. Plugins have no access to the frames.
|
||||||
|
*/
|
||||||
|
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<BackgroundFrame, 'previous' | 'transitionMs'>;
|
||||||
|
transitionMs?: number;
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,8 +29,9 @@ function checkTarget(target: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The background frames of one window, for each target. The Background feature (`src/lib/features/background/`) and
|
* The background frames of one window, for each target. The Background feature (`src/lib/features/background/`) sets
|
||||||
* plugins set them. The `app` frame sets the custom properties of the body that the workarea background reads.
|
* them, and Project Management reads the board targets. The `app` frame sets the custom properties of the body that the
|
||||||
|
* workarea background reads.
|
||||||
*/
|
*/
|
||||||
export class BackgroundHub {
|
export class BackgroundHub {
|
||||||
private frames = new Map<string, Map<symbol, BackgroundFrame>>();
|
private frames = new Map<string, Map<symbol, BackgroundFrame>>();
|
||||||
|
|||||||
+33
-18
@@ -28,10 +28,10 @@ export const pluginSplits = writable<SplitLayout[]>([]);
|
|||||||
export function pinPluginEditor(key: string) {
|
export function pinPluginEditor(key: string) {
|
||||||
pluginEditors.update(views => views.map(view => view.key === key ? { ...view, pinned: !view.pinned } : view));
|
pluginEditors.update(views => views.map(view => view.key === key ? { ...view, pinned: !view.pinned } : view));
|
||||||
}
|
}
|
||||||
export function pluginTabActions(view: OpenPluginView) { return sessions.get(view.owner)?.session.views.get(view.id)?.tabActions?.({ pinned: !!view.pinned }) ?? []; }
|
export function pluginTabActions(view: OpenPluginView) { return viewOf(view.owner, view.id)?.tabActions?.({ pinned: !!view.pinned }) ?? []; }
|
||||||
export function pluginTabState(view: OpenPluginView) {
|
export function pluginTabState(view: OpenPluginView) {
|
||||||
return { owner: view.owner, id: view.id, document: view.document, pinned: view.pinned,
|
return { owner: view.owner, id: view.id, document: view.document, pinned: view.pinned,
|
||||||
state: sessions.get(view.owner)?.session.views.get(view.id)?.saveTabState?.() };
|
state: viewOf(view.owner, view.id)?.saveTabState?.() };
|
||||||
}
|
}
|
||||||
export async function restorePluginTab(transfer: ReturnType<typeof pluginTabState>): Promise<boolean> {
|
export async function restorePluginTab(transfer: ReturnType<typeof pluginTabState>): Promise<boolean> {
|
||||||
if (!transfer || typeof transfer.owner !== "string" || typeof transfer.id !== "string"
|
if (!transfer || typeof transfer.owner !== "string" || typeof transfer.id !== "string"
|
||||||
@@ -47,7 +47,7 @@ export async function restorePluginTab(transfer: ReturnType<typeof pluginTabStat
|
|||||||
if (transfer.document) {
|
if (transfer.document) {
|
||||||
if (!await openPluginDocument(transfer.document.path)) return false;
|
if (!await openPluginDocument(transfer.document.path)) return false;
|
||||||
} else {
|
} else {
|
||||||
const view = session.views.get(transfer.id);
|
const view = viewOf(transfer.owner, transfer.id);
|
||||||
if (!view || view.placement !== "editor") return false;
|
if (!view || view.placement !== "editor") return false;
|
||||||
if (transfer.state !== undefined) {
|
if (transfer.state !== undefined) {
|
||||||
if (!view.restoreTabState) throw new Error("This plugin cannot restore its tab state.");
|
if (!view.restoreTabState) throw new Error("This plugin cannot restore its tab state.");
|
||||||
@@ -60,7 +60,7 @@ export async function restorePluginTab(transfer: ReturnType<typeof pluginTabStat
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
export function pluginTabDragData(view: OpenPluginView): string | undefined {
|
export function pluginTabDragData(view: OpenPluginView): string | undefined {
|
||||||
const data = sessions.get(view.owner)?.session.views.get(view.id)?.tabDragData?.({ pinned: !!view.pinned });
|
const data = viewOf(view.owner, view.id)?.tabDragData?.({ pinned: !!view.pinned });
|
||||||
return data === undefined ? undefined : JSON.stringify({ owner: view.owner, data });
|
return data === undefined ? undefined : JSON.stringify({ owner: view.owner, data });
|
||||||
}
|
}
|
||||||
export async function dropPluginTab(data: string) {
|
export async function dropPluginTab(data: string) {
|
||||||
@@ -72,7 +72,7 @@ export async function dropPluginTab(data: string) {
|
|||||||
await session.dropTab(payload.data);
|
await session.dropTab(payload.data);
|
||||||
}
|
}
|
||||||
export function findPluginEditor(view: OpenPluginView): boolean {
|
export function findPluginEditor(view: OpenPluginView): boolean {
|
||||||
const find = sessions.get(view.owner)?.session.views.get(view.id)?.find;
|
const find = viewOf(view.owner, view.id)?.find;
|
||||||
if (!find) return false;
|
if (!find) return false;
|
||||||
find(); return true;
|
find(); return true;
|
||||||
}
|
}
|
||||||
@@ -97,6 +97,11 @@ export const isBuiltInModule = (id: string) => builtInModules.some(module => mod
|
|||||||
*/
|
*/
|
||||||
type ViewSession = Pick<ExternalSession, "views" | "documentTypes" | "commands" | "controller" | "launch" | "run" | "mount" | "dropTab" | "stop">;
|
type ViewSession = Pick<ExternalSession, "views" | "documentTypes" | "commands" | "controller" | "launch" | "run" | "mount" | "dropTab" | "stop">;
|
||||||
const sessions = new Map<string, { hash: string; session: ViewSession }>();
|
const sessions = new Map<string, { hash: string; session: ViewSession }>();
|
||||||
|
/** The view `id` of an owner. A native feature also makes the views of its view patterns here, for example a board tab. */
|
||||||
|
function viewOf(owner: string, id: string): PluginView | undefined {
|
||||||
|
const session = sessions.get(owner)?.session;
|
||||||
|
return session instanceof FeatureSession ? session.patternView(id) : session?.views.get(id);
|
||||||
|
}
|
||||||
const packaged = (hash: string | undefined) => hash !== undefined && hash !== "builtin" && hash !== "feature";
|
const packaged = (hash: string | undefined) => hash !== undefined && hash !== "builtin" && hash !== "feature";
|
||||||
const failures = new Map<string, string>();
|
const failures = new Map<string, string>();
|
||||||
const errors: Record<string, string> = {};
|
const errors: Record<string, string> = {};
|
||||||
@@ -112,7 +117,7 @@ let settingsWindow = false;
|
|||||||
let generation = 0;
|
let generation = 0;
|
||||||
let documentOpenVersion = 0;
|
let documentOpenVersion = 0;
|
||||||
export function cancelPluginDocumentOpen() { documentOpenVersion++; }
|
export function cancelPluginDocumentOpen() { documentOpenVersion++; }
|
||||||
const workspaceListeners = new Set<() => void>();
|
const workspaceListeners = new Set<(paths?: readonly string[]) => void>();
|
||||||
let openFile: ((path: string) => Promise<void>) | undefined;
|
let openFile: ((path: string) => Promise<void>) | undefined;
|
||||||
export function handlePluginFileOpen(handler: (path: string) => Promise<void>): () => void {
|
export function handlePluginFileOpen(handler: (path: string) => Promise<void>): () => void {
|
||||||
openFile = handler;
|
openFile = handler;
|
||||||
@@ -128,7 +133,8 @@ export function guardPluginWrites(guard: (path: string) => void): () => void {
|
|||||||
canWrite = guard;
|
canWrite = guard;
|
||||||
return () => { if (canWrite === guard) canWrite = () => {}; };
|
return () => { if (canWrite === guard) canWrite = () => {}; };
|
||||||
}
|
}
|
||||||
export function notifyPluginWorkspace() { for (const listener of workspaceListeners) listener(); }
|
/** Tell plugins and features about a workspace change. `paths` lists the changed paths, when they are known. */
|
||||||
|
export function notifyPluginWorkspace(paths?: readonly string[]) { for (const listener of workspaceListeners) listener(paths); }
|
||||||
export function selectPluginEditor(view: OpenPluginView) { cancelPluginDocumentOpen(); pluginView.set(view); pluginEditorActive.set(true); }
|
export function selectPluginEditor(view: OpenPluginView) { cancelPluginDocumentOpen(); pluginView.set(view); pluginEditorActive.set(true); }
|
||||||
export function closePluginEditor(key: string) {
|
export function closePluginEditor(key: string) {
|
||||||
cancelPluginDocumentOpen();
|
cancelPluginDocumentOpen();
|
||||||
@@ -151,11 +157,11 @@ export function renamePluginDocuments(from: string, to: string) {
|
|||||||
pluginEditors.set(editors);
|
pluginEditors.set(editors);
|
||||||
const selected = editors.find(view => view.key === get(pluginView)?.key);
|
const selected = editors.find(view => view.key === get(pluginView)?.key);
|
||||||
if (selected) pluginView.set(selected);
|
if (selected) pluginView.set(selected);
|
||||||
pluginDocuments.set({}); notifyPluginWorkspace();
|
pluginDocuments.set({}); notifyPluginWorkspace([from, to]);
|
||||||
}
|
}
|
||||||
export function removePluginDocuments(path: string) {
|
export function removePluginDocuments(path: string) {
|
||||||
for (const view of get(pluginEditors)) if (view.document && (view.document.path === path || view.document.path.startsWith(path + "/"))) closePluginEditor(view.key);
|
for (const view of get(pluginEditors)) if (view.document && (view.document.path === path || view.document.path.startsWith(path + "/"))) closePluginEditor(view.key);
|
||||||
pluginDocuments.set({}); notifyPluginWorkspace();
|
pluginDocuments.set({}); notifyPluginWorkspace([path]);
|
||||||
}
|
}
|
||||||
const documentTitle = (path: string) => path.split("/").at(-1)!.replace(/\.[^.]+$/, "");
|
const documentTitle = (path: string) => path.split("/").at(-1)!.replace(/\.[^.]+$/, "");
|
||||||
async function identifyDocument(path: string) {
|
async function identifyDocument(path: string) {
|
||||||
@@ -203,11 +209,11 @@ export async function createPluginDocument(owner: string, id: string, path: stri
|
|||||||
const contents = create.contents();
|
const contents = create.contents();
|
||||||
if (typeof contents !== "string") throw new Error("Document contents must be text.");
|
if (typeof contents !== "string") throw new Error("Document contents must be text.");
|
||||||
await invoke("workspace_create", { rel: path, kind: "file", contents });
|
await invoke("workspace_create", { rel: path, kind: "file", contents });
|
||||||
notifyPluginWorkspace();
|
notifyPluginWorkspace([path]);
|
||||||
}
|
}
|
||||||
|
|
||||||
function publish() {
|
function publish() {
|
||||||
pluginEditors.update(views => views.map(view => view.document ? view : { ...view, title: sessions.get(view.owner)?.session.views.get(view.id)?.title ?? view.title, iconImage: sessions.get(view.owner)?.session.views.get(view.id)?.iconImage }));
|
pluginEditors.update(views => views.map(view => view.document ? view : { ...view, title: viewOf(view.owner, view.id)?.title ?? view.title, iconImage: viewOf(view.owner, view.id)?.iconImage }));
|
||||||
pluginNavigation.set([...sessions].flatMap(([owner, { session }]) => [...session.views.values()].filter(view => view.navigation || view.toolbar).map(view => ({ owner, id: view.id, title: view.title, icon: view.icon, placement: view.placement, toolbar: view.toolbar }))));
|
pluginNavigation.set([...sessions].flatMap(([owner, { session }]) => [...session.views.values()].filter(view => view.navigation || view.toolbar).map(view => ({ owner, id: view.id, title: view.title, icon: view.icon, placement: view.placement, toolbar: view.toolbar }))));
|
||||||
pluginDocumentTypes.set([...sessions].flatMap(([owner, { session }]) => [...session.documentTypes.values()].map(type => ({ owner, type }))));
|
pluginDocumentTypes.set([...sessions].flatMap(([owner, { session }]) => [...session.documentTypes.values()].map(type => ({ owner, type }))));
|
||||||
pluginTools.set([...sessions].flatMap(([owner, { session }]) => pluginAccess(owner, session.commands.values(), session.views.values())));
|
pluginTools.set([...sessions].flatMap(([owner, { session }]) => pluginAccess(owner, session.commands.values(), session.views.values())));
|
||||||
@@ -231,7 +237,7 @@ async function stop(id: string) {
|
|||||||
if (packaged(loaded.hash)) await release(id, error); publish();
|
if (packaged(loaded.hash)) await release(id, error); publish();
|
||||||
}
|
}
|
||||||
function show(owner: string, id: string, options?: PluginViewOpenOptions) {
|
function show(owner: string, id: string, options?: PluginViewOpenOptions) {
|
||||||
const view = sessions.get(owner)?.session.views.get(id);
|
const view = viewOf(owner, id);
|
||||||
if (view) {
|
if (view) {
|
||||||
const placement = view.placement ?? "dialog";
|
const placement = view.placement ?? "dialog";
|
||||||
if (placement === "sidebar") {
|
if (placement === "sidebar") {
|
||||||
@@ -261,7 +267,7 @@ function show(owner: string, id: string, options?: PluginViewOpenOptions) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
function replaceEditorView(owner: string, current: OpenPluginView | undefined, nextId: string) {
|
function replaceEditorView(owner: string, current: OpenPluginView | undefined, nextId: string) {
|
||||||
const next = sessions.get(owner)?.session.views.get(nextId);
|
const next = viewOf(owner, nextId);
|
||||||
if (!current || !next || next.placement !== "editor") throw new Error("The editor view is unavailable.");
|
if (!current || !next || next.placement !== "editor") throw new Error("The editor view is unavailable.");
|
||||||
for (const duplicate of get(pluginEditors)) {
|
for (const duplicate of get(pluginEditors)) {
|
||||||
if (duplicate.owner === owner && duplicate.id === nextId && !duplicate.document && duplicate.key !== current.key) closePluginEditor(duplicate.key);
|
if (duplicate.owner === owner && duplicate.id === nextId && !duplicate.document && duplicate.key !== current.key) closePluginEditor(duplicate.key);
|
||||||
@@ -276,17 +282,16 @@ async function activate(row: InstalledPlugin, builtin?: PluginModule) {
|
|||||||
const session = new ExternalSession(id, {
|
const session = new ExternalSession(id, {
|
||||||
completionTransport,
|
completionTransport,
|
||||||
files: filesTransport(id),
|
files: filesTransport(id),
|
||||||
backgrounds: true,
|
|
||||||
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
|
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
|
||||||
workspace: {
|
workspace: {
|
||||||
list: path => workspaceList(path ?? ""), read: workspaceRead,
|
list: path => workspaceList(path ?? ""), read: workspaceRead,
|
||||||
listMarkdown: () => invoke<string[]>("workspace_list_markdown"),
|
listMarkdown: () => invoke<string[]>("workspace_list_markdown"),
|
||||||
readMany: paths => invoke<{ path: string; source?: string; error?: string }[]>("workspace_read_many", { paths }),
|
readMany: paths => invoke<{ path: string; source?: string; error?: string }[]>("workspace_read_many", { paths }),
|
||||||
readBytes: workspaceReadBytes,
|
readBytes: workspaceReadBytes,
|
||||||
write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); },
|
write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace([path]); },
|
||||||
subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
|
subscribe: listener => { const call = () => listener(); workspaceListeners.add(call); return () => { workspaceListeners.delete(call); }; },
|
||||||
readOptional: rel => invoke<string | null>("workspace_read", { rel, missingOk: true }),
|
readOptional: rel => invoke<string | null>("workspace_read", { rel, missingOk: true }),
|
||||||
create: async (rel, contents) => { await invoke<void>("workspace_create", { rel, kind: "file", contents }); notifyPluginWorkspace(); },
|
create: async (rel, contents) => { await invoke<void>("workspace_create", { rel, kind: "file", contents }); notifyPluginWorkspace([rel]); },
|
||||||
},
|
},
|
||||||
settings: {
|
settings: {
|
||||||
subscribe: listener => {
|
subscribe: listener => {
|
||||||
@@ -378,10 +383,20 @@ export async function mountPluginView(owner: string, id: string, element: HTMLEl
|
|||||||
return session.mount(id, element, document, surface);
|
return session.mount(id, element, document, surface);
|
||||||
}
|
}
|
||||||
function featureContext(entry: FeatureEntry): FeatureContext {
|
function featureContext(entry: FeatureEntry): FeatureContext {
|
||||||
|
const owner = entry.owner;
|
||||||
return {
|
return {
|
||||||
openView: id => show(entry.owner, id),
|
openView: id => show(owner, id),
|
||||||
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
|
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
|
||||||
onWorkspaceChange: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
|
onWorkspaceChange: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
|
||||||
|
setViewTitle: (id, title) => {
|
||||||
|
const session = sessions.get(owner)?.session;
|
||||||
|
if (session instanceof FeatureSession && session.setViewTitle(id, title)) publish();
|
||||||
|
},
|
||||||
|
closeView: id => { for (const view of get(pluginEditors)) if (view.owner === owner && view.id === id && !view.document) closePluginEditor(view.key); },
|
||||||
|
replaceView: (currentId, nextId) => {
|
||||||
|
const current = get(pluginEditors).find(view => view.owner === owner && view.id === currentId && !view.document);
|
||||||
|
if (current) replaceEditorView(owner, current, nextId); else show(owner, nextId);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -2,14 +2,12 @@ import { pluginHost, type ContributionRegistry } from "./registry.ts";
|
|||||||
import { completionHub } from "../completion/hub.ts";
|
import { completionHub } from "../completion/hub.ts";
|
||||||
import { registerCompletionInput } from "../completion/input.ts";
|
import { registerCompletionInput } from "../completion/input.ts";
|
||||||
import { showActionMenu } from "../ui/managedActionMenu.ts";
|
import { showActionMenu } from "../ui/managedActionMenu.ts";
|
||||||
import { backgroundHub } from "./backgrounds.ts";
|
|
||||||
import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.ts";
|
import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.ts";
|
||||||
import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
|
import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
|
||||||
|
|
||||||
/** The host services that a session gives to its plugin. The host binds them to the plugin ID. */
|
/** The host services that a session gives to its plugin. The host binds them to the plugin ID. */
|
||||||
export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & {
|
export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & {
|
||||||
/** True gives the plugin `api.backgrounds`: the background frames of each target. */
|
openFile?: PluginApi["openFile"];
|
||||||
openFile?: PluginApi["openFile"]; backgrounds?: boolean;
|
|
||||||
completionTransport?: NonNullable<PluginApi["completion"]>["transport"];
|
completionTransport?: NonNullable<PluginApi["completion"]>["transport"];
|
||||||
files?: FilesTransport; serviceHub?: ServiceHub;
|
files?: FilesTransport; serviceHub?: ServiceHub;
|
||||||
};
|
};
|
||||||
@@ -33,8 +31,6 @@ export class ExternalSession {
|
|||||||
private mounted = new Set<Dispose>();
|
private mounted = new Set<Dispose>();
|
||||||
private contributions: Dispose[] = [];
|
private contributions: Dispose[] = [];
|
||||||
private registry: ContributionRegistry;
|
private registry: ContributionRegistry;
|
||||||
private backgroundOwner = Symbol('plugin backgrounds');
|
|
||||||
private backgroundSubscriptions = new Set<() => void>();
|
|
||||||
private serviceOwner = Symbol('plugin services');
|
private serviceOwner = Symbol('plugin services');
|
||||||
private serviceSubscriptions = new Set<() => void>();
|
private serviceSubscriptions = new Set<() => void>();
|
||||||
readonly id: string;
|
readonly id: string;
|
||||||
@@ -66,19 +62,6 @@ export class ExternalSession {
|
|||||||
id: this.id, signal: this.controller.signal,
|
id: this.id, signal: this.controller.signal,
|
||||||
...(this.services.files ? { files: this.filesApi(this.services.files) } : {}),
|
...(this.services.files ? { files: this.filesApi(this.services.files) } : {}),
|
||||||
services: this.servicesApi(this.services.serviceHub ?? defaultServiceHub),
|
services: this.servicesApi(this.services.serviceHub ?? defaultServiceHub),
|
||||||
...(this.services.backgrounds ? { backgrounds: {
|
|
||||||
version: 1 as const,
|
|
||||||
set: (target: string, frame: import('./backgroundContracts.ts').BackgroundFrame | null) => { this.check(); backgroundHub.set(this.backgroundOwner, target, frame); },
|
|
||||||
get: (target: string) => { this.check(); return backgroundHub.get(target); },
|
|
||||||
subscribe: (listener: (target: string) => void) => {
|
|
||||||
this.check();
|
|
||||||
if (typeof listener !== 'function') throw new Error('A background listener must be a function.');
|
|
||||||
const off = backgroundHub.subscribe(target => { if (!this.stopped) listener(target); });
|
|
||||||
const cleanup = () => { off(); this.backgroundSubscriptions.delete(cleanup); };
|
|
||||||
this.backgroundSubscriptions.add(cleanup);
|
|
||||||
return cleanup;
|
|
||||||
},
|
|
||||||
} } : {}),
|
|
||||||
ui: { showActionMenu: options => { this.check(); const menu = showActionMenu(options, this.controller.signal); return { close: () => menu.close() }; } },
|
ui: { showActionMenu: options => { this.check(); const menu = showActionMenu(options, this.controller.signal); return { close: () => menu.close() }; } },
|
||||||
completion: {
|
completion: {
|
||||||
version: 1,
|
version: 1,
|
||||||
@@ -231,8 +214,6 @@ export class ExternalSession {
|
|||||||
stop(): Promise<void> {
|
stop(): Promise<void> {
|
||||||
if (this.stopping) return this.stopping;
|
if (this.stopping) return this.stopping;
|
||||||
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.receiveTab = undefined; this.changed();
|
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.receiveTab = undefined; this.changed();
|
||||||
for (const off of this.backgroundSubscriptions) off();
|
|
||||||
backgroundHub.removeOwner(this.backgroundOwner);
|
|
||||||
for (const off of this.serviceSubscriptions) off();
|
for (const off of this.serviceSubscriptions) off();
|
||||||
(this.services.serviceHub ?? defaultServiceHub).removeOwner(this.serviceOwner);
|
(this.services.serviceHub ?? defaultServiceHub).removeOwner(this.serviceOwner);
|
||||||
for (const remove of this.contributions.splice(0)) remove();
|
for (const remove of this.contributions.splice(0)) remove();
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
import { invoke, isTauri } from '@tauri-apps/api/core';
|
import { invoke, isTauri } from '@tauri-apps/api/core';
|
||||||
import { listen } from '@tauri-apps/api/event';
|
import { listen } from '@tauri-apps/api/event';
|
||||||
|
|
||||||
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features', 'background', 'terminal'] as const;
|
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features', 'background', 'terminal', 'projectManagement'] as const;
|
||||||
export type SettingsSection = typeof SETTINGS_SECTIONS[number];
|
export type SettingsSection = typeof SETTINGS_SECTIONS[number];
|
||||||
export type SettingsSections = Partial<Record<SettingsSection, unknown>>;
|
export type SettingsSections = Partial<Record<SettingsSection, unknown>>;
|
||||||
|
|
||||||
@@ -24,6 +24,7 @@ export const LEGACY_KEYS: Readonly<Record<SettingsSection, string>> = {
|
|||||||
features: 'runestone.features',
|
features: 'runestone.features',
|
||||||
background: 'runestone.background',
|
background: 'runestone.background',
|
||||||
terminal: 'runestone.terminal',
|
terminal: 'runestone.terminal',
|
||||||
|
projectManagement: 'runestone.project-management',
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Make the first settings file from the old localStorage values. `read` returns the value of a key, or null. */
|
/** Make the first settings file from the old localStorage values. `read` returns the value of a key, or null. */
|
||||||
|
|||||||
@@ -210,7 +210,7 @@ function installMock(options, commands) {
|
|||||||
if (target !== pageId) channel.postMessage({ event, payload, target });
|
if (target !== pageId) channel.postMessage({ event, payload, target });
|
||||||
};
|
};
|
||||||
const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers";
|
const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers";
|
||||||
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal"];
|
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal", "projectManagement"];
|
||||||
const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } };
|
const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } };
|
||||||
const settingsFile = () => readJson(SETTINGS_FILE, null);
|
const settingsFile = () => readJson(SETTINGS_FILE, null);
|
||||||
const snapshot = () => {
|
const snapshot = () => {
|
||||||
|
|||||||
@@ -0,0 +1,160 @@
|
|||||||
|
// The native Project Management feature: no module loads before the first use, the ribbon button opens All tasks,
|
||||||
|
// the board scope opens a board in the same tab with the board name, a card moves to another list through the host menu,
|
||||||
|
// and a card edit saves to the hidden card file. Settings → Project Management saves the priority levels and the default
|
||||||
|
// board, and the ribbon button then opens that board. It also checks both themes and the shared tooltip of the ribbon button.
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import path from "node:path";
|
||||||
|
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||||
|
|
||||||
|
const roadmap = "6f4c2a3e-6a0b-4d57-9a3e-1c2b3d4e5f60";
|
||||||
|
const bugs = "0c18bcdc-f41e-4a31-87f4-87c369f398c1";
|
||||||
|
const board = id => ({
|
||||||
|
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" },
|
||||||
|
});
|
||||||
|
const cardPath = id => `.runestone/pm/cards/${Buffer.from(id).toString("hex")}.md`;
|
||||||
|
const card = (id, title, boardId, order) => [cardPath(id), [
|
||||||
|
"---", "runestone_pm:", " schema: 1", ` id: ${id}`, " kind: task", ` title: ${title}`, " createdAt: 2026-10-01T00:00:00.000Z",
|
||||||
|
` order: "${order}"`, " status: todo", " tags: []", " sessions: []", " archived: false", " placements:",
|
||||||
|
` ${boardId}:`, " listId: todo", ` order: "${order}"`, "---", `Body of ${title}.`, "",
|
||||||
|
].join("\n")];
|
||||||
|
const files = Object.fromEntries([
|
||||||
|
["note.md", "# Note\n"],
|
||||||
|
[".runestone/pm/.gitignore", "# RuneStone Project Management local data\n*\n"],
|
||||||
|
[".runestone/pm/cards/.gitignore", "*\n"],
|
||||||
|
[".runestone/pm/workspace.json", JSON.stringify({ schema: 1, boards: [{ name: "Roadmap", value: board(roadmap) }, { name: "Bugs", value: board(bugs) }] }, null, 2) + "\n"],
|
||||||
|
card("card-a", "Card A", roadmap, "a"),
|
||||||
|
card("card-b", "Card B", roadmap, "b"),
|
||||||
|
card("card-c", "Card C", bugs, "c"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await runSmoke("features/pm", async ({ browser }) => {
|
||||||
|
const output = await outputDir("features/pm");
|
||||||
|
const mock = {
|
||||||
|
state: { files },
|
||||||
|
commands: test => {
|
||||||
|
const workspace = test.workspace({ root: "C:\\pm-feature", files: test.state.files });
|
||||||
|
test.files = workspace.files;
|
||||||
|
return {
|
||||||
|
...workspace,
|
||||||
|
workspace_read: args => {
|
||||||
|
if (!workspace.files.has(args.rel) && args.missingOk) return null;
|
||||||
|
return workspace.workspace_read(args);
|
||||||
|
},
|
||||||
|
workspace_create: ({ rel, kind, contents }) => {
|
||||||
|
if (workspace.files.has(rel)) throw new Error("Destination exists");
|
||||||
|
if (kind === "file") workspace.files.set(rel, contents ?? "");
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
|
||||||
|
spelling_menu_install: () => null,
|
||||||
|
"plugin:window|is_maximized": () => false,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
// One context, so the settings window shares the settings file of the main window.
|
||||||
|
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
|
||||||
|
await mockTauri(context, mock);
|
||||||
|
const page = await openPage(context);
|
||||||
|
await page.goto(smokeUrl);
|
||||||
|
await page.locator('[data-tree-rel="note.md"]').waitFor();
|
||||||
|
const loaded = () => page.evaluate(() => performance.getEntriesByType("resource").some(entry => {
|
||||||
|
const { pathname } = new URL(entry.name);
|
||||||
|
return pathname.startsWith("/src/lib/features/pm/") || /\/deps\/yaml\b|\/node_modules\/yaml\//.test(pathname);
|
||||||
|
}));
|
||||||
|
const ribbon = page.locator(".plugin-ribbon").getByRole("button", { name: "Project Management", exact: true });
|
||||||
|
await ribbon.waitFor();
|
||||||
|
assert.equal(await loaded(), false, "No Project Management module and no YAML parser load before the first use");
|
||||||
|
assert.equal(await page.locator('[data-tree-rel="note.md"] .document-icon').count(), 0, "The file tree marks no Markdown file for Project Management");
|
||||||
|
await ribbon.hover();
|
||||||
|
await page.getByRole("tooltip").filter({ hasText: /^Project Management$/ }).waitFor();
|
||||||
|
|
||||||
|
// The ribbon button opens All tasks: no default board is set.
|
||||||
|
await ribbon.click();
|
||||||
|
const pane = page.locator(".plugin-editor-pane:visible");
|
||||||
|
await pane.locator(".pm-board").waitFor();
|
||||||
|
await page.getByRole("tab", { name: "Project Management", exact: true }).waitFor();
|
||||||
|
await page.waitForFunction(() => document.querySelectorAll(".plugin-editor-pane .pm-card").length === 3);
|
||||||
|
assert.equal(await loaded(), true, "The first use loads the feature");
|
||||||
|
assert.equal(await ribbon.getAttribute("aria-pressed"), "true", "The ribbon button shows the open view");
|
||||||
|
|
||||||
|
// The board scope opens a board in the same tab, with the board name as its title.
|
||||||
|
await pane.getByRole("button", { name: /^Board scope:/ }).click();
|
||||||
|
await page.getByRole("menuitemradio", { name: "Roadmap", exact: true }).click();
|
||||||
|
await page.getByRole("tab", { name: "Roadmap", exact: true }).waitFor();
|
||||||
|
assert.equal(await page.getByRole("tab", { name: "Project Management", exact: true }).count(), 0, "The board replaces All tasks in its tab");
|
||||||
|
await page.waitForFunction(() => [...document.querySelectorAll(".plugin-editor-pane .pm-card")].filter(card => card.getClientRects().length).length === 2);
|
||||||
|
|
||||||
|
for (const theme of ["dark", "light"]) {
|
||||||
|
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
|
||||||
|
await page.waitForFunction(mode => document.documentElement.dataset.theme === mode, theme);
|
||||||
|
await page.screenshot({ path: path.join(output, `board-${theme}.png`) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move a card to another list through the host action menu. The save writes only that card.
|
||||||
|
await pane.getByRole("button", { name: "Actions for Card A", exact: true }).click();
|
||||||
|
await page.getByRole("menuitem", { name: "Move to list", exact: true }).click();
|
||||||
|
await page.getByRole("menuitemradio", { name: "In progress", exact: true }).click();
|
||||||
|
await page.waitForFunction(path => /listId: doing/.test(window.__TEST__.files.get(path)), cardPath("card-a"));
|
||||||
|
const moved = await page.evaluate(path => window.__TEST__.files.get(path), cardPath("card-a"));
|
||||||
|
assert.match(moved, /status: doing/, "The list status applies to the card");
|
||||||
|
await pane.locator(".pm-column", { hasText: "In progress" }).locator(".pm-card", { hasText: "Card A" }).waitFor();
|
||||||
|
|
||||||
|
// Edit a card in its details and save it.
|
||||||
|
await pane.getByRole("button", { name: "Card B", exact: true }).click();
|
||||||
|
const editor = page.locator("dialog.pm-card-editor[open]");
|
||||||
|
await editor.waitFor();
|
||||||
|
await editor.getByRole("textbox", { name: "Title", exact: true }).fill("Card B edited");
|
||||||
|
await page.screenshot({ path: path.join(output, "card-editor-light.png") });
|
||||||
|
await editor.getByRole("button", { name: "Save card", exact: true }).click();
|
||||||
|
await editor.waitFor({ state: "detached" });
|
||||||
|
await page.waitForFunction(path => /title: Card B edited/.test(window.__TEST__.files.get(path)), cardPath("card-b"));
|
||||||
|
await pane.locator(".pm-card", { hasText: "Card B edited" }).waitFor();
|
||||||
|
assert.equal(await page.evaluate(path => window.__TEST__.files.get(path), cardPath("card-c")), files[cardPath("card-c")], "Other cards stay unchanged");
|
||||||
|
await page.screenshot({ path: path.join(output, "board-after-edit-light.png") });
|
||||||
|
// The board menu shows the same settings component as Settings → Project Management.
|
||||||
|
await pane.getByRole("button", { name: "More actions", exact: true }).click();
|
||||||
|
await page.getByRole("menuitem", { name: "Project Management settings", exact: true }).click();
|
||||||
|
const popup = page.getByRole("dialog", { name: "Project Management settings", exact: true });
|
||||||
|
await popup.getByRole("button", { name: "Priority levels", exact: true }).waitFor();
|
||||||
|
await popup.getByRole("button", { name: "Default board", exact: true }).waitFor();
|
||||||
|
await page.screenshot({ path: path.join(output, "board-settings-light.png") });
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
await popup.waitFor({ state: "detached" });
|
||||||
|
|
||||||
|
// Settings → Project Management in the settings window. Each page of the mock has its own copy of the workspace files.
|
||||||
|
const settings = await openPage(context);
|
||||||
|
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
|
||||||
|
await settings.getByRole("button", { name: "Project Management", exact: true }).click();
|
||||||
|
await settings.getByRole("heading", { name: "Project Management", exact: true }).waitFor();
|
||||||
|
const levels = settings.getByRole("button", { name: "Priority levels", exact: true });
|
||||||
|
assert.equal(await levels.innerText(), "3 — High, Medium, and Low");
|
||||||
|
await levels.click();
|
||||||
|
await settings.getByRole("menuitemradio", { name: "5 — Highest through Lowest", exact: true }).click();
|
||||||
|
await settings.waitForFunction(() => window.__TEST__.settings("projectManagement")?.priorityLevels === 5);
|
||||||
|
const defaultBoard = settings.getByRole("button", { name: "Default board", exact: true });
|
||||||
|
await settings.waitForFunction(() => !document.querySelector('[aria-label="Default board"]').disabled);
|
||||||
|
assert.equal(await defaultBoard.innerText(), "All tasks");
|
||||||
|
await defaultBoard.click();
|
||||||
|
assert.deepEqual(await settings.getByRole("menuitemradio").allInnerTexts(), ["All tasks", "Roadmap", "Bugs"]);
|
||||||
|
await settings.getByRole("menuitemradio", { name: "Roadmap", exact: true }).click();
|
||||||
|
await settings.waitForFunction(id => JSON.parse(window.__TEST__.files.get(".runestone/pm/workspace.json")).defaultBoardId === id, roadmap);
|
||||||
|
await settings.screenshot({ path: path.join(output, "settings-light.png") });
|
||||||
|
await settings.close();
|
||||||
|
|
||||||
|
// With a default board, the ribbon button opens it.
|
||||||
|
await page.evaluate(([board, catalog]) => {
|
||||||
|
const value = JSON.parse(catalog);
|
||||||
|
window.__TEST__.files.set(".runestone/pm/workspace.json", JSON.stringify({ ...value, defaultBoardId: board, defaultBoardPath: `pm-board:${board}` }));
|
||||||
|
}, [bugs, files[".runestone/pm/workspace.json"]]);
|
||||||
|
await ribbon.click();
|
||||||
|
await page.getByRole("tab", { name: "Bugs", exact: true }).waitFor();
|
||||||
|
await page.waitForFunction(() => [...document.querySelectorAll(".plugin-editor-pane .pm-card")].some(card => card.getClientRects().length && card.textContent.includes("Card C")));
|
||||||
|
assert.deepEqual([...page.errors, ...settings.errors], [], "No page errors");
|
||||||
|
await context.close();
|
||||||
|
});
|
||||||
@@ -20,7 +20,7 @@ await runSmoke("features/settings", async ({ browser }) => {
|
|||||||
const sourceControl = main.locator(".header-left").getByRole("button", { name: "Source control", exact: true });
|
const sourceControl = main.locator(".header-left").getByRole("button", { name: "Source control", exact: true });
|
||||||
await sourceControl.waitFor();
|
await sourceControl.waitFor();
|
||||||
// Without an old package, the migration stores the default of each feature.
|
// Without an old package, the migration stores the default of each feature.
|
||||||
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true, terminal: true, pdf: true });
|
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true, terminal: true, pdf: true, pm: true });
|
||||||
|
|
||||||
const settings = await openPage(context, { timeout: 10000 });
|
const settings = await openPage(context, { timeout: 10000 });
|
||||||
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
|
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
|
||||||
@@ -33,7 +33,7 @@ await runSmoke("features/settings", async ({ browser }) => {
|
|||||||
|
|
||||||
await git.click();
|
await git.click();
|
||||||
await sourceControl.waitFor({ state: "detached" });
|
await sourceControl.waitFor({ state: "detached" });
|
||||||
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true, terminal: true, pdf: true });
|
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true, terminal: true, pdf: true, pm: true });
|
||||||
assert.equal(await settings.getByRole("status").innerText(), "Changes saved.");
|
assert.equal(await settings.getByRole("status").innerText(), "Changes saved.");
|
||||||
await git.focus();
|
await git.focus();
|
||||||
await settings.keyboard.press("Space");
|
await settings.keyboard.press("Space");
|
||||||
|
|||||||
@@ -1,32 +1,35 @@
|
|||||||
// Find in plug-in views: privacy attributes, Project Management views, plug-in documents, custom find handlers, focus, both themes, and narrow layouts.
|
// Find in plug-in views: privacy attributes, Project Management views, plug-in documents, custom find handlers, focus, both themes, and narrow layouts.
|
||||||
// @requires repo:RuneStone_Project_Management/dist/plugin
|
// Project Management is a native feature. Its board is in the hidden storage of the workspace (.runestone/pm/).
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { readFile } from 'node:fs/promises';
|
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
|
||||||
import path from 'node:path';
|
|
||||||
import { mockTauri, outputDir, pluginRepo, runSmoke, smokeUrl } from '../_harness/index.mjs';
|
const board = {
|
||||||
|
schema: 1, kind: 'board', id: 'host-find-board',
|
||||||
|
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' },
|
||||||
|
};
|
||||||
|
|
||||||
await runSmoke('find/pluginViews', async ({ page }) => {
|
await runSmoke('find/pluginViews', async ({ page }) => {
|
||||||
const output = await outputDir('find/pluginViews');
|
const output = await outputDir('find/pluginViews');
|
||||||
const pmDist = pluginRepo('RuneStone_Project_Management/dist/plugin');
|
|
||||||
const pm = {
|
|
||||||
manifest: JSON.parse(await readFile(path.join(pmDist, 'plugin.json'), 'utf8')),
|
|
||||||
code: await readFile(path.join(pmDist, 'main.js'), 'utf8'),
|
|
||||||
};
|
|
||||||
// Unknown commands return null, as the original mock did.
|
// Unknown commands return null, as the original mock did.
|
||||||
await mockTauri(page, {
|
await mockTauri(page, {
|
||||||
strict: false,
|
strict: false,
|
||||||
state: { pm },
|
state: { catalog: JSON.stringify({ schema: 1, boards: [{ name: 'Find board', value: board }] }, null, 2) + '\n' },
|
||||||
commands: test => {
|
commands: test => {
|
||||||
const workspace = test.workspace({
|
const workspace = test.workspace({
|
||||||
root: 'C:/find-test',
|
root: 'C:/find-test',
|
||||||
files: {
|
files: {
|
||||||
'untitled.md': '# Existing note\n',
|
'untitled.md': '# Existing note\n',
|
||||||
'sample.finddoc': 'Alpha alpha alphabet',
|
'sample.finddoc': 'Alpha alpha alphabet',
|
||||||
'Board.md': '---\nrunestone_pm:\n schema: 1\n kind: board\n id: host-find-board\n lists:\n - {id: todo, name: To do, status: todo, collapsed: false}\n - {id: doing, name: In progress, status: doing, collapsed: false}\n - {id: done, name: Done, status: done, collapsed: false}\n defaults: {todo: todo, doing: doing, done: done}\n---\n',
|
'.runestone/pm/.gitignore': '*\n',
|
||||||
|
'.runestone/pm/workspace.json': test.state.catalog,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
test.files = workspace.files;
|
test.files = workspace.files;
|
||||||
const { pm } = test.state;
|
|
||||||
const manifest = { schemaVersion: 1, id: 'test.find', name: 'Find test', author: 'Test', description: 'Search checks', version: '1.0.0', apiVersion: 1, entry: 'main.js', access: 'full-app' };
|
const manifest = { schemaVersion: 1, id: 'test.find', name: 'Find test', author: 'Test', description: 'Search checks', version: '1.0.0', apiVersion: 1, entry: 'main.js', access: 'full-app' };
|
||||||
const code = `export function activate(api) {
|
const code = `export function activate(api) {
|
||||||
api.registerDocumentType({ id: 'document', title: 'Test document', extensions: ['finddoc'], identify: path => ({ id: path }), mount(root) {
|
api.registerDocumentType({ id: 'document', title: 'Test document', extensions: ['finddoc'], identify: path => ({ id: path }), mount(root) {
|
||||||
@@ -43,8 +46,8 @@ await runSmoke('find/pluginViews', async ({ page }) => {
|
|||||||
if (!workspace.files.has(args.rel) && args.missingOk) return null;
|
if (!workspace.files.has(args.rel) && args.missingOk) return null;
|
||||||
return workspace.workspace_read(args);
|
return workspace.workspace_read(args);
|
||||||
},
|
},
|
||||||
plugins_snapshot: () => ({ root: 'C:/test/plugins', plugins: [manifest, pm.manifest].map(item => ({ manifest: item, hash: item.id, enabled: true, path: 'C:/test/plugins/' + item.id, error: null, removal: false })) }),
|
plugins_snapshot: () => ({ root: 'C:/test/plugins', plugins: [manifest].map(item => ({ manifest: item, hash: item.id, enabled: true, path: 'C:/test/plugins/' + item.id, error: null, removal: false })) }),
|
||||||
plugins_load: args => args.id === pm.manifest.id ? pm.code : code,
|
plugins_load: () => code,
|
||||||
plugins_data: () => 'null',
|
plugins_data: () => 'null',
|
||||||
browser_connect: () => 'test',
|
browser_connect: () => 'test',
|
||||||
};
|
};
|
||||||
@@ -99,11 +102,14 @@ await runSmoke('find/pluginViews', async ({ page }) => {
|
|||||||
await page.screenshot({ path: `${output}/${name}-${theme}-narrow.png` });
|
await page.screenshot({ path: `${output}/${name}-${theme}-narrow.png` });
|
||||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||||
}
|
}
|
||||||
for (const surface of ['all-tasks', 'board-document']) {
|
for (const surface of ['all-tasks', 'board']) {
|
||||||
if (surface === 'all-tasks') {
|
// The ribbon button opens All tasks. The board scope opens the board in the same tab.
|
||||||
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
|
if (surface === 'all-tasks') await page.locator('.plugin-ribbon').getByRole('button', { name: 'Project Management', exact: true }).click();
|
||||||
await page.getByRole('menuitem', { name: /^Project Management/ }).click();
|
else {
|
||||||
} else await page.getByRole('tree', { name: 'Workspace files' }).getByText('Board', { exact: true }).dblclick();
|
await page.locator('.plugin-editor-pane:visible').getByRole('button', { name: /^Board scope:/ }).click();
|
||||||
|
await page.getByRole('menuitemradio', { name: 'Find board', exact: true }).click();
|
||||||
|
await page.getByRole('tab', { name: 'Find board', exact: true }).waitFor();
|
||||||
|
}
|
||||||
const pane = page.locator('.plugin-editor-pane:visible');
|
const pane = page.locator('.plugin-editor-pane:visible');
|
||||||
await pane.locator('.pm-board').waitFor();
|
await pane.locator('.pm-board').waitFor();
|
||||||
await pane.focus();
|
await pane.focus();
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { storedSwitches, switchesFrom } from "../../../src/lib/features/state.ts
|
|||||||
import { legacySwitch, migrateFeatures, type LegacyPlugin } from "../../../src/lib/features/migration.ts";
|
import { legacySwitch, migrateFeatures, type LegacyPlugin } from "../../../src/lib/features/migration.ts";
|
||||||
import type { BackgroundMigrationHost, BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
|
import type { BackgroundMigrationHost, BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
|
||||||
import type { TerminalMigrationHost } from "../../../src/lib/features/terminalSettings.ts";
|
import type { TerminalMigrationHost } from "../../../src/lib/features/terminalSettings.ts";
|
||||||
|
import type { ProjectManagementMigrationHost } from "../../../src/lib/features/pmSettings.ts";
|
||||||
import { featureErrors, featureRequested, loadFeature } from "../../../src/lib/features/loader.ts";
|
import { featureErrors, featureRequested, loadFeature } from "../../../src/lib/features/loader.ts";
|
||||||
import { FeatureSession } from "../../../src/lib/features/session.ts";
|
import { FeatureSession } from "../../../src/lib/features/session.ts";
|
||||||
import type { FeatureContext, FeatureInstance, FeatureModule } from "../../../src/lib/features/types.ts";
|
import type { FeatureContext, FeatureInstance, FeatureModule } from "../../../src/lib/features/types.ts";
|
||||||
@@ -33,9 +34,9 @@ test("switches keep known booleans only, and missing keys take the default", ()
|
|||||||
assert.deepEqual(storedSwitches({ git: false, terminal: "no", csv: true, other: "yes" }), { git: false });
|
assert.deepEqual(storedSwitches({ git: false, terminal: "no", csv: true, other: "yes" }), { git: false });
|
||||||
assert.deepEqual(storedSwitches(null), {});
|
assert.deepEqual(storedSwitches(null), {});
|
||||||
assert.deepEqual(storedSwitches(["git"]), {});
|
assert.deepEqual(storedSwitches(["git"]), {});
|
||||||
assert.deepEqual(switchesFrom(undefined), { git: true, background: true, terminal: true, pdf: true });
|
assert.deepEqual(switchesFrom(undefined), { git: true, background: true, terminal: true, pdf: true, pm: true });
|
||||||
assert.deepEqual(switchesFrom({ git: false, background: false, terminal: false, pdf: false }), { git: false, background: false, terminal: false, pdf: false });
|
assert.deepEqual(switchesFrom({ git: false, background: false, terminal: false, pdf: false, pm: false }), { git: false, background: false, terminal: false, pdf: false, pm: false });
|
||||||
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true, terminal: true, pdf: true });
|
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true, terminal: true, pdf: true, pm: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
test("an installed package gives its state, and without a package the default applies", () => {
|
test("an installed package gives its state, and without a package the default applies", () => {
|
||||||
@@ -63,6 +64,11 @@ function presentTerminal(): TerminalMigrationHost {
|
|||||||
return { missing: () => false, legacy: () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
|
return { missing: () => false, legacy: () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A Project Management host with a section already present. */
|
||||||
|
function presentProjectManagement(): ProjectManagementMigrationHost {
|
||||||
|
return { missing: () => false, write: async () => { throw new Error("not asked"); }, storage: { getItem: () => { throw new Error("not asked"); }, setItem: () => { throw new Error("not asked"); } } };
|
||||||
|
}
|
||||||
|
|
||||||
test("the migration asks only for features without a switch, and keeps other keys", async () => {
|
test("the migration asks only for features without a switch, and keeps other keys", async () => {
|
||||||
const writes: unknown[] = [];
|
const writes: unknown[] = [];
|
||||||
const asked: string[][] = [];
|
const asked: string[][] = [];
|
||||||
@@ -71,10 +77,10 @@ test("the migration asks only for features without a switch, and keeps other key
|
|||||||
write: async (value: unknown) => { writes.push(value); },
|
write: async (value: unknown) => { writes.push(value); },
|
||||||
legacy: async (ids: string[]) => { asked.push(ids); return packages; },
|
legacy: async (ids: string[]) => { asked.push(ids); return packages; },
|
||||||
});
|
});
|
||||||
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false, terminal: true, pdf: true }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground(), presentTerminal()), ["git"]);
|
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false, terminal: true, pdf: true, pm: true }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground(), presentTerminal(), presentProjectManagement()), ["git"]);
|
||||||
assert.deepEqual(asked, [["runestone.git"]]);
|
assert.deepEqual(asked, [["runestone.git"]]);
|
||||||
assert.deepEqual(writes, [{ future: 1, background: false, terminal: true, pdf: true, git: false }]);
|
assert.deepEqual(writes, [{ future: 1, background: false, terminal: true, pdf: true, pm: true, git: false }]);
|
||||||
assert.deepEqual(await migrateFeatures(host({ git: true, background: true, terminal: true, pdf: true }, []), presentBackground(), presentTerminal()), []);
|
assert.deepEqual(await migrateFeatures(host({ git: true, background: true, terminal: true, pdf: true, pm: true }, []), presentBackground(), presentTerminal(), presentProjectManagement()), []);
|
||||||
assert.equal(asked.length, 1, "A stored switch needs no package read.");
|
assert.equal(asked.length, 1, "A stored switch needs no package read.");
|
||||||
assert.equal(writes.length, 1);
|
assert.equal(writes.length, 1);
|
||||||
});
|
});
|
||||||
@@ -84,17 +90,17 @@ test("a missing background section asks for the slideshow package and makes the
|
|||||||
const switches: unknown[] = [];
|
const switches: unknown[] = [];
|
||||||
const sections: BackgroundSettings[] = [];
|
const sections: BackgroundSettings[] = [];
|
||||||
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } };
|
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } };
|
||||||
const host = { read: () => ({ git: true, background: false, terminal: true, pdf: true }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
|
const host = { read: () => ({ git: true, background: false, terminal: true, pdf: true, pm: true }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
|
||||||
assert.deepEqual(await migrateFeatures(host, background, presentTerminal()), []);
|
assert.deepEqual(await migrateFeatures(host, background, presentTerminal(), presentProjectManagement()), []);
|
||||||
assert.deepEqual(asked, [["runestone.bg-slideshow"]]);
|
assert.deepEqual(asked, [["runestone.bg-slideshow"]]);
|
||||||
assert.deepEqual(switches, [], "Stored switches stay.");
|
assert.deepEqual(switches, [], "Stored switches stay.");
|
||||||
assert.equal(sections.length, 1);
|
assert.equal(sections.length, 1);
|
||||||
assert.equal(sections[0].source, "image");
|
assert.equal(sections[0].source, "image");
|
||||||
// Both migrations together ask once for both packages.
|
// Both migrations together ask once for both packages.
|
||||||
asked.length = 0;
|
asked.length = 0;
|
||||||
await migrateFeatures({ ...host, read: () => undefined }, background, presentTerminal());
|
await migrateFeatures({ ...host, read: () => undefined }, background, presentTerminal(), presentProjectManagement());
|
||||||
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer"]]);
|
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm"]]);
|
||||||
assert.deepEqual(switches, [{ git: true, background: true, terminal: true, pdf: true }]);
|
assert.deepEqual(switches, [{ git: true, background: true, terminal: true, pdf: true, pm: true }]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("a failed package read writes nothing, so the next start tries again", async () => {
|
test("a failed package read writes nothing, so the next start tries again", async () => {
|
||||||
@@ -103,7 +109,7 @@ test("a failed package read writes nothing, so the next start tries again", asyn
|
|||||||
console.error = () => {};
|
console.error = () => {};
|
||||||
try {
|
try {
|
||||||
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { writes.push(value); } };
|
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { writes.push(value); } };
|
||||||
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } }, background, presentTerminal());
|
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } }, background, presentTerminal(), presentProjectManagement());
|
||||||
assert.deepEqual(result, []);
|
assert.deepEqual(result, []);
|
||||||
assert.deepEqual(writes, []);
|
assert.deepEqual(writes, []);
|
||||||
} finally { console.error = error; }
|
} finally { console.error = error; }
|
||||||
@@ -125,7 +131,7 @@ test("the loader imports a feature one time, reports a failure, and tries again
|
|||||||
});
|
});
|
||||||
|
|
||||||
function fakeContext(opened: string[] = []): FeatureContext {
|
function fakeContext(opened: string[] = []): FeatureContext {
|
||||||
return { openView: id => { opened.push(id); }, openFile: async () => {}, onWorkspaceChange: () => () => {} };
|
return { openView: id => { opened.push(id); }, openFile: async () => {}, onWorkspaceChange: () => () => {}, setViewTitle: () => {}, closeView: () => {}, replaceView: () => {} };
|
||||||
}
|
}
|
||||||
|
|
||||||
test("a feature session shows its views and commands without loading the feature", async () => {
|
test("a feature session shows its views and commands without loading the feature", async () => {
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ test("the catalog gives PDF Viewer the old package ID and one binary document ty
|
|||||||
});
|
});
|
||||||
|
|
||||||
function fakeContext(): FeatureContext {
|
function fakeContext(): FeatureContext {
|
||||||
return { openView: () => {}, openFile: async () => {}, onWorkspaceChange: () => () => {} };
|
return { openView: () => {}, openFile: async () => {}, onWorkspaceChange: () => () => {}, setViewTitle: () => {}, closeView: () => {}, replaceView: () => {} };
|
||||||
}
|
}
|
||||||
|
|
||||||
test("a feature session identifies PDF files without loading the feature", () => {
|
test("a feature session identifies PDF files without loading the feature", () => {
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
// An in-memory workspace for the tests of the native Project Management feature. It records each read.
|
||||||
|
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||||
|
import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
|
||||||
|
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
|
||||||
|
import { newTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||||
|
import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||||
|
import type { TaskFields, Workspace } from "../../../../src/lib/features/pm/model/model.ts";
|
||||||
|
|
||||||
|
export interface MemoryWorkspace extends Workspace {
|
||||||
|
files: Map<string, string>;
|
||||||
|
/** Each path that a read asked for, in order. A `readMany` row counts as one read. */
|
||||||
|
reads: string[];
|
||||||
|
/** Each folder that a listing asked for. */
|
||||||
|
lists: string[];
|
||||||
|
/** The number of Markdown listings. */
|
||||||
|
markdownLists: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function memoryWorkspace(initial: Record<string, string> = {}): MemoryWorkspace {
|
||||||
|
const files = new Map(Object.entries(initial));
|
||||||
|
const reads: string[] = [], lists: string[] = [];
|
||||||
|
const parent = (path: string) => path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
|
||||||
|
const workspace: MemoryWorkspace = {
|
||||||
|
files, reads, lists, markdownLists: 0,
|
||||||
|
async list(path = "") {
|
||||||
|
lists.push(path);
|
||||||
|
const names = new Map<string, "file" | "folder">();
|
||||||
|
for (const file of files.keys()) {
|
||||||
|
if (path && !file.startsWith(path + "/")) continue;
|
||||||
|
const rest = path ? file.slice(path.length + 1) : file;
|
||||||
|
const name = rest.split("/")[0];
|
||||||
|
names.set(name, rest.includes("/") ? "folder" : "file");
|
||||||
|
}
|
||||||
|
return [...names].map(([name, kind]) => ({ name, rel_path: path ? `${path}/${name}` : name, kind }));
|
||||||
|
},
|
||||||
|
async listMarkdown() {
|
||||||
|
workspace.markdownLists++;
|
||||||
|
return [...files.keys()].filter(path => /\.(md|markdown|mdown)$/i.test(path) && !path.startsWith(".")).sort();
|
||||||
|
},
|
||||||
|
async read(path) {
|
||||||
|
reads.push(path);
|
||||||
|
if (!files.has(path)) throw new Error(`Missing file: ${path}`);
|
||||||
|
return files.get(path)!;
|
||||||
|
},
|
||||||
|
async readMany(paths) {
|
||||||
|
reads.push(...paths);
|
||||||
|
return paths.map(path => files.has(path) ? { path, source: files.get(path) } : { path, error: "Missing file" });
|
||||||
|
},
|
||||||
|
async readOptional(path) {
|
||||||
|
reads.push(path);
|
||||||
|
return files.get(path) ?? null;
|
||||||
|
},
|
||||||
|
async write(path, contents, expected) {
|
||||||
|
if (files.get(path) !== expected) throw new Error(`The file changed: ${path}`);
|
||||||
|
files.set(path, contents);
|
||||||
|
},
|
||||||
|
async create(path, contents) {
|
||||||
|
if (files.has(path)) throw new Error(`The file exists: ${path}`);
|
||||||
|
void parent(path);
|
||||||
|
files.set(path, contents);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return workspace;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const fields = (extra: Partial<TaskFields> = {}): TaskFields => ({ status: "todo", tags: [], sessions: [], archived: false, ...extra });
|
||||||
|
|
||||||
|
/** A workspace with hidden storage: one board `board` and the given cards. */
|
||||||
|
export function hiddenWorkspace(cards: { id: string; title: string; fields?: Partial<TaskFields> }[] = [], extra: Record<string, string> = {}) {
|
||||||
|
const board = defaultBoard("board");
|
||||||
|
const files: Record<string, string> = {
|
||||||
|
[privateRulesPath]: "*\n",
|
||||||
|
[cardsMarker]: "*\n",
|
||||||
|
[catalogPath]: JSON.stringify({ schema: 1, boards: [{ name: "Board", value: board }] }, null, 2) + "\n",
|
||||||
|
...extra,
|
||||||
|
};
|
||||||
|
for (const card of cards) files[cardPath(card.id)] = newTask(card.title, fields({ title: card.title, placements: { board: { listId: "todo" } }, ...card.fields }), "Body", card.id).source;
|
||||||
|
return memoryWorkspace(files);
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { allTaskColumns, allTaskGroups } from "../../../../src/lib/features/pm/model/all-tasks.ts";
|
||||||
|
import { defaultBoard, type BoardDocument } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||||
|
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||||
|
import type { TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
|
||||||
|
const board = (id: string): BoardDocument => ({ id, path: `${id}.md`, name: id, source: "", value: defaultBoard(id) });
|
||||||
|
const task = (title: string, placements: TaskFields["placements"]) => {
|
||||||
|
const note = newTask(title, { status: "todo", archived: false, tags: [], sessions: [], placements });
|
||||||
|
return readTask(`${title}.md`, note.source)!;
|
||||||
|
};
|
||||||
|
|
||||||
|
test("All tasks merges list names, preserves custom lists, and includes every matching card once", () => {
|
||||||
|
const a = board("A"), b = board("B"), c = board("C");
|
||||||
|
a.value.lists.push({ id: "review", name: "Review", status: null, collapsed: true });
|
||||||
|
b.value.lists[0].name = " To Do ";
|
||||||
|
b.value.lists[0].id = "different-id";
|
||||||
|
c.value.lists[0].maxCards = 2;
|
||||||
|
const shared = task("Shared", { A: { listId: "todo" }, B: { listId: "different-id" } });
|
||||||
|
const other = task("Other", { C: { listId: "todo" } });
|
||||||
|
const review = task("Review", { A: { listId: "review" }, C: { listId: "todo" } });
|
||||||
|
const unlisted = task("Unlisted", { A: { listId: "removed" }, B: { listId: null } });
|
||||||
|
const orphan = task("Orphan", { deleted: { listId: "todo" } });
|
||||||
|
const original = JSON.stringify({ boards: [a, b, c], tasks: [shared, other, review, unlisted, orphan] });
|
||||||
|
const columns = allTaskColumns([a, b, c], [shared, other, review, unlisted, orphan]);
|
||||||
|
assert.equal(columns.length, 5);
|
||||||
|
assert.deepEqual(columns.find(c => c.list?.name === "To do")?.tasks, [shared, other, review, orphan]);
|
||||||
|
assert.deepEqual(columns.find(c => c.list?.name === "Review")?.tasks, [review]);
|
||||||
|
assert.deepEqual(columns.find(c => !c.list)?.tasks, [unlisted]);
|
||||||
|
assert.equal(columns.find(c => c.list?.name === "Review")?.list?.collapsed, false);
|
||||||
|
assert.equal(columns.find(c => c.list?.name === "To do")?.list?.maxCards, undefined);
|
||||||
|
assert.equal(columns.find(c => c.list?.name === "To do")?.allowCreate, false);
|
||||||
|
assert.equal(JSON.stringify({ boards: [a, b, c], tasks: [shared, other, review, unlisted, orphan] }), original);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("matching list IDs with different names remain separate and empty lists stay visible", () => {
|
||||||
|
const a = board("A"), b = board("B");
|
||||||
|
b.value.lists[0].name = "Backlog";
|
||||||
|
const columns = allTaskColumns([a, b], []);
|
||||||
|
assert.deepEqual(columns.map(c => c.list?.name), ["To do", "In progress", "Done", "Backlog"]);
|
||||||
|
assert.equal(new Set(columns.map(c => c.list?.id)).size, 4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("cards on archived boards remain visible and empty workspaces retain default lists", () => {
|
||||||
|
const archived = { ...board("Archived"), archived: true };
|
||||||
|
const card = task("Archived board card", { Archived: { listId: "todo" } });
|
||||||
|
const columns = allTaskColumns([archived], [card]);
|
||||||
|
assert.deepEqual(columns[0].tasks, [card]);
|
||||||
|
assert.equal(columns.length, 3);
|
||||||
|
assert.equal(columns[0].allowCreate, true);
|
||||||
|
assert.equal(allTaskColumns([], []).length, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("board dividers name shared memberships once and separate cards without active boards", () => {
|
||||||
|
const a = board("A"), b = board("B");
|
||||||
|
a.value.lists.push({ id: "review", name: "Review", status: null, collapsed: false });
|
||||||
|
const shared = task("Shared", { A: { listId: "todo" }, B: { listId: "todo" } });
|
||||||
|
const separate = task("Separate", { A: { listId: "review" }, B: { listId: "todo" } });
|
||||||
|
const orphan = task("Orphan", { deleted: { listId: "todo" } });
|
||||||
|
const columns = allTaskColumns([a, b], [shared, separate, orphan]);
|
||||||
|
const todo = columns.find(column => column.list?.name === "To do")!;
|
||||||
|
assert.deepEqual(allTaskGroups([a, b], todo).map(group => [group.name, group.tasks.map(task => task.title)]), [
|
||||||
|
["A · B", ["Shared"]], ["B", ["Separate"]], ["No active board", ["Orphan"]],
|
||||||
|
]);
|
||||||
|
assert.deepEqual(allTaskGroups([a, b], columns.find(column => column.list?.name === "Review")!).map(group => group.name), ["A"]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
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 { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||||
|
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
|
||||||
|
|
||||||
|
function fixture(count = 3) {
|
||||||
|
const files = new Map<string, string>([[cardsMarker, "*\n"], [privateRulesPath, "*\n"]]);
|
||||||
|
const ids = Array.from({ length: count }, () => crypto.randomUUID());
|
||||||
|
for (const [index, id] of ids.entries()) files.set(cardPath(id), newTask(`Card ${index}`, {
|
||||||
|
title: `Card ${index}`, status: "todo", tags: [], sessions: [], archived: false,
|
||||||
|
...(index === 0 ? { links: [{ taskId: ids[1], relation: "blocks" }, { taskId: ids[2], relation: "relates" }] as const } : {}),
|
||||||
|
}, "Keep body", id).source);
|
||||||
|
let batches = 0, singleReads = 0;
|
||||||
|
const workspace: Workspace = {
|
||||||
|
async listMarkdown() { return []; },
|
||||||
|
async list() { return [...files.keys()].filter(path => path.endsWith(".md")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); },
|
||||||
|
async read(path) { singleReads++; return files.get(path)!; },
|
||||||
|
async readOptional(path) { return files.get(path) ?? null; },
|
||||||
|
async readMany(paths) { assert.ok(paths.length <= 64); batches++; return paths.map(path => ({ path, source: files.get(path) })); },
|
||||||
|
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); },
|
||||||
|
};
|
||||||
|
return { files, ids, workspace, counts: () => ({ batches, singleReads }) };
|
||||||
|
}
|
||||||
|
|
||||||
|
test("1000 cards use 16 bounded reads and share parsed cards between board views", async t => {
|
||||||
|
const f = fixture(1000), store = new TaskStore(f.workspace);
|
||||||
|
let started = performance.now();
|
||||||
|
await store.reload();
|
||||||
|
t.diagnostic(`Initial 1000-card parse: ${Math.round(performance.now() - started)} ms`);
|
||||||
|
assert.deepEqual(f.counts(), { batches: 16, singleReads: 0 });
|
||||||
|
const first = store.tasks[0];
|
||||||
|
const next = new TaskStore(f.workspace);
|
||||||
|
started = performance.now(); await next.reload();
|
||||||
|
t.diagnostic(`Switch with unchanged sources: ${Math.round(performance.now() - started)} ms`);
|
||||||
|
assert.equal(next.tasks[0], first);
|
||||||
|
started = performance.now(); await next.save(first, { body: "Changed body" });
|
||||||
|
t.diagnostic(`Save with full conflict scan: ${Math.round(performance.now() - started)} ms`);
|
||||||
|
assert.deepEqual(f.counts(), { batches: 48, singleReads: 0 });
|
||||||
|
const stale = next.tasks.find(task => task.id === first.id)!;
|
||||||
|
f.files.set(stale.path, editTask(stale, { body: "External body" }));
|
||||||
|
await assert.rejects(next.save(stale, { body: "Overwrite" }), /changed/);
|
||||||
|
assert.equal(readTask(stale.path, f.files.get(stale.path)!)!.body, "External body");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("incoming unlink preserves unrelated links and rejects stale source cards", async () => {
|
||||||
|
const f = fixture(), store = new TaskStore(f.workspace); await store.reload();
|
||||||
|
const source = store.tasks.find(task => task.id === f.ids[0])!;
|
||||||
|
await store.unlinkIncoming(f.ids[1], [source]);
|
||||||
|
const saved = readTask(source.path, f.files.get(source.path)!)!;
|
||||||
|
assert.deepEqual(saved.links, [{ taskId: f.ids[2], relation: "relates" }]);
|
||||||
|
assert.equal(saved.body, "Keep body");
|
||||||
|
await store.unlinkIncoming(f.ids[1], [source]); // A retry is harmless.
|
||||||
|
f.files.set(saved.path, editTask(saved, { body: "External change" }));
|
||||||
|
await assert.rejects(store.unlinkIncoming(f.ids[2], [saved]), /linked card changed/);
|
||||||
|
assert.deepEqual(readTask(saved.path, f.files.get(saved.path)!)!.links, saved.links);
|
||||||
|
});
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { BoardStore, newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||||
|
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||||
|
import { newTask, readTask } 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: [],
|
||||||
|
sessions: [],
|
||||||
|
archived: false,
|
||||||
|
};
|
||||||
|
function fixture() {
|
||||||
|
const source = newBoardSource();
|
||||||
|
const files = new Map<string, string>([["Board.md", source]]);
|
||||||
|
const reference = { id: parseBoard(source).id, path: "Board.md" };
|
||||||
|
const workspace: Workspace = {
|
||||||
|
async readOptional(path) {
|
||||||
|
return files.get(path) ?? null;
|
||||||
|
},
|
||||||
|
async read(path) {
|
||||||
|
if (!files.has(path)) throw Error("Missing");
|
||||||
|
return files.get(path)!;
|
||||||
|
},
|
||||||
|
async create(path, text) {
|
||||||
|
if (files.has(path)) throw Error("Exists");
|
||||||
|
files.set(path, text);
|
||||||
|
},
|
||||||
|
async write(path, text, expected) {
|
||||||
|
if (files.get(path) !== expected) throw Error("Conflict");
|
||||||
|
files.set(path, text);
|
||||||
|
},
|
||||||
|
async list(parent = "") {
|
||||||
|
return [...files.keys()]
|
||||||
|
.filter((path) => !path.startsWith("."))
|
||||||
|
.map((path) => ({ name: path, rel_path: path, kind: "file" }));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { files, workspace, reference };
|
||||||
|
}
|
||||||
|
test("list names, completion mapping, order, and collapse survive reload", async () => {
|
||||||
|
const { workspace, reference } = fixture();
|
||||||
|
const board = new BoardStore(workspace, reference);
|
||||||
|
await board.reload();
|
||||||
|
await board.add("Review", null);
|
||||||
|
const review = board.value.lists.at(-1)!;
|
||||||
|
await board.edit(review.id, "Approved", "done");
|
||||||
|
await board.move(review.id, 0);
|
||||||
|
await board.collapse(review.id);
|
||||||
|
const reopened = new BoardStore(workspace, reference);
|
||||||
|
await reopened.reload();
|
||||||
|
assert.deepEqual(reopened.value.lists[0], {
|
||||||
|
id: review.id,
|
||||||
|
name: "Approved",
|
||||||
|
status: "done",
|
||||||
|
collapsed: true,
|
||||||
|
});
|
||||||
|
await assert.rejects(reopened.add("approved", null), /already exists/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("list maximum survives edits and reload, rejects invalid values, and can be removed", async () => {
|
||||||
|
const { workspace, reference } = fixture();
|
||||||
|
const board = new BoardStore(workspace, reference);
|
||||||
|
await board.reload();
|
||||||
|
await board.setLimit("todo", 2);
|
||||||
|
await board.edit("todo", "Next", "todo");
|
||||||
|
await board.collapse("todo");
|
||||||
|
await board.reload();
|
||||||
|
assert.equal(board.value.lists[0].maxCards, 2);
|
||||||
|
for (const invalid of [0, -1, 1.5, Infinity, NaN, Number.MAX_SAFE_INTEGER + 1])
|
||||||
|
await assert.rejects(board.setLimit("todo", invalid), /whole number/);
|
||||||
|
const source = newBoardSource().replace("collapsed: false", "collapsed: false\n maxCards: -2");
|
||||||
|
assert.throws(() => parseBoard(source), /invalid list/);
|
||||||
|
await board.setLimit("todo");
|
||||||
|
await board.reload();
|
||||||
|
assert.equal(board.value.lists[0].maxCards, undefined);
|
||||||
|
});
|
||||||
|
test("deleting a populated list preserves notes and sends its cards to Unlisted", async () => {
|
||||||
|
const { workspace, files, reference } = fixture();
|
||||||
|
const note = newTask(
|
||||||
|
"Keep me",
|
||||||
|
{ ...fields, placements: { [reference.id]: { listId: "todo" } } },
|
||||||
|
"Keep the body",
|
||||||
|
);
|
||||||
|
files.set("Keep me.md", note.source);
|
||||||
|
const store = new TaskStore(workspace, reference);
|
||||||
|
await store.reload();
|
||||||
|
await store.changeBoard(() => store.board.remove("todo"));
|
||||||
|
assert.equal(store.board.listFor(store.tasks[0]), undefined);
|
||||||
|
assert.equal(files.get("Keep me.md"), note.source);
|
||||||
|
await store.board.add("Replacement", null);
|
||||||
|
assert.equal(store.board.listFor(store.tasks[0]), undefined);
|
||||||
|
assert.equal(
|
||||||
|
store.board.listFor({ status: "todo", listId: undefined }),
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
test("moving a card stores its list and completion in one guarded note write", async () => {
|
||||||
|
const { workspace, files, reference } = fixture();
|
||||||
|
const note = newTask("Task", fields);
|
||||||
|
files.set("Task.md", note.source);
|
||||||
|
const store = new TaskStore(workspace, reference);
|
||||||
|
await store.reload();
|
||||||
|
await store.moveTask(store.tasks[0], "done");
|
||||||
|
const saved = readTask("Task.md", files.get("Task.md")!)!;
|
||||||
|
assert.equal(saved.placements?.[reference.id].listId, "done");
|
||||||
|
assert.equal(saved.status, "done");
|
||||||
|
assert.equal(saved.id, store.tasks[0].id);
|
||||||
|
await store.moveTask(store.tasks[0], null);
|
||||||
|
assert.equal(store.board.listFor(store.tasks[0]), undefined);
|
||||||
|
assert.equal(store.tasks[0].status, "todo");
|
||||||
|
});
|
||||||
|
test("stale list edits do not overwrite another board revision", async () => {
|
||||||
|
const { workspace, files, reference } = fixture();
|
||||||
|
const first = new BoardStore(workspace, reference),
|
||||||
|
second = new BoardStore(workspace, reference);
|
||||||
|
await first.reload();
|
||||||
|
await second.reload();
|
||||||
|
await first.add("Review", null);
|
||||||
|
const saved = files.get("Board.md");
|
||||||
|
await assert.rejects(second.add("Other", null), /changed/);
|
||||||
|
assert.equal(files.get("Board.md"), saved);
|
||||||
|
});
|
||||||
|
test("malformed or future board files stay untouched", async () => {
|
||||||
|
const { workspace, files, reference } = fixture();
|
||||||
|
const text = newBoardSource().replace("schema: 1", "schema: 2");
|
||||||
|
files.set("Board.md", text);
|
||||||
|
const board = new BoardStore(workspace, reference);
|
||||||
|
await assert.rejects(board.reload(), /unsupported/);
|
||||||
|
await assert.rejects(board.add("Oops", null), /Open an available board/);
|
||||||
|
assert.equal(files.get("Board.md"), text);
|
||||||
|
});
|
||||||
|
test("deleting all lists remains empty after reload and allows a new list", async () => {
|
||||||
|
const { workspace, reference } = fixture();
|
||||||
|
const board = new BoardStore(workspace, reference);
|
||||||
|
await board.reload();
|
||||||
|
for (const id of ["todo", "doing", "done"]) await board.remove(id);
|
||||||
|
const next = new BoardStore(workspace, reference);
|
||||||
|
await next.reload();
|
||||||
|
assert.equal(next.value.lists.length, 0);
|
||||||
|
await next.add("First", null);
|
||||||
|
assert.equal(next.value.lists[0].name, "First");
|
||||||
|
});
|
||||||
|
test("All tasks cannot save board lists", async () => {
|
||||||
|
const { workspace, reference } = fixture();
|
||||||
|
const board = new BoardStore(workspace);
|
||||||
|
await board.reload();
|
||||||
|
await assert.rejects(board.add("Review", null), /Open an available board/);
|
||||||
|
assert.equal(board.value.lists.length, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("archiving a list scopes by board placement and preserves status, bodies, and other memberships", async () => {
|
||||||
|
const { workspace, files, reference } = fixture();
|
||||||
|
const sourceBoard = files.get(reference.path);
|
||||||
|
for (const [title, placements] of [
|
||||||
|
["Target", { [reference.id]: { listId: "todo" }, other: { listId: "doing" } }],
|
||||||
|
["Other list", { [reference.id]: { listId: "doing" } }],
|
||||||
|
["Other board", { other: { listId: "todo" } }],
|
||||||
|
] as const) {
|
||||||
|
const task = newTask(title, { ...fields, placements }, "Keep body");
|
||||||
|
files.set(task.path, task.source);
|
||||||
|
}
|
||||||
|
const store = new TaskStore(workspace, reference);
|
||||||
|
await store.reload();
|
||||||
|
const original = store.tasks.find(task => task.title === "Target")!;
|
||||||
|
await store.archiveList("todo");
|
||||||
|
await store.reload();
|
||||||
|
const archived = store.tasks.find(task => task.title === "Target")!;
|
||||||
|
assert.equal(archived.archived, true);
|
||||||
|
assert.equal(archived.status, original.status);
|
||||||
|
assert.deepEqual(archived.placements, original.placements);
|
||||||
|
assert.equal(archived.body, original.body);
|
||||||
|
assert.equal(store.tasks.filter(task => task.archived).length, 1);
|
||||||
|
assert.equal(files.get(reference.path), sourceBoard);
|
||||||
|
await store.archiveList("todo");
|
||||||
|
await assert.rejects(store.archiveList("missing"), /unavailable/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("board image appearance survives legacy saves and hidden catalog saves independently", async () => {
|
||||||
|
const { workspace, reference } = fixture();
|
||||||
|
const board = new BoardStore(workspace, reference); await board.reload();
|
||||||
|
const appearance = { overlay: -0.4, position: "bottom right", size: "contain" } as const;
|
||||||
|
await board.update(value => { value.backgroundImage = "11111111-1111-4111-8111-111111111111"; value.backgroundAppearance = appearance; });
|
||||||
|
await board.reload(); assert.equal(board.value.backgroundImage, "11111111-1111-4111-8111-111111111111"); assert.deepEqual(board.value.backgroundAppearance, appearance);
|
||||||
|
const store = new TaskStore(workspace); await store.reload(); const hidden = await store.createBoard("Hidden");
|
||||||
|
const managed = new BoardStore(workspace, hidden); await managed.reload();
|
||||||
|
await managed.update(value => { value.backgroundImage = "22222222-2222-4222-8222-222222222222"; value.backgroundAppearance = { overlay: 0.7, position: "top", size: "auto" }; });
|
||||||
|
await managed.reload(); assert.equal(managed.value.backgroundImage, "22222222-2222-4222-8222-222222222222"); assert.equal(managed.value.backgroundAppearance!.overlay, 0.7);
|
||||||
|
await board.reload(); assert.deepEqual(board.value.backgroundAppearance, appearance);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
test("leaving a Done rule reopens a card and neutral moves preserve manual completion", async () => {
|
||||||
|
const { workspace, files, reference } = fixture();
|
||||||
|
const note = newTask("Task", { ...fields, status: "done", placements: { [reference.id]: { listId: "done" } } });
|
||||||
|
files.set("Task.md", note.source);
|
||||||
|
const store = new TaskStore(workspace, reference); await store.reload();
|
||||||
|
await store.changeBoard(() => store.board.add("Review", null));
|
||||||
|
const review = store.board.value.lists.at(-1)!.id;
|
||||||
|
await store.moveTask(store.tasks[0], review);
|
||||||
|
await store.reload();
|
||||||
|
assert.equal(store.tasks[0].status, "todo");
|
||||||
|
assert.equal(store.tasks[0].placements![reference.id].listId, review);
|
||||||
|
await store.save(store.tasks[0], { status: "done" });
|
||||||
|
await store.moveTask(store.tasks[0], null);
|
||||||
|
await store.reload();
|
||||||
|
assert.equal(store.tasks[0].status, "done");
|
||||||
|
await store.changeBoard(() => store.board.edit(review, "Review", "doing"));
|
||||||
|
await store.moveTask(store.tasks[0], review);
|
||||||
|
await store.reload(); assert.equal(store.tasks[0].status, "doing");
|
||||||
|
await store.moveTask(store.tasks[0], "todo");
|
||||||
|
await store.changeBoard(() => store.board.edit(review, "Review", null));
|
||||||
|
await store.save(store.tasks[0], { listId: review }, true);
|
||||||
|
await store.reload(); assert.equal(store.tasks[0].status, "todo");
|
||||||
|
assert.equal(store.board.value.lists.find(list => list.id === review)!.status, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
test("overview creation writes one assigned card and rejects stale destinations without extra cards", async () => {
|
||||||
|
const { workspace, files, reference } = fixture();
|
||||||
|
const store = new TaskStore(workspace);
|
||||||
|
await store.reload();
|
||||||
|
await store.create("Assigned card", { ...fields, listId: "doing" }, "Card body", reference.id);
|
||||||
|
const task = store.tasks.find(task => task.title === "Assigned card")!;
|
||||||
|
assert.equal(task.placements?.[reference.id].listId, "doing");
|
||||||
|
assert.equal(Object.keys(task.placements ?? {}).length, 1);
|
||||||
|
assert.equal(task.body.trim(), "Card body");
|
||||||
|
const snapshot = new Map(files);
|
||||||
|
await assert.rejects(store.create("Missing board", fields, "", "missing"), /active board/);
|
||||||
|
await assert.rejects(store.create("Missing list", { ...fields, listId: "missing" }, "", reference.id), /list no longer exists/);
|
||||||
|
assert.deepEqual(files, snapshot);
|
||||||
|
files.delete("Board.md");
|
||||||
|
const afterDelete = new Map(files);
|
||||||
|
await assert.rejects(store.create("Deleted board", fields, "", reference.id), /active board/);
|
||||||
|
assert.deepEqual(files, afterDelete);
|
||||||
|
});
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||||
|
import { priorities, type TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
|
||||||
|
import { renderMarkdown } from "../../../../src/lib/features/pm/model/markdown.ts";
|
||||||
|
|
||||||
|
const fields: TaskFields = {
|
||||||
|
status: "todo",
|
||||||
|
tags: [],
|
||||||
|
labels: ["high-priority"],
|
||||||
|
sessions: [],
|
||||||
|
archived: false,
|
||||||
|
};
|
||||||
|
test("priority round-trips independently of labels and survives unrelated changes", () => {
|
||||||
|
for (const priority of [...priorities, null]) {
|
||||||
|
const note = newTask("Priority card", { ...fields, priority });
|
||||||
|
const task = readTask(note.path, note.source)!;
|
||||||
|
assert.equal(task.priority, priority);
|
||||||
|
const changed = readTask(
|
||||||
|
note.path,
|
||||||
|
editTask(task, { status: "doing", listId: "review", body: "Edited" }),
|
||||||
|
)!;
|
||||||
|
assert.equal(changed.priority, priority);
|
||||||
|
assert.deepEqual(changed.labels, fields.labels);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
test("unrelated edits preserve absent priority and explicit removal writes null", () => {
|
||||||
|
const note = newTask("Legacy", fields);
|
||||||
|
const task = readTask(note.path, note.source)!;
|
||||||
|
assert.doesNotMatch(editTask(task, { body: "Edit" }), /priority:/);
|
||||||
|
const cleared = editTask(task, { priority: null });
|
||||||
|
assert.match(cleared, /priority: null/);
|
||||||
|
assert.deepEqual(readTask(note.path, cleared)!.labels, fields.labels);
|
||||||
|
assert.throws(
|
||||||
|
() => newTask("Invalid", { ...fields, priority: "urgent" as never }),
|
||||||
|
/priority/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
test("Markdown preview escapes HTML and rejects active links and external images", () => {
|
||||||
|
const result = renderMarkdown(
|
||||||
|
"# Heading\n\n**Bold**\n\n<script>alert(1)</script>\n\n[x](javascript:alert(1))\n\n\n\n\n\n[safe](https://example.com)",
|
||||||
|
);
|
||||||
|
assert.match(result, /<h1>Heading<\/h1>/);
|
||||||
|
assert.match(result, /<strong>Bold<\/strong>/);
|
||||||
|
assert.doesNotMatch(result, /<script|src=|href="javascript:/);
|
||||||
|
assert.match(result, /data-pm-image="12345678-1234-1234-1234-123456789abc"/);
|
||||||
|
assert.match(result, /rel="noopener noreferrer"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("covers, subtasks, and card links round-trip without changing other fields", () => {
|
||||||
|
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/);
|
||||||
|
});
|
||||||
@@ -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: "[email protected]" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"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);
|
||||||
|
});
|
||||||
@@ -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<void>((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/);
|
||||||
|
});
|
||||||
@@ -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<string, string> = {}) {
|
||||||
|
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(!/(?<!\r)\n/.test(next));
|
||||||
|
});
|
||||||
|
test("adding an existing note preserves its content and does not duplicate its identity", () => {
|
||||||
|
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/);
|
||||||
|
});
|
||||||
@@ -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:")));
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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 });
|
||||||
|
});
|
||||||
@@ -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, ``);
|
||||||
|
const body = `Before\n${markdown}\nAfter`;
|
||||||
|
assert.deepEqual(imageReferences(body), [
|
||||||
|
{ id, name: "shot one test.png", markdown, index: 7 },
|
||||||
|
]);
|
||||||
|
assert.deepEqual(
|
||||||
|
imageReferences(
|
||||||
|
" ",
|
||||||
|
),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
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<string, string>();
|
||||||
|
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<string, 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) { 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<string, string>();
|
||||||
|
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/);
|
||||||
|
});
|
||||||
@@ -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<string, string>();
|
||||||
|
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<void>((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
});
|
||||||
|
const started = new Promise<void>((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);
|
||||||
|
});
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
@@ -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<string, string>([
|
||||||
|
["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, "");
|
||||||
|
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);
|
||||||
|
});
|
||||||
@@ -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<string, string> = {}) {
|
||||||
|
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"); });
|
||||||
|
});
|
||||||
@@ -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<string, string>();
|
||||||
|
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);
|
||||||
|
});
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
@@ -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],
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -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/);
|
||||||
|
});
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
@@ -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<string, BackgroundFrame>();
|
||||||
|
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<BackgroundFrame>(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<BackgroundFrame>( (_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();
|
||||||
|
});
|
||||||
@@ -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 { SELECTION_ALPHA, TERMINAL_TOKENS, terminalColors } from "../../../src/lib/features/terminal/theme.ts";
|
||||||
import { ANSI_COLORS } from "../../../src/lib/theme/roles.ts";
|
import { ANSI_COLORS } from "../../../src/lib/theme/roles.ts";
|
||||||
import { SETTINGS_SECTIONS, LEGACY_KEYS } from "../../../src/lib/settings/store.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", () => {
|
test("Terminal keeps the ID of the Terminal plugin and follows its package", () => {
|
||||||
const terminal = featureEntry("terminal");
|
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 terminal = terminalHost(true, JSON.stringify({ fontSize: 20 }));
|
||||||
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
|
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"); } };
|
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 }]);
|
assert.deepEqual(terminal.written, [{ ...DEFAULT_TERMINAL, fontSize: 20 }]);
|
||||||
} finally { console.error = error; }
|
} finally { console.error = error; }
|
||||||
});
|
});
|
||||||
|
|
||||||
test("the terminal switch follows the enabled state of an installed Terminal plugin", async () => {
|
test("the terminal switch follows the enabled state of an installed Terminal plugin", async () => {
|
||||||
const writes: unknown[] = [];
|
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 })) };
|
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 () => {} };
|
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
|
||||||
assert.deepEqual(await migrateFeatures(host, background, terminalHost(false, null)), ["terminal"]);
|
assert.deepEqual(await migrateFeatures(host, background, terminalHost(false, null), presentProjectManagement()), ["terminal"]);
|
||||||
assert.deepEqual(writes, [{ git: true, background: true, pdf: true, terminal: false }]);
|
assert.deepEqual(writes, [{ git: true, background: true, pdf: true, pm: true, terminal: false }]);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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
|
assert.throws(() => requireFeature(api, "files"), (error: unknown) => error instanceof MissingFeatureError
|
||||||
&& error.name === "MissingFeatureError" && error.features.length === 1 && error.features[0] === "files"
|
&& 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.");
|
&& 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"]), {
|
assert.throws(() => requireFeatures(api, ["files", "workspace.readBytes", "openFile"]), {
|
||||||
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.",
|
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, "pty" as never), TypeError);
|
||||||
|
assert.throws(() => hasFeature(api, "backgrounds" as never), TypeError);
|
||||||
assert.doesNotThrow(() => requireFeatures(api, ["services", "workspace.readBytes"]));
|
assert.doesNotThrow(() => requireFeatures(api, ["services", "workspace.readBytes"]));
|
||||||
assert.throws(() => hasFeature(api, "workspace.read" as never), TypeError);
|
assert.throws(() => hasFeature(api, "workspace.read" as never), TypeError);
|
||||||
assert.equal(describeFeature("ui.showActionMenu"), "the shared action menu (api.ui.showActionMenu)");
|
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 () => {
|
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 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({
|
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: () => () => {} },
|
workspace: { ...base.workspace, listMarkdown: async () => [], readMany: async () => [], readBytes: async () => new Uint8Array(), readOptional: async () => null, create: async () => {}, subscribe: () => () => {} },
|
||||||
settings: { ...base.settings, subscribe: () => () => {} },
|
settings: { ...base.settings, subscribe: () => () => {} },
|
||||||
}, true);
|
}, 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 () => {
|
test("the host without optional services lacks only the features that depend on them", async () => {
|
||||||
const { api, session } = await hostApi({});
|
const { api, session } = await hostApi({});
|
||||||
assert.deepEqual(missingFeatures(api, pluginFeatures).sort(), [
|
assert.deepEqual(missingFeatures(api, pluginFeatures).sort(), [
|
||||||
"backgrounds", "closeView", "completion.transport", "files",
|
"closeView", "completion.transport", "files",
|
||||||
"openFile", "renameDocument", "replaceDocumentWithView", "replaceView", "settings.subscribe",
|
"openFile", "renameDocument", "replaceDocumentWithView", "replaceView", "settings.subscribe",
|
||||||
"workspace.create", "workspace.listMarkdown", "workspace.readBytes", "workspace.readMany", "workspace.readOptional", "workspace.subscribe",
|
"workspace.create", "workspace.listMarkdown", "workspace.readBytes", "workspace.readMany", "workspace.readOptional", "workspace.subscribe",
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -67,5 +67,6 @@ test('Migration keeps renamed theme IDs and a background image data URL', () =>
|
|||||||
test('Every section has one old key', () => {
|
test('Every section has one old key', () => {
|
||||||
// `runestone.features` and `runestone.background` came after the settings file. Only the browser preview uses them.
|
// `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.
|
// `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']);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ import { readFileSync } from 'node:fs';
|
|||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { BackgroundHub, backgroundHub } from '../../../src/lib/plugins/backgrounds.ts';
|
import { BackgroundHub, backgroundHub } from '../../../src/lib/plugins/backgrounds.ts';
|
||||||
import { ExternalSession } from '../../../src/lib/plugins/externalSession.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' };
|
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);
|
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;
|
let api!: PluginApi;
|
||||||
const session = new ExternalSession('org.test.backgrounds', {
|
const session = new ExternalSession('org.test.backgrounds', {
|
||||||
workspace: { list: async () => [], read: async () => '', write: async () => {} },
|
workspace: { list: async () => [], read: async () => '', write: async () => {} },
|
||||||
settings: { read: async () => null, write: async () => {} },
|
settings: { read: async () => null, write: async () => {} },
|
||||||
assets: { read: async () => new Uint8Array() },
|
assets: { read: async () => new Uint8Array() },
|
||||||
backgrounds: true,
|
|
||||||
}, () => {}, () => {});
|
}, () => {}, () => {});
|
||||||
let notifications = 0;
|
await session.start({ activate(value) { api = value; } });
|
||||||
await session.start({ activate(value) {
|
// Project Management was the last plugin user of `api.backgrounds`. It reads `backgroundHub` as a native feature.
|
||||||
api = value;
|
assert.equal('backgrounds' in api, false);
|
||||||
api.backgrounds!.subscribe(() => { notifications++; });
|
const owner = Symbol();
|
||||||
api.backgrounds!.set('app', frame);
|
backgroundHub.set(owner, 'pm-all', 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.stop();
|
await session.stop();
|
||||||
assert.equal(notifications, 2);
|
assert.deepEqual(backgroundHub.get('pm-all'), frame);
|
||||||
assert.throws(() => api.backgrounds!.set('app', frame), /disabled/);
|
backgroundHub.removeOwner(owner);
|
||||||
assert.throws(() => api.backgrounds!.subscribe(() => {}), /disabled/);
|
|
||||||
assert.equal(backgroundHub.get('app'), null);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
test('the Background commands are allowed in the windows that use them, and the old plugin commands are gone', () => {
|
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 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'];
|
const all = ['background_choose_folder', 'background_folder', 'background_clear_folder', 'background_list', 'background_read', 'background_read_sidecar', 'background_write_sidecar', 'background_migrate'];
|
||||||
|
|||||||
Reference in New Issue
Block a user