Translate Project Management and add its tests and guide

- 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.
This commit is contained in:
Knotty Wyvern
2026-10-29 21:53:09 -07:00
parent e66f089176
commit 956ead818b
53 changed files with 2510 additions and 867 deletions
@@ -6,27 +6,30 @@
-->
<script lang="ts">
import { onDestroy, onMount } from "svelte";
import { t } from "$lib/i18n";
import { message, t } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
import { showActionMenu } from "$lib/ui/managedActionMenu";
import { PRIORITY_LEVELS, onProjectManagementChange, readProjectManagement, writeProjectManagement, type PriorityLevels, type ProjectManagementSettings } from "./pmSettings";
import { readBoardCatalog, writeDefaultBoard, type BoardSummary } from "./pmBoards";
let { compact = false }: { compact?: boolean } = $props();
// The errors here are catalog keys without values (pmBoards.ts) or host text. The full `errorText()` of the feature
// (pm/ui/text.ts) is not necessary, and this component must load no feature module.
const errorText = (reason: unknown) => $t(reason instanceof Error ? reason.message : String(reason));
const levelNames: Record<PriorityLevels, string> = { 2: "2 — High and Low", 3: "3 — High, Medium, and Low", 5: "5 — Highest through Lowest" };
const levelNames: Record<PriorityLevels, string> = { 2: message("2 — High and Low"), 3: message("3 — High, Medium, and Low"), 5: message("5 — Highest through Lowest") };
let settings = $state<ProjectManagementSettings>(readProjectManagement());
let boards = $state<BoardSummary[]>([]);
let defaultBoard = $state("");
let boardsReady = $state(false);
let boardNote = $state("");
let saving = $state(false);
let message = $state("");
let notice = $state("");
let error = $state("");
let closeMenu = () => {};
let disposed = false;
const active = $derived(boards.filter(board => !board.archived));
const boardName = $derived(defaultBoard ? active.find(board => board.id === defaultBoard)?.name ?? "Unavailable board (opens All tasks)" : "All tasks");
const boardName = $derived(defaultBoard ? active.find(board => board.id === defaultBoard)?.name ?? $t("Unavailable board (opens All tasks)") : $t("All tasks"));
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
closeMenu();
@@ -39,15 +42,15 @@
function saveLevels(priorityLevels: PriorityLevels) {
error = "";
settings = { ...settings, priorityLevels };
writeProjectManagement(settings).then(() => { message = $t("Changes saved."); })
.catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; settings = readProjectManagement(); });
writeProjectManagement(settings).then(() => { notice = $t("Changes saved."); })
.catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); notice = ""; settings = readProjectManagement(); });
}
async function saveDefault(id: string) {
const previous = defaultBoard;
error = ""; saving = true; defaultBoard = id;
try { await writeDefaultBoard(id || null); if (!disposed) message = $t("Changes saved."); }
catch (reason) { if (!disposed) { defaultBoard = previous; message = ""; error = reason instanceof Error ? reason.message : String(reason); } }
try { await writeDefaultBoard(id || null); if (!disposed) notice = $t("Changes saved."); }
catch (reason) { if (!disposed) { defaultBoard = previous; notice = ""; error = errorText(reason); } }
finally { saving = false; }
}
@@ -60,7 +63,7 @@
boardsReady = true;
boardNote = "";
} catch (reason) {
if (!disposed) boardNote = /no workspace/i.test(String(reason)) ? "Open a workspace to choose its default board." : reason instanceof Error ? reason.message : String(reason);
if (!disposed) boardNote = /no workspace/i.test(String(reason)) ? $t("Open a workspace to choose its default board.") : errorText(reason);
}
}
@@ -74,21 +77,21 @@
<div class="pm-settings">
{#if !compact}
<h2>{$t("Project Management")}</h2>
<p class="intro">The boards of each workspace stay in .runestone/pm in the workspace.</p>
<p class="intro">{$t("The boards of each workspace stay in {folder} in the workspace.", { folder: ".runestone/pm" })}</p>
{/if}
<div class="card">
<div class="setting-row">
<div><span class="name" id="pm-priority-label">Priority levels</span><p id="pm-priority-description">Existing card priorities stay unchanged when you change this setting.</p></div>
<button class="picker" type="button" aria-label="Priority levels" aria-describedby="pm-priority-description" aria-haspopup="menu"
onclick={event => picker(event, "Priority levels", PRIORITY_LEVELS.map(levels => ({ label: levelNames[levels], checked: settings.priorityLevels === levels, run: () => saveLevels(levels) })))}>
{levelNames[settings.priorityLevels]}<Icon icon="chevron-down" />
<div><span class="name" id="pm-priority-label">{$t("Priority levels")}</span><p id="pm-priority-description">{$t("Existing card priorities stay unchanged when you change this setting.")}</p></div>
<button class="picker" type="button" aria-label={$t("Priority levels")} aria-describedby="pm-priority-description" aria-haspopup="menu"
onclick={event => picker(event, $t("Priority levels"), PRIORITY_LEVELS.map(levels => ({ label: $t(levelNames[levels]), checked: settings.priorityLevels === levels, run: () => saveLevels(levels) })))}>
{$t(levelNames[settings.priorityLevels])}<Icon icon="chevron-down" />
</button>
</div>
<div class="setting-row">
<div><span class="name" id="pm-default-label">Default board</span><p id="pm-default-description">{boardNote || "Choose the board that opens in this workspace. Restored tabs keep their board."}</p></div>
<button class="picker" type="button" aria-label="Default board" aria-describedby="pm-default-description" aria-haspopup="menu" disabled={!boardsReady || saving}
onclick={event => picker(event, "Default board", [
{ label: "All tasks", checked: !defaultBoard, run: () => void saveDefault("") },
<div><span class="name" id="pm-default-label">{$t("Default board")}</span><p id="pm-default-description">{boardNote || $t("Choose the board that opens in this workspace. Restored tabs keep their board.")}</p></div>
<button class="picker" type="button" aria-label={$t("Default board")} aria-describedby="pm-default-description" aria-haspopup="menu" disabled={!boardsReady || saving}
onclick={event => picker(event, $t("Default board"), [
{ label: $t("All tasks"), checked: !defaultBoard, run: () => void saveDefault("") },
...active.map(board => ({ label: board.name, checked: defaultBoard === board.id, run: () => void saveDefault(board.id) })),
])}>
{boardName}<Icon icon="chevron-down" />
@@ -96,7 +99,7 @@
</div>
</div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<p class="saved" role="status">{message}</p>
<p class="saved" role="status">{notice}</p>
</div>
<style>
+5 -4
View File
@@ -8,6 +8,7 @@ import type { FeatureContext, FeatureInstance } from "../types.ts";
import { boardKey, isManagedBoard, readCatalog } from "./storage/catalog.ts";
import { findLegacy, hasLegacy, type LegacyContent } from "./storage/legacy.ts";
import { isHiddenCard } from "./storage/persistence.ts";
import { message } from "./storage/message.ts";
import type { BoardReference } from "./storage/board.ts";
import { TaskStore } from "./model/store.ts";
import { hostMenus } from "./ui/host.ts";
@@ -45,7 +46,7 @@ export function start(context: FeatureContext): FeatureInstance {
if (fresh) legacy.delete(key);
let pending = legacy.get(key);
if (!pending) {
pending = findLegacy(workspace, () => { if (disposed) throw new Error("Project Management is off."); });
pending = findLegacy(workspace, () => { if (disposed) throw new Error(message("Project Management is off.")); });
pending.catch(() => legacy.delete(key));
legacy.set(key, pending);
}
@@ -67,7 +68,7 @@ export function start(context: FeatureContext): FeatureInstance {
const openBoard = async (path: string, from?: string) => {
const snapshot = await readCatalog(workspace);
const board = isManagedBoard(path) ? snapshot.value.boards.find(item => boardKey(item.value.id) === path) : undefined;
if (!board) throw new Error("This board is unavailable. Refresh Project Management.");
if (!board) throw new Error(message("This board is unavailable. Refresh Project Management."));
const id = boardViewId(board.value.id);
context.setViewTitle(id, board.name);
if (from) context.replaceView(from, id); else context.openView(id);
@@ -75,7 +76,7 @@ export function start(context: FeatureContext): FeatureInstance {
function mountView(view: string, element: HTMLElement) {
const boardId = view === PLANNING ? null : boardOfView(view);
if (view !== PLANNING && !boardId) throw new Error("This view is unavailable.");
if (view !== PLANNING && !boardId) throw new Error(message("This view is unavailable."));
const reference: BoardReference | undefined = boardId ? { id: boardId, path: boardKey(boardId) } : undefined;
if (!states.has(view)) states.set(view, {});
const store = new TaskStore(workspace, reference, { legacy: false });
@@ -117,7 +118,7 @@ export function start(context: FeatureContext): FeatureInstance {
},
saveTabState: view => structuredClone(states.get(view) ?? {}),
restoreTabState(view, value) {
if (view !== PLANNING && !boardOfView(view)) throw new Error("This view is unavailable.");
if (view !== PLANNING && !boardOfView(view)) throw new Error(message("This view is unavailable."));
states.set(view, parseViewState(value));
persist(view);
},
+2 -1
View File
@@ -1,5 +1,6 @@
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;
@@ -64,7 +65,7 @@ export function allTaskGroups(boards: BoardDocument[], column: TaskColumn): Task
const key = JSON.stringify(boardIds);
let group = groups.get(key);
if (!group) {
group = { boardIds, name: owners.length ? owners.map(board => board.name).join(" · ") : "No active board", tasks: [] };
group = { boardIds, name: owners.length ? owners.map(board => board.name).join(" · ") : message("No active board"), tasks: [] };
groups.set(key, group);
}
group.tasks.push(task);
+35 -29
View File
@@ -1,3 +1,5 @@
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;
@@ -6,11 +8,17 @@ export function availablePriorities(levels: PriorityLevels): readonly Priority[]
return levels === 2 ? ["high", "low"] : levels === 3 ? ["high", "medium", "low"] : priorities;
}
export type Priority = (typeof priorities)[number];
export const priorityNames: Record<Priority, string> = { highest: "Highest", high: "High", medium: "Medium", low: "Low", lowest: "Lowest" };
export const 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: "To do",
doing: "In progress",
done: "Done",
todo: message("To do"),
doing: message("In progress"),
done: message("Done"),
};
export const cardColors = {
red: "#df7373",
@@ -91,7 +99,7 @@ export function validDate(value: unknown): value is string {
return !isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
}
export function addDays(value: string, days: number): string {
if (!validDate(value)) throw new Error("Enter a valid calendar date.");
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);
@@ -112,24 +120,24 @@ export function localTime(instant: string): string {
export function localInstant(value: string): string {
const date = new Date(value);
if (isNaN(date.getTime()) || localTime(date.toISOString()) !== value)
throw new Error("Enter an existing local date and time.");
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("The card creation timestamp is invalid.");
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("Each image attachment needs a unique image ID and a name of 1 to 255 characters.");
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("Choose a supported priority or No 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("Choose an image from this card.");
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("Each subtask needs a unique ID, a title, and a completion state.");
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("Choose each linked card once and select its relationship.");
throw new Error(message("Choose each linked card once and select its relationship."));
if (
fields.title !== undefined &&
(typeof fields.title !== "string" ||
@@ -137,19 +145,19 @@ export function validateFields(fields: TaskFields): void {
fields.title.length > 100 ||
/[\x00-\x1f]/.test(fields.title))
)
throw new Error("Enter a card title of 1 to 100 characters.");
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("The card order is invalid. Refresh the board.");
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("Board placements must be a mapping.");
throw new Error(message("Board placements must be a mapping."));
for (const [id, placement] of Object.entries(fields.placements)) {
if (
!id.trim() ||
@@ -160,9 +168,7 @@ export function validateFields(fields: TaskFields): void {
(typeof placement.listId !== "string" || !placement.listId)) ||
!validOrder(placement.order)
)
throw new Error(
"Each board placement needs a board ID and a valid list ID.",
);
throw new Error(message("Each board placement needs a board ID and a valid list ID."));
}
}
if (
@@ -170,13 +176,13 @@ export function validateFields(fields: TaskFields): void {
(typeof fields.color !== "string" ||
!Object.hasOwn(cardColors, fields.color))
)
throw new Error("Choose a supported card 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("Assignments must contain names.");
throw new Error(message("Assignments must contain names."));
if (fields.customFields !== undefined) {
if (
!Array.isArray(fields.customFields) ||
@@ -188,26 +194,26 @@ export function validateFields(fields: TaskFields): void {
typeof field.value !== "string",
)
)
throw new Error("Each custom field needs a name and a text value.");
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("Use a different name for each custom field.");
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("The task has an invalid list ID.");
throw new Error(message("The task has an invalid list ID."));
if (!statuses.includes(fields.status))
throw new Error("Choose a supported task 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("Tags must be text.");
throw new Error(message("Tags must be text."));
if (
fields.labels !== undefined &&
(!Array.isArray(fields.labels) ||
@@ -216,16 +222,16 @@ export function validateFields(fields: TaskFields): void {
) ||
new Set(fields.labels).size !== fields.labels.length)
)
throw new Error("Labels must contain unique saved label IDs.");
throw new Error(message("Labels must contain unique saved label IDs."));
if (fields.due && !validDate(fields.due.date))
throw new Error("Enter a valid deadline 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("The planned end must follow the start.");
throw new Error(message("The planned end must follow the start."));
}
const ids = new Set<string>();
for (const session of fields.sessions) {
@@ -242,7 +248,7 @@ export function validateFields(fields: TaskFields): void {
!Number.isFinite(Date.parse(session.end)) ||
Date.parse(session.end) <= Date.parse(session.start)
)
throw new Error("Each session needs a unique ID and a valid time range.");
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);
}
+82 -104
View File
@@ -1,5 +1,5 @@
import { readTask, editTask, adoptNote, split } from "../storage/notes.ts";
import { createCard, readCards, cardOrigin, cardPath, migrateCards, parseCard, prepareCards } from "../storage/cards.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";
@@ -14,6 +14,7 @@ import {
createBoard,
} from "../storage/catalog.ts";
import { migrateStorage } from "../storage/migration.ts";
import { format, message } from "../storage/message.ts";
import {
BoardStore,
boardDocument,
@@ -32,7 +33,10 @@ export interface TaskStoreOptions {
legacy?: boolean;
}
const message = (error: unknown) => error instanceof Error ? error.message : String(error);
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 {
@@ -78,7 +82,7 @@ export class TaskStore {
}
private check() {
if (this.disposed)
throw new Error("The Project Management view is closed. Reopen it before saving.");
throw new Error(message("The Project Management view is closed. Reopen it before saving."));
}
/** Read all Project Management data again. */
async reload(): Promise<void> {
@@ -99,7 +103,7 @@ export class TaskStore {
for (const path of paths) this.acceptCard(state, path, sources.get(path)!, previous.get(path));
}
} catch (error) {
state.cardsError = message(error);
state.cardsError = errorMessage(error);
}
await Promise.all([this.readHiddenCatalog(state), this.readHiddenLabels(state), this.readHiddenDeleted(state)]);
this.check();
@@ -148,12 +152,12 @@ export class TaskStore {
}
private acceptCard(state: HiddenState, path: string, result: { source?: string; error?: string }, cached?: Task) {
try {
if (result.error || result.source === undefined) throw new Error(result.error ?? "The card is unavailable.");
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, message(error));
state.cardIssues.set(path, errorMessage(error));
}
}
private async readHiddenCatalog(state: HiddenState) {
@@ -162,25 +166,25 @@ export class TaskStore {
state.catalog = { source: catalog.source, boards: managedDocuments(catalog.value, catalog.source ?? ""), error: "" };
} catch (error) {
// Do not expose boards as writable when hidden storage cannot be read.
state.catalog = { source: null, boards: [], error: message(error) };
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: message(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: message(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]) => `${path}: ${issue}`)];
if (state.cardsError) issues.push("Hidden cards: " + state.cardsError);
if (state.catalog.error) issues.push("Hidden Project Management storage: " + state.catalog.error);
if (state.labels.error) issues.push("Saved labels: " + state.labels.error);
if (state.deleted.error) issues.push("Deleted cards: " + state.deleted.error);
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()]
@@ -191,7 +195,7 @@ export class TaskStore {
if (this.board.reference) {
this.board.load(this.boards.find((board) => board.id === this.board.reference!.id));
if (!this.board.available)
issues.push("This board is missing, invalid, or duplicated. Task notes remain available in All tasks.");
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);
@@ -210,16 +214,14 @@ export class TaskStore {
this.check();
try {
const result = sources.get(path)!;
if (result.error || result.source === undefined) throw new Error(result.error ?? "The file is unavailable.");
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: `${path}: ${error instanceof Error ? error.message : String(error)}`,
};
return { issue: fileIssue(path, errorMessage(error)) };
}
});
for (const document of documents) {
@@ -241,17 +243,15 @@ export class TaskStore {
)
tasks.splice(tasks.indexOf(original), 1);
else
issues.push(
`The original card differs from hidden storage: ${original.path}. Preserve both versions.`,
);
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(
"Hidden cards: " +
(error instanceof Error ? error.message : String(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;
}
@@ -271,17 +271,15 @@ export class TaskStore {
)
boards.splice(boards.indexOf(board), 1);
else
issues.push(
`Legacy board differs from hidden storage: ${board.path}. Preserve both versions before cleanup.`,
);
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(
"Hidden Project Management storage: " +
(error instanceof Error ? error.message : String(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;
}
@@ -290,8 +288,8 @@ export class TaskStore {
try {
labels = await this.labels.read();
} catch (error) {
labelError = error instanceof Error ? error.message : String(error);
issues.push("Saved labels: " + labelError);
labelError = errorMessage(error);
issues.push(format(message("Saved labels: {error}"), { error: labelError }));
}
this.check();
if (revision !== this.revision) return;
@@ -301,14 +299,11 @@ export class TaskStore {
for (const task of tasks)
counts.set(task.id, (counts.get(task.id) ?? 0) + 1);
for (const [id, count] of counts)
if (count > 1)
issues.push(
`Duplicate task ID ${id}: resolve the copied notes before editing them.`,
);
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("Deleted cards: " + (error instanceof Error ? error.message : String(error)));
issues.push(format(message("Deleted cards: {error}"), { error: errorMessage(error) }));
tasks.length = 0;
}
this.check();
@@ -321,9 +316,7 @@ export class TaskStore {
boardCounts.set(board.id, (boardCounts.get(board.id) ?? 0) + 1);
for (const [id, count] of boardCounts)
if (count > 1)
issues.push(
`Duplicate board ID ${id}: resolve the copied boards before editing them.`,
);
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));
@@ -332,9 +325,7 @@ export class TaskStore {
this.boards.find((board) => board.id === this.board.reference!.id),
);
if (!this.board.available)
issues.push(
"This board is missing, invalid, or duplicated. Task notes remain available in All tasks.",
);
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);
@@ -360,7 +351,7 @@ export class TaskStore {
await this.reloadFor([task.path]);
const current = this.tasks.find(item => item.id === task.id && item.path === task.path);
if (!current || current.source !== task.source)
throw new Error("The card changed or is unavailable. Refresh before deleting it.");
throw new Error(message("The card changed or is unavailable. Refresh before deleting it."));
await recordCardDeletion(this.workspace, task.id);
await this.reloadFor([deletedCardsPath]);
});
@@ -373,7 +364,7 @@ export class TaskStore {
const found = this.tasks.find(task => task.id === source.id && task.path === source.path);
if (found && !found.links?.some(link => link.taskId === targetId)) return undefined;
if (!found || found.source !== source.source)
throw new Error("A linked card changed. Refresh before removing its link.");
throw new Error(message("A linked card changed. Refresh before removing its link."));
return found;
});
for (const source of current) {
@@ -395,17 +386,15 @@ export class TaskStore {
(item) => item.id === task.id && item.path === task.path,
);
if (!current || current.source !== task.source)
throw new Error(
"The task changed or has a duplicate ID. Cancel, refresh, and review the note before saving.",
);
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("Restore this board before moving cards.");
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("This list no longer exists. Refresh the board.");
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;
@@ -414,7 +403,7 @@ export class TaskStore {
const id = this.board.reference?.id;
if (id) {
if (!this.board.available)
throw new Error("The board is unavailable. Reopen it before saving.");
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) ||
@@ -491,9 +480,9 @@ export class TaskStore {
return this.run(async () => {
await this.reloadFor(this.cardsInList(listId).map(task => task.path));
if (!this.board.editable || !this.board.value.lists.some((list) => list.id === listId))
throw new Error("The list is unavailable. Refresh the board.");
throw new Error(message("The list is unavailable. Refresh the board."));
if (this.issues.length)
throw new Error("Resolve workspace issues before archiving cards: " + this.issues.join(" "));
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);
@@ -513,7 +502,7 @@ export class TaskStore {
beforeId == null
? cards.length
: cards.findIndex((card) => card.id === beforeId);
if (index < 0) throw new Error("The target card moved. Refresh the board.");
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,
@@ -524,30 +513,28 @@ export class TaskStore {
const path = title.trim().replaceAll("\\", "/").replace(/^\.\//, "");
if (!/\.(md|markdown|mdown)$/i.test(path)) return this.create(title, fields, "");
if (/^(?:[a-z]+:|\/)/i.test(path) || path.split("/").some(part => !part || part === "." || part === ".."))
throw new Error("Use a relative Markdown path inside this workspace.");
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("The linked card is unavailable. Refresh the board.");
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(
"This RuneStone version cannot create plugin notes. Add an existing note or install the host bridge.",
);
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("Choose an available, active board for this card.");
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("The board is unavailable. Reopen it before saving.");
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("Restore this board before adding cards.");
throw new Error(message("Restore this board before adding cards."));
const targetBoard = destination?.value ?? this.board.value;
const listId =
fields.listId === undefined
@@ -558,7 +545,7 @@ export class TaskStore {
listId !== null &&
!targetBoard.lists.some((list) => list.id === listId)
)
throw new Error("This list no longer exists. Refresh the board.");
throw new Error(message("This list no longer exists. Refresh the board."));
const lastGlobalCard = this.tasks
.filter(
(task) =>
@@ -602,10 +589,10 @@ export class TaskStore {
await this.reloadFor([cardPath(parentId)]);
const parent = this.tasks.find(task => task.id === parentId);
const item = parent?.subtasks?.find(item => item.id === subtaskId);
if (!parent || !item) throw new Error("The subtask is unavailable. Refresh the board.");
if (!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("The subtask card is unavailable. Refresh the board.");
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.
@@ -637,7 +624,7 @@ export class TaskStore {
removeFromBoard(task: Task): Promise<void> {
const id = this.board.reference?.id;
if (!id)
return Promise.reject(new Error("Open a board before removing a card."));
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 });
@@ -647,8 +634,8 @@ export class TaskStore {
await this.reloadFor([task.path]);
const destination = this.boards.find(board => board.id === destinationId);
if (!destination || destination.archived || (listId !== null && !destination.value.lists.some(list => list.id === listId)))
throw new Error("The destination board or list is unavailable. Refresh the board.");
if (this.board.reference && (!this.board.available || this.board.archived)) throw new Error("Open an available, active board before moving a card.");
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);
@@ -669,21 +656,21 @@ export class TaskStore {
await this.reloadFor([task.path]);
const sourceId = this.board.reference?.id;
if (!sourceId || !this.board.available || this.board.archived)
throw new Error("Open an available, active board before moving a card.");
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("The card changed. Cancel, refresh, and review it before moving.");
throw new Error(message("The card changed. Cancel, refresh, and review it before moving."));
if (!Object.hasOwn(current.placements ?? {}, sourceId))
throw new Error("This card no longer belongs to the source board.");
throw new Error(message("This card no longer belongs to the source board."));
if (sourceId === destinationId)
throw new Error("Choose a different destination board.");
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("The destination board is unavailable or archived. Choose another board.");
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("The destination list no longer exists. Choose another list.");
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) &&
@@ -724,9 +711,9 @@ export class TaskStore {
if (removed.size) {
await this.reloadFor([labelsPath]);
if (this.labels.source !== expected)
throw new Error("Saved labels changed. Refresh before deleting labels.");
throw new Error(message("Saved labels changed. Refresh before deleting labels."));
if (this.issues.length)
throw new Error("Resolve workspace issues before deleting labels: " + this.issues.join(" "));
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))) {
@@ -751,16 +738,11 @@ export class TaskStore {
return this.run(async () => {
await this.reload();
if (this.issues.length)
throw new Error(
"Resolve the workspace issues before migration: " +
this.issues.join(" "),
);
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(
"A selected card is unavailable. Refresh before migration.",
);
throw new Error(message("A selected card is unavailable. Refresh before migration."));
return task;
});
const result = await migrateStorage(
@@ -779,14 +761,14 @@ export class TaskStore {
return this.run(async () => {
await this.reloadFor([catalogPath]);
if (!this.board.editable)
throw new Error("Open an available board before renaming it.");
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("Migrate this board before renaming it.");
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();
@@ -801,15 +783,13 @@ export class TaskStore {
if (!this.legacy) return this.run(() => this.adoptHidden(path));
return this.run(async () => {
if (!/\.(md|markdown|mdown)$/i.test(path))
throw new Error("Choose a Markdown note from this workspace.");
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(
"The board is unavailable. Reopen it before adding a note.",
);
throw new Error(message("The board is unavailable. Reopen it before adding a note."));
if (this.board.archived)
throw new Error("Restore this board before adding cards.");
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)!;
@@ -817,11 +797,9 @@ export class TaskStore {
this.tasks.some(
(other) => other.id === task.id && other.path !== path,
) ||
this.issues.some((issue) =>
issue.startsWith(`Duplicate task ID ${task.id}:`),
)
this.issues.includes(duplicateTaskIssue(task.id))
)
throw new Error("Resolve this task's duplicate ID before adding it.");
throw new Error(message("Resolve this task's duplicate ID before adding it."));
if (id && !Object.hasOwn(task.placements ?? {}, id))
next = editTask(task, {
placements: {
@@ -839,23 +817,23 @@ export class TaskStore {
await saveDocument(this.workspace, path, next, source);
await this.reload();
const added = this.tasks.find(item => item.path === path);
if (!added) throw new Error("The linked card is unavailable. Refresh the board.");
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("Choose a Markdown note from this workspace.");
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("The board is unavailable. Reopen it before adding a note.");
throw new Error(message("The board is unavailable. Reopen it before adding a note."));
if (this.board.archived)
throw new Error("Restore this board before adding cards.");
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("The linked card is unavailable. Refresh the board.");
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);
@@ -868,11 +846,11 @@ export class TaskStore {
await this.reloadFor([cardPath(note.id)]);
card = this.tasks.find(task => task.id === note.id);
}
if (!card) throw new Error("The linked card is unavailable. Refresh the board.");
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("This document already contains Project Management data and cannot become a task.");
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", {
+32 -39
View File
@@ -8,6 +8,7 @@ import {
writeCatalog,
validateName,
} from "./catalog.ts";
import { message } from "./message.ts";
export interface BoardReference {
id: string;
@@ -41,9 +42,9 @@ export function defaultBoard(id: string = crypto.randomUUID()): Board {
kind: "board",
id,
lists: [
{ id: "todo", name: "To do", status: "todo", collapsed: false },
{ id: "doing", name: "In progress", status: "doing", collapsed: false },
{ id: "done", name: "Done", status: "done", collapsed: false },
{ id: "todo", name: message("To do"), status: "todo", collapsed: false },
{ id: "doing", name: message("In progress"), status: "doing", collapsed: false },
{ id: "done", name: message("Done"), status: "done", collapsed: false },
],
defaults: { todo: "todo", doing: "doing", done: "done" },
};
@@ -59,10 +60,8 @@ export function parseBoard(source: string): Board {
!Array.isArray(value.lists) ||
!value.defaults
)
throw new Error(
"The board file has an unsupported format. Restore or repair it before editing lists.",
);
if (value.backgroundImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(value.backgroundImage)) throw new Error("The board background image is invalid.");
throw new Error(message("The board file has an unsupported format. Restore or repair it before editing lists."));
if (value.backgroundImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(value.backgroundImage)) throw new Error(message("The board background image is invalid."));
const ids = new Set<string>();
for (const list of value.lists) {
if (
@@ -77,14 +76,12 @@ export function parseBoard(source: string): Board {
typeof list.collapsed !== "boolean" ||
(list.maxCards !== undefined && (!Number.isSafeInteger(list.maxCards) || list.maxCards < 1))
)
throw new Error(
"The board contains an invalid list. Repair the board file before editing.",
);
throw new Error(message("The board contains an invalid list. Repair the board file before editing."));
ids.add(list.id);
}
for (const status of statuses)
if (value.defaults[status] !== null && !ids.has(value.defaults[status]))
throw new Error("The board has an invalid default list.");
throw new Error(message("The board has an invalid default list."));
return value;
}
export function boardDocument(
@@ -110,7 +107,7 @@ export function newBoardSource(): string {
}
export class BoardStore {
value = defaultBoard("all-tasks");
name = "All tasks";
name: string = message("All tasks");
available = true;
archived = false;
private source: string | null = null;
@@ -134,7 +131,7 @@ export class BoardStore {
const snapshot = await readCatalog(this.workspace);
if (snapshot.value.deletedBoardIds?.includes(this.reference.id)) {
this.load();
throw new Error("This board was deleted. Open All tasks to find its cards.");
throw new Error(message("This board was deleted. Open All tasks to find its cards."));
}
const managed = snapshot.value.boards.find(
(board) => board.value.id === this.reference!.id,
@@ -145,9 +142,7 @@ export class BoardStore {
managed.original?.path !== this.reference.path ||
(current !== null && current !== managed.original.source)
)
throw new Error(
"The legacy board differs from hidden storage. Preserve both versions.",
);
throw new Error(message("The legacy board differs from hidden storage. Preserve both versions."));
this.load(
managedDocuments(snapshot.value, snapshot.source!).find(
(board) => board.id === this.reference!.id,
@@ -164,13 +159,13 @@ export class BoardStore {
),
);
if (!this.available)
throw new Error("This board is unavailable. Refresh Project Management.");
throw new Error(message("This board is unavailable. Refresh Project Management."));
return;
}
const source = await this.workspace.read(this.reference.path);
const document = boardDocument(source, this.reference.path);
if (!document || document.id !== this.reference.id)
throw new Error("The board changed. Reopen it from navigation.");
throw new Error(message("The board changed. Reopen it from navigation."));
this.load(document);
}
load(document?: BoardDocument) {
@@ -195,29 +190,27 @@ export class BoardStore {
}
async update(change: (board: Board) => void) {
if (!this.editable)
throw new Error("Open an available board to edit its lists.");
throw new Error(message("Open an available board to edit its lists."));
const expected = this.source;
if (!isManagedBoard(this.reference!.path) && this.workspace.readOptional) {
const snapshot = await readCatalog(this.workspace);
if (snapshot.value.deletedBoardIds?.includes(this.reference!.id))
throw new Error("This board was deleted. Open All tasks to find its cards.");
throw new Error(message("This board was deleted. Open All tasks to find its cards."));
if (
snapshot.value.boards.some(
(board) => board.value.id === this.reference!.id,
)
)
throw new Error(
"This board moved to hidden storage. Refresh before editing.",
);
throw new Error(message("This board moved to hidden storage. Refresh before editing."));
}
if (isManagedBoard(this.reference!.path)) {
const snapshot = await readCatalog(this.workspace);
if (snapshot.source !== expected)
throw new Error("The board changed. Refresh before editing its lists.");
throw new Error(message("The board changed. Refresh before editing its lists."));
const board = snapshot.value.boards.find(
(item) => item.value.id === this.reference!.id,
);
if (!board) throw new Error("The board is unavailable.");
if (!board) throw new Error(message("The board is unavailable."));
change(board.value);
this.source = await writeCatalog(
this.workspace,
@@ -229,7 +222,7 @@ export class BoardStore {
}
const current = await this.workspace.read(this.reference!.path);
if (current !== expected)
throw new Error("The board changed. Refresh before editing its lists.");
throw new Error(message("The board changed. Refresh before editing its lists."));
const next = structuredClone(this.value);
change(next);
const { doc, body, newline, match } = split(expected!);
@@ -243,21 +236,21 @@ export class BoardStore {
}
async deleteBoard() {
if (!this.reference || !this.available || this.source === null)
throw new Error("Open an available board before deleting it.");
throw new Error(message("Open an available board before deleting it."));
const { id, path } = this.reference;
const snapshot = await readCatalog(this.workspace);
if (snapshot.value.deletedBoardIds?.includes(id))
throw new Error("This board was already deleted. Refresh Project Management.");
throw new Error(message("This board was already deleted. Refresh Project Management."));
if (isManagedBoard(path)) {
if (snapshot.source !== this.source)
throw new Error("The board changed. Cancel, refresh, and review it before deleting.");
throw new Error(message("The board changed. Cancel, refresh, and review it before deleting."));
if (!snapshot.value.boards.some((board) => board.value.id === id))
throw new Error("The board is unavailable. Refresh Project Management.");
throw new Error(message("The board is unavailable. Refresh Project Management."));
} else {
if (snapshot.value.boards.some((board) => board.value.id === id))
throw new Error("This board moved to hidden storage. Refresh before deleting.");
throw new Error(message("This board moved to hidden storage. Refresh before deleting."));
if ((await this.workspace.read(path)) !== this.source)
throw new Error("The board changed. Cancel, refresh, and review it before deleting.");
throw new Error(message("The board changed. Cancel, refresh, and review it before deleting."));
}
snapshot.value.boards = snapshot.value.boards.filter((board) => board.value.id !== id);
// Keep originals and card memberships intact. The record prevents legacy rediscovery.
@@ -271,10 +264,10 @@ export class BoardStore {
!isManagedBoard(this.reference.path) ||
!this.available
)
throw new Error("Migrate this board before managing hidden storage.");
throw new Error(message("Migrate this board before managing hidden storage."));
const snapshot = await readCatalog(this.workspace);
if (snapshot.source !== this.source)
throw new Error("The board changed. Refresh before saving.");
throw new Error(message("The board changed. Refresh before saving."));
const board = snapshot.value.boards.find(
(item) => item.value.id === this.reference!.id,
)!;
@@ -288,7 +281,7 @@ export class BoardStore {
patch.name!.trim().toLocaleLowerCase(),
)
)
throw new Error("A board with this name already exists.");
throw new Error(message("A board with this name already exists."));
board.name = patch.name.trim();
}
if (patch.archived !== undefined) board.archived = patch.archived;
@@ -327,7 +320,7 @@ export class BoardStore {
}
async setLimit(id: string, maximum?: number) {
if (maximum !== undefined && (!Number.isSafeInteger(maximum) || maximum < 1))
throw new Error("Enter a whole number of at least 1, or leave the maximum blank.");
throw new Error(message("Enter a whole number of at least 1, or leave the maximum blank."));
await this.update((board) => {
const list = this.requireList(board, id);
if (maximum === undefined) delete list.maxCards;
@@ -356,12 +349,12 @@ export class BoardStore {
private requireList(board: Board, id: string) {
const list = board.lists.find((item) => item.id === id);
if (!list)
throw new Error("This list no longer exists. Refresh the board.");
throw new Error(message("This list no longer exists. Refresh the board."));
return list;
}
private checkName(board: Board, name: string, except?: string) {
if (!name.trim() || name.trim().length > 80)
throw new Error("Enter a list name of 1 to 80 characters.");
throw new Error(message("Enter a list name of 1 to 80 characters."));
if (
board.lists.some(
(list) =>
@@ -369,6 +362,6 @@ export class BoardStore {
list.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
)
)
throw new Error("A list with this name already exists.");
throw new Error(message("A list with this name already exists."));
}
}
+16 -12
View File
@@ -10,6 +10,12 @@ import {
readOptional,
saveDocument,
} from "./persistence.ts";
import { format, message } from "./message.ts";
/** The issue of one file: its path and its problem. */
export function fileIssue(path: string, problem: string) {
return format(message("In {path}: {problem}"), { path, problem });
}
export function cardPath(id: string) {
const key = Array.from(new TextEncoder().encode(id), (byte) =>
@@ -34,9 +40,7 @@ export function cardOrigin(source: string): OriginalFile | undefined {
.some((part: string) => !part || part === "." || part === "..") ||
origin.backup !== `.runestone/pm/backups/${origin.path}`
)
throw new Error(
"The card migration record is invalid. Keep the original note.",
);
throw new Error(message("The card migration record is invalid. Keep the original note."));
return origin;
}
/** Read one hidden card file. It throws when the file is invalid or when its name does not match the card ID. */
@@ -44,7 +48,7 @@ export function parseCard(path: string, source: string): Task {
cardOrigin(source);
const task = readTask(path, source);
if (!task || cardPath(task.id) !== path)
throw new Error("The hidden card ID does not match its storage path.");
throw new Error(message("The hidden card ID does not match its storage path."));
return task;
}
export async function prepareCards(workspace: Workspace) {
@@ -75,14 +79,14 @@ export async function readCards(
const documents = await mapConcurrent(entries, async (entry) => {
try {
const result = sources.get(entry.rel_path)!;
if (result.error || result.source === undefined) throw new Error(result.error ?? "The card is unavailable.");
if (result.error || result.source === undefined) throw new Error(result.error ?? message("The card is unavailable."));
const source = result.source;
const cached = previous.get(entry.rel_path);
if (cached?.source === source) return { task: cached };
return { task: parseCard(entry.rel_path, source) };
} catch (error) {
return {
issue: `${entry.rel_path}: ${error instanceof Error ? error.message : String(error)}`,
issue: fileIssue(entry.rel_path, error instanceof Error ? error.message : String(error)),
};
}
});
@@ -111,19 +115,19 @@ export async function migrateCards(workspace: Workspace, tasks: Task[]) {
if (isHiddenCard(task.path)) continue;
if ((await workspace.read(task.path)) !== task.source)
throw new Error(
`The card changed: ${task.path}. Refresh before migration.`,
format(message("The card changed: {path}. Refresh before migration."), { path: task.path }),
);
const destination = await readOptional(workspace, cardPath(task.id));
if (destination !== null) {
const origin = cardOrigin(destination);
if (origin?.path !== task.path || origin.source !== task.source)
throw new Error(
`A different hidden card already uses the ID from ${task.path}.`,
format(message("A different hidden card already uses the ID from {path}."), { path: task.path }),
);
}
if (split(task.source).doc.has("runestone_pm_origin"))
throw new Error(
`The note already contains a migration record: ${task.path}. Review it before migration.`,
format(message("The note already contains a migration record: {path}. Review it before migration."), { path: task.path }),
);
}
for (const task of tasks) {
@@ -149,15 +153,15 @@ export async function migrateCards(workspace: Workspace, tasks: Task[]) {
copied.body !== task.body
)
throw new Error(
`The card copy differs from ${task.path}. Keep the original.`,
format(message("The card copy differs from {path}. Keep the original."), { path: task.path }),
);
if ((await workspace.read(task.path)) !== task.source)
throw new Error(`The card changed: ${task.path}. Retry migration.`);
throw new Error(format(message("The card changed: {path}. Retry migration."), { path: task.path }));
await prepareCards(workspace);
await saveDocument(workspace, path, source, null);
if ((await workspace.read(path)) !== source)
throw new Error(
`The saved card check failed: ${task.path}. Keep the original.`,
format(message("The saved card check failed: {path}. Keep the original."), { path: task.path }),
);
}
}
+14 -15
View File
@@ -7,6 +7,7 @@ import {
} from "./board.ts";
import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts";
import { format, message } from "./message.ts";
export const catalogPath = ".runestone/pm/workspace.json";
export const boardKey = (id: string) => `pm-board:${id}`;
@@ -33,15 +34,13 @@ export function boardMarkdown(value: Board): string {
}
export function validateName(name: string) {
if (!name.trim() || name.trim().length > 100 || /[\x00-\x1f]/.test(name))
throw new Error("Enter a board name of 1 to 100 characters.");
throw new Error(message("Enter a board name of 1 to 100 characters."));
}
export function parseCatalog(source: string | null): Catalog {
if (source === null) return { schema: 1, boards: [] };
const data = JSON.parse(source);
if (!data || data.schema !== 1 || !Array.isArray(data.boards))
throw new Error(
"The Project Management storage format is unsupported. Restore a backup or update Project Management.",
);
throw new Error(message("The Project Management storage format is unsupported. Restore a backup or update Project Management."));
const ids = new Set<string>();
if (
data.deletedBoardIds !== undefined &&
@@ -49,26 +48,26 @@ export function parseCatalog(source: string | null): Catalog {
data.deletedBoardIds.some((id: unknown) => typeof id !== "string" || !id.trim()) ||
new Set(data.deletedBoardIds).size !== data.deletedBoardIds.length)
)
throw new Error("The deleted board record is invalid.");
throw new Error(message("The deleted board record is invalid."));
for (const board of data.boards) {
if (!board || typeof board.name !== "string")
throw new Error("A saved board has no name.");
throw new Error(message("A saved board has no name."));
validateName(board.name);
parseBoard(boardMarkdown(board.value));
if (ids.has(board.value.id))
throw new Error("Project Management storage contains duplicate board IDs.");
throw new Error(message("Project Management storage contains duplicate board IDs."));
ids.add(board.value.id);
if (data.deletedBoardIds?.includes(board.value.id))
throw new Error("A deleted board still has an active storage entry.");
throw new Error(message("A deleted board still has an active storage entry."));
if (board.archived !== undefined && typeof board.archived !== "boolean")
throw new Error("The board archive state is invalid.");
throw new Error(message("The board archive state is invalid."));
if (
board.original &&
(typeof board.original.path !== "string" ||
typeof board.original.source !== "string" ||
typeof board.original.backup !== "string")
)
throw new Error("The board migration record is invalid.");
throw new Error(message("The board migration record is invalid."));
}
return data;
}
@@ -82,7 +81,7 @@ export async function writeCatalog(
expected: string | null,
) {
if (!workspace.readOptional)
throw new Error("Update RuneStone to use hidden Project Management storage.");
throw new Error(message("Update RuneStone to use hidden Project Management storage."));
const source = JSON.stringify(value, null, 2) + "\n";
parseCatalog(source);
await saveDocument(workspace, catalogPath, source, expected);
@@ -110,7 +109,7 @@ export async function createBoard(workspace: Workspace, name: string) {
board.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
)
)
throw new Error("A board with this name already exists.");
throw new Error(message("A board with this name already exists."));
const value = defaultBoard();
snapshot.value.boards.push({ name: name.trim(), value });
await writeCatalog(workspace, snapshot.value, snapshot.source);
@@ -126,15 +125,15 @@ export async function backupFile(
path.includes("\\") ||
path.split("/").some((part) => !part || part === ".." || part === ".")
)
throw new Error("The migration source path is invalid.");
throw new Error(message("The migration source path is invalid."));
const backup = `.runestone/pm/backups/${path}`;
const saved = await readOptional(workspace, backup);
if (saved === null) await saveDocument(workspace, backup, source, null);
else if (saved !== source)
throw new Error(
`The backup differs from ${path}. Preserve both versions before migration.`,
format(message("The backup differs from {path}. Preserve both versions before migration."), { path }),
);
if ((await workspace.read(backup)) !== source)
throw new Error(`Backup check failed for ${path}.`);
throw new Error(format(message("The backup check failed for {path}."), { path }));
return { path, source, backup };
}
+2 -1
View File
@@ -1,5 +1,6 @@
import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts";
import { message } from "./message.ts";
export const deletedCardsPath = ".runestone/pm/deleted-cards.json";
@@ -10,7 +11,7 @@ export async function readDeletedCards(workspace: Workspace) {
if (value?.schema !== 1 || !Array.isArray(value.ids) ||
value.ids.some((id: unknown) => typeof id !== "string" || !id.trim()) ||
new Set(value.ids).size !== value.ids.length)
throw new Error("The deleted card record is invalid. Restore it before editing cards.");
throw new Error(message("The deleted card record is invalid. Restore it before editing cards."));
return { source, ids: value.ids as string[] };
}
@@ -1,5 +1,6 @@
import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts";
import { message } from "./message.ts";
/** A draft is separate from the saved card and uses compare-and-write protection. */
export class DescriptionDraft {
@@ -17,7 +18,7 @@ export class DescriptionDraft {
if (this.source === null) return null;
const value = JSON.parse(this.source);
if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string"))
throw new Error("The description draft is invalid. Preserve it before recovery.");
throw new Error(message("The description draft is invalid. Preserve it before recovery."));
return value.body;
}
save(body: string | null): Promise<void> {
+5 -4
View File
@@ -1,5 +1,6 @@
import type { Workspace, TaskFields } from "../model/model.ts";
import { saveDocument, storageRoot } from "./persistence.ts";
import { message } from "./message.ts";
export const maxImageBytes = 50 * 1024 * 1024;
export const imageTypes = [
@@ -13,7 +14,7 @@ const idPattern =
export const imageFolder = `${storageRoot}/images`;
export function imagePath(id: string) {
if (!new RegExp(`^${idPattern}$`).test(id))
throw new Error("The image ID is invalid.");
throw new Error(message("The image ID is invalid."));
return `${imageFolder}/${id}.json`;
}
export function imageReferences(body: string) {
@@ -34,10 +35,10 @@ export function imageMarkdown(name: string, id: string) {
}
export function parseImage(source: string): string {
if (source.length > Math.ceil(maxImageBytes / 3) * 4 + 256)
throw new Error("The saved image exceeds the 50 MiB limit.");
throw new Error(message("The saved image exceeds the 50 MiB limit."));
const value = JSON.parse(source);
if (value?.schema !== 1 || typeof value.data !== "string")
throw new Error("The saved image is invalid.");
throw new Error(message("The saved image is invalid."));
const match =
/^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec(
value.data,
@@ -47,7 +48,7 @@ export function parseImage(source: string): string {
match[2].length % 4 !== 0 ||
atob(match[2]).length > maxImageBytes
)
throw new Error("The saved image is invalid or exceeds 50 MiB.");
throw new Error(message("The saved image is invalid or exceeds 50 MiB."));
return value.data;
}
export async function saveImages(
+13 -18
View File
@@ -1,5 +1,6 @@
import { cardColors, type Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts";
import { message } from "./message.ts";
export const labelsPath = ".runestone/pm/labels.json";
export const legacyLabelsPath = "runestone-pm-labels.json";
@@ -24,7 +25,7 @@ export function defaultLabels(): SavedLabel[] {
export function validateLabels(
labels: unknown,
): asserts labels is SavedLabel[] {
if (!Array.isArray(labels)) throw new Error("Saved labels must be a list.");
if (!Array.isArray(labels)) throw new Error(message("Saved labels must be a list."));
const ids = new Set<string>(),
names = new Set<string>();
for (const label of labels) {
@@ -36,26 +37,24 @@ export function validateLabels(
!/^[a-zA-Z0-9_-]{1,100}$/.test(label.id) ||
ids.has(label.id)
)
throw new Error("Each saved label needs a unique ID.");
throw new Error(message("Each saved label needs a unique ID."));
if (
typeof label.name !== "string" ||
!label.name.trim() ||
label.name.trim().length > 80 ||
/[\x00-\x1f\x7f]/.test(label.name)
)
throw new Error("Enter a label name of 1 to 80 characters.");
throw new Error(message("Enter a label name of 1 to 80 characters."));
const name = label.name.trim().toLocaleLowerCase();
if (names.has(name))
throw new Error(
"Use a different name for each label, including archived labels.",
);
throw new Error(message("Use a different name for each label, including archived labels."));
if (
typeof label.color !== "string" ||
!Object.hasOwn(cardColors, label.color)
)
throw new Error("Choose a supported label color.");
throw new Error(message("Choose a supported label color."));
if (label.archived !== undefined && typeof label.archived !== "boolean")
throw new Error("Label archive state must be true or false.");
throw new Error(message("The label archive state must be true or false."));
ids.add(label.id);
names.add(name);
}
@@ -66,7 +65,7 @@ export function parseLabels(source: string | null): LabelSnapshot {
try {
data = JSON.parse(source);
} catch {
throw new Error("Fix the saved labels file before editing labels.");
throw new Error(message("Fix the saved labels file before editing labels."));
}
if (
!data ||
@@ -74,7 +73,7 @@ export function parseLabels(source: string | null): LabelSnapshot {
Array.isArray(data) ||
data.schema !== 1
)
throw new Error("The saved labels file has an unsupported schema.");
throw new Error(message("The saved labels file has an unsupported schema."));
validateLabels(data.labels);
return { source, labels: data.labels };
}
@@ -102,15 +101,11 @@ export class LabelStore {
}
checkSave(labels: SavedLabel[], expected: string | null | undefined): asserts expected is string | null {
if (this.legacy)
throw new Error(
"Use the workspace migration tool before editing legacy labels. See the Project Management development guide.",
);
throw new Error(message("Use the workspace migration tool before editing legacy labels. See the Project Management development guide."));
if (!this.workspace.readOptional)
throw new Error("Update RuneStone to use hidden Project Management storage.");
throw new Error(message("Update RuneStone to use hidden Project Management storage."));
if (expected === undefined || this.error)
throw new Error(
"Saved labels are unavailable. Refresh before editing labels.",
);
throw new Error(message("Saved labels are unavailable. Refresh before editing labels."));
validateLabels(labels);
}
async save(labels: SavedLabel[], expected: string | null | undefined, allowDelete = false) {
@@ -121,7 +116,7 @@ export class LabelStore {
(label) => !labels.some((next) => next.id === label.id),
)
)
throw new Error("Archive unused labels to preserve existing cards.");
throw new Error(message("Archive unused labels to preserve existing cards."));
const data = expected === null ? { schema: 1 } : JSON.parse(expected);
const source =
JSON.stringify(
+13
View File
@@ -0,0 +1,13 @@
// The user-visible text of the storage code and the domain code. These folders use no host module, so the skill helper
// can bundle them for Node. `message()` marks a key of the host catalog (`src/lib/i18n/messages.ts`), and the catalog
// audit counts it. The text stays English here. The interface translates it with `localize()` (`../ui/text.ts`).
/** Mark a catalog key. It returns the text unchanged. */
export function message<T extends string>(text: T): T {
return text;
}
/** Put the values into the `{name}` placeholders of a catalog key. */
export function format(template: string, values: Record<string, string | number>): string {
return template.replace(/\{(\w+)\}/g, (match, key: string) => Object.hasOwn(values, key) ? String(values[key]) : match);
}
+12 -13
View File
@@ -14,6 +14,7 @@ import {
saveDocument,
ensurePrivateStorage,
} from "./persistence.ts";
import { format, message } from "./message.ts";
/** Retain originals until the user checks the boards and removes the listed files. */
export async function migrateStorage(
@@ -22,7 +23,7 @@ export async function migrateStorage(
cards: Task[] = [],
) {
if (!workspace.readOptional || !workspace.create)
throw new Error("Update RuneStone before migrating Project Management storage.");
throw new Error(message("Update RuneStone before migrating Project Management storage."));
const snapshot = await readCatalog(workspace);
const legacy = boards.filter((board) => !isManagedBoard(board.path));
const legacyLabels = await readOptional(workspace, legacyLabelsPath);
@@ -32,10 +33,10 @@ export async function migrateStorage(
// Validate every source before creating backups or publishing any changes.
for (const board of legacy) {
if (snapshot.value.deletedBoardIds?.includes(board.id))
throw new Error("This board was deleted. Refresh Project Management before migration.");
throw new Error(message("This board was deleted. Refresh Project Management before migration."));
if ((await workspace.read(board.path)) !== board.source)
throw new Error(
`The board changed: ${board.path}. Refresh before migration.`,
format(message("The board changed: {path}. Refresh before migration."), { path: board.path }),
);
const existing = snapshot.value.boards.find(
(item) => item.value.id === board.id,
@@ -46,7 +47,7 @@ export async function migrateStorage(
existing.original.source !== board.source)
)
throw new Error(
`A different board already uses the ID from ${board.path}.`,
format(message("A different board already uses the ID from {path}."), { path: board.path }),
);
}
if (legacyLabels !== null && savedLabels !== null) {
@@ -55,9 +56,7 @@ export async function migrateStorage(
original?.path !== legacyLabelsPath ||
original?.source !== legacyLabels
)
throw new Error(
"Hidden labels and legacy labels both exist. Resolve their differences before migration.",
);
throw new Error(message("Hidden labels and legacy labels both exist. Resolve their differences before migration."));
}
await ensurePrivateStorage(workspace);
let changed = false;
@@ -79,10 +78,10 @@ export async function migrateStorage(
for (const board of legacy)
if ((await workspace.read(board.path)) !== board.source)
throw new Error(
`The board changed: ${board.path}. Refresh before migration.`,
format(message("The board changed: {path}. Refresh before migration."), { path: board.path }),
);
if (legacyLabels !== (await readOptional(workspace, legacyLabelsPath)))
throw new Error("Legacy labels changed. Refresh before migration.");
throw new Error(message("Legacy labels changed. Refresh before migration."));
if (changed) await writeCatalog(workspace, snapshot.value, snapshot.source);
if (labelBackup) {
const source =
@@ -93,7 +92,7 @@ export async function migrateStorage(
) + "\n";
await saveDocument(workspace, labelsPath, source, null);
if ((await workspace.read(labelsPath)) !== source)
throw new Error("The saved label check failed. Retry migration.");
throw new Error(message("The saved label check failed. Retry migration."));
}
const saved = await readCatalog(workspace);
for (const board of legacy) {
@@ -105,19 +104,19 @@ export async function migrateStorage(
entry?.original?.source !== board.source ||
JSON.stringify(entry) !== JSON.stringify(expected)
)
throw new Error("The saved board check failed. Retry migration.");
throw new Error(message("The saved board check failed. Retry migration."));
}
await migrateCards(workspace, cards);
const files = await migrationFiles(workspace);
for (const file of files) {
if ((await workspace.read(file.backup)) !== file.source)
throw new Error(
`Backup check failed for ${file.path}. Keep the original.`,
format(message("The backup check failed for {path}. Keep the original."), { path: file.path }),
);
const current = await readOptional(workspace, file.path);
if (current !== null && current !== file.source)
throw new Error(
`The original changed: ${file.path}. Keep both versions.`,
format(message("The original changed: {path}. Keep both versions."), { path: file.path }),
);
}
return files;
+12 -17
View File
@@ -7,24 +7,21 @@ import {
type Status,
type Session,
} from "../model/model.ts";
import { message } from "./message.ts";
const frontmatter =
/^(\uFEFF?)(---[ \t]*\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$))/;
export function split(source: string) {
const match = frontmatter.exec(source);
if (!match && /^\uFEFF?---[ \t]*\r?\n/.test(source))
throw new Error(
"Close the YAML properties block before editing this note.",
);
throw new Error(message("Close the YAML properties block before editing this note."));
const doc = match
? parseDocument(match[3], { uniqueKeys: true, keepSourceTokens: true })
: new Document({});
if (doc.errors.length || doc.warnings.length)
throw new Error(
"Fix invalid or unsupported YAML properties before editing this note.",
);
throw new Error(message("Fix invalid or unsupported YAML properties before editing this note."));
if (!isMap(doc.contents))
throw new Error("Note properties must be a YAML mapping.");
throw new Error(message("Note properties must be a YAML mapping."));
return {
match,
doc,
@@ -48,22 +45,22 @@ export function readTask(path: string, source: string): Task | null {
typeof pm.id !== "string" ||
!pm.id.trim()
) {
throw new Error("This note has an unsupported Project Management schema, kind, or ID.");
throw new Error(message("This note has an unsupported Project Management schema, kind, or ID."));
}
if (pm.archived !== undefined && typeof pm.archived !== "boolean")
throw new Error("Archive state must be true or false.");
throw new Error(message("The archive state must be true or false."));
if (
pm.due !== undefined &&
(!record(pm.due) || typeof pm.due.date !== "string")
)
throw new Error("This preview supports date-only deadlines.");
throw new Error(message("This preview supports date-only deadlines."));
if (
pm.plan !== undefined &&
(!record(pm.plan) ||
typeof pm.plan.start !== "string" ||
typeof pm.plan.end !== "string")
)
throw new Error("The plan needs a start and an exclusive end date.");
throw new Error(message("The plan needs a start and an exclusive end date."));
if (
pm.sessions !== undefined &&
(!Array.isArray(pm.sessions) ||
@@ -76,7 +73,7 @@ export function readTask(path: string, source: string): Task | null {
typeof value.timeZone !== "string",
))
) {
throw new Error("Sessions need an ID, start, end, and time zone.");
throw new Error(message("Sessions need an ID, start, end, and time zone."));
}
const task: Task = {
id: pm.id,
@@ -126,7 +123,7 @@ export function editTask(
): string {
const fields = { ...task, title: undefined, ...patch };
if (Object.hasOwn(patch, "createdAt") && patch.createdAt !== task.createdAt)
throw new Error("The card creation timestamp cannot change.");
throw new Error(message("The card creation timestamp cannot change."));
validateFields(fields);
const { doc, match, newline } = split(task.source);
for (const key of [
@@ -180,7 +177,7 @@ export function newTask(
/[. ]$/.test(title) ||
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(title)
)
throw new Error("Use a valid note name of 1 to 100 characters.");
throw new Error(message("Use a valid note name of 1 to 100 characters."));
validateFields(fields);
const doc = new Document({
runestone_pm: { schema: 1, id, kind: "task", ...fields, createdAt: fields.createdAt ?? new Date().toISOString() },
@@ -194,9 +191,7 @@ export function adoptNote(path: string, source: string): string {
if (readTask(path, source)) return source;
const { doc, body, match, newline } = split(source);
if (doc.has("runestone_pm"))
throw new Error(
"This document already contains Project Management data and cannot become a task.",
);
throw new Error(message("This document already contains Project Management data and cannot become a task."));
doc.set("runestone_pm", {
schema: 1,
id: crypto.randomUUID(),
+2 -1
View File
@@ -1,4 +1,5 @@
import type { Task } from "../model/model.ts";
import { message } from "./message.ts";
const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
const encode = (text: string) =>
@@ -27,7 +28,7 @@ export function compareCards(a: Task, b: Task, boardId?: string): number {
export function orderBetween(lower?: string, upper?: string): string {
if (lower !== undefined && upper !== undefined && lower >= upper)
throw new Error("The card order changed. Refresh the board.");
throw new Error(message("The card order changed. Refresh the board."));
let result = "";
for (let index = 0; ; index++) {
const low =
+4 -5
View File
@@ -1,4 +1,5 @@
import type { Workspace } from "../model/model.ts";
import { message } from "./message.ts";
export const storageRoot = ".runestone/pm";
export const privateRulesPath = `${storageRoot}/.gitignore`;
@@ -10,7 +11,7 @@ export const isHiddenCard = (path: string) =>
/** Install the local exclusion before publishing any private Project Management data. */
export async function ensurePrivateStorage(workspace: Workspace) {
if (!workspace.readOptional || !workspace.create)
throw new Error("Update RuneStone to use hidden Project Management storage.");
throw new Error(message("Update RuneStone to use hidden Project Management storage."));
const expected = await workspace.readOptional(privateRulesPath);
const rules = expected
?.split(/\r?\n/)
@@ -28,9 +29,7 @@ export async function ensurePrivateStorage(workspace: Workspace) {
}
} else await workspace.write(privateRulesPath, source, expected);
if ((await workspace.readOptional(privateRulesPath)) !== source)
throw new Error(
"The Project Management Git exclusion changed. Retry before saving private data.",
);
throw new Error(message("The Project Management Git exclusion changed. Retry before saving private data."));
}
/** Older hosts cannot discover hidden files through the root listing. */
@@ -55,7 +54,7 @@ export async function saveDocument(
await ensurePrivateStorage(workspace);
if (expected === null) {
if (!workspace.create)
throw new Error("Update RuneStone to create Project Management storage.");
throw new Error(message("Update RuneStone to create Project Management storage."));
await workspace.create(path, source);
} else await workspace.write(path, source, expected);
}
+2 -1
View File
@@ -1,4 +1,5 @@
import type { Workspace } from "../model/model.ts";
import { message } from "./message.ts";
// Limit concurrent bridge requests, including large workspaces with many notes.
export const scanConcurrency = 8;
@@ -12,7 +13,7 @@ export async function readSources(workspace: Workspace, paths: string[]) {
const rows = await workspace.readMany(batch);
for (const path of batch) {
const row = rows.find(row => row.path === path);
results.set(path, row && (typeof row.source === "string" || row.error) ? row : { error: "The batch did not return this file." });
results.set(path, row && (typeof row.source === "string" || row.error) ? row : { error: message("The batch did not return this file.") });
}
}
} else {
+3 -2
View File
@@ -1,4 +1,5 @@
import type { MenuHost } from "./host.ts";
import { tr } from "../../../i18n/index.ts";
/** Keep form values native while the host renders every choice menu. */
export function createSharedChoices(root: HTMLElement, ui: MenuHost) {
@@ -20,7 +21,7 @@ export function createSharedChoices(root: HTMLElement, ui: MenuHost) {
use(select: HTMLSelectElement) {
const existing = choices.get(select);
if (existing) { existing.update(); return existing.trigger; }
const label = select.getAttribute("aria-label") ?? select.closest("label")?.firstChild?.textContent?.trim() ?? "Choose";
const label = select.getAttribute("aria-label") ?? select.closest("label")?.firstChild?.textContent?.trim() ?? tr("Choose");
const trigger = document.createElement("button");
trigger.type = "button";
trigger.className = "pm-button pm-choice-button";
@@ -31,7 +32,7 @@ export function createSharedChoices(root: HTMLElement, ui: MenuHost) {
icon.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>';
trigger.append(text, icon);
const update = () => {
const value = select.selectedOptions[0]?.textContent ?? "Choose";
const value = select.selectedOptions[0]?.textContent ?? tr("Choose");
if (text.textContent !== value) text.textContent = value;
if (trigger.disabled !== select.disabled) trigger.disabled = select.disabled;
};
+16 -3
View File
@@ -1,6 +1,21 @@
import { cardColors } from "../model/model.ts";
import { message, tr } from "../../../i18n/index.ts";
// Labels retain the saved color names and use a vivid palette for recognition.
/** The English name of each saved color, a catalog key. `colorName()` translates it. */
export const colorNames: Record<keyof typeof cardColors, string> = {
red: message("Red"), orange: message("Orange"), amber: message("Amber"), yellow: message("Yellow"),
lime: message("Lime"), green: message("Green"), teal: message("Teal"), cyan: message("Cyan"),
blue: message("Blue"), indigo: message("Indigo"), purple: message("Purple"), magenta: message("Magenta"),
pink: message("Pink"), brown: message("Brown"), slate: message("Slate"), gray: message("Gray"),
};
/** The name of a saved color in the language of the interface. An empty value is no color. */
export function colorName(value: string): string {
if (!value) return tr("None");
return Object.hasOwn(colorNames, value) ? tr(colorNames[value as keyof typeof cardColors]) : value;
}
// Labels keep the saved color names and use a vivid palette, so that the user can recognize them.
export const labelColors: Record<keyof typeof cardColors, string> = {
red: "#ff0000", orange: "#ff8000", amber: "#ffb000", yellow: "#ffe000",
lime: "#99ee00", green: "#00cc66", teal: "#00bfa5", cyan: "#00ccff",
@@ -37,8 +52,6 @@ export function createColorPalette(
current.setAttribute("aria-hidden", "true");
const group = "pm-colors-" + crypto.randomUUID();
const inputs: HTMLInputElement[] = [];
const colorName = (value: string) =>
value ? value[0].toUpperCase() + value.slice(1) : "None";
const values = [...(allowNone ? [""] : []), ...Object.keys(cardColors)];
let selected = initial;
const set = (value: string) => {
+15 -12
View File
@@ -1,15 +1,18 @@
import { tooltip } from "./host.ts";
/** Find within the Markdown field, using the host's shared Find presentation. */
import { tr } from "../../../i18n/index.ts";
/** Find in the Markdown field, with the shared Find presentation of the host. */
export function createDescriptionFind(textarea: HTMLTextAreaElement) {
const element = document.createElement("section");
element.className = "rs-find-bar";
element.setAttribute("aria-label", "Find in description");
element.setAttribute("aria-label", tr("Find in description"));
element.hidden = true;
element.innerHTML = `<div class="rs-find-row">
<div class="rs-find-field"><span class="pm-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="10" cy="10" r="7"/><path d="m15 15 6 6"/></svg></span><input type="text" name="search" autocomplete="off" aria-label="Find in description" placeholder="Find in description"></div>
<div class="rs-find-field"><span class="pm-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="10" cy="10" r="7"/><path d="m15 15 6 6"/></svg></span><input type="text" name="search" autocomplete="off"></div>
<div class="rs-find-actions"></div>
</div><div class="rs-find-options"></div>`;
const input = element.querySelector("input")!;
input.setAttribute("aria-label", tr("Find in description"));
input.placeholder = tr("Find in description");
const actions = element.querySelector(".rs-find-actions")!;
const options = element.querySelector(".rs-find-options")!;
const status = document.createElement("span");
@@ -45,9 +48,9 @@ export function createDescriptionFind(textarea: HTMLTextAreaElement) {
wrapper.append(checkbox, document.createTextNode(label)); options.append(wrapper);
return checkbox;
}
const matchCase = option("Match case");
const wholeWord = option("Whole word");
const regex = option("Regex");
const matchCase = option(tr("Match case"));
const wholeWord = option(tr("Whole word"));
const regex = option(tr("Regex"));
options.append(status);
function close() {
hide();
@@ -64,11 +67,11 @@ export function createDescriptionFind(textarea: HTMLTextAreaElement) {
button.onclick = run; actions.append(button);
return button;
}
const previous = action("Previous match (Shift+Enter)", "m18 15-6-6-6 6", () => next(true));
const following = action("Next match (Enter)", "m6 9 6 6 6-6", () => next());
action("Close find (Escape)", "m6 6 12 12M18 6 6 18", close);
const previous = action(tr("Previous match (Shift+Enter)"), "m18 15-6-6-6 6", () => next(true));
const following = action(tr("Next match (Enter)"), "m6 9 6 6 6-6", () => next());
action(tr("Close find (Escape)"), "m6 6 12 12M18 6 6 18", close);
function announce() {
status.textContent = input.value ? (matches.length ? `${current < 0 ? 0 : current + 1} of ${matches.length}` : "No matches") : "";
status.textContent = input.value ? (matches.length ? tr("{current} of {total}", { current: current < 0 ? 0 : current + 1, total: matches.length }) : tr("No matches")) : "";
}
function refresh() {
current = -1; matches = [];
@@ -85,7 +88,7 @@ export function createDescriptionFind(textarea: HTMLTextAreaElement) {
}
}
previous.disabled = following.disabled = !matches.length;
if (input.getAttribute("aria-invalid") === "true") status.textContent = "Invalid expression";
if (input.getAttribute("aria-invalid") === "true") status.textContent = tr("Invalid expression");
else announce();
paint();
}
@@ -95,7 +98,7 @@ export function createDescriptionFind(textarea: HTMLTextAreaElement) {
const match = matches[current];
returnStart = match.from; returnEnd = match.to;
textarea.setSelectionRange(match.from, match.to);
// Reveal the matching line without moving focus out of the Find controls.
// Show the matching line, but keep the focus in the Find controls.
const style = getComputedStyle(textarea);
const mirror = document.createElement("div");
mirror.style.cssText = `position:absolute;visibility:hidden;white-space:pre-wrap;overflow-wrap:break-word;box-sizing:border-box;width:${textarea.clientWidth}px;font:${style.font};line-height:${style.lineHeight};padding:${style.padding}`;
+27 -23
View File
@@ -3,37 +3,41 @@ import type { createCardImages } from "./images-ui.ts";
import { renderMarkdown } from "../model/markdown.ts";
import { headingEdit } from "../model/description-format.ts";
import { createDescriptionFind } from "./description-find.ts";
import { tr } from "../../../i18n/index.ts";
import { message } from "../storage/message.ts";
/** Description edits and formatted content share the card detail view. */
export function createDescriptionEditor(
textarea: HTMLTextAreaElement,
images: ReturnType<typeof createCardImages>,
/** Make a control. `name` is a catalog key in English. The control shows its translation. */
control: (name: string, action: () => void) => HTMLButtonElement,
persistence?: { save(): Promise<void>; cancel(): Promise<string>; },
) {
const element = document.createElement("section");
element.className = "pm-description-editor pm-wide";
element.setAttribute("aria-label", "Description");
element.setAttribute("aria-label", tr("Description"));
const header = document.createElement("div");
header.className = "pm-description-heading";
const heading = document.createElement("h3");
const toggleSection = document.createElement("button");
toggleSection.type = "button"; toggleSection.className = "pm-section-toggle";
toggleSection.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg><span>Description</span>';
toggleSection.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg><span></span>';
toggleSection.lastElementChild!.textContent = tr("Description");
toggleSection.setAttribute("aria-expanded", "true"); heading.append(toggleSection);
const source = document.createElement("label");
source.className = "pm-field pm-description-source";
textarea.setAttribute("aria-label", "Details (Markdown)");
textarea.setAttribute("aria-label", tr("Details (Markdown)"));
source.append(textarea);
const find = createDescriptionFind(textarea);
const preview = document.createElement("div");
preview.className = "pm-markdown-preview";
preview.setAttribute("role", "region");
preview.setAttribute("aria-label", "Description preview");
preview.setAttribute("aria-label", tr("Description preview"));
const toolbar = document.createElement("div");
toolbar.className = "pm-description-toolbar";
toolbar.setAttribute("role", "group");
toolbar.setAttribute("aria-label", "Markdown formatting");
toolbar.setAttribute("aria-label", tr("Markdown formatting"));
textarea.spellcheck = true;
const resize = () => {
if (source.hidden || !textarea.isConnected) return;
@@ -57,7 +61,7 @@ export function createDescriptionEditor(
let pending = false;
const unsaved = document.createElement("span");
unsaved.className = "pm-description-unsaved";
unsaved.textContent = "Unsaved changes";
unsaved.textContent = tr("Unsaved changes");
unsaved.hidden = true;
unsaved.setAttribute("aria-live", "polite");
function insert(before: string, after: string, placeholder: string) {
@@ -69,7 +73,7 @@ export function createDescriptionEditor(
textarea.focus();
}
const formatting = [
control("Heading", () => {
control(message("Heading"), () => {
const edit = headingEdit(textarea.value, textarea.selectionStart, textarea.selectionEnd);
const direction = textarea.selectionDirection;
textarea.setRangeText(edit.text, edit.start, edit.end, "preserve");
@@ -77,52 +81,52 @@ export function createDescriptionEditor(
textarea.dispatchEvent(new Event("input", { bubbles: true }));
textarea.focus();
}),
control("Bold", () => insert("**", "**", "Bold text")),
control("Italic", () => insert("*", "*", "Italic text")),
control("Bullet list", () => insert("\n- ", "\n", "List item")),
control("Link", () => insert("[", "](https://example.com)", "Link text")),
control("Code", () => insert("`", "`", "Code")),
control(message("Bold"), () => insert("**", "**", tr("Bold text"))),
control(message("Italic"), () => insert("*", "*", tr("Italic text"))),
control(message("Bullet list"), () => insert("\n- ", "\n", tr("List item"))),
control(message("Link"), () => insert("[", "](https://example.com)", tr("Link text"))),
control(message("Code"), () => insert("`", "`", tr("Code"))),
];
async function render() {
const current = ++revision;
const body = persistence && !editing ? original : textarea.value;
preview.innerHTML = renderMarkdown(body);
if (!body.trim()) preview.textContent = "Add a description.";
if (!body.trim()) preview.textContent = tr("Add a description.");
for (const image of preview.querySelectorAll<HTMLImageElement>("img[data-pm-image]")) {
const trigger = document.createElement("button");
trigger.type = "button";
trigger.className = "pm-image-preview-trigger";
trigger.setAttribute("aria-label", `View image ${image.alt}`);
trigger.setAttribute("aria-label", tr("View image {name}", { name: image.alt }));
image.removeAttribute("title");
trigger.onclick = () => images.showImage(image, trigger);
image.replaceWith(trigger);
tooltip(trigger, `View image ${image.alt}`);
tooltip(trigger, tr("View image {name}", { name: image.alt }));
trigger.append(image);
const fail = (message: string) => trigger.replaceWith(document.createTextNode(message));
try {
const data = await images.resolveImage(image.dataset.pmImage!);
if (disposed || current !== revision) return;
image.src = data;
image.onerror = () => fail(`Cannot display image: ${image.alt}`);
image.onerror = () => fail(tr("Cannot display image: {name}", { name: image.alt }));
} catch {
if (!disposed && current === revision)
fail(`Cannot load image: ${image.alt}`);
fail(tr("Cannot load image: {name}", { name: image.alt }));
}
}
}
const edit = control("Edit", () => {
const edit = control(message("Edit"), () => {
if (!persistence) original = textarea.value;
editing = true;
update();
textarea.focus();
resize();
});
const toggle = control("Preview", () => {
const toggle = control(message("Preview"), () => {
if (!find.element.hidden) find.close();
source.hidden = !source.hidden;
preview.hidden = !source.hidden;
images.setEditing(!source.hidden);
toggle.lastChild!.textContent = source.hidden ? "Edit Markdown" : "Preview";
toggle.lastChild!.textContent = source.hidden ? tr("Edit Markdown") : tr("Preview");
toggle.setAttribute("aria-pressed", String(source.hidden));
if (source.hidden) void render();
updateLoading();
@@ -147,8 +151,8 @@ export function createDescriptionEditor(
} catch { /* The card editor shows the persistence error. */ }
finally { pending = false; updateLoading(); }
};
const cancel = control("Cancel", () => { void finish(true); });
const apply = control("Save", () => { void finish(false); });
const cancel = control(message("Cancel"), () => { void finish(true); });
const apply = control(message("Save"), () => { void finish(false); });
actions.append(cancel, apply);
for (const item of [...formatting, images.addControl]) {
const name = item.textContent ?? "";
@@ -187,7 +191,7 @@ export function createDescriptionEditor(
source.hidden = !editing;
images.setEditing(editing);
preview.hidden = editing;
toggle.lastChild!.textContent = "Preview";
toggle.lastChild!.textContent = tr("Preview");
toggle.setAttribute("aria-pressed", "false");
updateLoading();
if (!editing) void render();
+7 -5
View File
@@ -1,19 +1,21 @@
/** A searchable field picker. Field forms stay inside the card draft. */
import { tr } from "../../../i18n/index.ts";
/** A field picker with a search. The field forms stay in the card draft. */
export function createDetailsPicker(trigger: HTMLButtonElement) {
const panel = document.createElement("div");
panel.className = "pm-label-options pm-details-picker rs-picker";
panel.id = `pm-details-${crypto.randomUUID()}`;
panel.popover = "auto";
panel.setAttribute("role", "dialog");
panel.setAttribute("aria-label", "Add card details");
panel.setAttribute("aria-label", tr("Add card details"));
const search = document.createElement("input");
search.type = "search";
search.placeholder = "Find a detail";
search.setAttribute("aria-label", "Find a detail");
search.placeholder = tr("Find a detail");
search.setAttribute("aria-label", tr("Find a detail"));
const choices = document.createElement("div");
choices.className = "pm-detail-choices";
const empty = document.createElement("p");
empty.textContent = "No matching details.";
empty.textContent = tr("No matching details.");
empty.hidden = true;
panel.append(search, choices, empty);
trigger.popoverTargetElement = panel;
+27 -28
View File
@@ -1,4 +1,6 @@
import { tooltip } from "./host.ts";
import { message, tr } from "../../../i18n/index.ts";
import { errorText } from "./text.ts";
import type { Workspace, TaskFields } from "../model/model.ts";
import {
imageMarkdown,
@@ -10,10 +12,11 @@ import {
saveImages,
} from "../storage/images.ts";
/** Image data stays outside card Markdown and loads only in the open editor. */
/** The image data stays outside the card Markdown and loads only in the open editor. */
export function createCardImages(
workspace: Workspace,
description: HTMLTextAreaElement,
/** Make a control. `name` is a catalog key in English. The control shows its translation. */
control: (name: string, action: () => void) => HTMLButtonElement,
removeControl: (name: string, action: () => void) => HTMLButtonElement,
changed: (loading: boolean) => void,
@@ -25,8 +28,7 @@ export function createCardImages(
const hint = document.createElement("p");
hint.className = "pm-muted";
hint.id = `pm-image-hint-${crypto.randomUUID()}`;
hint.textContent =
"Paste or drop an image into Details, or choose Add image. PNG, JPEG, GIF, or WebP. Up to 50 MiB each.";
hint.textContent = tr("Paste or drop an image into Details, or choose Add image. PNG, JPEG, GIF, or WebP. Up to 50 MiB each.");
description.setAttribute("aria-describedby", hint.id);
const error = document.createElement("p");
error.className = "pm-error";
@@ -34,24 +36,24 @@ export function createCardImages(
const gallery = document.createElement("div");
gallery.className = "pm-image-gallery";
gallery.setAttribute("role", "group");
gallery.setAttribute("aria-label", "Images in card details");
gallery.setAttribute("aria-label", tr("Images in card details"));
const input = document.createElement("input");
input.type = "file";
input.accept = imageTypes.join(",");
input.multiple = true;
input.hidden = true;
input.setAttribute("aria-label", "Insert images in description");
const add = control("Add image", () => input.click());
input.setAttribute("aria-label", tr("Insert images in description"));
const add = control(message("Add image"), () => input.click());
const attachmentInput = input.cloneNode() as HTMLInputElement;
attachmentInput.setAttribute("aria-label", "Attach images to card");
const attach = control("Attach image", () => attachmentInput.click());
const heading = document.createElement("h3"); heading.textContent = "Attachments";
attachmentInput.setAttribute("aria-label", tr("Attach images to card"));
const attach = control(message("Attach image"), () => attachmentInput.click());
const heading = document.createElement("h3"); heading.textContent = tr("Attachments");
const header = document.createElement("div"); header.className = "pm-attachment-heading";
header.append(heading, attach);
const attachmentGallery = document.createElement("div"); attachmentGallery.className = "pm-image-gallery";
attachmentGallery.setAttribute("role", "group"); attachmentGallery.setAttribute("aria-label", "Image attachments");
attachmentGallery.setAttribute("role", "group"); attachmentGallery.setAttribute("aria-label", tr("Image attachments"));
const attachmentsElement = document.createElement("section"); attachmentsElement.className = "pm-attachments pm-wide";
attachmentsElement.setAttribute("aria-label", "Attachments");
attachmentsElement.setAttribute("aria-label", tr("Attachments"));
const attachmentError = document.createElement("p"); attachmentError.className = "pm-error"; attachmentError.setAttribute("role", "alert");
attachmentsElement.append(header, attachmentInput, attachmentError, attachmentGallery);
element.append(input, hint, error, gallery);
@@ -87,13 +89,13 @@ export function createCardImages(
full.src = source.src;
full.alt = source.alt;
frame.append(full);
const size = control("Actual size", () => {
const size = control(message("Actual size"), () => {
const actual = frame.classList.toggle("pm-image-actual");
size.setAttribute("aria-pressed", String(actual));
placeControls();
});
size.setAttribute("aria-pressed", "false");
const close = removeControl("Close image", () => dialog.close());
const close = removeControl(tr("Close image"), () => dialog.close());
header.append(title, size, close);
dialog.append(header, frame);
const placeControls = () => {
@@ -119,7 +121,7 @@ export function createCardImages(
viewer = undefined;
if (!disposed && trigger.isConnected) trigger.focus({ preventScroll: true });
};
// Keep the viewer outside the gallery, which is hidden in description previews.
// Keep the viewer outside the gallery, because the description preview hides the gallery.
(description.closest(".pm-editor") ?? element.parentElement ?? element).append(dialog);
const outside = (target: EventTarget | null) => target === dialog || target === frame;
let outsidePointer = false;
@@ -147,7 +149,7 @@ export function createCardImages(
});
dialog.showModal();
placeControls();
// Focus the surface first so pointer users can see an unobstructed image.
// Focus the surface first, so that a pointer user can see all of the image.
dialog.tabIndex = -1;
dialog.focus();
idleTimer = setTimeout(() => dialog.classList.add("pm-image-controls-idle"), 2000);
@@ -165,7 +167,7 @@ export function createCardImages(
name.title = ref.name;
caption.append(
name,
removeControl(`Remove image ${ref.name}`, () => {
removeControl(tr("Remove image {name}", { name: ref.name }), () => {
if (attached) {
attachments.splice(attachments.findIndex(item => item.id === ref.id), 1);
description.dispatchEvent(new Event("input", { bubbles: true }));
@@ -192,8 +194,8 @@ export function createCardImages(
const thumbnail = document.createElement("button");
thumbnail.type = "button";
thumbnail.className = "pm-image-thumbnail";
thumbnail.setAttribute("aria-label", `View image ${ref.name}`);
tooltip(thumbnail, `View image ${ref.name}`);
thumbnail.setAttribute("aria-label", tr("View image {name}", { name: ref.name }));
tooltip(thumbnail, tr("View image {name}", { name: ref.name }));
thumbnail.onclick = () => showImage(image, thumbnail);
thumbnail.append(image);
const failure = document.createElement("p");
@@ -201,7 +203,7 @@ export function createCardImages(
failure.setAttribute("role", "alert");
const fail = () => {
thumbnail.remove();
failure.textContent = `Cannot display ${ref.name}. Restore the image file or remove its reference.`;
failure.textContent = tr("Cannot display {name}. Restore the image file or remove its reference.", { name: ref.name });
};
image.onerror = fail;
figure.append(thumbnail, caption, failure);
@@ -237,9 +239,9 @@ export function createCardImages(
const staged: { id: string; name: string; data: string }[] = [];
for (const file of files) {
if (!imageTypes.includes(file.type))
throw new Error("Use a PNG, JPEG, GIF, or WebP image.");
throw new Error(message("Use a PNG, JPEG, GIF, or WebP image."));
if (!file.size || file.size > maxImageBytes)
throw new Error("Use an image between 1 byte and 50 MiB.");
throw new Error(message("Use an image between 1 byte and 50 MiB."));
const bytes = new Uint8Array(await file.arrayBuffer());
let binary = "";
for (let offset = 0; offset < bytes.length; offset += 8192)
@@ -247,17 +249,15 @@ export function createCardImages(
...bytes.subarray(offset, offset + 8192),
);
const data = `data:${file.type};base64,${btoa(binary)}`;
// Decode before inserting a reference, so invalid clipboard files preserve the draft.
// Decode the image before the reference goes in, so that an invalid clipboard file keeps the draft.
const image = new Image();
image.src = data;
await image.decode().catch(() => {
throw new Error(
"The image cannot be read. Copy it again or choose another file.",
);
throw new Error(message("The image cannot be read. Copy it again or choose another file."));
});
staged.push({
id: crypto.randomUUID(),
name: (file.name || "Pasted image").slice(0, 255),
name: (file.name || tr("Pasted image")).slice(0, 255),
data,
});
}
@@ -271,8 +271,7 @@ export function createCardImages(
description.dispatchEvent(new Event("input", { bubbles: true }));
} catch (reason) {
if (!disposed)
(attachOnly ? attachmentError : error).textContent =
reason instanceof Error ? reason.message : String(reason);
(attachOnly ? attachmentError : error).textContent = errorText(reason);
} finally {
loading = false;
if (!disposed) {
+43 -40
View File
@@ -1,6 +1,8 @@
import { type LabelStore, type SavedLabel } from "../storage/labels.ts";
import { actionIcons, tooltip } from "./host.ts";
import { createColorPalette, labelColors } from "./colors.ts";
import { colorName, createColorPalette, labelColors } from "./colors.ts";
import { tr } from "../../../i18n/index.ts";
import { errorText, localize } from "./text.ts";
function node<K extends keyof HTMLElementTagNameMap>(
tag: K,
@@ -21,14 +23,14 @@ function control(text: string, action: () => void) {
export function labelBadge(label?: SavedLabel, id = "") {
const badge = node(
"span",
label?.name ?? "Unavailable label",
label?.name ?? tr("Unavailable label"),
"pm-label-badge",
);
if (label)
badge.style.setProperty("--pm-label-color", labelColors[label.color]);
badge.setAttribute("aria-label", label
? `${label.name} · ${label.color}${label.archived ? " · Archived" : ""}`
: `Unavailable label: ${id}`);
? tr(label.archived ? "{name}, {color}, archived" : "{name}, {color}", { name: label.name, color: colorName(label.color) })
: tr("Unavailable label: {id}", { id }));
return badge;
}
@@ -39,39 +41,39 @@ export function createLabelPicker(
quickAccess = false,
) {
const element = node("section", "", "pm-label-picker pm-wide");
element.setAttribute("aria-label", "Card labels");
element.setAttribute("aria-label", tr("Card labels"));
const selected = new Set(initial);
const known = new Set(catalog.value.map((label) => label.id));
const chips = node("div", "", "pm-label-chips");
chips.setAttribute("role", "group");
chips.setAttribute("aria-label", "Selected labels");
chips.setAttribute("aria-label", tr("Selected labels"));
const panel = node("div", "", "pm-label-options rs-picker");
panel.id = "pm-labels-" + crypto.randomUUID();
panel.popover = "auto";
panel.setAttribute("role", "dialog");
panel.setAttribute("aria-label", "Choose labels");
panel.setAttribute("aria-label", tr("Choose labels"));
const toggle = control("", () => {});
toggle.classList.add("pm-label-add");
const plus = node("span", "", "pm-icon");
plus.innerHTML = quickAccess
? '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 3h8l10 10-8 8L3 11z"/><circle cx="7.5" cy="7.5" r="1"/></svg>'
: `<svg viewBox="0 0 24 24" aria-hidden="true">${actionIcons.plus}</svg>`;
const toggleText = node("span", quickAccess ? "Labels" : "Add labels");
const toggleText = node("span", tr(quickAccess ? "Labels" : "Add labels"));
toggle.append(plus, toggleText);
toggle.setAttribute("aria-label", quickAccess ? "Labels" : "Add labels");
toggle.setAttribute("aria-label", tr(quickAccess ? "Labels" : "Add labels"));
toggle.popoverTargetElement = panel;
toggle.setAttribute("aria-controls", panel.id);
toggle.setAttribute("aria-expanded", "false");
toggle.setAttribute("aria-haspopup", "dialog");
const search = node("input");
search.type = "search";
search.placeholder = "Find a label";
search.setAttribute("aria-label", "Find a label");
search.placeholder = tr("Find a label");
search.setAttribute("aria-label", tr("Find a label"));
const choices = node("div", "", "pm-label-choices");
choices.setAttribute("role", "group");
choices.setAttribute("aria-label", "Available labels");
choices.setAttribute("aria-label", tr("Available labels"));
const hint = node("p", "", "pm-muted");
const manageButton = control("Manage labels", () => {
const manageButton = control(tr("Manage labels"), () => {
close();
toggle.focus();
manage();
@@ -151,17 +153,17 @@ export function createLabelPicker(
});
});
row.className = "pm-label-option rs-picker-row";
row.setAttribute("aria-label", "Add label " + label.name);
row.setAttribute("aria-label", tr("Add label {name}", { name: label.name }));
row.append(labelBadge(label));
choices.append(row);
});
hint.textContent =
catalog.error ||
localize(catalog.error) ||
(matches.length
? ""
: search.value.trim()
? "No matching labels."
: "No available labels.");
? tr("No matching labels.")
: tr("No available labels."));
hint.hidden = !hint.textContent;
manageButton.disabled = catalog.source === undefined;
position();
@@ -177,7 +179,7 @@ export function createLabelPicker(
drawChoices();
toggle.focus();
});
remove.setAttribute("aria-label", "Remove label " + (label?.name ?? id));
remove.setAttribute("aria-label", tr("Remove label {name}", { name: label?.name ?? id }));
tooltip(remove, remove.getAttribute("aria-label")!);
chip.append(remove);
chips.insertBefore(chip, toggle.parentElement === chips ? toggle : null);
@@ -231,61 +233,63 @@ export function createLabelManager(
close: () => void,
) {
const dialog = node("dialog", "", "pm-editor pm-label-manager");
dialog.setAttribute("aria-label", "Manage labels");
dialog.setAttribute("aria-label", tr("Manage labels"));
const form = node("form");
const draft = structuredClone(catalog.value);
const expected = catalog.source;
const rows = node("div", "", "pm-label-definitions");
const error = node("p", catalog.error, "pm-error");
const error = node("p", localize(catalog.error), "pm-error");
error.setAttribute("role", "alert");
let saving = false;
const addRow = (label: SavedLabel) => {
const row = node("fieldset", "", "pm-label-definition");
row.setAttribute("aria-label", "Label " + (label.name || "New label"));
row.setAttribute("aria-label", tr("Label {name}", { name: label.name || tr("New label") }));
const legend = node("legend");
const badge = labelBadge(label);
legend.append(badge);
const fields = node("div", "", "pm-label-definition-fields");
const nameWrap = node("label", "Name", "pm-field");
const nameWrap = node("label", tr("Name"), "pm-field");
const name = node("input");
name.value = label.name;
name.required = true;
name.maxLength = 80;
nameWrap.append(name);
const color = createColorPalette("Color", label.color, (value) => {
const color = createColorPalette(tr("Color"), label.color, (value) => {
label.color = value as SavedLabel["color"];
update();
}, false, labelColors);
const state = node("span", "", "pm-muted");
const update = () => {
row.setAttribute("aria-label", "Label " + (label.name || "New label"));
badge.textContent = label.name || "New label";
const title = label.name || tr("New label");
row.setAttribute("aria-label", tr("Label {name}", { name: title }));
badge.textContent = title;
badge.style.setProperty("--pm-label-color", labelColors[label.color]);
badge.setAttribute("aria-label", `${label.name || "New label"} · ${label.color}`);
state.textContent = label.archived ? "Archived" : "";
remove.setAttribute("aria-label", `Delete ${label.name || "new label"}`);
tooltip(remove, `Delete ${label.name || "new label"}`);
badge.setAttribute("aria-label", tr("{name}, {color}", { name: title, color: colorName(label.color) }));
state.textContent = label.archived ? tr("Archived") : "";
remove.setAttribute("aria-label", deleteName());
tooltip(remove, deleteName());
};
name.oninput = () => {
label.name = name.value;
update();
};
const remove = control("Delete", () => {
const deleteName = () => label.name ? tr("Delete {name}", { name: label.name }) : tr("Delete the new label");
const remove = control(tr("Delete"), () => {
draft.splice(draft.indexOf(label), 1);
row.remove();
add.focus();
});
remove.setAttribute("aria-label", `Delete ${label.name || "new label"}`);
remove.setAttribute("aria-label", deleteName());
remove.classList.add("pm-icon-button");
remove.innerHTML = `<span class="pm-icon"><svg viewBox="0 0 24 24" aria-hidden="true">${actionIcons.trash}</svg></span>`;
tooltip(remove, `Delete ${label.name || "new label"}`);
tooltip(remove, deleteName());
fields.append(nameWrap, remove, color.element);
row.append(legend, fields, state);
rows.append(row);
update();
return name;
};
const add = control("New label", () => {
const add = control(tr("New label"), () => {
const label: SavedLabel = {
id: crypto.randomUUID(),
name: "",
@@ -296,25 +300,25 @@ export function createLabelManager(
});
draft.forEach(addRow);
const actions = node("div", "", "pm-editor-actions");
const cancel = control("Cancel", () => {
const cancel = control(tr("Cancel"), () => {
if (!saving) dialog.close();
});
const submit = control("Save labels", () => {});
const submit = control(tr("Save labels"), () => {});
submit.type = "submit";
submit.classList.add("pm-primary");
actions.append(cancel, submit);
form.append(
node("h2", "Manage labels"),
node("h2", tr("Manage labels")),
node(
"p",
"Labels are shared across all boards in this workspace. Name and color changes apply to every card that uses a label.",
tr("All boards in this workspace share the labels. A change of name or color applies to each card with the label."),
"pm-muted",
),
rows,
add,
node(
"p",
"Deleting a label removes it from every card when you save.",
tr("When you save, RuneStone removes each deleted label from all cards."),
"pm-muted",
),
error,
@@ -335,8 +339,7 @@ export function createLabelManager(
await save(draft, expected);
if (dialog.isConnected) dialog.close();
} catch (reason) {
error.textContent =
reason instanceof Error ? reason.message : String(reason);
error.textContent = errorText(reason);
} finally {
saving = false;
controls.forEach((control) => {
+9 -3
View File
@@ -1,5 +1,11 @@
import type { MenuHost } from "./host.ts";
import { availablePriorities, priorityNames, type Priority, type PriorityLevels } from "../model/model.ts";
import { tr } from "../../../i18n/index.ts";
/** The name of a priority in the language of the interface, for example "High priority". */
export function priorityLabel(value: Priority | null): string {
return value ? tr("{priority} priority", { priority: tr(priorityNames[value]) }) : tr("No priority");
}
export const priorityIcons: Record<Priority, string> = {
highest: '<path d="m6 9 6-6 6 6M6 15l6-6 6 6M6 21l6-6 6 6"/>',
@@ -25,14 +31,14 @@ export function createPriorityPicker(
let changed = false;
trigger.setAttribute("aria-haspopup", "menu");
const update = () => {
trigger.lastChild!.textContent = value ? `${priorityNames[value]} priority` : "Priority";
trigger.lastChild!.textContent = value ? priorityLabel(value) : tr("Priority");
setPriorityAppearance(trigger, value);
};
let menu: { close(): void } | undefined;
const open = () => {
menu?.close(); const bounds = trigger.getBoundingClientRect();
menu = ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: "Choose priority", parent: trigger.closest("dialog") ?? undefined,
items: [...availablePriorities(levels), null].map(priority => ({ label: priority ? `${priorityNames[priority]} priority` : "No priority", checked: value === priority, radio: true,
menu = ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: tr("Choose priority"), parent: trigger.closest("dialog") ?? undefined,
items: [...availablePriorities(levels), null].map(priority => ({ label: priorityLabel(priority), checked: value === priority, radio: true,
run: () => { value = priority; changed = true; update(); } })) });
};
trigger.onclick = open;
+37 -31
View File
@@ -1,6 +1,12 @@
import { priorityNames, type Task, type TaskFields } from "../model/model.ts";
import type { Task, TaskFields } from "../model/model.ts";
import type { BoardDocument } from "../storage/board.ts";
import { setPriorityAppearance } from "./priority-ui.ts";
import { priorityLabel, setPriorityAppearance } from "./priority-ui.ts";
import { tr } from "../../../i18n/index.ts";
/** The board and the list of a card placement. A missing name shows as unavailable. */
function placementText(board: string | undefined, list: string | null | undefined): string {
return tr("{board}: {list}", { board: board ?? tr("Unavailable board"), list: list === null ? tr("Unlisted") : list ?? tr("Unavailable list") });
}
export function createRelations(
task: Task | undefined, tasks: Task[],
@@ -20,20 +26,20 @@ export function createRelations(
const removedIncoming = new Map<string, Task>();
const cardRow = (target: Task | undefined, title: string, action: () => void, relation?: string) => {
const button = document.createElement("button"); button.type = "button"; button.className = "pm-related-card";
button.setAttribute("aria-label", `Open ${title}`); button.onclick = action;
button.setAttribute("aria-label", tr("Open {name}", { name: title })); button.onclick = action;
const name = document.createElement("span"); name.className = "pm-related-title";
name.textContent = relation ? `${relation}: ${title}` : title;
name.textContent = relation ? tr("{relation}: {title}", { relation, title }) : title;
const metadata = document.createElement("span"); metadata.className = "pm-related-metadata";
const placement = document.createElement("span");
const positions = Object.entries(target?.placements ?? {}).map(([boardId, position]) => {
const board = boards.find(board => board.id === boardId);
const list = board?.value.lists.find(list => list.id === position.listId);
return `${board?.name ?? "Unavailable board"}: ${position.listId === null ? "Unlisted" : list?.name ?? "Unavailable list"}`;
return placementText(board?.name, position.listId === null ? null : list?.name);
});
placement.textContent = positions.length ? positions.join(" · ") : "Unlisted";
placement.textContent = positions.length ? positions.join(" · ") : tr("Unlisted");
const priority = document.createElement("span"); priority.className = "pm-related-priority";
priority.innerHTML = '<span class="pm-icon"></span>';
priority.append(document.createTextNode(target?.priority ? `${priorityNames[target.priority]} priority` : "No priority"));
priority.append(document.createTextNode(priorityLabel(target?.priority ?? null)));
setPriorityAppearance(priority, target?.priority ?? null);
metadata.append(placement, priority); button.append(name, metadata);
return button;
@@ -52,7 +58,7 @@ export function createRelations(
heading.append(toggle); header.append(heading); root.append(header, content); element.append(root);
return { header, content, toggle, expand() { content.hidden = false; toggle.setAttribute("aria-expanded", "true"); } };
};
const sub = section("Subtasks");
const sub = section(tr("Subtasks"));
const rows = document.createElement("div"); rows.className = "pm-subtask-rows";
const count = document.createElement("span"); count.className = "pm-muted"; sub.header.append(count);
const render = () => {
@@ -63,17 +69,17 @@ export function createRelations(
const target = tasks.find(task => task.id === item.taskId);
const done = document.createElement("input"); done.type = "checkbox"; done.checked = target ? target.status === "done" : item.done;
done.disabled = !!item.taskId;
done.setAttribute("aria-label", `Complete ${item.title}`); done.onchange = () => { item.done = done.checked; count.textContent = `${subtasks.filter(item => item.done).length}/${subtasks.length}`; };
done.setAttribute("aria-label", tr("Complete {name}", { name: item.title })); done.onchange = () => { item.done = done.checked; count.textContent = `${subtasks.filter(item => item.done).length}/${subtasks.length}`; };
const title = cardRow(target, target?.title ?? item.title, () => open({ subtaskId: item.id }));
row.append(done, title, removeControl(`Delete subtask ${item.title}`, () => { subtasks.splice(subtasks.indexOf(item), 1); render(); }));
row.append(done, title, removeControl(tr("Delete subtask {name}", { name: item.title }), () => { subtasks.splice(subtasks.indexOf(item), 1); render(); }));
rows.append(row);
}
};
const draft = document.createElement("input"); draft.placeholder = "New subtask"; draft.maxLength = 200; draft.setAttribute("aria-label", "New subtask");
const draft = document.createElement("input"); draft.placeholder = tr("New subtask"); draft.maxLength = 200; draft.setAttribute("aria-label", tr("New subtask"));
const addRow = document.createElement("div"); addRow.className = "pm-relation-row"; addRow.hidden = true;
const reveal = control("Add subtask", () => { sub.expand(); addRow.hidden = false; reveal.hidden = true; draft.focus(); });
const reveal = control(tr("Add subtask"), () => { sub.expand(); addRow.hidden = false; reveal.hidden = true; draft.focus(); });
const dismiss = () => { draft.value = ""; add.disabled = true; addRow.hidden = true; reveal.hidden = false; reveal.focus(); };
const add = control("Create subtask", () => {
const add = control(tr("Create subtask"), () => {
if (!draft.value.trim()) return;
subtasks.push({ id: crypto.randomUUID(), title: draft.value.trim(), done: false }); render(); dismiss();
});
@@ -83,20 +89,20 @@ export function createRelations(
if (event.key === "Enter") { event.preventDefault(); add.click(); }
if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); dismiss(); }
};
addRow.append(draft, add, removeControl("Cancel subtask", dismiss));
addRow.append(draft, add, removeControl(tr("Cancel subtask"), dismiss));
sub.header.append(reveal); sub.content.append(rows, addRow);
const linkedSection = section("Linked cards");
const linkedSection = section(tr("Linked cards"));
const linked = document.createElement("div");
const names = { relates: "Relates to", blocks: "Blocks", "blocked-by": "Blocked by" };
const search = document.createElement("input"); search.type = "search"; search.placeholder = "Find a card"; search.setAttribute("aria-label", "Find a card to link");
const names = { relates: tr("Relates to"), blocks: tr("Blocks"), "blocked-by": tr("Blocked by") };
const search = document.createElement("input"); search.type = "search"; search.placeholder = tr("Find a card"); search.setAttribute("aria-label", tr("Find a card to link"));
const choices = document.createElement("div"); choices.className = "pm-link-results rs-picker";
choices.id = "pm-link-results-" + crypto.randomUUID();
choices.setAttribute("role", "group"); choices.setAttribute("aria-label", "Matching cards");
choices.setAttribute("role", "group"); choices.setAttribute("aria-label", tr("Matching cards"));
search.setAttribute("aria-controls", choices.id);
const resultStatus = document.createElement("p"); resultStatus.className = "rs-picker-hint";
resultStatus.setAttribute("role", "status"); resultStatus.setAttribute("aria-live", "polite");
const relation = document.createElement("select"); relation.setAttribute("aria-label", "Relationship");
const relation = document.createElement("select"); relation.setAttribute("aria-label", tr("Relationship"));
for (const [value, name] of Object.entries(names)) { const option = document.createElement("option"); option.value = value; option.textContent = name; relation.append(option); }
const candidates = () => tasks.filter(item => item.id !== task?.id && !item.archived
&& !links.some(link => link.taskId === item.id)
@@ -107,7 +113,7 @@ export function createRelations(
const matches = candidates();
for (const item of matches) {
const row = document.createElement("button"); row.type = "button"; row.className = "rs-picker-row";
row.setAttribute("aria-label", `Link ${item.title}`);
row.setAttribute("aria-label", tr("Link {name}", { name: item.title }));
const icon = document.createElement("span"); icon.className = "pm-icon rs-picker-icon";
icon.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m10 13 4-4M8 16l-1 1a4 4 0 0 1-6-6l4-4a4 4 0 0 1 6 0m2 1 1-1a4 4 0 0 1 6 6l-4 4a4 4 0 0 1-6 0"/></svg>';
const text = document.createElement("span"); text.className = "pm-link-result-text";
@@ -115,8 +121,8 @@ export function createRelations(
const hint = document.createElement("span"); hint.className = "rs-picker-hint";
hint.textContent = Object.entries(item.placements ?? {}).map(([id, position]) => {
const board = boards.find(board => board.id === id);
return `${board?.name ?? "Unavailable board"}: ${position.listId === null ? "Unlisted" : board?.value.lists.find(list => list.id === position.listId)?.name ?? "Unavailable list"}`;
}).join(" · ") || "Unlisted";
return placementText(board?.name, position.listId === null ? null : board?.value.lists.find(list => list.id === position.listId)?.name);
}).join(" · ") || tr("Unlisted");
text.append(title, hint); row.append(icon, text);
row.onclick = () => {
if (!candidates().some(candidate => candidate.id === item.id)) return;
@@ -125,7 +131,7 @@ export function createRelations(
};
choices.append(row);
}
resultStatus.textContent = matches.length ? "" : search.value.trim() ? "No matching cards." : "No available cards to link.";
resultStatus.textContent = matches.length ? "" : search.value.trim() ? tr("No matching cards.") : tr("No available cards to link.");
resultStatus.hidden = matches.length > 0;
choices.hidden = matches.length === 0;
};
@@ -134,25 +140,25 @@ export function createRelations(
for (const item of links) {
const row = document.createElement("div"); row.className = "pm-relation-row";
const target = tasks.find(candidate => candidate.id === item.taskId);
const text = cardRow(target, target?.title ?? "Unavailable card", () => open({ taskId: item.taskId }), names[item.relation]);
const text = cardRow(target, target?.title ?? tr("Unavailable card"), () => open({ taskId: item.taskId }), names[item.relation]);
text.disabled = !target;
row.append(text, removeControl(`Unlink ${target?.title ?? "card"}`, () => { links.splice(links.indexOf(item), 1); drawLinks(); })); linked.append(row);
row.append(text, removeControl(target ? tr("Unlink {name}", { name: target.title }) : tr("Unlink the card"), () => { links.splice(links.indexOf(item), 1); drawLinks(); })); linked.append(row);
}
// Inverse links remain visible without duplicate writes to another card.
// The inverse links stay visible, but the editor does not write them to the other card.
for (const source of tasks) for (const link of source.links ?? []) if (link.taskId === task?.id && !removedIncoming.has(source.id) && !links.some(item => item.taskId === source.id)) {
const row = document.createElement("div"); row.className = "pm-relation-row";
row.append(cardRow(source, source.title, () => open({ taskId: source.id }), link.relation === "blocks" ? "Blocked by" : link.relation === "blocked-by" ? "Blocks" : "Relates to"));
row.append(removeControl(`Unlink ${source.title}`, () => { removedIncoming.set(source.id, source); drawLinks(); }));
row.append(cardRow(source, source.title, () => open({ taskId: source.id }), link.relation === "blocks" ? names["blocked-by"] : link.relation === "blocked-by" ? names.blocks : names.relates));
row.append(removeControl(tr("Unlink {name}", { name: source.title }), () => { removedIncoming.set(source.id, source); drawLinks(); }));
linked.append(row);
}
for (const parent of tasks.filter(source => task && source.subtasks?.some(item => item.taskId === task.id))) {
const row = document.createElement("div"); row.className = "pm-relation-row";
row.append(cardRow(parent, parent.title, () => open({ taskId: parent.id }), "Subtask of")); linked.append(row);
row.append(cardRow(parent, parent.title, () => open({ taskId: parent.id }), tr("Subtask of"))); linked.append(row);
}
drawChoices();
};
const linkEditor = document.createElement("div"); linkEditor.className = "pm-link-editor"; linkEditor.hidden = true;
const revealLink = control("Add linked card", () => { linkedSection.expand(); linkEditor.hidden = false; revealLink.hidden = true; search.focus(); });
const revealLink = control(tr("Add linked card"), () => { linkedSection.expand(); linkEditor.hidden = false; revealLink.hidden = true; search.focus(); });
const dismissLink = () => { search.value = ""; drawChoices(); linkEditor.hidden = true; revealLink.hidden = false; revealLink.focus(); };
search.oninput = drawChoices;
search.onkeydown = event => {
@@ -172,7 +178,7 @@ export function createRelations(
rows[event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : (index + (event.key === "ArrowDown" ? 1 : rows.length - 1)) % rows.length]?.focus();
};
linkEditor.addEventListener("keydown", event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); dismissLink(); } });
const linkRow = document.createElement("div"); linkRow.className = "pm-relation-row"; linkRow.append(search, relation, removeControl("Cancel linked card", dismissLink));
const linkRow = document.createElement("div"); linkRow.className = "pm-relation-row"; linkRow.append(search, relation, removeControl(tr("Cancel linked card"), dismissLink));
useSharedChoices?.(relation);
linkEditor.append(linkRow, choices, resultStatus); linkedSection.header.append(revealLink); linkedSection.content.append(linked, linkEditor);
render(); drawLinks();
+8 -7
View File
@@ -1,17 +1,19 @@
import { tr } from "../../../i18n/index.ts";
export function createTagInput(initial: string[], existing: string[]) {
const element = document.createElement("div");
element.className = "pm-tag-editor pm-wide";
const chips = document.createElement("div");
chips.className = "pm-tag-chips";
chips.setAttribute("role", "list");
chips.setAttribute("aria-label", "Selected tags");
chips.setAttribute("aria-label", tr("Selected tags"));
const label = document.createElement("label");
label.className = "pm-field";
label.textContent = "Add a tag";
label.textContent = tr("Add a tag");
const input = document.createElement("input");
input.type = "text";
input.autocomplete = "off";
input.placeholder = "Type a tag and press Enter";
input.placeholder = tr("Type a tag and press Enter");
input.setAttribute("role", "combobox");
input.setAttribute("aria-autocomplete", "list");
input.setAttribute("aria-expanded", "false");
@@ -19,14 +21,13 @@ export function createTagInput(initial: string[], existing: string[]) {
suggestions.className = "pm-tag-suggestions rs-picker";
suggestions.id = "pm-tags-" + crypto.randomUUID();
suggestions.setAttribute("role", "listbox");
suggestions.setAttribute("aria-label", "Existing tags");
suggestions.setAttribute("aria-label", tr("Existing tags"));
suggestions.hidden = true;
input.setAttribute("aria-controls", suggestions.id);
const hint = document.createElement("p");
hint.className = "pm-muted";
hint.id = suggestions.id + "-hint";
hint.textContent =
"Press Enter to add a tag. Use the arrow keys to choose an existing tag.";
hint.textContent = tr("Press Enter to add a tag. Use the arrow keys to choose an existing tag.");
input.setAttribute("aria-describedby", hint.id);
label.append(input);
element.append(chips, label, suggestions, hint);
@@ -112,7 +113,7 @@ export function createTagInput(initial: string[], existing: string[]) {
const remove = document.createElement("button");
remove.type = "button";
remove.textContent = "×";
remove.setAttribute("aria-label", "Remove tag " + tag);
remove.setAttribute("aria-label", tr("Remove tag {name}", { name: tag }));
remove.onclick = () => {
selected = selected.filter((value) => value !== tag);
renderChips();
+49
View File
@@ -0,0 +1,49 @@
// The translation of text that the storage code and the domain code give to the interface: error messages, workspace
// issues, and names. That code stays English (`../storage/message.ts`). It fills the `{name}` placeholders of a catalog
// key with `format()`, so this module finds the key again and translates the text and its values.
import { get } from "svelte/store";
import { locale, translate } from "../../../i18n/index.ts";
import { catalogs, messageRows } from "../../../i18n/messages.ts";
interface Pattern { key: string; names: string[]; regex: RegExp; literal: number }
let patterns: Pattern[] | undefined;
/** The catalog keys with placeholders, as patterns. A key with more fixed text comes first. */
function templatePatterns(): Pattern[] {
patterns ??= messageRows.map(row => row[0]).flatMap(key => {
const literal = key.replace(/\{\w+\}/g, "").length;
// A key that is almost only placeholders matches too much text.
if (literal < 4 || !/\{\w+\}/.test(key) || /\}\{/.test(key)) return [];
const names: string[] = [];
const source = key.split(/(\{\w+\})/).map(part => {
const name = /^\{(\w+)\}$/.exec(part)?.[1];
if (name) { names.push(name); return "([\\s\\S]+?)"; }
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}).join("");
return [{ key, names, regex: new RegExp(`^${source}$`), literal }];
}).sort((a, b) => b.literal - a.literal);
return patterns;
}
/**
* The text in the language of the interface. A catalog key translates at once. A text that `format()` made from a key
* translates with its values, and a value that is a catalog text also translates. Other text stays as it is.
*/
export function localize(text: string, depth = 0): string {
const language = get(locale);
if (language === "en") return text;
if (Object.hasOwn(catalogs[language], text)) return catalogs[language][text];
if (depth > 2) return text;
for (const pattern of templatePatterns()) {
const match = pattern.regex.exec(text);
if (!match) continue;
const values = Object.fromEntries(pattern.names.map((name, index) => [name, localize(match[index + 1], depth + 1)]));
return translate(language, pattern.key, values);
}
return text;
}
/** The translated message of an error or another thrown value. */
export function errorText(reason: unknown): string {
return localize(reason instanceof Error ? reason.message : String(reason));
}
File diff suppressed because it is too large Load Diff
+4 -3
View File
@@ -3,6 +3,7 @@
// It reads JSON only. The feature code (`src/lib/features/pm/storage/catalog.ts`) owns the full format and validation.
import { invoke } from "@tauri-apps/api/core";
import { workspaceWrite } from "../workspace/api.ts";
import { message } from "../i18n/index.ts";
export const BOARD_CATALOG_PATH = ".runestone/pm/workspace.json";
@@ -37,7 +38,7 @@ function record(value: unknown): Record<string, unknown> | null {
export function parseBoardCatalog(source: string | null): BoardCatalog {
if (source === null) return { boards: [], defaultBoardId: null, source };
const data = record(JSON.parse(source));
if (!data || data.schema !== 1 || !Array.isArray(data.boards)) throw new Error("The Project Management storage format is unsupported.");
if (!data || data.schema !== 1 || !Array.isArray(data.boards)) throw new Error(message("The Project Management storage format is unsupported."));
const boards: BoardSummary[] = [];
for (const row of data.boards) {
const board = record(row), value = record(board?.value);
@@ -62,9 +63,9 @@ export async function writeDefaultBoard(id: string | null, read: ReadOptional =
const catalog = parseBoardCatalog(source);
if (source === null) {
if (id === null) return;
throw new Error("This board is unavailable. Refresh Project Management.");
throw new Error(message("This board is unavailable. Refresh Project Management."));
}
if (id !== null && !catalog.boards.some(board => board.id === id)) throw new Error("This board is unavailable. Refresh Project Management.");
if (id !== null && !catalog.boards.some(board => board.id === id)) throw new Error(message("This board is unavailable. Refresh Project Management."));
const data = JSON.parse(source) as Record<string, unknown>;
data.defaultBoardId = id;
data.defaultBoardPath = id === null ? null : `pm-board:${id}`;