RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+77
View File
@@ -0,0 +1,77 @@
import { defaultBoard, type BoardDocument, type BoardList } from "../storage/board.ts";
import type { Task } from "./model.ts";
import { message } from "../storage/message.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(" · ") : message("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);
});
}
+13
View File
@@ -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) };
}
+31
View File
@@ -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);
}
+255
View File
@@ -0,0 +1,255 @@
import { message } from "../storage/message.ts";
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: message("Highest"),
high: message("High"),
medium: message("Medium"),
low: message("Low"),
lowest: message("Lowest"),
};
export const statusNames: Record<Status, string> = {
todo: message("To do"),
doing: message("In progress"),
done: message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("Use a different name for each custom field."));
}
if (
fields.listId !== undefined &&
fields.listId !== null &&
(typeof fields.listId !== "string" || !fields.listId)
)
throw new Error(message("The task has an invalid list ID."));
if (!statuses.includes(fields.status))
throw new Error(message("Choose a supported task status."));
if (
!Array.isArray(fields.tags) ||
fields.tags.some((tag) => typeof tag !== "string")
)
throw new Error(message("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(message("Labels must contain unique saved label IDs."));
if (fields.due && !validDate(fields.due.date))
throw new Error(message("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(message("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(message("Each session needs a unique ID and a valid time range."));
new Intl.DateTimeFormat("en", { timeZone: session.timeZone }).format();
ids.add(session.id);
}
}
+880
View File
@@ -0,0 +1,880 @@
import { readTask, editTask, adoptNote, split } from "../storage/notes.ts";
import { createCard, readCards, cardOrigin, cardPath, fileIssue, 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 { format, message } from "../storage/message.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 errorMessage = (error: unknown) => error instanceof Error ? error.message : String(error);
/** The issue of a task ID that more than one note uses. `adopt()` looks for this issue. */
const duplicateTaskIssue = (id: string) =>
format(message("Duplicate task ID {id}: resolve the copied notes before editing them."), { id });
/** 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(message("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 = errorMessage(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 ?? message("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, errorMessage(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: errorMessage(error) };
}
}
private async readHiddenLabels(state: HiddenState) {
try { state.labels = { snapshot: await this.labels.read(), error: "" }; }
catch (error) { state.labels = { error: errorMessage(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: errorMessage(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]) => fileIssue(path, issue))];
if (state.cardsError) issues.push(format(message("Hidden cards: {error}"), { error: state.cardsError }));
if (state.catalog.error) issues.push(format(message("Hidden Project Management storage: {error}"), { error: state.catalog.error }));
if (state.labels.error) issues.push(format(message("Saved labels: {error}"), { error: state.labels.error }));
if (state.deleted.error) issues.push(format(message("Deleted cards: {error}"), { error: 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(message("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 ?? message("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: fileIssue(path, errorMessage(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(format(
message("The original card differs from hidden storage: {path}. Preserve both versions."),
{ path: original.path },
));
}
}
tasks.push(...hidden.tasks);
} catch (error) {
issues.push(format(message("Hidden cards: {error}"), { error: errorMessage(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(format(
message("The legacy board differs from hidden storage: {path}. Preserve both versions before cleanup."),
{ path: board.path },
));
}
}
boards.push(...managedDocuments(catalog.value, catalog.source ?? ""));
} catch (error) {
issues.push(format(message("Hidden Project Management storage: {error}"), { error: errorMessage(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 = errorMessage(error);
issues.push(format(message("Saved labels: {error}"), { error: 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(duplicateTaskIssue(id));
let deletedIds = new Set<string>();
try { deletedIds = new Set((await readDeletedCards(this.workspace)).ids); }
catch (error) {
issues.push(format(message("Deleted cards: {error}"), { error: errorMessage(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(format(message("Duplicate board ID {id}: resolve the copied boards before editing them."), { id }));
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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("The list is unavailable. Refresh the board."));
if (this.issues.length)
throw new Error(format(message("Resolve workspace issues before archiving cards: {issues}"), { issues: 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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("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(message("The destination board or list is unavailable. Refresh the board."));
if (this.board.reference && (!this.board.available || this.board.archived)) throw new Error(message("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(message("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(message("The card changed. Cancel, refresh, and review it before moving."));
if (!Object.hasOwn(current.placements ?? {}, sourceId))
throw new Error(message("This card no longer belongs to the source board."));
if (sourceId === destinationId)
throw new Error(message("Choose a different destination board."));
const destination = this.boards.find((board) => board.id === destinationId);
if (!destination || destination.archived)
throw new Error(message("The destination board is unavailable or archived. Choose another board."));
if (listId !== null && !destination.value.lists.some((list) => list.id === listId))
throw new Error(message("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(message("Saved labels changed. Refresh before deleting labels."));
if (this.issues.length)
throw new Error(format(message("Resolve workspace issues before deleting labels: {issues}"), { issues: 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(format(message("Resolve the workspace issues before migration: {issues}"), { issues: this.issues.join(" ") }));
const selected = cardIds.map((id) => {
const task = this.tasks.find((task) => task.id === id);
if (!task)
throw new Error(message("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(message("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(message("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(message("Choose a Markdown note from this workspace."));
await this.reload();
const id = this.board.reference?.id;
if (id && !this.board.available)
throw new Error(message("The board is unavailable. Reopen it before adding a note."));
if (this.board.archived)
throw new Error(message("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.includes(duplicateTaskIssue(task.id))
)
throw new Error(message("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(message("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(message("Choose a Markdown note from this workspace."));
const id = this.board.reference?.id;
if (id && !this.board.available)
throw new Error(message("The board is unavailable. Reopen it before adding a note."));
if (this.board.archived)
throw new Error(message("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(message("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(message("The linked card is unavailable. Refresh the board."));
} else {
const { doc, body, match, newline } = split(source);
if (doc.has("runestone_pm"))
throw new Error(message("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; }
}