- Every interface string of Project Management goes through the catalog: 539 new rows with fr, ja, and zh-CN. - Storage and model messages use a local message() marker and stay free of host imports. The interface translates them. - A board renders again when the language changes. Dates use the interface language. - Fix: the ribbon button waits for the feature switches at startup, and the settings code loads no feature module. - Add six smoke tests: board state, cards, menus, drag and drop, views, and language. - Add docs/guides/project-management.md and UI-060. Update the user, plugin, SDK, host, development, and interface docs and CLAUDE.md. - Name the fake board view of tree/renameUndo "Board fixture", because the native Project Management button is now in the ribbon.
881 lines
40 KiB
TypeScript
881 lines
40 KiB
TypeScript
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;
|
|
}
|
|
}
|