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:
@@ -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 { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { onSettingsChange } from "$lib/settings/store";
|
||||
import { serviceHub } from "$lib/plugins/services";
|
||||
import { featureSwitches } from "$lib/features/state";
|
||||
import { readBoardCatalog } from "../pmBoards";
|
||||
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, saveAppearance, type Appearance } from "$lib/theme/appearance";
|
||||
import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages";
|
||||
import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings";
|
||||
@@ -17,8 +18,7 @@
|
||||
import { imageNames } from "./imageSettings";
|
||||
import ImageEditor from "./ImageEditor.svelte";
|
||||
|
||||
/** The Project Management service that lists the boards of the workspace as `{ id, name }[]`. Stage 7-5 makes it native. */
|
||||
const BOARD_SERVICE = ["runestone.pm", "boards"] as const;
|
||||
/** The background targets of single boards need a UUID board ID. */
|
||||
const boardId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
let settings = $state<BackgroundSettings>(readBackground());
|
||||
@@ -148,20 +148,17 @@
|
||||
save({ ...settings, targets: on ? [...new Set([...settings.targets, id])] : settings.targets.filter(target => target !== id) });
|
||||
}
|
||||
|
||||
async function discoverBoards() {
|
||||
/** The active boards of `.runestone/pm/workspace.json`. It needs no Project Management code. */
|
||||
async function discoverBoards(on: boolean) {
|
||||
const revision = ++boardRevision;
|
||||
const service = serviceHub.get(...BOARD_SERVICE, () => !disposed);
|
||||
if (!service || typeof service.list !== "function") {
|
||||
if (!on) {
|
||||
boards = []; boardsNote = tr("Turn on Project Management to show the background on one board.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const rows = await service.list();
|
||||
const catalog = await readBoardCatalog();
|
||||
if (disposed || revision !== boardRevision) return;
|
||||
boards = (Array.isArray(rows) ? rows : []).flatMap((row: unknown) => {
|
||||
if (!row || typeof row !== "object" || !("id" in row) || typeof row.id !== "string" || !boardId.test(row.id)) return [];
|
||||
return [{ id: row.id, name: "name" in row && typeof row.name === "string" && row.name ? row.name : row.id }];
|
||||
}).filter((board, index, rows) => rows.findIndex(other => other.id === board.id) === index);
|
||||
boards = catalog.boards.filter(board => !board.archived && boardId.test(board.id)).map(board => ({ id: board.id, name: board.name }));
|
||||
boardsNote = boards.length ? "" : tr("The workspace has no boards.");
|
||||
} catch (reason) {
|
||||
if (!disposed && revision === boardRevision) boardsNote = tr("Could not read the workspace boards: {error}", { error: reason instanceof Error ? reason.message : String(reason) });
|
||||
@@ -190,9 +187,8 @@
|
||||
|
||||
onMount(() => {
|
||||
const read = () => { settings = readBackground(); appearance = readAppearance(); };
|
||||
const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), serviceHub.subscribe((plugin, name) => { if (plugin === BOARD_SERVICE[0] && name === BOARD_SERVICE[1]) void discoverBoards(); })];
|
||||
const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), featureSwitches.subscribe(switches => { void discoverBoards(switches.pm); })];
|
||||
void folderHost.current().then(value => { if (!disposed) { folder = value; void inspectFolder(); } }, () => { folder = null; });
|
||||
void discoverBoards();
|
||||
return () => stops.forEach(stop => stop());
|
||||
});
|
||||
onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); });
|
||||
|
||||
@@ -5,7 +5,7 @@ import { message, tr } from "../i18n/index.ts";
|
||||
import type { PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
|
||||
import { identifyPdf } from "./pdfDocument.ts";
|
||||
|
||||
export type FeatureId = "git" | "background" | "terminal" | "pdf";
|
||||
export type FeatureId = "git" | "background" | "terminal" | "pdf" | "pm";
|
||||
|
||||
/** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */
|
||||
export interface FeatureViewInfo {
|
||||
@@ -16,6 +16,21 @@ export interface FeatureViewInfo {
|
||||
icon?: PluginView["icon"];
|
||||
/** Show a navigation button for the view. */
|
||||
navigation?: boolean;
|
||||
/** True when a launch, such as a ribbon button, asks the feature which view to open (`FeatureInstance.launch`). */
|
||||
launch?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A family of editor views whose IDs follow a pattern, for example one tab for each board. The session answers for each
|
||||
* matching ID before the feature module loads, so a tab transfer from another window can restore it.
|
||||
* The feature gives the real title later (`FeatureContext.setViewTitle`).
|
||||
*/
|
||||
export interface FeatureViewPattern {
|
||||
/** Matches the whole view ID. */
|
||||
match: RegExp;
|
||||
/** The title until the feature gives one. */
|
||||
title: () => string;
|
||||
icon?: PluginView["icon"];
|
||||
}
|
||||
|
||||
/** A command of a feature. The command palette lists it. */
|
||||
@@ -58,6 +73,8 @@ export interface FeatureEntry {
|
||||
/** True when the first start gives the switch the state of the old package. False when every user gets `defaultOn`. */
|
||||
followsPackage: boolean;
|
||||
views: readonly FeatureViewInfo[];
|
||||
/** Editor views with IDs that follow a pattern. */
|
||||
viewPatterns?: readonly FeatureViewPattern[];
|
||||
commands: readonly FeatureCommandInfo[];
|
||||
documentTypes: readonly FeatureDocumentInfo[];
|
||||
}
|
||||
@@ -114,6 +131,20 @@ export const FEATURES: readonly FeatureEntry[] = [
|
||||
{ id: "pdf", title: () => tr("PDF document"), icon: "file", extensions: ["pdf"], content: "binary", identify: identifyPdf },
|
||||
],
|
||||
},
|
||||
{
|
||||
// Project Management replaces the Project Management plugin. It reads only `.runestone/pm/` in the workspace, so the
|
||||
// file tree reads no Markdown file for it. Its ribbon button opens `planning`: the default board of the workspace, or
|
||||
// All tasks. Each board has its own tab, `board-<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 {
|
||||
|
||||
@@ -9,6 +9,7 @@ const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
|
||||
background: () => import("./background/index.ts"),
|
||||
terminal: () => import("./terminal/index.ts"),
|
||||
pdf: () => import("./pdf/index.ts"),
|
||||
pm: () => import("./pm/index.ts"),
|
||||
};
|
||||
|
||||
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`).
|
||||
// `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing.
|
||||
// The first start also makes the `background` section from the old Background Slideshow settings (`backgroundSettings.ts`),
|
||||
// and the `terminal` section from the localStorage key of the Terminal plugin (`terminalSettings.ts`).
|
||||
// the `terminal` section from the localStorage key of the Terminal plugin (`terminalSettings.ts`), and the
|
||||
// `projectManagement` section and the tab view states from the kept Project Management settings (`pmSettings.ts`).
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { readSection, writeSection } from "../settings/store.ts";
|
||||
import { readAppearance } from "../theme/appearance.ts";
|
||||
@@ -10,6 +11,7 @@ import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "./cat
|
||||
import { storedSwitches } from "./state.ts";
|
||||
import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts";
|
||||
import { LEGACY_TERMINAL_KEY, migrateTerminal, writeTerminal, type TerminalMigrationHost } from "./terminalSettings.ts";
|
||||
import { migrateProjectManagement, writeProjectManagement, type ProjectManagementMigrationHost } from "./pmSettings.ts";
|
||||
|
||||
/** What the host reports about one old plugin package. */
|
||||
export interface LegacyPlugin {
|
||||
@@ -44,6 +46,12 @@ const desktopBackground: BackgroundMigrationHost = {
|
||||
write: writeBackground,
|
||||
};
|
||||
|
||||
const desktopProjectManagement: ProjectManagementMigrationHost = {
|
||||
missing: () => readSection("projectManagement") === undefined,
|
||||
write: writeProjectManagement,
|
||||
get storage() { return localStorage; },
|
||||
};
|
||||
|
||||
const desktopTerminal: TerminalMigrationHost = {
|
||||
missing: () => readSection("terminal") === undefined,
|
||||
legacy: () => localStorage.getItem(LEGACY_TERMINAL_KEY),
|
||||
@@ -51,12 +59,13 @@ const desktopTerminal: TerminalMigrationHost = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Give each feature without a stored switch the state of its old package, and make a missing `background` or `terminal` section.
|
||||
* Give each feature without a stored switch the state of its old package, and make a missing `background`, `terminal`,
|
||||
* or `projectManagement` section.
|
||||
* It runs before the first render. When the host cannot report the packages, nothing is written, so the next start tries again.
|
||||
* The `terminal` section needs no package report, so it migrates also then.
|
||||
*/
|
||||
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground,
|
||||
terminal: TerminalMigrationHost = desktopTerminal): Promise<FeatureId[]> {
|
||||
terminal: TerminalMigrationHost = desktopTerminal, projectManagement: ProjectManagementMigrationHost = desktopProjectManagement): Promise<FeatureId[]> {
|
||||
try { await migrateTerminal(terminal); }
|
||||
catch (reason) { console.error("RuneStone could not copy the old terminal settings.", reason); }
|
||||
const current = host.read();
|
||||
@@ -64,7 +73,9 @@ export async function migrateFeatures(host: MigrationHost = desktopHost, backgro
|
||||
const missing = FEATURES.filter(entry => stored[entry.id] === undefined);
|
||||
const backgroundOwner = featureEntry("background").owner;
|
||||
const backgroundMissing = background.missing();
|
||||
const owners = [...new Set([...missing.map(entry => entry.owner), ...backgroundMissing ? [backgroundOwner] : []])];
|
||||
const pmOwner = featureEntry("pm").owner;
|
||||
const pmMissing = projectManagement.missing();
|
||||
const owners = [...new Set([...missing.map(entry => entry.owner), ...backgroundMissing ? [backgroundOwner] : [], ...pmMissing ? [pmOwner] : []])];
|
||||
if (!owners.length) return [];
|
||||
let legacy: LegacyPlugin[];
|
||||
try { legacy = await host.legacy(owners); }
|
||||
@@ -78,6 +89,7 @@ export async function migrateFeatures(host: MigrationHost = desktopHost, backgro
|
||||
await host.write(next);
|
||||
}
|
||||
if (backgroundMissing) await migrateBackground(legacy.find(item => item.id === backgroundOwner), background);
|
||||
if (pmMissing) await migrateProjectManagement(legacy.find(item => item.id === pmOwner), projectManagement);
|
||||
return missing.map(entry => entry.id);
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
// navigation buttons, the command palette, and the file tree show them without the feature code. The first mount,
|
||||
// restore, or action command loads the feature module and starts one instance for this window.
|
||||
// A view pattern of the catalog makes a view for each matching ID on request (`patternView`), also before the module loads.
|
||||
// A launch rule (`launch.ts`) can also start the instance at once.
|
||||
import { tr } from "../i18n/index.ts";
|
||||
import type { Dispose, PluginCommand, PluginDocumentContext, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
|
||||
@@ -18,6 +19,8 @@ export class FeatureSession {
|
||||
private load: () => Promise<FeatureModule>;
|
||||
private instance?: Promise<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)) {
|
||||
this.entry = entry;
|
||||
@@ -30,6 +33,10 @@ export class FeatureSession {
|
||||
mount: element => this.mountView(info.id, element),
|
||||
saveTabState: () => this.ready?.saveTabState?.(info.id),
|
||||
restoreTabState: async state => { await (await this.running()).restoreTabState?.(info.id, state); },
|
||||
...info.launch ? { launch: async () => {
|
||||
const instance = await this.running();
|
||||
if (instance.launch) await instance.launch(info.id); else context.openView(info.id);
|
||||
} } : {},
|
||||
});
|
||||
}
|
||||
for (const info of entry.documentTypes) {
|
||||
@@ -46,6 +53,34 @@ export class FeatureSession {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The view with this ID: a catalog view, or a new editor view when a view pattern of the catalog matches the ID.
|
||||
* A new view keeps the title of the pattern until the feature gives one.
|
||||
*/
|
||||
patternView(id: string): PluginView | undefined {
|
||||
const existing = this.views.get(id);
|
||||
if (existing || this.controller.signal.aborted) return existing;
|
||||
const pattern = this.entry.viewPatterns?.find(item => item.match.test(id));
|
||||
if (!pattern) return undefined;
|
||||
const view: PluginView = {
|
||||
id, title: pattern.title(), placement: "editor", icon: pattern.icon, navigation: false, launcher: false,
|
||||
mount: element => this.mountView(id, element),
|
||||
saveTabState: () => this.ready?.saveTabState?.(id),
|
||||
restoreTabState: async state => { await (await this.running()).restoreTabState?.(id, state); },
|
||||
};
|
||||
this.views.set(id, view);
|
||||
this.patterned.add(id);
|
||||
return view;
|
||||
}
|
||||
|
||||
/** Give a view of a view pattern its title. Returns true when the title changed. */
|
||||
setViewTitle(id: string, title: string): boolean {
|
||||
const view = this.patterned.has(id) ? this.views.get(id) : this.patternView(id);
|
||||
if (!view || !this.patterned.has(id) || !title.trim() || view.title === title) return false;
|
||||
view.title = title;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The instance of this window. A failed load leaves no instance, so a later call tries again. */
|
||||
private running(): Promise<FeatureInstance> {
|
||||
if (this.controller.signal.aborted) return Promise.reject(new Error(tr("This feature is off.")));
|
||||
@@ -68,7 +103,7 @@ export class FeatureSession {
|
||||
|
||||
/** Mount a view, or with `document`, a document of the document type `id`. */
|
||||
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<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."));
|
||||
const dispose = document ? await (view as PluginDocumentType).mount(element, document) : await (view as PluginView).mount(element, { surface: "view" });
|
||||
return async () => {
|
||||
@@ -77,7 +112,11 @@ export class FeatureSession {
|
||||
};
|
||||
}
|
||||
|
||||
async launch(id: string) { this.context.openView(id); }
|
||||
async launch(id: string) {
|
||||
const view = this.views.get(id);
|
||||
if (view?.launch) await view.launch();
|
||||
else this.context.openView(id);
|
||||
}
|
||||
|
||||
/** Load the module and start the instance now, without a view. Later calls use the same instance. */
|
||||
async start(): Promise<void> { await this.running(); }
|
||||
|
||||
@@ -6,8 +6,17 @@ export interface FeatureContext {
|
||||
openView(id: string): void;
|
||||
/** Open a workspace file in the editor. */
|
||||
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. */
|
||||
@@ -18,6 +27,8 @@ export interface FeatureInstance {
|
||||
* The returned function removes the document and stops its work, for example a worker.
|
||||
*/
|
||||
mountDocument?(type: string, element: HTMLElement, document: PluginDocumentContext): Dispose | Promise<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?(command: string): void | Promise<void>;
|
||||
/** 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}"],
|
||||
// The native features without the desktop host.
|
||||
["This feature needs the desktop app.", "Cette fonctionnalité nécessite l’application de bureau.", "この機能にはデスクトップアプリが必要です。", "此功能需要桌面应用。"],
|
||||
// Project Management (src/lib/features/catalog.ts, PluginRibbon.svelte, SettingsDialog.svelte). Part B of stage 7-5 translates the board interface.
|
||||
["Project Management", "Project Management", "Project Management", "Project Management"],
|
||||
["Plan work on Kanban boards, in All tasks, and on Gantt and calendar views. The cards stay in the workspace.", "Planifiez le travail sur des tableaux Kanban, dans Toutes les tâches, et dans les vues Gantt et calendrier. Les cartes restent dans l’espace de travail.", "Kanban ボード、すべてのタスク、ガントビューとカレンダービューで作業を計画します。カードはワークスペースに保存されます。", "在看板、所有任务以及甘特图和日历视图中规划工作。卡片保存在工作区中。"],
|
||||
];
|
||||
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
|
||||
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
<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
|
||||
// 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 IconButton from "$lib/ui/IconButton.svelte";
|
||||
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
|
||||
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";
|
||||
|
||||
let { items, actions, workspaceAnchor = $bindable(), onChooseWorkspace, onHelp, onSettings,
|
||||
@@ -30,6 +36,7 @@
|
||||
<div class="ribbon-tools">
|
||||
{#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 $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="commands" compact side="right" />
|
||||
</div>
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
import { featureErrors } from "$lib/features/loader";
|
||||
import { TERMINAL_SHORTCUTS } from "$lib/features/terminalKeys";
|
||||
import TerminalSettings from "$lib/features/TerminalSettings.svelte";
|
||||
import ProjectManagementSettings from "$lib/features/ProjectManagementSettings.svelte";
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { confirm } from "@tauri-apps/plugin-dialog";
|
||||
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`,
|
||||
})));
|
||||
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 selectedPlugin = $derived(pluginSections.find(item => item.id === selected?.id));
|
||||
|
||||
@@ -235,6 +237,8 @@
|
||||
<BrowserSlot kind="settings" />
|
||||
{:else if selected.id === "terminal"}
|
||||
<TerminalSettings />
|
||||
{:else if selected.id === "project-management"}
|
||||
<ProjectManagementSettings />
|
||||
{:else if selectedPlugin}
|
||||
{#key selectedPlugin.id}<PluginSettings owner={selectedPlugin.owner} id={selectedPlugin.view} />{/key}
|
||||
{:else}
|
||||
|
||||
@@ -128,11 +128,11 @@
|
||||
} else if (change.type === "deleted") {
|
||||
removePluginDocuments(change.path);
|
||||
void documents?.refresh();
|
||||
notifyPluginWorkspace();
|
||||
notifyPluginWorkspace([change.path]);
|
||||
} else if (change.type === "changed") {
|
||||
void documents?.refresh();
|
||||
notifyPluginWorkspace();
|
||||
} else if (change.type === "internal") notifyPluginWorkspace();
|
||||
notifyPluginWorkspace(change.paths);
|
||||
} else if (change.type === "internal") notifyPluginWorkspace(change.paths);
|
||||
}));
|
||||
|
||||
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
|
||||
* plugins set them. The `app` frame sets the custom properties of the body that the workarea background reads.
|
||||
* The background frames of one window, for each target. The Background feature (`src/lib/features/background/`) sets
|
||||
* 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 {
|
||||
private frames = new Map<string, Map<symbol, BackgroundFrame>>();
|
||||
|
||||
+33
-18
@@ -28,10 +28,10 @@ export const pluginSplits = writable<SplitLayout[]>([]);
|
||||
export function pinPluginEditor(key: string) {
|
||||
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) {
|
||||
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> {
|
||||
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 (!await openPluginDocument(transfer.document.path)) return false;
|
||||
} else {
|
||||
const view = session.views.get(transfer.id);
|
||||
const view = viewOf(transfer.owner, transfer.id);
|
||||
if (!view || view.placement !== "editor") return false;
|
||||
if (transfer.state !== undefined) {
|
||||
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;
|
||||
}
|
||||
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 });
|
||||
}
|
||||
export async function dropPluginTab(data: string) {
|
||||
@@ -72,7 +72,7 @@ export async function dropPluginTab(data: string) {
|
||||
await session.dropTab(payload.data);
|
||||
}
|
||||
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;
|
||||
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">;
|
||||
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 failures = new Map<string, string>();
|
||||
const errors: Record<string, string> = {};
|
||||
@@ -112,7 +117,7 @@ let settingsWindow = false;
|
||||
let generation = 0;
|
||||
let documentOpenVersion = 0;
|
||||
export function cancelPluginDocumentOpen() { documentOpenVersion++; }
|
||||
const workspaceListeners = new Set<() => void>();
|
||||
const workspaceListeners = new Set<(paths?: readonly string[]) => void>();
|
||||
let openFile: ((path: string) => Promise<void>) | undefined;
|
||||
export function handlePluginFileOpen(handler: (path: string) => Promise<void>): () => void {
|
||||
openFile = handler;
|
||||
@@ -128,7 +133,8 @@ export function guardPluginWrites(guard: (path: string) => void): () => void {
|
||||
canWrite = guard;
|
||||
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 closePluginEditor(key: string) {
|
||||
cancelPluginDocumentOpen();
|
||||
@@ -151,11 +157,11 @@ export function renamePluginDocuments(from: string, to: string) {
|
||||
pluginEditors.set(editors);
|
||||
const selected = editors.find(view => view.key === get(pluginView)?.key);
|
||||
if (selected) pluginView.set(selected);
|
||||
pluginDocuments.set({}); notifyPluginWorkspace();
|
||||
pluginDocuments.set({}); notifyPluginWorkspace([from, to]);
|
||||
}
|
||||
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);
|
||||
pluginDocuments.set({}); notifyPluginWorkspace();
|
||||
pluginDocuments.set({}); notifyPluginWorkspace([path]);
|
||||
}
|
||||
const documentTitle = (path: string) => path.split("/").at(-1)!.replace(/\.[^.]+$/, "");
|
||||
async function identifyDocument(path: string) {
|
||||
@@ -203,11 +209,11 @@ export async function createPluginDocument(owner: string, id: string, path: stri
|
||||
const contents = create.contents();
|
||||
if (typeof contents !== "string") throw new Error("Document contents must be text.");
|
||||
await invoke("workspace_create", { rel: path, kind: "file", contents });
|
||||
notifyPluginWorkspace();
|
||||
notifyPluginWorkspace([path]);
|
||||
}
|
||||
|
||||
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 }))));
|
||||
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())));
|
||||
@@ -231,7 +237,7 @@ async function stop(id: string) {
|
||||
if (packaged(loaded.hash)) await release(id, error); publish();
|
||||
}
|
||||
function show(owner: string, id: string, options?: PluginViewOpenOptions) {
|
||||
const view = sessions.get(owner)?.session.views.get(id);
|
||||
const view = viewOf(owner, id);
|
||||
if (view) {
|
||||
const placement = view.placement ?? "dialog";
|
||||
if (placement === "sidebar") {
|
||||
@@ -261,7 +267,7 @@ function show(owner: string, id: string, options?: PluginViewOpenOptions) {
|
||||
}
|
||||
}
|
||||
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.");
|
||||
for (const duplicate of get(pluginEditors)) {
|
||||
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, {
|
||||
completionTransport,
|
||||
files: filesTransport(id),
|
||||
backgrounds: true,
|
||||
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
|
||||
workspace: {
|
||||
list: path => workspaceList(path ?? ""), read: workspaceRead,
|
||||
listMarkdown: () => invoke<string[]>("workspace_list_markdown"),
|
||||
readMany: paths => invoke<{ path: string; source?: string; error?: string }[]>("workspace_read_many", { paths }),
|
||||
readBytes: workspaceReadBytes,
|
||||
write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); },
|
||||
subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
|
||||
write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace([path]); },
|
||||
subscribe: listener => { const call = () => listener(); workspaceListeners.add(call); return () => { workspaceListeners.delete(call); }; },
|
||||
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: {
|
||||
subscribe: listener => {
|
||||
@@ -378,10 +383,20 @@ export async function mountPluginView(owner: string, id: string, element: HTMLEl
|
||||
return session.mount(id, element, document, surface);
|
||||
}
|
||||
function featureContext(entry: FeatureEntry): FeatureContext {
|
||||
const owner = entry.owner;
|
||||
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); },
|
||||
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 { registerCompletionInput } from "../completion/input.ts";
|
||||
import { showActionMenu } from "../ui/managedActionMenu.ts";
|
||||
import { backgroundHub } from "./backgrounds.ts";
|
||||
import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.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. */
|
||||
export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & {
|
||||
/** True gives the plugin `api.backgrounds`: the background frames of each target. */
|
||||
openFile?: PluginApi["openFile"]; backgrounds?: boolean;
|
||||
openFile?: PluginApi["openFile"];
|
||||
completionTransport?: NonNullable<PluginApi["completion"]>["transport"];
|
||||
files?: FilesTransport; serviceHub?: ServiceHub;
|
||||
};
|
||||
@@ -33,8 +31,6 @@ export class ExternalSession {
|
||||
private mounted = new Set<Dispose>();
|
||||
private contributions: Dispose[] = [];
|
||||
private registry: ContributionRegistry;
|
||||
private backgroundOwner = Symbol('plugin backgrounds');
|
||||
private backgroundSubscriptions = new Set<() => void>();
|
||||
private serviceOwner = Symbol('plugin services');
|
||||
private serviceSubscriptions = new Set<() => void>();
|
||||
readonly id: string;
|
||||
@@ -66,19 +62,6 @@ export class ExternalSession {
|
||||
id: this.id, signal: this.controller.signal,
|
||||
...(this.services.files ? { files: this.filesApi(this.services.files) } : {}),
|
||||
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() }; } },
|
||||
completion: {
|
||||
version: 1,
|
||||
@@ -231,8 +214,6 @@ export class ExternalSession {
|
||||
stop(): Promise<void> {
|
||||
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();
|
||||
for (const off of this.backgroundSubscriptions) off();
|
||||
backgroundHub.removeOwner(this.backgroundOwner);
|
||||
for (const off of this.serviceSubscriptions) off();
|
||||
(this.services.serviceHub ?? defaultServiceHub).removeOwner(this.serviceOwner);
|
||||
for (const remove of this.contributions.splice(0)) remove();
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
import { invoke, isTauri } from '@tauri-apps/api/core';
|
||||
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 SettingsSections = Partial<Record<SettingsSection, unknown>>;
|
||||
|
||||
@@ -24,6 +24,7 @@ export const LEGACY_KEYS: Readonly<Record<SettingsSection, string>> = {
|
||||
features: 'runestone.features',
|
||||
background: 'runestone.background',
|
||||
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. */
|
||||
|
||||
Reference in New Issue
Block a user