RuneStone 1.0.0
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
<!--
|
||||
Settings → Project Management, and the Project Management settings of the board menu. It is in the main bundle and
|
||||
loads no feature code: the priority levels are in the `projectManagement` settings section (`pmSettings.ts`), and
|
||||
the default board is in `.runestone/pm/workspace.json` of the workspace (`pmBoards.ts`). It shows only while
|
||||
Project Management is on. Each change saves at once.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { 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: 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 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 ?? $t("Unavailable board (opens All tasks)") : $t("All tasks"));
|
||||
|
||||
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
|
||||
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
|
||||
}
|
||||
|
||||
function saveLevels(priorityLevels: PriorityLevels) {
|
||||
error = "";
|
||||
settings = { ...settings, priorityLevels };
|
||||
writeProjectManagement(settings).then(() => { 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) notice = $t("Changes saved."); }
|
||||
catch (reason) { if (!disposed) { defaultBoard = previous; notice = ""; error = errorText(reason); } }
|
||||
finally { saving = false; }
|
||||
}
|
||||
|
||||
async function readBoards() {
|
||||
try {
|
||||
const catalog = await readBoardCatalog();
|
||||
if (disposed) return;
|
||||
boards = catalog.boards;
|
||||
defaultBoard = catalog.defaultBoardId ?? "";
|
||||
boardsReady = true;
|
||||
boardNote = "";
|
||||
} catch (reason) {
|
||||
if (!disposed) boardNote = /no workspace/i.test(String(reason)) ? $t("Open a workspace to choose its default board.") : errorText(reason);
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
void readBoards();
|
||||
return onProjectManagementChange(() => { settings = readProjectManagement(); });
|
||||
});
|
||||
onDestroy(() => { disposed = true; closeMenu(); });
|
||||
</script>
|
||||
|
||||
<div class="pm-settings">
|
||||
{#if !compact}
|
||||
<h2>{$t("Project Management")}</h2>
|
||||
<p class="intro">{$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">{$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">{$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" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<p class="saved" role="status">{notice}</p>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.pm-settings { min-width: 0; }
|
||||
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
|
||||
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
|
||||
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
|
||||
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
|
||||
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
||||
.name { font-weight: 500; color: var(--rs-text); }
|
||||
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
|
||||
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); box-sizing: border-box; max-width: 100%; min-width: 160px; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: left; cursor: pointer; }
|
||||
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
|
||||
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
|
||||
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
.picker:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
|
||||
.error { color: var(--rs-error); margin-top: 10px; }
|
||||
</style>
|
||||
@@ -0,0 +1,39 @@
|
||||
<script lang="ts">
|
||||
// The place of the terminal panel in the workbench and in the terminal window. It is in the main bundle.
|
||||
// The first mount loads the Terminal feature (xterm included). An unmount closes the sessions of this panel.
|
||||
import { onMount } from "svelte";
|
||||
import { t } from "$lib/i18n";
|
||||
import { terminalInstance, type TerminalAction, type TerminalMount, type TerminalProps } from "./terminalHost";
|
||||
let props: TerminalProps = $props();
|
||||
let container: HTMLDivElement;
|
||||
let mounted = $state.raw<TerminalMount>();
|
||||
let loading = $state(true);
|
||||
let error = $state("");
|
||||
let ready: Promise<TerminalMount | undefined> = Promise.resolve(undefined);
|
||||
onMount(() => {
|
||||
let disposed = false;
|
||||
ready = terminalInstance().then(instance => {
|
||||
if (disposed) return undefined;
|
||||
mounted = instance.mountDock(container, { ...props });
|
||||
return mounted;
|
||||
}).catch(reason => { if (!disposed) error = String(reason); return undefined; }).finally(() => { loading = false; });
|
||||
return () => {
|
||||
disposed = true;
|
||||
const current = mounted;
|
||||
mounted = undefined;
|
||||
void current?.dispose().catch(reason => console.error("The terminal panel did not close cleanly.", reason));
|
||||
};
|
||||
});
|
||||
$effect(() => { mounted?.update({ ...props }); });
|
||||
/** Run a terminal action. It waits for the first load. */
|
||||
export async function command(action: Exclude<TerminalAction, "toggle">) { await (await ready)?.command(action); }
|
||||
</script>
|
||||
{#if error}<p class="error" role="alert">{$t("The terminal could not start: {error}", { error })}</p>{/if}
|
||||
{#if loading}<p class="loading">{$t("Loading the terminal…")}</p>{/if}
|
||||
<div class="terminal-host" bind:this={container}></div>
|
||||
<style>
|
||||
.terminal-host { display: flex; flex-direction: column; flex: 1; height: 100%; min-height: 0; min-width: 0; }
|
||||
.error, .loading { margin: 0; padding: 7px 12px; font-size: 12px; }
|
||||
.error { color: var(--rs-error); }
|
||||
.loading { color: var(--rs-text-dim); }
|
||||
</style>
|
||||
@@ -0,0 +1,113 @@
|
||||
<!--
|
||||
Settings → Terminal. It is in the main bundle and loads no feature code, so it does not load xterm.
|
||||
It shows only while Terminal is on. Each change saves at once to the `terminal` section, and open terminals take it.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { FONT_SIZE, SCROLLBACK, onTerminalChange, readTerminal, writeTerminal, type TerminalSettings } from "./terminalSettings";
|
||||
|
||||
type Profile = { id: string; title: string; kind: string };
|
||||
const initial = readTerminal();
|
||||
let settings = $state<TerminalSettings>(initial);
|
||||
let fontSize = $state<number | undefined>(initial.fontSize);
|
||||
let scrollback = $state<number | undefined>(initial.scrollback);
|
||||
let profiles = $state<Profile[]>([]);
|
||||
let profileNote = $state("");
|
||||
let message = $state("");
|
||||
let error = $state("");
|
||||
let closeMenu = () => {};
|
||||
/** The shells that a new terminal can use. The Node.js debug terminal is not a default. */
|
||||
const shells = $derived(profiles.filter(profile => profile.kind !== "node"));
|
||||
const current = $derived(shells.find(profile => profile.id === settings.defaultProfile) ?? shells[0]);
|
||||
|
||||
function read() {
|
||||
settings = readTerminal();
|
||||
fontSize = settings.fontSize;
|
||||
scrollback = settings.scrollback;
|
||||
}
|
||||
function save(next: TerminalSettings) {
|
||||
error = "";
|
||||
settings = next;
|
||||
writeTerminal(next).then(() => { message = tr("Changes saved."); })
|
||||
.catch(() => { error = tr("Could not save these settings. Your previous settings still apply. Try again."); message = ""; });
|
||||
}
|
||||
function changeNumber(value: number | undefined, range: { min: number; max: number }, key: "fontSize" | "scrollback") {
|
||||
if (typeof value !== "number" || !Number.isInteger(value) || value < range.min || value > range.max) {
|
||||
error = tr("Choose a whole number from {min} to {max}.", { min: range.min.toLocaleString(), max: range.max.toLocaleString() });
|
||||
message = "";
|
||||
return;
|
||||
}
|
||||
save({ ...settings, [key]: value });
|
||||
}
|
||||
function profileMenu(event: MouseEvent) {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: tr("Default terminal profile"), parent: anchor.closest("dialog") ?? undefined,
|
||||
items: shells.map(profile => ({ label: profile.title, icon: "code", radio: true, checked: current?.id === profile.id,
|
||||
run: () => save({ ...settings, defaultProfile: profile.id }) })) }).close;
|
||||
}
|
||||
onMount(() => {
|
||||
const stop = onTerminalChange(read);
|
||||
if (!isTauri()) profileNote = tr("The desktop app lists the installed shells.");
|
||||
else invoke<Profile[]>("pty_profiles").then(found => {
|
||||
profiles = found;
|
||||
if (!found.some(profile => profile.kind !== "node")) profileNote = tr("RuneStone found no supported shells on PATH.");
|
||||
}).catch(reason => { profileNote = tr("RuneStone could not list the shells: {error}", { error: String(reason) }); });
|
||||
return stop;
|
||||
});
|
||||
onDestroy(() => closeMenu());
|
||||
</script>
|
||||
|
||||
<div class="terminal-settings">
|
||||
<h2>{$t("Terminal")}</h2>
|
||||
<p class="intro">{$t("Font, scrollback, and cursor apply to open terminals. The default profile applies to new terminals.")}</p>
|
||||
<div class="card">
|
||||
<div class="setting-row">
|
||||
<div><span class="name" id="terminal-profile-label">{$t("Default profile")}</span><p id="terminal-profile-description">{profileNote || $t("The shell of a new terminal.")}</p></div>
|
||||
<button class="picker" type="button" aria-label={$t("Default profile")} aria-describedby="terminal-profile-description" aria-haspopup="menu" disabled={!shells.length} onclick={profileMenu}>
|
||||
{current?.title ?? $t("No shell")}<Icon icon="chevron-down" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><label for="terminal-font-size">{$t("Font size")}</label><p id="terminal-font-description">{$t("From {min} to {max} pixels.", { min: FONT_SIZE.min, max: FONT_SIZE.max })}</p></div>
|
||||
<input id="terminal-font-size" type="number" min={FONT_SIZE.min} max={FONT_SIZE.max} step="1" required aria-describedby="terminal-font-description" bind:value={fontSize} onchange={() => changeNumber(fontSize, FONT_SIZE, "fontSize")} />
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><label for="terminal-scrollback">{$t("Scrollback lines")}</label><p id="terminal-scrollback-description">{$t("The lines that a terminal keeps above the screen, from {min} to {max}.", { min: SCROLLBACK.min.toLocaleString(), max: SCROLLBACK.max.toLocaleString() })}</p></div>
|
||||
<input id="terminal-scrollback" type="number" min={SCROLLBACK.min} max={SCROLLBACK.max} step="100" required aria-describedby="terminal-scrollback-description" bind:value={scrollback} onchange={() => changeNumber(scrollback, SCROLLBACK, "scrollback")} />
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><label for="terminal-cursor-blink">{$t("Blink cursor")}</label><p id="terminal-blink-description">{$t("The cursor blinks in the focused terminal.")}</p></div>
|
||||
<input id="terminal-cursor-blink" class="rs-switch" type="checkbox" role="switch" aria-describedby="terminal-blink-description" checked={settings.cursorBlink} onchange={event => save({ ...settings, cursorBlink: event.currentTarget.checked })} />
|
||||
</div>
|
||||
</div>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<p class="saved" role="status">{message}</p>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.terminal-settings { min-width: 0; }
|
||||
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
|
||||
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
|
||||
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
|
||||
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
|
||||
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
||||
.setting-row label, .name { font-weight: 500; color: var(--rs-text); }
|
||||
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
|
||||
input[type=number], .picker { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
input[type=number] { width: 96px; }
|
||||
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); max-width: 100%; min-width: 160px; text-align: left; cursor: pointer; }
|
||||
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
|
||||
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
|
||||
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
:is(.picker, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
|
||||
.error { color: var(--rs-error); margin-top: 10px; }
|
||||
</style>
|
||||
@@ -0,0 +1,295 @@
|
||||
<!--
|
||||
Appearance → Background. The source is a folder (a slideshow), one image, or none. The folder layout and the order
|
||||
are in the `background` settings section. The image and its layout stay in `appearance.newTabBackground`.
|
||||
This component also works in the settings window, where the slideshow does not run. It sends Next to every window.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { onSettingsChange } from "$lib/settings/store";
|
||||
import { featureSwitches } from "$lib/features/state";
|
||||
import { readBoardCatalog } from "../pmBoards";
|
||||
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, saveAppearance, type Appearance } from "$lib/theme/appearance";
|
||||
import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages";
|
||||
import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings";
|
||||
import { folderHost, readSavedImage, sendBackgroundCommand } from "./sources";
|
||||
import { imageNames } from "./imageSettings";
|
||||
import ImageEditor from "./ImageEditor.svelte";
|
||||
|
||||
/** The background targets of single boards need a UUID board ID. */
|
||||
const boardId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
let settings = $state<BackgroundSettings>(readBackground());
|
||||
let appearance = $state<Appearance>(readAppearance());
|
||||
let folder = $state<string | null>(null);
|
||||
let folderNote = $state("");
|
||||
let boards = $state<{ id: string; name: string }[]>([]);
|
||||
let boardsNote = $state("");
|
||||
let previewUrl = $state("");
|
||||
let error = $state("");
|
||||
let imageInput: HTMLInputElement;
|
||||
let imageRevision = 0;
|
||||
let boardRevision = 0;
|
||||
let previewKey = "";
|
||||
let closeMenu = () => {};
|
||||
let disposed = false;
|
||||
|
||||
const image = $derived(appearance.newTabBackground);
|
||||
const layout = $derived<BackgroundLayout | null>(settings.source === "folder" ? normalizeLayout(settings) : settings.source === "image" && hasImage(appearance) ? normalizeLayout(image) : null);
|
||||
const sourceLabels = $derived<Record<BackgroundSource, string>>({ folder: $t("Folder"), image: $t("Image"), none: $t("None") });
|
||||
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
|
||||
const sizeLabels = $derived([$t("Fill"), $t("Fit"), $t("Actual size")]);
|
||||
const orderLabels = $derived({ name: $t("File name"), random: $t("Random") });
|
||||
const targets = $derived([
|
||||
{ id: "app", name: $t("The workspace and new tabs") },
|
||||
{ id: "pm-all", name: $t("All Project Management boards") },
|
||||
...boards.map(board => ({ id: `pm-board:${board.id}`, name: $t("Board: {name}", { name: board.name }) })),
|
||||
// Keep saved targets without a current board, so that the user can remove them.
|
||||
...settings.targets.filter(id => id.startsWith("pm-board:") && !boards.some(board => `pm-board:${board.id}` === id))
|
||||
.map(id => ({ id, name: $t("Unavailable board: {id}", { id: id.slice(9) }) })),
|
||||
]);
|
||||
|
||||
const report = (reason: unknown) => { if (!disposed) error = reason instanceof Error ? reason.message : String(reason); };
|
||||
|
||||
function save(next: BackgroundSettings) {
|
||||
settings = next; error = "";
|
||||
writeBackground(next).catch(() => report(tr("Could not save the background settings.")));
|
||||
}
|
||||
|
||||
function saveImageAppearance(next: Appearance) {
|
||||
try {
|
||||
saveAppearance(next).catch(() => report(tr("Could not save appearance settings.")));
|
||||
appearance = readAppearance(); error = ""; return true;
|
||||
} catch { report(tr("Could not save appearance settings.")); return false; }
|
||||
}
|
||||
|
||||
function changeLayout(patch: Partial<BackgroundLayout>) {
|
||||
if (settings.source === "folder") save({ ...settings, ...patch });
|
||||
else if (image) saveImageAppearance({ ...appearance, newTabBackground: { ...image, ...patch } });
|
||||
}
|
||||
|
||||
function changeOverlay(input: HTMLInputElement) {
|
||||
const percent = input.valueAsNumber;
|
||||
if (!Number.isFinite(percent)) return;
|
||||
changeLayout({ overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 });
|
||||
}
|
||||
|
||||
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
|
||||
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
|
||||
}
|
||||
|
||||
async function chooseSource(source: BackgroundSource) {
|
||||
error = "";
|
||||
if (source === "folder" && !folder) { await chooseFolder(); return; }
|
||||
if (source === "image" && !hasImage(appearance)) { imageInput.click(); return; }
|
||||
save({ ...settings, source });
|
||||
}
|
||||
|
||||
async function chooseFolder() {
|
||||
try {
|
||||
const chosen = await folderHost.choose(tr("Choose the background folder"));
|
||||
if (!chosen || disposed) return;
|
||||
folder = chosen;
|
||||
save({ ...settings, source: "folder" });
|
||||
await sendBackgroundCommand("reload");
|
||||
void inspectFolder();
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
async function removeFolder() {
|
||||
try {
|
||||
await folderHost.clear();
|
||||
folder = null; folderNote = "";
|
||||
if (settings.source === "folder") save({ ...settings, source: "none" });
|
||||
await sendBackgroundCommand("reload");
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
/** Count the images of the folder, so that the user sees a problem at once. */
|
||||
async function inspectFolder() {
|
||||
if (!folder) { folderNote = ""; return; }
|
||||
try {
|
||||
const count = imageNames(await folderHost.list()).length;
|
||||
if (!disposed) folderNote = count ? tr(count === 1 ? "{count} image." : "{count} images.", { count }) : tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files.");
|
||||
} catch (reason) { if (!disposed) folderNote = reason instanceof Error ? reason.message : String(reason); }
|
||||
}
|
||||
|
||||
async function importImage(file?: File) {
|
||||
if (!file) return;
|
||||
const revision = ++imageRevision;
|
||||
try {
|
||||
if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)) throw new Error(tr("Choose a PNG, JPEG, WebP, or GIF image."));
|
||||
const imageId = await saveBackgroundImage(file);
|
||||
if (revision !== imageRevision) { await removeBackgroundImage(imageId); return; }
|
||||
const old = appearance.newTabBackground?.imageId;
|
||||
if (saveImageAppearance({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
|
||||
if (settings.source !== "image") save({ ...settings, source: "image" });
|
||||
if (old) await removeBackgroundImage(old);
|
||||
} else await removeBackgroundImage(imageId);
|
||||
} catch (reason) { if (revision === imageRevision) report(reason); }
|
||||
finally { if (revision === imageRevision) imageInput.value = ""; }
|
||||
}
|
||||
|
||||
async function removeImage() {
|
||||
imageRevision++;
|
||||
const old = appearance.newTabBackground?.imageId;
|
||||
if (saveImageAppearance({ ...appearance, newTabBackground: undefined }) && old) {
|
||||
try { await removeBackgroundImage(old); } catch { report(tr("Could not remove the saved image from storage.")); }
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTarget(id: string, on: boolean) {
|
||||
save({ ...settings, targets: on ? [...new Set([...settings.targets, id])] : settings.targets.filter(target => target !== id) });
|
||||
}
|
||||
|
||||
/** The active boards of `.runestone/pm/workspace.json`. It needs no Project Management code. */
|
||||
async function discoverBoards(on: boolean) {
|
||||
const revision = ++boardRevision;
|
||||
if (!on) {
|
||||
boards = []; boardsNote = tr("Turn on Project Management to show the background on one board.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const catalog = await readBoardCatalog();
|
||||
if (disposed || revision !== boardRevision) return;
|
||||
boards = catalog.boards.filter(board => !board.archived && boardId.test(board.id)).map(board => ({ id: board.id, name: board.name }));
|
||||
boardsNote = boards.length ? "" : tr("The workspace has no boards.");
|
||||
} catch (reason) {
|
||||
if (!disposed && revision === boardRevision) boardsNote = tr("Could not read the workspace boards: {error}", { error: reason instanceof Error ? reason.message : String(reason) });
|
||||
}
|
||||
}
|
||||
|
||||
/** The preview of the saved image. It uses its own blob URL, so it works in every window. */
|
||||
async function updatePreview() {
|
||||
const saved = settings.source === "image" ? appearance.newTabBackground : undefined;
|
||||
const key = saved && hasImage(appearance) ? saved.imageId ?? `${saved.image?.length}:${saved.image?.slice(-48)}` : "";
|
||||
if (key === previewKey) return;
|
||||
previewKey = key;
|
||||
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
||||
previewUrl = "";
|
||||
if (!key || !saved) return;
|
||||
try {
|
||||
const url = URL.createObjectURL(await readSavedImage(saved));
|
||||
if (disposed || previewKey !== key) { URL.revokeObjectURL(url); return; }
|
||||
previewUrl = url;
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
const overlayShade = $derived(layout ? `linear-gradient(rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}),rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}))` : "none");
|
||||
|
||||
$effect(() => { void settings.source; void appearance.newTabBackground; void updatePreview(); });
|
||||
|
||||
onMount(() => {
|
||||
const read = () => { settings = readBackground(); appearance = readAppearance(); };
|
||||
const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), featureSwitches.subscribe(switches => { void discoverBoards(switches.pm); })];
|
||||
void folderHost.current().then(value => { if (!disposed) { folder = value; void inspectFolder(); } }, () => { folder = null; });
|
||||
return () => stops.forEach(stop => stop());
|
||||
});
|
||||
onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); });
|
||||
</script>
|
||||
|
||||
<div class="background-settings">
|
||||
<div class="card">
|
||||
<div class="setting-row"><span>{$t("Background source")}</span><button class="picker" aria-label={$t("Background source")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Background source"), (["folder", "image", "none"] as const).map(source => ({ label: sourceLabels[source], checked: settings.source === source, run: () => void chooseSource(source) })))}>{sourceLabels[settings.source]}<Icon icon="chevron-down" /></button></div>
|
||||
{#if settings.source === "folder"}
|
||||
<div class="setting-row folder-row"><label for="background-folder">{$t("Image folder")}</label><div class="controls folder-controls">
|
||||
<input id="background-folder" readonly value={folder ?? ""} title={folder ?? ""} placeholder={$t("No folder selected")} />
|
||||
<button onclick={() => void chooseFolder()}><Icon icon="folder-open" />{$t("Choose folder…")}</button>
|
||||
{#if folder}<button onclick={() => void removeFolder()}>{$t("Remove folder")}</button>{/if}
|
||||
</div></div>
|
||||
<div class="setting-row"><label for="background-seconds">{$t("Seconds per image")}</label><input id="background-seconds" type="number" min="1" max="86400" step="1" value={settings.seconds}
|
||||
onchange={event => { if (event.currentTarget.reportValidity()) save({ ...settings, seconds: event.currentTarget.valueAsNumber }); }} /></div>
|
||||
<div class="setting-row"><span>{$t("Image order")}</span><button class="picker" aria-label={$t("Image order")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Image order"), (["name", "random"] as const).map(order => ({ label: orderLabels[order], checked: settings.order === order, run: () => save({ ...settings, order }) })))}>{orderLabels[settings.order]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="setting-row"><span>{$t("Slideshow")}</span><div class="controls">
|
||||
<button onclick={() => void sendBackgroundCommand("next").catch(report)}><Icon icon="arrow-right" />{$t("Next image")}</button>
|
||||
<button aria-pressed={settings.paused} onclick={() => save({ ...settings, paused: !settings.paused })}>{settings.paused ? $t("Resume slideshow") : $t("Pause slideshow")}</button>
|
||||
</div></div>
|
||||
{:else if settings.source === "image"}
|
||||
<div class="background-preview" role="img" aria-label={$t("Background image preview")}
|
||||
style:background-image={previewUrl ? `${overlayShade}, url("${previewUrl}")` : "none"}
|
||||
style:background-size={layout ? `100% 100%, ${layout.size}` : undefined}
|
||||
style:background-position={layout ? `center, ${layout.position}` : undefined}><span>{$t("Background")}</span></div>
|
||||
<div class="actions">
|
||||
<button onclick={() => imageInput.click()}>{$t("Choose image…")}</button>
|
||||
{#if image}<button onclick={() => void removeImage()}>{$t("Remove image")}</button>{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{#if layout}
|
||||
<div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Image position"), BACKGROUND_POSITIONS.map((value, index) => ({ label: positionLabels[index], checked: layout?.position === value, run: () => changeLayout({ position: value }) })))}>{positionLabels[BACKGROUND_POSITIONS.indexOf(layout.position)]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="setting-row"><span>{$t("Image size")}</span><button class="picker" aria-label={$t("Image size")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Image size"), BACKGROUND_SIZES.map((value, index) => ({ label: sizeLabels[index], checked: layout?.size === value, run: () => changeLayout({ size: value }) })))}>{sizeLabels[BACKGROUND_SIZES.indexOf(layout.size)]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="setting-row"><span>{$t("Image overlay")}</span><div class="controls overlay-controls">
|
||||
<input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round(layout.overlay * 100)} oninput={event => changeOverlay(event.currentTarget)} />
|
||||
<label class="overlay-value"><input type="number" aria-label={$t("Image overlay percentage")} min="-100" max="100" step="1" value={Math.round(layout.overlay * 100)}
|
||||
oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((layout?.overlay ?? 0) * 100)); }} /><span>%</span></label>
|
||||
</div></div>
|
||||
{/if}
|
||||
</div>
|
||||
<input bind:this={imageInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importImage(event.currentTarget.files?.[0])} />
|
||||
{#if settings.source === "folder"}
|
||||
<p>{$t("Add PNG, JPEG, GIF, or WebP images to the folder. Portrait images show in full over a blurred fill.")}</p>
|
||||
{#if folderNote}<p role="status">{folderNote}</p>{/if}
|
||||
{:else if settings.source === "image"}
|
||||
<p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image stays on this device.")}</p>
|
||||
{:else}
|
||||
<p>{$t("Choose a folder for a slideshow, or one image.")}</p>
|
||||
{/if}
|
||||
{#if layout}<p>{$t("Move the overlay left to lighten the image or right to darken it.")}</p>{/if}
|
||||
{#if settings.source === "folder" && folder}
|
||||
<ImageEditor {settings} />
|
||||
{/if}
|
||||
{#if settings.source !== "none"}
|
||||
<fieldset class="targets">
|
||||
<legend>{$t("Show the background in")}</legend>
|
||||
{#each targets as target (target.id)}
|
||||
<label class="check"><input type="checkbox" checked={settings.targets.includes(target.id)} onchange={event => toggleTarget(target.id, event.currentTarget.checked)} /><span>{target.name}</span></label>
|
||||
{/each}
|
||||
{#if boardsNote}<p>{boardsNote}</p>{/if}
|
||||
</fieldset>
|
||||
{/if}
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.background-settings { display: grid; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.card { padding: 0 var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); min-width: 0; }
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; min-width: 0; }
|
||||
.card > * + * { border-top: 1px solid var(--rs-border); }
|
||||
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; max-width: 100%; }
|
||||
.folder-controls { flex: 1 1 320px; justify-content: flex-end; }
|
||||
.folder-controls input { flex: 1 1 160px; min-width: 120px; width: 0; }
|
||||
input:not([type=checkbox]):not([type=range]), button { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
button { display: inline-flex; align-items: center; gap: 6px; background: var(--rs-bg-elevated); cursor: pointer; }
|
||||
button:hover { background: var(--rs-bg-active); }
|
||||
button[aria-pressed="true"] { border-color: var(--rs-accent); }
|
||||
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
.picker { max-width: 100%; background: var(--rs-bg); }
|
||||
input[type=number] { width: 88px; }
|
||||
:is(button, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; }
|
||||
.background-preview { height: 120px; margin-top: var(--rs-settings-row-padding); background-color: var(--rs-bg); background-repeat: no-repeat; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); display: grid; place-items: center; }
|
||||
.background-preview span { padding: 8px 14px; background: var(--rs-bg-elevated); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range] { width: 160px; max-width: 100%; min-width: 0; appearance: none; background: transparent; height: var(--rs-settings-control-height); margin: 0; cursor: pointer; }
|
||||
.overlay-controls input[type=range]::-webkit-slider-runnable-track { height: 6px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range]::-webkit-slider-thumb { appearance: none; width: 18px; height: 18px; margin-top: -7px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
||||
.overlay-controls input[type=range]::-moz-range-track { height: 4px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range]::-moz-range-thumb { width: 14px; height: 14px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
||||
.overlay-controls input[type=range]:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; border-radius: var(--rs-control-radius); }
|
||||
.overlay-value { display: flex; align-items: center; gap: 4px; }
|
||||
.overlay-value input { width: 64px; }
|
||||
.targets { display: grid; gap: 2px; min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
||||
.targets legend { padding: 0 4px; color: var(--rs-text); }
|
||||
.check { display: flex; align-items: center; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); overflow-wrap: anywhere; }
|
||||
.check input { flex-shrink: 0; accent-color: var(--rs-accent); }
|
||||
[role=alert] { color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -0,0 +1,227 @@
|
||||
<!--
|
||||
The appearance of one image of the folder: fit, position, and overlay. It saves the sidecar file of the folder
|
||||
(`.runestone-backgrounds.json`) only when the file did not change since the read. Then every window reads it again.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, untrack } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { BACKGROUND_POSITIONS } from "$lib/theme/appearance";
|
||||
import { normalizeLayout, type BackgroundSettings } from "../backgroundSettings";
|
||||
import { folderHost, sendBackgroundCommand } from "./sources";
|
||||
import { imageAppearance, imageFits, imageNames, parseImageSettings, sidecarName, type ImageAppearance, type ImageSettings } from "./imageSettings";
|
||||
|
||||
let { settings }: { settings: BackgroundSettings } = $props();
|
||||
|
||||
let names = $state<string[]>([]);
|
||||
let selected = $state("");
|
||||
let query = $state("");
|
||||
let pickerOpen = $state(false);
|
||||
let draft = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
||||
let baseline = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
||||
let saved = $state<ImageSettings>({ schema: 1, images: {} });
|
||||
let source: string | null = null;
|
||||
let url = $state("");
|
||||
let portrait = false;
|
||||
let loaded = $state(false);
|
||||
let busy = $state(false);
|
||||
let status = $state({ text: "", error: false });
|
||||
let generation = 0;
|
||||
let closed = false;
|
||||
let closeMenu = () => {};
|
||||
let trigger: HTMLButtonElement | undefined = $state();
|
||||
let search: HTMLInputElement | undefined = $state();
|
||||
const pickerId = $props.id();
|
||||
|
||||
const filtered = $derived(names.filter(name => name.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())));
|
||||
const fitLabels = $derived<Record<string, string>>({ cover: $t("Fill"), contain: $t("Fit"), auto: $t("Actual size"), blurred: $t("Full image with blurred fill") });
|
||||
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
|
||||
const changed = $derived(draft.fit !== baseline.fit || draft.position !== baseline.position || draft.overlay !== baseline.overlay);
|
||||
|
||||
const report = (reason: unknown) => { if (!closed) status = { text: reason instanceof Error ? reason.message : String(reason), error: true }; };
|
||||
|
||||
/** The values that differ from the inherited appearance. Only these go to the file. */
|
||||
function changes(): Partial<ImageAppearance> {
|
||||
return {
|
||||
...(draft.fit !== baseline.fit ? { fit: draft.fit } : {}),
|
||||
...(draft.position !== baseline.position ? { position: draft.position } : {}),
|
||||
...(draft.overlay !== baseline.overlay ? { overlay: draft.overlay } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const revision = ++generation;
|
||||
loaded = false; pickerOpen = false; names = [];
|
||||
if (url) URL.revokeObjectURL(url);
|
||||
url = "";
|
||||
try {
|
||||
const [text, list] = await Promise.all([folderHost.readSidecar(), folderHost.list()]);
|
||||
if (closed || revision !== generation) return;
|
||||
saved = parseImageSettings(text); source = text;
|
||||
names = imageNames(list);
|
||||
if (!names.includes(selected)) selected = names[0] ?? "";
|
||||
if (selected) await choose(selected);
|
||||
else status = { text: tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."), error: false };
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
async function choose(name: string) {
|
||||
const revision = ++generation;
|
||||
selected = name; loaded = false;
|
||||
if (url) URL.revokeObjectURL(url);
|
||||
url = "";
|
||||
try {
|
||||
const next = URL.createObjectURL(await folderHost.read(name));
|
||||
try {
|
||||
const image = new Image(); image.src = next; await image.decode();
|
||||
if (closed || revision !== generation) { URL.revokeObjectURL(next); return; }
|
||||
portrait = image.naturalHeight > image.naturalWidth;
|
||||
} catch (error) { URL.revokeObjectURL(next); throw error; }
|
||||
url = next;
|
||||
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
||||
baseline = { ...draft };
|
||||
loaded = true;
|
||||
status = { text: saved.images[name] ? tr("Saved appearance.") : tr("Default appearance."), error: false };
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
/** A change of the folder layout changes the inherited values. Keep the edits of the user. */
|
||||
function inherit() {
|
||||
if (!loaded) return;
|
||||
const next = imageAppearance(normalizeLayout(settings), saved.images[selected], portrait);
|
||||
if (next.fit === baseline.fit && next.position === baseline.position && next.overlay === baseline.overlay) return;
|
||||
const edited = changes();
|
||||
baseline = next;
|
||||
draft = { ...next, ...edited };
|
||||
}
|
||||
|
||||
async function write(reset: boolean) {
|
||||
if (!loaded || busy) return;
|
||||
const edited = changes();
|
||||
if (!reset && !Object.keys(edited).length) return;
|
||||
busy = true;
|
||||
const revision = generation, name = selected;
|
||||
try {
|
||||
const next = structuredClone($state.snapshot(saved)) as ImageSettings;
|
||||
if (reset) delete next.images[name]; else next.images[name] = { ...next.images[name], ...edited };
|
||||
const contents = JSON.stringify(next, null, 2) + "\n";
|
||||
await folderHost.writeSidecar(contents, source);
|
||||
if (closed || revision !== generation) return;
|
||||
source = contents; saved = next;
|
||||
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
||||
baseline = { ...draft };
|
||||
status = { text: reset ? tr("Default appearance restored.") : tr("Image appearance saved."), error: false };
|
||||
await sendBackgroundCommand("reload");
|
||||
} catch (reason) { report(reason); }
|
||||
finally { busy = false; }
|
||||
}
|
||||
|
||||
function menu(event: MouseEvent, field: "fit" | "position") {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
const values: readonly string[] = field === "fit" ? imageFits : BACKGROUND_POSITIONS;
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === "fit" ? $t("Image fit") : $t("Position of this image"), parent: anchor.closest("dialog") ?? undefined,
|
||||
items: values.map((value, index) => ({ label: field === "fit" ? fitLabels[value] : positionLabels[index], radio: true, checked: draft[field] === value,
|
||||
run: () => { draft = { ...draft, [field]: value }; } })) }).close;
|
||||
}
|
||||
|
||||
function overlay(input: HTMLInputElement) {
|
||||
if (input.validity.valid && Number.isFinite(input.valueAsNumber)) draft = { ...draft, overlay: Math.round(Math.max(-100, Math.min(100, input.valueAsNumber))) / 100 };
|
||||
}
|
||||
|
||||
function openPicker() {
|
||||
if (pickerOpen) { pickerOpen = false; return; }
|
||||
query = ""; pickerOpen = true;
|
||||
queueMicrotask(() => search?.focus());
|
||||
}
|
||||
|
||||
function pick(name: string) {
|
||||
pickerOpen = false;
|
||||
void choose(name).then(() => trigger?.focus());
|
||||
}
|
||||
|
||||
function moveFocus(event: KeyboardEvent, list: HTMLElement) {
|
||||
const rows = [...list.querySelectorAll<HTMLButtonElement>("button")];
|
||||
if (!rows.length) return;
|
||||
const index = rows.indexOf(document.activeElement as HTMLButtonElement);
|
||||
const next = event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : index < 0 ? (event.key === "ArrowDown" ? 0 : rows.length - 1) : Math.max(0, Math.min(rows.length - 1, index + (event.key === "ArrowDown" ? 1 : -1)));
|
||||
event.preventDefault();
|
||||
rows[next].focus();
|
||||
}
|
||||
|
||||
$effect(() => { void settings.size; void settings.position; void settings.overlay; untrack(inherit); });
|
||||
void load();
|
||||
onDestroy(() => { closed = true; generation++; closeMenu(); if (url) URL.revokeObjectURL(url); });
|
||||
</script>
|
||||
|
||||
<details class="image-editor">
|
||||
<summary>{$t("Per-image appearance")}</summary>
|
||||
<p>{$t("Choose an image to change its fit, position, and overlay. Portrait images show in full over a blurred fill by default.")}</p>
|
||||
<fieldset disabled={busy}>
|
||||
<div class="row"><span>{$t("Image")}</span>
|
||||
<button bind:this={trigger} class="choice" aria-label={$t("Image to change")} aria-expanded={pickerOpen} aria-controls={pickerId} disabled={!names.length} onclick={openPicker}>
|
||||
<span class="name">{selected || $t("Choose an image")}</span><Icon icon="chevron-down" /></button></div>
|
||||
{#if pickerOpen}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions (Escape closes the picker.) -->
|
||||
<div id={pickerId} class="rs-picker image-picker" onkeydown={event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); pickerOpen = false; trigger?.focus(); } }}>
|
||||
<input bind:this={search} type="search" aria-label={$t("Find an image")} placeholder={$t("Find an image")} bind:value={query}
|
||||
onkeydown={event => { if (event.key === "ArrowDown" || event.key === "ArrowUp") moveFocus(event, event.currentTarget.nextElementSibling as HTMLElement); else if (event.key === "Enter" && filtered[0]) { event.preventDefault(); pick(filtered[0]); } }} />
|
||||
<div class="options" role="listbox" aria-label={$t("Image files")} tabindex="-1"
|
||||
onkeydown={event => { if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) moveFocus(event, event.currentTarget); }}>
|
||||
{#each filtered.slice(0, 100) as name (name)}
|
||||
<button class="rs-picker-row" role="option" tabindex="-1" aria-selected={name === selected} onclick={() => pick(name)}>{name}</button>
|
||||
{/each}
|
||||
</div>
|
||||
<p role="status">{!filtered.length ? $t("No matching images.") : filtered.length > 100 ? $t("{count} matches. Type more of the name to see other images.", { count: filtered.length }) : $t(filtered.length === 1 ? "{count} image." : "{count} images.", { count: filtered.length })}</p>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="preview" role="img" aria-label={selected ? $t("Selected image preview: {name}", { name: selected }) : $t("Selected image preview")}>
|
||||
{#if url}
|
||||
{#if draft.fit === "blurred"}<span class="fill" style:background-image={`url("${url}")`}></span>{/if}
|
||||
<span class="foreground" style:background-image={`url("${url}")`} style:background-size={draft.fit === "blurred" ? "contain" : draft.fit} style:background-position={draft.position}></span>
|
||||
{/if}
|
||||
<span class="shade" style:background={draft.overlay < 0 ? "white" : "black"} style:opacity={String(Math.abs(draft.overlay))}></span>
|
||||
</div>
|
||||
<div class="row"><span>{$t("Fit")}</span><button class="choice" aria-label={$t("Image fit")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "fit")}>{fitLabels[draft.fit]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="row"><span>{$t("Position")}</span><button class="choice" aria-label={$t("Position of this image")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "position")}>{positionLabels[BACKGROUND_POSITIONS.indexOf(draft.position)]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="row"><span>{$t("Overlay")}</span><div class="controls">
|
||||
<input type="range" min="-100" max="100" aria-label={$t("Overlay of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} />
|
||||
<input type="number" min="-100" max="100" step="1" required aria-label={$t("Overlay percentage of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} /><span>%</span>
|
||||
</div></div>
|
||||
<div class="controls">
|
||||
<button disabled={!loaded || !changed} onclick={() => void write(false)}><Icon icon="save" />{$t("Save image appearance")}</button>
|
||||
<button disabled={!loaded || !saved.images[selected]} onclick={() => void write(true)}><Icon icon="undo" />{$t("Reset image appearance")}</button>
|
||||
<button onclick={() => void load()}><Icon icon="refresh" />{$t("Reload image settings")}</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
{#if status.text}<p role={status.error ? "alert" : "status"} class:error={status.error}>{status.text}</p>{/if}
|
||||
</details>
|
||||
|
||||
<style>
|
||||
.image-editor { display: grid; gap: var(--rs-settings-gap); min-width: 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
||||
summary { cursor: pointer; min-height: var(--rs-settings-control-height); line-height: var(--rs-settings-control-height); border-radius: var(--rs-control-radius); }
|
||||
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.error { color: var(--rs-error); }
|
||||
fieldset { display: grid; gap: var(--rs-settings-gap); min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: 0; border: 0; }
|
||||
.row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
button:not(.rs-picker-row), input:not([type=range]) { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
button:not(.rs-picker-row) { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
|
||||
button:not(.rs-picker-row):hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||
button:disabled, input:disabled { opacity: .55; cursor: default; }
|
||||
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
:is(button, input, summary):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.choice { max-width: 100%; min-width: 0; }
|
||||
.choice .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
input[type=number] { width: 72px; }
|
||||
input[type=range] { width: 160px; max-width: 100%; accent-color: var(--rs-accent); }
|
||||
.image-picker { display: grid; gap: var(--rs-settings-gap); width: 100%; min-width: 0; position: static; }
|
||||
.image-picker input { width: 100%; min-width: 0; }
|
||||
.options { display: grid; gap: 2px; max-height: 220px; overflow: auto; min-width: 0; }
|
||||
.options button { justify-content: flex-start; text-align: left; overflow-wrap: anywhere; }
|
||||
.preview { position: relative; width: 100%; height: 170px; overflow: hidden; border-radius: var(--rs-control-radius); background-color: var(--rs-bg-active); }
|
||||
.fill, .foreground, .shade { position: absolute; inset: 0; background-repeat: no-repeat; pointer-events: none; }
|
||||
.fill { inset: -24px; filter: blur(18px); background-size: cover; background-position: center; }
|
||||
</style>
|
||||
@@ -0,0 +1,83 @@
|
||||
// The blurred fill of a portrait image. One worker does the decode, the resize, and the filter away from the
|
||||
// input and paint work of the window. It lives as long as the Background instance.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
|
||||
const workerSource = `
|
||||
self.onmessage = async ({ data: { id, url, width, height } }) => {
|
||||
let image;
|
||||
try {
|
||||
const source = await (await fetch(url)).blob();
|
||||
image = await createImageBitmap(source, { resizeWidth: width, resizeHeight: height, resizeQuality: 'high' });
|
||||
const canvas = new OffscreenCanvas(width, height);
|
||||
const context = canvas.getContext('2d');
|
||||
context.filter = 'blur(24px)';
|
||||
context.drawImage(image, -48, -48, width + 96, height + 96);
|
||||
self.postMessage({ id, blob: await canvas.convertToBlob({ type: 'image/png' }) });
|
||||
} catch (error) {
|
||||
self.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
|
||||
} finally { image?.close(); }
|
||||
};`;
|
||||
|
||||
/** The size of the blurred copy. Its long side is at most 1024 pixels. */
|
||||
export function blurSize(width: number, height: number): { width: number; height: number } {
|
||||
const scale = Math.min(1, 1024 / Math.max(width, height, 1));
|
||||
return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
|
||||
}
|
||||
|
||||
export class BlurWorker {
|
||||
private worker?: Worker;
|
||||
private workerUrl?: string;
|
||||
private serial = 0;
|
||||
private pending = new Map<number, { resolve: (blob: Blob) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||
|
||||
/** A blob URL of the blurred copy of the image at `url`. The caller releases it. */
|
||||
async blur(url: string, width: number, height: number): Promise<string> {
|
||||
const size = blurSize(width, height);
|
||||
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") return URL.createObjectURL(await this.inWindow(url, size));
|
||||
const worker = this.start();
|
||||
const id = ++this.serial;
|
||||
const blob = await new Promise<Blob>((resolve, reject) => {
|
||||
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(tr("The blurred image took too long to load."))); }, 10000);
|
||||
this.pending.set(id, { resolve, reject, timer });
|
||||
worker.postMessage({ id, url, ...size });
|
||||
});
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
private start(): Worker {
|
||||
if (this.worker) return this.worker;
|
||||
this.workerUrl = URL.createObjectURL(new Blob([workerSource], { type: "text/javascript" }));
|
||||
const worker = this.worker = new Worker(this.workerUrl);
|
||||
worker.onmessage = ({ data }) => {
|
||||
const request = this.pending.get(data?.id);
|
||||
if (!request) return;
|
||||
this.pending.delete(data.id); clearTimeout(request.timer);
|
||||
if (data.blob instanceof Blob) request.resolve(data.blob);
|
||||
else request.reject(new Error(data.error || tr("Cannot create the blurred image.")));
|
||||
};
|
||||
worker.onerror = () => this.fail(new Error(tr("Cannot create the blurred image.")));
|
||||
return worker;
|
||||
}
|
||||
|
||||
/** A fallback for a window without OffscreenCanvas. */
|
||||
private async inWindow(url: string, size: { width: number; height: number }): Promise<Blob> {
|
||||
const image = new Image(); image.src = url; await image.decode();
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = size.width; canvas.height = size.height;
|
||||
const context = canvas.getContext("2d")!;
|
||||
context.filter = "blur(24px)";
|
||||
context.drawImage(image, -48, -48, size.width + 96, size.height + 96);
|
||||
return new Promise<Blob>((resolve, reject) => canvas.toBlob(value => value ? resolve(value) : reject(new Error(tr("Cannot create the blurred image."))), "image/png"));
|
||||
}
|
||||
|
||||
private fail(error: Error) {
|
||||
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
|
||||
this.pending.clear();
|
||||
// A failed worker starts again at the next request.
|
||||
this.worker?.terminate(); this.worker = undefined;
|
||||
if (this.workerUrl) URL.revokeObjectURL(this.workerUrl);
|
||||
this.workerUrl = undefined;
|
||||
}
|
||||
|
||||
dispose() { this.fail(new Error(tr("This feature is off."))); }
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
// The Background engine: it shows the images of a source as background frames, one after the other.
|
||||
// It comes from the engine of the Background Slideshow plugin, with these changes for the open card
|
||||
// "Lag before image transition": the next image loads and decodes before its fade, the blurred fills of the
|
||||
// last images stay in a cache, and the folder list and the sidecar are read again only after a settings change,
|
||||
// on window focus, or after every 10 images.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { BackgroundFrame } from "../../plugins/backgroundContracts.ts";
|
||||
import type { BackgroundLayout } from "../backgroundSettings.ts";
|
||||
import { imageAppearance, imageNames, parseImageSettings, sequence, type ImageAppearance, type ImageSettings } from "./imageSettings.ts";
|
||||
|
||||
/** The time of the fade from one image to the next. */
|
||||
export const transitionMs = 2000;
|
||||
/** The folder list and the sidecar are read again after this number of images. */
|
||||
export const RESCAN_SLIDES = 10;
|
||||
/** The number of blurred fills that stay in the cache. */
|
||||
export const BLUR_CACHE = 3;
|
||||
/** The shortest wait before a new try after an error. */
|
||||
export const RETRY_MS = 5000;
|
||||
|
||||
/** Where the images come from: the image folder of the host, or the one saved image. */
|
||||
export interface ImageSource {
|
||||
/** A different key means a different folder or image. The engine then starts again. */
|
||||
readonly key: string;
|
||||
/** True for a folder: the images change on a timer, and the sidecar and the portrait default apply. */
|
||||
readonly timed: boolean;
|
||||
/** The image names. */
|
||||
list(): Promise<string[]>;
|
||||
read(name: string): Promise<Blob>;
|
||||
/** The text of the sidecar file, or null. */
|
||||
sidecar(): Promise<string | null>;
|
||||
}
|
||||
|
||||
export interface LoadedImage { url: string; width: number; height: number }
|
||||
|
||||
/** The browser services of the engine. Tests replace them. */
|
||||
export interface Runtime {
|
||||
/** Make a blob URL and decode the image before it shows. */
|
||||
load(blob: Blob): Promise<LoadedImage>;
|
||||
/** Make the blurred fill of a loaded image. The engine releases the URL. */
|
||||
blur(image: LoadedImage): Promise<string>;
|
||||
release(url: string): void;
|
||||
later(callback: () => void, milliseconds: number): unknown;
|
||||
cancel(timer: unknown): void;
|
||||
random(): number;
|
||||
now(): number;
|
||||
}
|
||||
|
||||
export interface Frames { set(target: string, frame: BackgroundFrame | null): void }
|
||||
|
||||
export interface EngineSettings extends BackgroundLayout {
|
||||
seconds: number;
|
||||
order: "name" | "random";
|
||||
paused: boolean;
|
||||
targets: string[];
|
||||
}
|
||||
|
||||
export interface Status { message: string; image: string | null; count: number; error: boolean }
|
||||
|
||||
interface Shown { name: string; key: string; image: LoadedImage; appearance: ImageAppearance; blurred?: string }
|
||||
interface Prepared { name: string; key: string; image: LoadedImage }
|
||||
|
||||
function toFrame(shown: Shown): BackgroundFrame {
|
||||
const frame: BackgroundFrame = { url: shown.image.url, overlay: shown.appearance.overlay, position: shown.appearance.position,
|
||||
size: shown.appearance.fit === "blurred" ? "contain" : shown.appearance.fit };
|
||||
if (shown.blurred) frame.blurredUrl = shown.blurred;
|
||||
return frame;
|
||||
}
|
||||
|
||||
const sameAppearance = (a: ImageAppearance, b: ImageAppearance) => a.fit === b.fit && a.position === b.position && a.overlay === b.overlay;
|
||||
|
||||
export class Slideshow {
|
||||
status: Status = { message: "", image: null, count: 0, error: false };
|
||||
private source: ImageSource | null = null;
|
||||
private settings: EngineSettings | null = null;
|
||||
private revision = 0;
|
||||
private stopped = false;
|
||||
private timer: unknown;
|
||||
/** When the current timer fires, or null without a timer. */
|
||||
private due: number | null = null;
|
||||
private names: string[] | null = null;
|
||||
private imageSettings: ImageSettings = { schema: 1, images: {} };
|
||||
private sidecarError = "";
|
||||
private stale = true;
|
||||
private slides = 0;
|
||||
private shown: Shown | null = null;
|
||||
/** The image that the current frame fades from. */
|
||||
private previous: Shown | null = null;
|
||||
private targets = new Set<string>();
|
||||
/** The blurred fills, oldest first. */
|
||||
private blurs = new Map<string, string>();
|
||||
private prepared: { name: string; work: Promise<Prepared | null>; discarded: boolean } | null = null;
|
||||
/** Changes at each `clear`, so that a late blurred fill of an old image does not enter the cache. */
|
||||
private epoch = 0;
|
||||
private listeners = new Set<() => void>();
|
||||
private frames: Frames;
|
||||
private runtime: Runtime;
|
||||
|
||||
constructor(frames: Frames, runtime: Runtime) { this.frames = frames; this.runtime = runtime; }
|
||||
|
||||
subscribe(listener: () => void) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
|
||||
private notify() { for (const listener of [...this.listeners]) listener(); }
|
||||
|
||||
/** Use a new source or new settings. The current image stays when the source is the same and still has it. */
|
||||
configure(source: ImageSource | null, settings: EngineSettings): Promise<void> {
|
||||
if (this.stopped) return Promise.resolve();
|
||||
if (source?.key !== this.source?.key) {
|
||||
this.clear();
|
||||
this.names = null;
|
||||
}
|
||||
this.source = source;
|
||||
this.settings = { ...settings, targets: [...settings.targets] };
|
||||
this.stale = true;
|
||||
return this.update(false);
|
||||
}
|
||||
|
||||
/** Read the list and the sidecar again before the next image, for example after a window focus. */
|
||||
invalidate() { this.stale = true; }
|
||||
|
||||
/** Read the list and the sidecar again now, and apply them to the current image. */
|
||||
reload = () => { this.stale = true; return this.update(false); };
|
||||
|
||||
/** Show the next image now. */
|
||||
next = () => this.update(true);
|
||||
|
||||
dispose() {
|
||||
if (this.stopped) return;
|
||||
this.stopped = true; this.revision++;
|
||||
this.runtime.cancel(this.timer); this.timer = undefined;
|
||||
this.clear(); this.listeners.clear();
|
||||
}
|
||||
|
||||
private async update(advance: boolean): Promise<void> {
|
||||
if (this.stopped) return;
|
||||
const revision = ++this.revision;
|
||||
const remaining = this.due === null ? null : Math.max(0, this.due - this.runtime.now());
|
||||
this.runtime.cancel(this.timer); this.timer = undefined; this.due = null;
|
||||
const valid = () => !this.stopped && revision === this.revision;
|
||||
const source = this.source, settings = this.settings;
|
||||
try {
|
||||
if (!source || !settings) { this.clear(); this.setStatus(tr("Choose a folder or an image to show a background.")); return; }
|
||||
if (!settings.targets.length) { this.clear(); this.setStatus(tr("Select where to show the background.")); return; }
|
||||
if (this.stale || !this.names) {
|
||||
const [list, sidecar] = await Promise.all([source.list(), source.timed ? source.sidecar() : Promise.resolve(null)]);
|
||||
if (!valid()) return;
|
||||
this.names = source.timed ? imageNames(list) : [...list];
|
||||
try { this.imageSettings = parseImageSettings(sidecar); this.sidecarError = ""; }
|
||||
catch (reason) { this.imageSettings = { schema: 1, images: {} }; this.sidecarError = reason instanceof Error ? reason.message : String(reason); }
|
||||
this.stale = false; this.slides = 0;
|
||||
if (this.prepared && !this.names.includes(this.prepared.name)) this.discardPrepared();
|
||||
}
|
||||
const names = this.names;
|
||||
this.status.count = names.length;
|
||||
if (!names.length) throw new Error(tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."));
|
||||
const shown = this.shown;
|
||||
if (shown && names.includes(shown.name) && (!advance || names.length === 1)) {
|
||||
await this.reapply(shown, settings, valid);
|
||||
if (!valid()) return;
|
||||
this.schedule(remaining ?? settings.seconds * 1000, revision);
|
||||
this.prepare();
|
||||
return;
|
||||
}
|
||||
let failures = 0;
|
||||
const order = sequence(names, shown?.name ?? null, settings.order, this.runtime.random);
|
||||
const candidates = this.prepared && order.includes(this.prepared.name) ? [this.prepared.name, ...order.filter(name => name !== this.prepared!.name)] : order;
|
||||
for (const name of candidates) {
|
||||
let loaded: Prepared | null = null;
|
||||
let next: Shown;
|
||||
try {
|
||||
loaded = await this.load(name);
|
||||
if (!valid()) { if (loaded) this.runtime.release(loaded.image.url); return; }
|
||||
if (!loaded) throw new Error(tr("The image cannot be displayed."));
|
||||
next = { ...loaded, appearance: this.appearanceOf(name, loaded.image, settings) };
|
||||
if (next.appearance.fit === "blurred") {
|
||||
next.blurred = await this.blurOf(loaded);
|
||||
if (!valid()) { this.runtime.release(loaded.image.url); return; }
|
||||
}
|
||||
} catch {
|
||||
if (loaded) this.runtime.release(loaded.image.url);
|
||||
if (!valid()) return;
|
||||
failures++; continue;
|
||||
}
|
||||
this.publish(next, settings, true);
|
||||
const message = failures ? tr("{name}: skipped {count} unreadable images.", { name, count: failures }) : name;
|
||||
this.status = { image: name, count: names.length, error: !!this.sidecarError, message: this.sidecarError ? `${message} ${this.sidecarError}` : message };
|
||||
this.notify();
|
||||
if (++this.slides >= RESCAN_SLIDES) this.stale = true;
|
||||
this.schedule(settings.seconds * 1000, revision);
|
||||
this.prepare();
|
||||
return;
|
||||
}
|
||||
throw new Error(tr("No readable images in this folder. Check the image files."));
|
||||
} catch (error) {
|
||||
if (!valid()) return;
|
||||
this.clear();
|
||||
this.status = { ...this.status, image: null, error: true, message: error instanceof Error ? error.message : String(error) };
|
||||
this.notify();
|
||||
if (source?.timed && settings) this.schedule(Math.max(RETRY_MS, settings.seconds * 1000), revision, true);
|
||||
}
|
||||
}
|
||||
|
||||
private setStatus(message: string) {
|
||||
this.status = { message, image: null, count: 0, error: false };
|
||||
this.notify();
|
||||
}
|
||||
|
||||
private appearanceOf(name: string, image: LoadedImage, settings: EngineSettings): ImageAppearance {
|
||||
if (!this.source?.timed) return { fit: settings.size, position: settings.position, overlay: settings.overlay };
|
||||
return imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
|
||||
}
|
||||
|
||||
/** The image of `name`: the prepared image when it matches, or a new read. */
|
||||
private async load(name: string): Promise<Prepared | null> {
|
||||
const prepared = this.prepared;
|
||||
if (prepared?.name === name) {
|
||||
this.prepared = null;
|
||||
const result = await prepared.work.catch(() => null);
|
||||
if (result) return result;
|
||||
}
|
||||
const source = this.source!;
|
||||
const blob = await source.read(name);
|
||||
const image = await this.runtime.load(blob);
|
||||
return { name, key: `${source.key}\n${name}\n${blob.size}`, image };
|
||||
}
|
||||
|
||||
/** Load and decode the next image of a timed source now, so that its fade starts on time. */
|
||||
private prepare() {
|
||||
const source = this.source, settings = this.settings, names = this.names, shown = this.shown;
|
||||
if (!source?.timed || !settings || settings.paused || !names || names.length < 2 || !shown || this.prepared) return;
|
||||
const name = sequence(names, shown.name, settings.order, this.runtime.random)[0];
|
||||
const entry: { name: string; work: Promise<Prepared | null>; discarded: boolean } = { name, work: Promise.resolve(null), discarded: false };
|
||||
entry.work = (async (): Promise<Prepared | null> => {
|
||||
const blob = await source.read(name);
|
||||
const image = await this.runtime.load(blob);
|
||||
// A prepared image that nobody wants any more goes away at once.
|
||||
if (this.stopped || entry.discarded) { this.runtime.release(image.url); return null; }
|
||||
const result = { name, key: `${source.key}\n${name}\n${blob.size}`, image };
|
||||
const appearance = imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
|
||||
if (appearance.fit === "blurred") await this.blurOf(result).catch(() => undefined);
|
||||
return result;
|
||||
})();
|
||||
entry.work.catch(() => undefined);
|
||||
this.prepared = entry;
|
||||
}
|
||||
|
||||
private discardPrepared() {
|
||||
const prepared = this.prepared;
|
||||
this.prepared = null;
|
||||
if (!prepared) return;
|
||||
prepared.discarded = true;
|
||||
void prepared.work.then(result => { if (result) this.runtime.release(result.image.url); }, () => undefined);
|
||||
}
|
||||
|
||||
/** The blurred fill of an image, from the cache when possible. */
|
||||
private async blurOf(image: Prepared): Promise<string> {
|
||||
const cached = this.blurs.get(image.key);
|
||||
if (cached) { this.blurs.delete(image.key); this.blurs.set(image.key, cached); return cached; }
|
||||
const epoch = this.epoch;
|
||||
const url = await this.runtime.blur(image.image);
|
||||
if (this.stopped || epoch !== this.epoch) { this.runtime.release(url); throw new Error(tr("The background changed.")); }
|
||||
const again = this.blurs.get(image.key);
|
||||
if (again) { this.runtime.release(url); return again; }
|
||||
this.blurs.set(image.key, url);
|
||||
this.trimBlurs(url);
|
||||
return url;
|
||||
}
|
||||
|
||||
/** Release the oldest blurred fills beyond the cache size. Fills that a frame shows stay. */
|
||||
private trimBlurs(keep?: string) {
|
||||
const used = new Set([this.shown?.blurred, this.previous?.blurred, keep]);
|
||||
for (const [key, url] of this.blurs) {
|
||||
if (this.blurs.size <= BLUR_CACHE) break;
|
||||
if (used.has(url)) continue;
|
||||
this.blurs.delete(key); this.runtime.release(url);
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply new settings or new image settings to the image that shows, without a fade. */
|
||||
private async reapply(shown: Shown, settings: EngineSettings, valid: () => boolean) {
|
||||
const appearance = this.appearanceOf(shown.name, shown.image, settings);
|
||||
const sameTargets = settings.targets.length === this.targets.size && settings.targets.every(target => this.targets.has(target));
|
||||
const needsBlur = appearance.fit === "blurred" && !shown.blurred;
|
||||
if (sameTargets && sameAppearance(appearance, shown.appearance) && !needsBlur) return;
|
||||
const next: Shown = { ...shown, appearance, blurred: undefined };
|
||||
if (appearance.fit === "blurred") {
|
||||
next.blurred = await this.blurOf(shown);
|
||||
if (!valid()) return;
|
||||
}
|
||||
this.publish(next, settings, false);
|
||||
this.notify();
|
||||
}
|
||||
|
||||
/** Show `next` on every target. With `fade`, the frame fades from the image that showed before. */
|
||||
private publish(next: Shown, settings: EngineSettings, fade: boolean) {
|
||||
const old = this.shown;
|
||||
const frame = toFrame(next);
|
||||
if (fade && old) { frame.previous = toFrame(old); frame.transitionMs = transitionMs; }
|
||||
try {
|
||||
for (const target of this.targets) if (!settings.targets.includes(target)) this.frames.set(target, null);
|
||||
// Track the new targets before the frames go out, so that a cleanup also clears a partial publish.
|
||||
for (const target of settings.targets) this.targets.add(target);
|
||||
for (const target of settings.targets) this.frames.set(target, frame);
|
||||
} catch (error) {
|
||||
if (next.image !== old?.image) this.runtime.release(next.image.url);
|
||||
throw error;
|
||||
}
|
||||
this.targets = new Set(settings.targets);
|
||||
// Keep the image of the fade until the next frame replaces it.
|
||||
const release = this.previous;
|
||||
if (release && release.image !== next.image && release.image !== old?.image) this.runtime.release(release.image.url);
|
||||
this.previous = fade && old && old.image !== next.image ? old : null;
|
||||
if (!fade && old && old.image !== next.image) this.runtime.release(old.image.url);
|
||||
this.shown = next;
|
||||
this.trimBlurs();
|
||||
}
|
||||
|
||||
/** Remove the frames of every target and release every image. */
|
||||
private clear() {
|
||||
for (const target of this.targets) { try { this.frames.set(target, null); } catch { /* The window can close before the cleanup. */ } }
|
||||
this.targets.clear();
|
||||
const images = new Set([this.shown?.image.url, this.previous?.image.url]);
|
||||
for (const url of images) if (url) this.runtime.release(url);
|
||||
for (const url of this.blurs.values()) this.runtime.release(url);
|
||||
this.blurs.clear();
|
||||
this.epoch++;
|
||||
this.discardPrepared();
|
||||
this.shown = null; this.previous = null;
|
||||
this.status = { ...this.status, image: null };
|
||||
}
|
||||
|
||||
private schedule(milliseconds: number, revision: number, retry = false) {
|
||||
const settings = this.settings;
|
||||
if (this.stopped || this.revision !== revision || !this.source?.timed || !settings) return;
|
||||
if (settings.paused && !retry) return;
|
||||
this.due = this.runtime.now() + milliseconds;
|
||||
this.timer = this.runtime.later(() => { this.timer = undefined; this.due = null; void this.update(true); }, milliseconds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// The per-image settings: the sidecar file `.runestone-backgrounds.json` in the image folder.
|
||||
// The Background Slideshow plugin used the same file, so the settings of each image stay.
|
||||
import { BACKGROUND_POSITIONS } from "../../theme/appearance.ts";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { BackgroundLayout, BackgroundPosition } from "../backgroundSettings.ts";
|
||||
|
||||
export const sidecarName = ".runestone-backgrounds.json";
|
||||
/** `blurred` shows the full image over a blurred copy that fills the view. Portrait images use it by default. */
|
||||
export const imageFits = ["cover", "contain", "auto", "blurred"] as const;
|
||||
export type ImageFit = typeof imageFits[number];
|
||||
export interface ImageAppearance { fit: ImageFit; position: BackgroundPosition; overlay: number }
|
||||
/** Unknown keys of the file and of each image stay when RuneStone saves the file. */
|
||||
export interface ImageSettings { schema: 1; images: Record<string, Partial<ImageAppearance>>; [key: string]: unknown }
|
||||
|
||||
/** Read the sidecar text. `null` (no file) gives empty settings. Invalid settings throw an error. */
|
||||
export function parseImageSettings(source: string | null): ImageSettings {
|
||||
if (source === null) return { schema: 1, images: {} };
|
||||
const value = JSON.parse(source);
|
||||
if (!value || value.schema !== 1 || !value.images || typeof value.images !== "object" || Array.isArray(value.images)) {
|
||||
throw new Error(tr("The image settings file must use schema 1 and an images object."));
|
||||
}
|
||||
for (const [name, raw] of Object.entries(value.images)) {
|
||||
const appearance = raw as Partial<ImageAppearance>;
|
||||
if (!name || /[\\/]/.test(name) || !appearance || typeof appearance !== "object" || Array.isArray(appearance)
|
||||
|| ("fit" in appearance && !imageFits.includes(appearance.fit!))
|
||||
|| ("position" in appearance && !BACKGROUND_POSITIONS.includes(appearance.position!))
|
||||
|| ("overlay" in appearance && (typeof appearance.overlay !== "number" || !Number.isFinite(appearance.overlay) || Math.abs(appearance.overlay) > 1))) {
|
||||
throw new Error(tr("Invalid image settings for {name}.", { name }));
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** The appearance of one image: the folder layout, the portrait default, then the saved values of the image. */
|
||||
export function imageAppearance(layout: BackgroundLayout, override: Partial<ImageAppearance> | undefined, portrait: boolean): ImageAppearance {
|
||||
return { fit: portrait ? "blurred" : layout.size, position: layout.position, overlay: layout.overlay, ...override };
|
||||
}
|
||||
|
||||
/** The supported image names, without duplicates, in natural order. */
|
||||
export function imageNames(names: readonly string[]): string[] {
|
||||
return [...new Set(names.filter(name => !/[\\/]/.test(name) && /\.(png|jpe?g|gif|webp)$/i.test(name)))]
|
||||
.sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }) || a.localeCompare(b, "en"));
|
||||
}
|
||||
|
||||
/** The order of the next images after `current`. A random order puts the current image last. */
|
||||
export function sequence(names: readonly string[], current: string | null, order: "name" | "random", random = Math.random): string[] {
|
||||
if (order === "name") {
|
||||
const index = current === null ? -1 : names.indexOf(current);
|
||||
return [...names.slice(index + 1), ...names.slice(0, index + 1)];
|
||||
}
|
||||
const rest = names.filter(name => name !== current);
|
||||
for (let i = rest.length - 1; i > 0; i--) {
|
||||
const j = Math.min(i, Math.max(0, Math.floor(random() * (i + 1))));
|
||||
[rest[i], rest[j]] = [rest[j], rest[i]];
|
||||
}
|
||||
return current && names.includes(current) ? [...rest, current] : rest;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// The Background feature. `loader.ts` imports this module when a folder or an image is selected (`launch.ts`),
|
||||
// at a palette command, or when Appearance → Background shows its settings.
|
||||
// It shows the images through `backgroundHub`, so the workarea, browser tabs, and Project Management boards get the frames.
|
||||
import { mount, unmount } from "svelte";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { backgroundHub } from "../../plugins/backgrounds.ts";
|
||||
import { readAppearance } from "../../theme/appearance.ts";
|
||||
import { hasImage, normalizeLayout, onBackgroundChange, readBackground, writeBackground } from "../backgroundSettings.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||
import { BlurWorker } from "./blur.ts";
|
||||
import { Slideshow, type ImageSource } from "./engine.ts";
|
||||
import { browserRuntime, folderHost, folderSource, imageSource, onBackgroundCommand, sendBackgroundCommand } from "./sources.ts";
|
||||
import BackgroundSettings from "./BackgroundSettings.svelte";
|
||||
|
||||
export function start(_context: FeatureContext): FeatureInstance {
|
||||
const owner = Symbol("background");
|
||||
const blur = new BlurWorker();
|
||||
const engine = new Slideshow({ set: (target, frame) => backgroundHub.set(owner, target, frame) }, browserRuntime(blur));
|
||||
/** The host folder for display. `undefined` until the first read. */
|
||||
let folder: string | null | undefined;
|
||||
let generation = 0;
|
||||
let disposed = false;
|
||||
/** The last source and settings. A change of another appearance setting, such as the theme, gives the same value. */
|
||||
let applied = "";
|
||||
|
||||
/** Give the engine the current source and settings. `reread` asks the host for its folder again. */
|
||||
async function apply(reread: boolean) {
|
||||
const run = ++generation;
|
||||
const settings = readBackground();
|
||||
const appearance = readAppearance();
|
||||
let source: ImageSource | null = null;
|
||||
let layout = normalizeLayout(settings);
|
||||
if (settings.source === "folder") {
|
||||
if (reread || folder === undefined) {
|
||||
try { folder = await folderHost.current(); } catch { folder = null; }
|
||||
if (disposed || run !== generation) return;
|
||||
}
|
||||
source = folder ? folderSource(folder) : null;
|
||||
} else if (settings.source === "image" && hasImage(appearance)) {
|
||||
source = imageSource(appearance.newTabBackground!);
|
||||
layout = normalizeLayout(appearance.newTabBackground);
|
||||
}
|
||||
const next = { ...settings, ...layout };
|
||||
const signature = JSON.stringify([source?.key ?? null, next]);
|
||||
if (!reread && signature === applied) return;
|
||||
applied = signature;
|
||||
await engine.configure(source, next);
|
||||
}
|
||||
|
||||
const stopSettings = onBackgroundChange(() => { void apply(false); });
|
||||
const stopCommands = onBackgroundCommand(command => {
|
||||
if (command === "next") void engine.next();
|
||||
else { engine.invalidate(); void apply(true); }
|
||||
});
|
||||
// Another window or program can change the folder. A focus reads the folder, the list, and the sidecar again.
|
||||
const focus = () => { engine.invalidate(); void apply(true); };
|
||||
window.addEventListener("focus", focus);
|
||||
void apply(true);
|
||||
|
||||
return {
|
||||
mount() { throw new Error(tr("This view is unavailable.")); },
|
||||
async run(command) {
|
||||
if (command === "next") await sendBackgroundCommand("next");
|
||||
else if (command === "pause") {
|
||||
const settings = readBackground();
|
||||
await writeBackground({ ...settings, paused: !settings.paused });
|
||||
} else throw new Error(tr("This command is unavailable."));
|
||||
},
|
||||
dispose() {
|
||||
disposed = true; generation++;
|
||||
stopSettings(); stopCommands();
|
||||
window.removeEventListener("focus", focus);
|
||||
engine.dispose();
|
||||
blur.dispose();
|
||||
backgroundHub.removeOwner(owner);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The settings of Appearance → Background. They work also in a window where Background does not run. */
|
||||
export function mountSettings(element: HTMLElement) {
|
||||
const component = mount(BackgroundSettings, { target: element });
|
||||
return () => { void unmount(component); };
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// The image sources of Background, the host folder commands (`src-tauri/src/backgrounds.rs`), the browser runtime of the
|
||||
// engine, and the commands that reach the Background instance of every window.
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { emit, listen } from "@tauri-apps/api/event";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { readBackgroundImage } from "../../theme/backgroundImages.ts";
|
||||
import type { Appearance } from "../../theme/appearance.ts";
|
||||
import type { BlurWorker } from "./blur.ts";
|
||||
import type { ImageSource, LoadedImage, Runtime } from "./engine.ts";
|
||||
|
||||
const types: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
|
||||
const typeOf = (name: string) => types[name.split(".").pop()!.toLowerCase()] ?? "application/octet-stream";
|
||||
|
||||
/** The host commands of the image folder. The host keeps the folder, so no command takes a path. */
|
||||
export const folderHost = {
|
||||
/** Show the folder dialog. Returns the chosen folder for display, or null after Cancel. */
|
||||
choose: (title: string) => invoke<string | null>("background_choose_folder", { title }),
|
||||
/** The current folder for display, or null. */
|
||||
current: () => invoke<string | null>("background_folder"),
|
||||
clear: () => invoke<void>("background_clear_folder"),
|
||||
list: () => invoke<string[]>("background_list"),
|
||||
read: async (name: string): Promise<Blob> => {
|
||||
const bytes = await invoke<ArrayBuffer | Uint8Array | number[]>("background_read", { name });
|
||||
return new Blob([bytes instanceof ArrayBuffer ? bytes : Uint8Array.from(bytes)], { type: typeOf(name) });
|
||||
},
|
||||
readSidecar: () => invoke<string | null>("background_read_sidecar"),
|
||||
writeSidecar: (contents: string, expected: string | null) => invoke<void>("background_write_sidecar", { contents, expected }),
|
||||
};
|
||||
|
||||
/** The images of the host folder. `folder` is the path for display. It makes the key, so another folder starts again. */
|
||||
export function folderSource(folder: string): ImageSource {
|
||||
return { key: `folder:${folder}`, timed: true, list: folderHost.list, read: folderHost.read, sidecar: folderHost.readSidecar };
|
||||
}
|
||||
|
||||
/** The saved image of Appearance, from IndexedDB or from an old data URL. */
|
||||
export async function readSavedImage(background: NonNullable<Appearance["newTabBackground"]>): Promise<Blob> {
|
||||
if (background.imageId) {
|
||||
const blob = await readBackgroundImage(background.imageId);
|
||||
if (!blob) throw new Error(tr("The saved background image is missing. Choose the image again."));
|
||||
return blob;
|
||||
}
|
||||
const image = background.image ?? "";
|
||||
const [header, data] = image.split(",");
|
||||
const bytes = Uint8Array.from(atob(data ?? ""), character => character.charCodeAt(0));
|
||||
return new Blob([bytes], { type: header.slice(5, header.indexOf(";")) });
|
||||
}
|
||||
|
||||
/** A short hash of a data URL, so that another old image gets another key. */
|
||||
function hash(text: string): string {
|
||||
let value = 0x811c9dc5;
|
||||
for (let index = 0; index < text.length; index++) value = Math.imul(value ^ text.charCodeAt(index), 0x01000193);
|
||||
return (value >>> 0).toString(16);
|
||||
}
|
||||
|
||||
/** The one saved image. It has no timer. */
|
||||
export function imageSource(background: NonNullable<Appearance["newTabBackground"]>): ImageSource {
|
||||
const id = background.imageId ?? `data:${background.image?.length ?? 0}:${hash(background.image ?? "")}`;
|
||||
return { key: `image:${id}`, timed: false, list: async () => ["image"], read: () => readSavedImage(background), sidecar: async () => null };
|
||||
}
|
||||
|
||||
/** Make a blob URL and decode the image before it shows, so the fade does not wait for the decode. */
|
||||
export async function loadImage(blob: Blob): Promise<LoadedImage> {
|
||||
const url = URL.createObjectURL(blob);
|
||||
try {
|
||||
const image = new Image();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
image.src = url;
|
||||
await Promise.race([image.decode(), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(tr("The image took too long to load."))), 10000); })])
|
||||
.finally(() => clearTimeout(timer));
|
||||
return { url, width: image.naturalWidth, height: image.naturalHeight };
|
||||
} catch (error) { URL.revokeObjectURL(url); throw error; }
|
||||
}
|
||||
|
||||
export function browserRuntime(blur: BlurWorker): Runtime {
|
||||
return {
|
||||
load: loadImage,
|
||||
blur: image => blur.blur(image.url, image.width, image.height),
|
||||
release: url => URL.revokeObjectURL(url),
|
||||
later: (callback, milliseconds) => setTimeout(callback, milliseconds),
|
||||
cancel: timer => clearTimeout(timer as ReturnType<typeof setTimeout>),
|
||||
random: Math.random,
|
||||
now: () => Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
/** `next` shows the next image. `reload` reads the folder, the list, and the sidecar again. */
|
||||
export type BackgroundCommand = "next" | "reload";
|
||||
const EVENT = "background-command";
|
||||
|
||||
/** Send a command to the Background instance of every window, this window too. */
|
||||
export async function sendBackgroundCommand(command: BackgroundCommand): Promise<void> {
|
||||
if (isTauri()) await emit(EVENT, command);
|
||||
else window.dispatchEvent(new CustomEvent(EVENT, { detail: command }));
|
||||
}
|
||||
|
||||
/** Receive the commands of every window. Returns the function that stops it. */
|
||||
export function onBackgroundCommand(listener: (command: BackgroundCommand) => void): () => void {
|
||||
const accept = (value: unknown) => { if (value === "next" || value === "reload") listener(value); };
|
||||
if (!isTauri()) {
|
||||
const handle = (event: Event) => accept((event as CustomEvent).detail);
|
||||
window.addEventListener(EVENT, handle);
|
||||
return () => window.removeEventListener(EVENT, handle);
|
||||
}
|
||||
let stopped = false;
|
||||
let off: (() => void) | undefined;
|
||||
void listen<unknown>(EVENT, event => accept(event.payload)).then(unlisten => { if (stopped) unlisten(); else off = unlisten; }, () => undefined);
|
||||
return () => { stopped = true; off?.(); };
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// The settings of the Background feature: the `background` section of the settings file.
|
||||
// This file is in the main bundle, because the launch rule and the first-start migration need it without the feature code.
|
||||
// The image source keeps its image and its layout in `appearance.newTabBackground`, so an older version still shows it.
|
||||
// The host keeps the image folder itself (`src-tauri/src/backgrounds.rs`). The interface never sends a folder path.
|
||||
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
|
||||
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, type Appearance } from "../theme/appearance.ts";
|
||||
import type { LegacyPlugin } from "./migration.ts";
|
||||
|
||||
export const BACKGROUND_SOURCES = ["folder", "image", "none"] as const;
|
||||
export type BackgroundSource = typeof BACKGROUND_SOURCES[number];
|
||||
export type BackgroundPosition = typeof BACKGROUND_POSITIONS[number];
|
||||
export type BackgroundSize = typeof BACKGROUND_SIZES[number];
|
||||
/** The views that show the background: the workspace, all Project Management boards, or one board. */
|
||||
export const BACKGROUND_TARGET = /^(?:app|pm-all|pm-board:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
||||
|
||||
export interface BackgroundLayout {
|
||||
/** From -1 (white) to 1 (black). */
|
||||
overlay: number;
|
||||
position: BackgroundPosition;
|
||||
size: BackgroundSize;
|
||||
}
|
||||
|
||||
export interface BackgroundSettings extends BackgroundLayout {
|
||||
source: BackgroundSource;
|
||||
/** The time of each image of a folder, from 1 to 86,400 seconds. */
|
||||
seconds: number;
|
||||
order: "name" | "random";
|
||||
/** A paused folder keeps its current image. */
|
||||
paused: boolean;
|
||||
targets: string[];
|
||||
}
|
||||
|
||||
export const DEFAULT_BACKGROUND: Readonly<BackgroundSettings> = Object.freeze({
|
||||
source: "none", seconds: 60, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover",
|
||||
});
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
/** The folder layout fields from any value. Invalid fields take the defaults. */
|
||||
export function normalizeLayout(value: unknown): BackgroundLayout {
|
||||
const raw = record(value);
|
||||
return {
|
||||
overlay: typeof raw.overlay === "number" && Number.isFinite(raw.overlay) ? Math.max(-1, Math.min(1, raw.overlay)) : 0,
|
||||
position: BACKGROUND_POSITIONS.includes(raw.position as BackgroundPosition) ? raw.position as BackgroundPosition : "center",
|
||||
size: BACKGROUND_SIZES.includes(raw.size as BackgroundSize) ? raw.size as BackgroundSize : "cover",
|
||||
};
|
||||
}
|
||||
|
||||
/** Valid settings from any value. Invalid fields take the defaults. */
|
||||
export function normalizeBackground(value: unknown): BackgroundSettings {
|
||||
const raw = record(value);
|
||||
return {
|
||||
source: BACKGROUND_SOURCES.includes(raw.source as BackgroundSource) ? raw.source as BackgroundSource : "none",
|
||||
seconds: typeof raw.seconds === "number" && Number.isFinite(raw.seconds) ? Math.max(1, Math.min(86400, Math.round(raw.seconds))) : 60,
|
||||
order: raw.order === "random" ? "random" : "name",
|
||||
paused: raw.paused === true,
|
||||
targets: Array.isArray(raw.targets)
|
||||
? [...new Set(raw.targets.filter((target): target is string => typeof target === "string" && BACKGROUND_TARGET.test(target)))]
|
||||
: ["app"],
|
||||
...normalizeLayout(raw),
|
||||
};
|
||||
}
|
||||
|
||||
export function readBackground(): BackgroundSettings {
|
||||
return normalizeBackground(readSection("background"));
|
||||
}
|
||||
|
||||
/** Save the settings. Keys of a newer version stay. */
|
||||
export function writeBackground(next: BackgroundSettings): Promise<void> {
|
||||
return writeSection("background", { ...record(readSection("background")), ...normalizeBackground(next) });
|
||||
}
|
||||
|
||||
/** True when the appearance has a saved background image. */
|
||||
export function hasImage(appearance: Appearance = readAppearance()): boolean {
|
||||
return !!(appearance.newTabBackground?.image || appearance.newTabBackground?.imageId);
|
||||
}
|
||||
|
||||
/** True when Background has something to show: a folder, or an image that exists. */
|
||||
export function hasBackgroundSource(settings: BackgroundSettings = readBackground(), appearance: Appearance = readAppearance()): boolean {
|
||||
return settings.source === "folder" || (settings.source === "image" && hasImage(appearance));
|
||||
}
|
||||
|
||||
/** Run `listener` after each change of the background or appearance settings. Returns the function that stops it. */
|
||||
export function onBackgroundChange(listener: () => void): () => void {
|
||||
const stops = [onSettingsChange("background", listener), onSettingsChange("appearance", listener)];
|
||||
return () => stops.forEach(stop => stop());
|
||||
}
|
||||
|
||||
/** The host side of the first-start migration of the `background` section. */
|
||||
export interface BackgroundMigrationHost {
|
||||
/** True when the settings file has no `background` section. */
|
||||
missing(): boolean;
|
||||
/** True when the appearance has a saved background image. */
|
||||
hasImage(): boolean;
|
||||
/** Copy the folder of the old plugin grant to the host. True when the host has a folder after the call. */
|
||||
migrateFolder(): Promise<boolean>;
|
||||
write(value: BackgroundSettings): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the `background` section from the old Background Slideshow plugin and the old background image.
|
||||
* The source is the folder when the plugin was installed, enabled, and on, and its folder migrated.
|
||||
* Otherwise it is the image when one exists. The kept plugin settings give the sequence, the targets, and the layout.
|
||||
*/
|
||||
export async function migrateBackground(legacy: LegacyPlugin | undefined, host: BackgroundMigrationHost): Promise<BackgroundSettings> {
|
||||
const kept = record(legacy?.settings);
|
||||
// Migrate the folder whenever a grant exists, so that a later choice of Folder brings it back.
|
||||
let folder = false;
|
||||
if (typeof kept.grant === "string" && kept.grant) {
|
||||
try { folder = await host.migrateFolder(); } catch (reason) { console.error("RuneStone could not take the old background folder.", reason); }
|
||||
}
|
||||
const slideshow = !!legacy?.installed && legacy.enabled && kept.enabled === true && folder;
|
||||
const copied = Object.fromEntries(["seconds", "order", "targets", "overlay", "position", "size"].filter(key => key in kept).map(key => [key, kept[key]]));
|
||||
const value = normalizeBackground({ ...copied, source: slideshow ? "folder" : host.hasImage() ? "image" : "none", paused: false });
|
||||
await host.write(value);
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// The native features of RuneStone. Each feature has an off switch in Settings → Features.
|
||||
// This file is in the main bundle, so it holds only small static data: names, views, commands, and document types.
|
||||
// The code of a feature loads with a dynamic import at first need (see `loader.ts`), and never while its switch is off.
|
||||
import { message, tr } from "../i18n/index.ts";
|
||||
import type { PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
|
||||
import { identifyPdf } from "./pdfDocument.ts";
|
||||
|
||||
export type FeatureId = "git" | "background" | "terminal" | "pdf" | "pm";
|
||||
|
||||
/** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */
|
||||
export interface FeatureViewInfo {
|
||||
id: string;
|
||||
/** Returns the title in the current language. */
|
||||
title: () => string;
|
||||
placement: "editor" | "sidebar";
|
||||
icon?: PluginView["icon"];
|
||||
/** Show a navigation button for the view. */
|
||||
navigation?: boolean;
|
||||
/** True when a launch, such as a ribbon button, asks the feature which view to open (`FeatureInstance.launch`). */
|
||||
launch?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A family of editor views whose IDs follow a pattern, for example one tab for each board. The session answers for each
|
||||
* matching ID before the feature module loads, so a tab transfer from another window can restore it.
|
||||
* The feature gives the real title later (`FeatureContext.setViewTitle`).
|
||||
*/
|
||||
export interface FeatureViewPattern {
|
||||
/** Matches the whole view ID. */
|
||||
match: RegExp;
|
||||
/** The title until the feature gives one. */
|
||||
title: () => string;
|
||||
icon?: PluginView["icon"];
|
||||
}
|
||||
|
||||
/** A command of a feature. The command palette lists it. */
|
||||
export interface FeatureCommandInfo {
|
||||
id: string;
|
||||
title: () => string;
|
||||
icon?: PluginCommand["icon"];
|
||||
/** The view that the command opens. Without a view, the command loads the feature and calls `FeatureInstance.run`. */
|
||||
view?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A document type of a feature. The file tree marks the files of the type, and a click opens them in a tab,
|
||||
* without the feature code. The first tab of the type loads the feature and calls `FeatureInstance.mountDocument`.
|
||||
*/
|
||||
export interface FeatureDocumentInfo {
|
||||
id: string;
|
||||
/** Returns the title in the current language. The file tree shows it as the tooltip of the file icon. */
|
||||
title: () => string;
|
||||
icon: NonNullable<PluginDocumentType["icon"]>;
|
||||
/** Lowercase file extensions without the dot. */
|
||||
extensions: readonly string[];
|
||||
/** "binary" when `identify` needs no file contents. */
|
||||
content: "text" | "binary";
|
||||
/** The document ID of a file, or null when the file is not of this type. */
|
||||
identify(path: string, source: string): { id: string } | null;
|
||||
}
|
||||
|
||||
export interface FeatureEntry {
|
||||
id: FeatureId;
|
||||
/** The ID of the old plugin package. Saved tabs and tab transfers keep it as the owner ID. */
|
||||
owner: string;
|
||||
/** Catalog keys for Settings → Features. */
|
||||
name: string;
|
||||
description: string;
|
||||
/** Extra words for the Settings search. */
|
||||
keywords: string;
|
||||
/** The switch for a user who never installed the old package. */
|
||||
defaultOn: boolean;
|
||||
/** True when the first start gives the switch the state of the old package. False when every user gets `defaultOn`. */
|
||||
followsPackage: boolean;
|
||||
views: readonly FeatureViewInfo[];
|
||||
/** Editor views with IDs that follow a pattern. */
|
||||
viewPatterns?: readonly FeatureViewPattern[];
|
||||
commands: readonly FeatureCommandInfo[];
|
||||
documentTypes: readonly FeatureDocumentInfo[];
|
||||
}
|
||||
|
||||
export const FEATURES: readonly FeatureEntry[] = [
|
||||
{
|
||||
id: "git", owner: "runestone.git", name: message("Git"),
|
||||
description: message("Review changes, stage files, commit, and see the commit graph of the workspace repository."),
|
||||
keywords: "git source control commit stage diff graph branch push pull blame",
|
||||
defaultOn: true, followsPackage: true,
|
||||
views: [
|
||||
{ id: "source-control", title: () => tr("Source control"), placement: "sidebar", icon: "git", navigation: true },
|
||||
{ id: "diff", title: () => tr("Git diff"), placement: "editor", icon: "git" },
|
||||
{ id: "graph", title: () => tr("Git graph"), placement: "editor", icon: "git" },
|
||||
],
|
||||
commands: [{ id: "graph", title: () => tr("Show Git graph"), icon: "git", view: "graph" }],
|
||||
documentTypes: [],
|
||||
},
|
||||
{
|
||||
// Background replaces the Background Slideshow plugin and the background image of Appearance. Its settings are in
|
||||
// Appearance → Background. It loads at the start only when a folder or an image is selected (see `launch.ts`).
|
||||
id: "background", owner: "runestone.bg-slideshow", name: message("Background"),
|
||||
description: message("Show a folder of images as a slideshow, or one image, behind the workspace and the boards."),
|
||||
keywords: "background image wallpaper slideshow folder picture photo overlay blur",
|
||||
defaultOn: true, followsPackage: false,
|
||||
views: [],
|
||||
commands: [
|
||||
{ id: "next", title: () => tr("Next background image"), icon: "image" },
|
||||
{ id: "pause", title: () => tr("Pause background"), icon: "pause" },
|
||||
],
|
||||
documentTypes: [],
|
||||
},
|
||||
{
|
||||
// Terminal replaces the Terminal plugin. Its panel is not a view: the workbench and the terminal window show it
|
||||
// (`src/lib/features/TerminalHost.svelte`), and the first use loads the module. Its settings are in Settings → Terminal.
|
||||
id: "terminal", owner: "runestone.terminal", name: message("Terminal"),
|
||||
description: message("Run shells, tasks, and the active file in a panel below the editor or in a separate window."),
|
||||
keywords: "terminal shell console powershell bash cmd command prompt task run pty xterm",
|
||||
defaultOn: true, followsPackage: true,
|
||||
views: [],
|
||||
commands: [],
|
||||
documentTypes: [],
|
||||
},
|
||||
{
|
||||
// PDF Viewer replaces the PDF Viewer plugin. It has no view: its document type opens each PDF file in its own tab.
|
||||
// The file tree marks PDF files without the module. The first PDF tab loads the module and PDF.js.
|
||||
id: "pdf", owner: "runestone.pdf-viewer", name: message("PDF Viewer"),
|
||||
description: message("Read PDF files of the workspace in tabs, with page controls, zoom, rotation, and text selection."),
|
||||
keywords: "pdf document viewer page zoom rotate password pdf.js",
|
||||
defaultOn: true, followsPackage: true,
|
||||
views: [],
|
||||
commands: [],
|
||||
documentTypes: [
|
||||
{ id: "pdf", title: () => tr("PDF document"), icon: "file", extensions: ["pdf"], content: "binary", identify: identifyPdf },
|
||||
],
|
||||
},
|
||||
{
|
||||
// Project Management replaces the Project Management plugin. It reads only `.runestone/pm/` in the workspace, so the
|
||||
// file tree reads no Markdown file for it. Its ribbon button opens `planning`: the default board of the workspace, or
|
||||
// All tasks. Each board has its own tab, `board-<hex of the board ID>`, as in the plugin, so tab transfers between
|
||||
// the plugin and the feature work. Its settings are in Settings → Project Management (`ProjectManagementSettings.svelte`).
|
||||
id: "pm", owner: "runestone.pm", name: message("Project Management"),
|
||||
description: message("Plan work on Kanban boards, in All tasks, and on Gantt and calendar views. The cards stay in the workspace."),
|
||||
keywords: "project management kanban board card task list gantt calendar label priority backlog todo plan",
|
||||
defaultOn: true, followsPackage: true,
|
||||
views: [{ id: "planning", title: () => tr("Project Management"), placement: "editor", icon: "kanban", launch: true }],
|
||||
viewPatterns: [{ match: /^board-(?:[0-9a-f]{2})+$/, title: () => tr("Project Management"), icon: "kanban" }],
|
||||
commands: [],
|
||||
documentTypes: [],
|
||||
},
|
||||
];
|
||||
|
||||
export function featureEntry(id: FeatureId): FeatureEntry {
|
||||
const entry = FEATURES.find(item => item.id === id);
|
||||
if (!entry) throw new Error(`Unknown feature: ${id}`);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/** The feature that uses `owner` as its owner ID, if any. */
|
||||
export function featureOfOwner(owner: string): FeatureEntry | undefined {
|
||||
return FEATURES.find(item => item.owner === owner);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<script lang="ts">
|
||||
import { diffLineKind } from "./model";
|
||||
let { text, error = false, label }: { text: string; error?: boolean; label: string } = $props();
|
||||
const lines = $derived(text.split("\n"));
|
||||
</script>
|
||||
|
||||
<!-- One block element for each line, so that the add and remove fills cover the full width.
|
||||
The diff takes focus, so that a keyboard user can scroll it. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
|
||||
<pre class="diff" class:error tabindex="0" aria-label={label}>{#each lines as line, index (index)}<span class="line {diffLineKind(line)}">{line || " "}</span>{/each}</pre>
|
||||
|
||||
<style>
|
||||
.diff { flex: 1; min-height: 0; margin: 0; padding: 8px; overflow: auto; font: 12px/1.6 var(--rs-font-mono); font-weight: var(--rs-code-font-weight); tab-size: 4; background: var(--rs-image-editor-bg, var(--rs-bg)); border-radius: var(--rs-control-radius); }
|
||||
.diff:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.line { display: block; min-width: max-content; min-height: 1.6em; }
|
||||
.add { background: color-mix(in srgb, var(--rs-ok) 18%, transparent); }
|
||||
.remove { background: color-mix(in srgb, var(--rs-error) 18%, transparent); }
|
||||
.range { color: var(--rs-accent); }
|
||||
.error { color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -0,0 +1,39 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import DiffText from "./DiffText.svelte";
|
||||
import type { GitState } from "./state.svelte";
|
||||
|
||||
let { git, openFile }: { git: GitState; openFile: (path: string) => Promise<void> } = $props();
|
||||
let error = $state("");
|
||||
|
||||
const title = $derived(git.selected
|
||||
? git.selected.staged ? $t("{path} · Staged", { path: git.selected.path }) : $t("{path} · Working tree", { path: git.selected.path })
|
||||
: $t("Git diff"));
|
||||
|
||||
async function open() {
|
||||
if (!git.selected) return;
|
||||
error = "";
|
||||
try { await openFile(git.selected.path); }
|
||||
catch (reason) { error = String(reason); }
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="git-diff">
|
||||
<div class="header">
|
||||
<strong>{title}</strong>
|
||||
<button class="text-button" type="button" disabled={!git.selected} onclick={open}>{$t("Open file")}</button>
|
||||
</div>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<DiffText text={git.selected?.text ?? $t("Select a file in Source control to see its diff.")} error={!!git.selected?.error} label={$t("Git diff")} />
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.git-diff { display: flex; flex-direction: column; gap: 10px; height: 100%; padding: 12px; box-sizing: border-box; overflow: hidden; font-size: 13px; }
|
||||
.header { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
strong { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
||||
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
|
||||
.text-button:hover:not(:disabled) { background: var(--rs-hover-bg); }
|
||||
.text-button:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.text-button:disabled { color: var(--rs-text-dim); }
|
||||
.error { margin: 0; color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -0,0 +1,244 @@
|
||||
<script lang="ts">
|
||||
import { onMount, tick, untrack } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { attachTooltip } from "$lib/ui/tooltip";
|
||||
import { gitApi } from "$lib/git/service";
|
||||
import type { GitCommitDetails, GitCommitFile, GitGraph } from "$lib/git/contracts";
|
||||
import { graphLayout } from "./model";
|
||||
import DiffText from "./DiffText.svelte";
|
||||
import type { GitState } from "./state.svelte";
|
||||
|
||||
let { git }: { git: GitState } = $props();
|
||||
|
||||
const rowHeight = 30;
|
||||
const x = (lane: number) => 12 + lane * 18;
|
||||
const y = (row: number) => rowHeight / 2 + row * rowHeight;
|
||||
|
||||
let history = $state.raw<GitGraph | null>(null);
|
||||
let graphMessage = $state(tr("Loading history…"));
|
||||
let graphError = $state(false);
|
||||
let refreshing = $state(false);
|
||||
let detail = $state.raw<GitCommitDetails | null>(null);
|
||||
let detailMessage = $state(tr("Select a commit."));
|
||||
let diff = $state<{ text: string; error: boolean } | null>(null);
|
||||
let list: HTMLOListElement | undefined = $state();
|
||||
let disposed = false, generation = 0, selection = 0, fileRequest = 0;
|
||||
|
||||
const layout = $derived(graphLayout(history));
|
||||
|
||||
function tooltip(node: HTMLElement, text: string) {
|
||||
let current = text;
|
||||
const dispose = attachTooltip(node, () => current);
|
||||
return { update(value: string) { current = value; }, destroy: dispose };
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const request = ++generation;
|
||||
refreshing = true;
|
||||
try {
|
||||
const result = await gitApi.graph();
|
||||
if (disposed || request !== generation) return;
|
||||
history = result;
|
||||
graphError = false;
|
||||
graphMessage = result.commits.length ? "" : tr("No commits yet. Create a commit to start the graph.");
|
||||
const kept = result.commits.some(commit => commit.id === git.history.selectedId) ? git.history.selectedId : result.commits[0]?.id ?? null;
|
||||
if (kept) {
|
||||
if (kept !== detail?.id || kept !== git.history.selectedId) void select(kept);
|
||||
} else {
|
||||
git.history.selectedId = null;
|
||||
++selection; ++fileRequest;
|
||||
detail = null; diff = null;
|
||||
detailMessage = tr("No commit is selected.");
|
||||
}
|
||||
} catch (reason) {
|
||||
if (disposed || request !== generation) return;
|
||||
history = null;
|
||||
graphError = true;
|
||||
graphMessage = String(reason);
|
||||
++selection; ++fileRequest;
|
||||
detail = null; diff = null;
|
||||
detailMessage = tr("Select Refresh to try again.");
|
||||
} finally {
|
||||
if (!disposed && request === generation) refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function select(id: string) {
|
||||
git.history.selectedId = id;
|
||||
const request = ++selection;
|
||||
++fileRequest;
|
||||
detailMessage = tr("Loading commit…");
|
||||
try {
|
||||
const result = await gitApi.commitDetails(id);
|
||||
if (disposed || request !== selection) return;
|
||||
detail = result;
|
||||
diff = null;
|
||||
const file = result.files.find(item => item.path === git.history.file) ?? result.files[0];
|
||||
if (file) void selectFile(file, result);
|
||||
} catch (reason) {
|
||||
if (disposed || request !== selection) return;
|
||||
detail = null;
|
||||
detailMessage = String(reason);
|
||||
}
|
||||
}
|
||||
|
||||
async function selectFile(file: GitCommitFile, commit: GitCommitDetails) {
|
||||
git.history.file = file.path;
|
||||
const request = ++fileRequest;
|
||||
diff = { text: tr("Loading diff…"), error: false };
|
||||
try {
|
||||
const text = await gitApi.commitDiff(commit.id, file.path);
|
||||
if (disposed || request !== fileRequest || git.history.selectedId !== commit.id) return;
|
||||
diff = { text: text || tr("No text changes."), error: false };
|
||||
} catch (reason) {
|
||||
if (!disposed && request === fileRequest) diff = { text: String(reason), error: true };
|
||||
}
|
||||
}
|
||||
|
||||
async function keydown(event: KeyboardEvent) {
|
||||
const commits = layout.nodes;
|
||||
const index = commits.findIndex(commit => commit.id === git.history.selectedId);
|
||||
const next = event.key === "ArrowDown" ? Math.min(commits.length - 1, index + 1)
|
||||
: event.key === "ArrowUp" ? Math.max(0, index - 1)
|
||||
: event.key === "Home" ? 0 : event.key === "End" ? commits.length - 1 : -1;
|
||||
if (next < 0 || !commits[next]) return;
|
||||
event.preventDefault();
|
||||
void select(commits[next].id);
|
||||
await tick();
|
||||
list?.querySelector<HTMLButtonElement>(`[data-commit="${commits[next].id}"]`)?.focus();
|
||||
}
|
||||
|
||||
// The graph reads the history again after a commit, push, or pull, and on window focus.
|
||||
$effect(() => {
|
||||
void git.historyVersion;
|
||||
untrack(() => void refresh());
|
||||
});
|
||||
onMount(() => {
|
||||
const focus = () => void refresh();
|
||||
window.addEventListener("focus", focus);
|
||||
return () => { disposed = true; ++generation; ++selection; ++fileRequest; window.removeEventListener("focus", focus); };
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="git-graph" aria-label={$t("Git history")}>
|
||||
<div class="header">
|
||||
<strong>{$t("Commit graph")}</strong>
|
||||
<IconButton icon="refresh" label={$t("Refresh commit graph")} disabled={refreshing} onclick={() => void refresh()} />
|
||||
</div>
|
||||
<p class="hint">{$t("Latest 100 commits. Select a commit to see its files. Dashed lines continue beyond this history.")}</p>
|
||||
<div class="body">
|
||||
<div class="graph" aria-label={$t("Commit graph with branches, authors, and dates")}>
|
||||
{#if graphMessage}
|
||||
<p class:error={graphError}>{graphMessage}</p>
|
||||
{:else}
|
||||
<div class="canvas">
|
||||
<svg width={layout.lanes * 18 + 12} height={layout.nodes.length * rowHeight} aria-hidden="true" class="lines">
|
||||
{#each layout.edges as edge (`${edge.from}:${edge.to}`)}
|
||||
{@const middle = y(edge.row) + rowHeight / 2}
|
||||
<path class="edge" class:boundary={edge.outside} style:color={`var(--git-lane-${edge.color + 1})`}
|
||||
d={`M ${x(edge.lane)} ${y(edge.row)} C ${x(edge.lane)} ${middle} ${x(edge.parentLane)} ${middle} ${x(edge.parentLane)} ${y(edge.row) + rowHeight} L ${x(edge.parentLane)} ${y(edge.endRow)}`} />
|
||||
{/each}
|
||||
{#each layout.nodes as commit (commit.id)}
|
||||
<circle class="node" cx={x(commit.lane)} cy={y(commit.row)} r="4" style:color={`var(--git-lane-${commit.color + 1})`} />
|
||||
{/each}
|
||||
</svg>
|
||||
<ol role="listbox" aria-label={$t("Commits")} bind:this={list} onkeydown={keydown}>
|
||||
{#each layout.nodes as commit (commit.id)}
|
||||
{@const selected = commit.id === git.history.selectedId}
|
||||
<li>
|
||||
<button type="button" role="option" data-commit={commit.id} aria-selected={selected}
|
||||
tabindex={selected || (!git.history.selectedId && commit.row === 0) ? 0 : -1}
|
||||
use:tooltip={`${commit.summary}\n${commit.author} · ${commit.date}\n${commit.id}`}
|
||||
onclick={() => void select(commit.id)}>
|
||||
<span class="description">
|
||||
{#if commit.refs.length}<span class="refs">{commit.refs.join(" · ")}</span>{/if}
|
||||
<span class="summary">{commit.summary}</span>
|
||||
</span>
|
||||
<span class="meta author">{commit.author}</span>
|
||||
<span class="meta date">{commit.date}</span>
|
||||
<span class="meta">{commit.id.slice(0, 7)}</span>
|
||||
<span class="screen-reader">{commit.parents.length ? $t("Parents: {parents}", { parents: commit.parents.join(", ") }) : $t("Root commit")}</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ol>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<section class="details" aria-label={$t("Commit details")}>
|
||||
{#if detail}
|
||||
<div class="detail-meta">
|
||||
<strong>{detail.author}</strong>
|
||||
<time>{detail.date}</time>
|
||||
<code>{detail.id}</code>
|
||||
{#if detail.parents.length > 1}<span class="dim">{$t("Changes against the first parent.")}</span>{/if}
|
||||
</div>
|
||||
<p class="message">{detail.message}</p>
|
||||
<strong>{$t("Changed files: {count}", { count: detail.files.length })}</strong>
|
||||
<div class="files" aria-label={$t("Changed files")}>
|
||||
{#each detail.files as file (file.path)}
|
||||
<button type="button" class="file" aria-pressed={file.path === git.history.file}
|
||||
use:tooltip={file.originalPath ? `${file.originalPath} → ${file.path}` : file.path}
|
||||
onclick={() => void selectFile(file, detail!)}>
|
||||
<span>{file.path}</span><span class="dim">{file.status}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{#if diff}
|
||||
<DiffText text={diff.text} error={diff.error} label={$t("Commit file diff")} />
|
||||
{:else}
|
||||
<p class="dim">{detail.files.length ? $t("Select a file to see its diff.") : $t("This commit contains no file changes.")}</p>
|
||||
{/if}
|
||||
{:else}
|
||||
<p class="dim">{detailMessage}</p>
|
||||
{/if}
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.git-graph { container-type: inline-size; display: flex; flex-direction: column; gap: 6px; height: 100%; padding: 8px; box-sizing: border-box; overflow: hidden; font-size: 13px;
|
||||
--git-lane-1: #007fff; --git-lane-2: #ca7000; --git-lane-3: #f000ff; --git-lane-4: #00a000; --git-lane-5: #aa00ff; --git-lane-6: #ff0033; }
|
||||
.header, .hint { padding: 4px 6px; border-radius: var(--rs-control-radius); background: var(--rs-image-control-bg, var(--rs-bg)); }
|
||||
.header { display: flex; align-items: center; gap: 6px; }
|
||||
.header strong { flex: 1; }
|
||||
.hint { margin: 0; font-size: 11px; color: var(--rs-text-dim); }
|
||||
.body { display: grid; grid-template-columns: minmax(0, 1fr) minmax(260px, 32%); flex: 1; min-height: 0; min-width: 0; }
|
||||
.graph { min-height: 0; min-width: 0; padding: 4px; overflow: auto; background: var(--rs-image-editor-bg, var(--rs-bg)); }
|
||||
.graph p { margin: 8px; color: var(--rs-text-dim); }
|
||||
.graph p.error { color: var(--rs-error); }
|
||||
.canvas { display: flex; align-items: flex-start; min-width: 0; }
|
||||
.lines { flex: 0 0 auto; overflow: hidden; }
|
||||
.edge { fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
.boundary { stroke-dasharray: 3 3; }
|
||||
.node { fill: currentColor; stroke: currentColor; stroke-width: 2; }
|
||||
ol { flex: 1; min-width: 0; margin: 0; padding: 0; list-style: none; }
|
||||
li { height: 30px; min-width: 0; }
|
||||
ol button { display: grid; grid-template-columns: minmax(0, 1fr) 95px 78px 54px; align-items: center; gap: 8px; width: 100%; height: 30px; padding: 0 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
|
||||
ol button:hover { background: var(--rs-hover-bg); }
|
||||
ol button[aria-selected="true"], .file[aria-pressed="true"] { background: var(--rs-item-selection-bg); border-color: var(--rs-item-selection-border); }
|
||||
ol button:focus-visible, .file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.description { display: flex; align-items: center; gap: 5px; min-width: 0; }
|
||||
.summary, .refs, .meta { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.summary { flex: 1; }
|
||||
.refs { max-width: 45%; padding: 1px 4px; border-radius: var(--rs-control-radius); background: var(--rs-bg-active); color: var(--rs-accent); font-size: 11px; }
|
||||
.meta, .dim { color: var(--rs-text-dim); font-size: 11px; }
|
||||
.screen-reader { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
|
||||
.details { display: flex; flex-direction: column; gap: 8px; min-height: 0; min-width: 0; padding: 10px; overflow: auto; border-left: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-image-editor-bg, var(--rs-bg)); }
|
||||
.details p { margin: 0; }
|
||||
.detail-meta { display: flex; flex-direction: column; gap: 3px; overflow-wrap: anywhere; }
|
||||
time { color: var(--rs-text-dim); }
|
||||
code { font: 11px var(--rs-font-mono); overflow-wrap: anywhere; }
|
||||
.message { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.files { display: flex; flex-direction: column; flex-shrink: 0; max-height: 180px; overflow: auto; }
|
||||
.file { display: flex; flex-shrink: 0; align-items: center; gap: 6px; min-width: 0; min-height: 28px; padding: 3px 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
|
||||
.file:hover { background: var(--rs-hover-bg); }
|
||||
.file span:first-child { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.details :global(.diff) { min-height: 140px; }
|
||||
@container (max-width: 950px) { ol button { grid-template-columns: minmax(0, 1fr) 54px; } .author, .date { display: none; } }
|
||||
@container (max-width: 650px) {
|
||||
.body { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(140px, 45%) minmax(0, 1fr); }
|
||||
.details { border-left: 0; border-top: 1px solid var(--rs-border); }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,201 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { attachTooltip } from "$lib/ui/tooltip";
|
||||
import { keys } from "$lib/ui/shortcuts";
|
||||
import { gitApi } from "$lib/git/service";
|
||||
import type { GitChange, GitStatus } from "$lib/git/contracts";
|
||||
import { changeLabel, groups, isConflict, pathsFor } from "./model";
|
||||
import type { GitState } from "./state.svelte";
|
||||
|
||||
let { git, showDiff, showGraph, onWorkspaceChange }: {
|
||||
git: GitState;
|
||||
showDiff: (path: string, staged: boolean) => void;
|
||||
showGraph: () => void;
|
||||
onWorkspaceChange: (listener: () => void) => () => void;
|
||||
} = $props();
|
||||
|
||||
let snapshot = $state<GitStatus | null>(null);
|
||||
let busy = $state(false);
|
||||
let refreshing = $state(false);
|
||||
let message = $state("");
|
||||
let notice = $state({ text: tr("Loading repository…"), error: false });
|
||||
let disposed = false;
|
||||
let sequence = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const grouped = $derived(snapshot?.repository ? groups(snapshot.changes) : { staged: [], working: [] });
|
||||
const conflicts = $derived(!!snapshot?.changes.some(isConflict));
|
||||
const canCommit = $derived(!!snapshot?.repository && grouped.staged.length > 0 && !conflicts && message.trim().length > 0);
|
||||
|
||||
function tooltip(node: HTMLElement, text: string) {
|
||||
let current = text;
|
||||
const dispose = attachTooltip(node, () => current);
|
||||
return { update(value: string) { current = value; }, destroy: dispose };
|
||||
}
|
||||
function report(text: string, error = false) { notice = { text, error }; }
|
||||
|
||||
async function refresh(keepNotice = false) {
|
||||
if (disposed || busy) return;
|
||||
const request = ++sequence;
|
||||
refreshing = true;
|
||||
try {
|
||||
const result = await gitApi.status();
|
||||
if (disposed || request !== sequence) return;
|
||||
snapshot = result;
|
||||
if (!result.available) report(tr("Git is not installed. Install Git, then restart RuneStone."));
|
||||
else if (!result.repository) report(tr("Open a Git repository root as your workspace. Create repositories with Git outside RuneStone."));
|
||||
else if (result.changes.some(isConflict)) report(tr("Resolve the conflicts, then stage the files before you commit."));
|
||||
else if (!keepNotice) report(result.changes.length ? "" : tr("No changes. Your working tree is clean."));
|
||||
} catch (reason) {
|
||||
if (!disposed && request === sequence) { snapshot = null; report(String(reason), true); }
|
||||
} finally {
|
||||
if (request === sequence) refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Run one Git action at a time, then read the status again. */
|
||||
async function perform(action: () => Promise<void>, changesHistory = false) {
|
||||
if (busy || disposed) return;
|
||||
busy = true;
|
||||
clearTimeout(timer);
|
||||
++sequence;
|
||||
report("");
|
||||
try {
|
||||
await action();
|
||||
if (changesHistory) git.historyVersion++;
|
||||
} catch (reason) {
|
||||
if (!disposed) report(String(reason), true);
|
||||
} finally {
|
||||
busy = false;
|
||||
if (!disposed) await refresh(true);
|
||||
}
|
||||
}
|
||||
|
||||
function stage(changes: GitChange[], staged: boolean) {
|
||||
void perform(() => staged ? gitApi.unstage(pathsFor(changes)) : gitApi.stage(pathsFor(changes)));
|
||||
}
|
||||
function commit() {
|
||||
if (!canCommit) return;
|
||||
void perform(async () => {
|
||||
await gitApi.commit(message);
|
||||
message = "";
|
||||
report(tr("Commit created."));
|
||||
}, true);
|
||||
}
|
||||
function pull() {
|
||||
void perform(async () => {
|
||||
report(tr("Pull in progress…"));
|
||||
await gitApi.pull();
|
||||
report(tr("Pull complete. The branch is up to date."));
|
||||
}, true);
|
||||
}
|
||||
function push() {
|
||||
void perform(async () => {
|
||||
report(tr("Push in progress…"));
|
||||
await gitApi.push();
|
||||
report(tr("Push complete."));
|
||||
}, true);
|
||||
}
|
||||
function rowLabel(change: GitChange, staged: boolean) {
|
||||
const status = changeLabel(change, staged);
|
||||
return change.originalPath
|
||||
? $t("{path} — {status}, from {original}", { path: change.path, status, original: change.originalPath })
|
||||
: $t("{path} — {status}", { path: change.path, status });
|
||||
}
|
||||
|
||||
// The status refreshes after a workspace change, which includes the `.git` folder, and on window focus.
|
||||
function schedule() {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => void refresh(), 350);
|
||||
}
|
||||
onMount(() => {
|
||||
const off = onWorkspaceChange(schedule);
|
||||
window.addEventListener("focus", schedule);
|
||||
void refresh();
|
||||
return () => {
|
||||
disposed = true;
|
||||
sequence++;
|
||||
clearTimeout(timer);
|
||||
off();
|
||||
window.removeEventListener("focus", schedule);
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="source-control" aria-label={$t("Git source control")} aria-busy={busy}>
|
||||
<div class="header">
|
||||
<span class="branch" use:tooltip={snapshot?.branch ?? $t("Source control")}>{snapshot?.branch ?? $t("Source control")}</span>
|
||||
{#if snapshot?.repository}
|
||||
<IconButton icon="git" label={$t("Show Git graph")} disabled={busy} onclick={showGraph} />
|
||||
<IconButton icon="download" label={$t("Pull from the upstream branch")} disabled={busy} onclick={pull} />
|
||||
<IconButton icon="upload" label={$t("Push to the upstream branch")} disabled={busy} onclick={push} />
|
||||
{/if}
|
||||
<IconButton icon="refresh" label={$t("Refresh source control")} disabled={busy || refreshing} onclick={() => void refresh()} />
|
||||
</div>
|
||||
<p class="notice" class:error={notice.error} role="status" hidden={!notice.text}>{notice.text}</p>
|
||||
{#if snapshot?.repository}
|
||||
<form class="commit" onsubmit={event => { event.preventDefault(); commit(); }}>
|
||||
<textarea rows="3" maxlength="65536" placeholder={$t("Commit message")} aria-label={$t("Commit message")} disabled={busy} bind:value={message}
|
||||
onkeydown={event => { if ((event.ctrlKey || event.metaKey) && event.key === "Enter") { event.preventDefault(); commit(); } }}></textarea>
|
||||
<button class="primary" type="submit" disabled={busy || !canCommit}><Icon icon="check" /><span>{$t("Commit staged")}</span></button>
|
||||
<small>{$t("Only staged files enter the commit. Press {shortcut} to commit.", { shortcut: keys("Mod+Enter") })}</small>
|
||||
</form>
|
||||
<details class="changes" open>
|
||||
<summary>{$t("Changes ({count})", { count: snapshot.changes.length })}</summary>
|
||||
{#each [{ staged: true, changes: grouped.staged }, { staged: false, changes: grouped.working }] as group (group.staged)}
|
||||
{#if group.changes.length}
|
||||
<section class="group">
|
||||
<div class="group-header">
|
||||
<h3>{group.staged ? $t("Staged changes ({count})", { count: group.changes.length }) : $t("Unstaged changes ({count})", { count: group.changes.length })}</h3>
|
||||
<IconButton icon={group.staged ? "minus" : "plus"} label={group.staged ? $t("Unstage all") : $t("Stage all")} disabled={busy} onclick={() => stage(group.changes, group.staged)} />
|
||||
</div>
|
||||
{#each group.changes as change (change.path)}
|
||||
<div class="row">
|
||||
<button class="file" type="button" disabled={busy} aria-label={rowLabel(change, group.staged)} use:tooltip={rowLabel(change, group.staged)} onclick={() => showDiff(change.path, group.staged)}>
|
||||
<Icon icon="text" /><span>{change.path}</span>
|
||||
</button>
|
||||
<span class="status">{changeLabel(change, group.staged)}</span>
|
||||
<IconButton icon={group.staged ? "minus" : "plus"} label={group.staged ? $t("Unstage {path}", { path: change.path }) : $t("Stage {path}", { path: change.path })} disabled={busy} onclick={() => stage([change], group.staged)} />
|
||||
</div>
|
||||
{/each}
|
||||
</section>
|
||||
{/if}
|
||||
{/each}
|
||||
</details>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.source-control { display: flex; flex-direction: column; gap: 8px; height: 100%; min-width: 0; padding: 6px; overflow: auto; box-sizing: border-box; font-size: 13px; }
|
||||
.header { display: flex; align-items: center; gap: 2px; min-width: 0; }
|
||||
.branch { flex: 1; min-width: 0; padding-left: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
|
||||
.notice { margin: 0; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; color: var(--rs-text-dim); }
|
||||
.notice.error { color: var(--rs-error); }
|
||||
.notice[hidden] { display: none; }
|
||||
.commit { display: flex; flex-direction: column; gap: 5px; flex: 0 0 auto; }
|
||||
textarea { box-sizing: border-box; width: 100%; min-height: 60px; resize: vertical; padding: 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
textarea:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
|
||||
.primary { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 28px; padding: 3px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; font-weight: 600; }
|
||||
.primary:hover:not(:disabled) { background: var(--rs-hover-bg); }
|
||||
.primary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.primary:disabled { color: var(--rs-text-dim); }
|
||||
small { color: var(--rs-text-dim); line-height: 1.5; }
|
||||
.changes { min-width: 0; border-top: 1px solid var(--rs-border); }
|
||||
summary { padding: 8px 4px; border-radius: var(--rs-control-radius); cursor: pointer; font-weight: 600; }
|
||||
summary:hover { background: var(--rs-hover-bg); }
|
||||
summary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.group { margin-bottom: 6px; }
|
||||
.group-header { display: flex; align-items: center; gap: 6px; padding-bottom: 4px; }
|
||||
h3 { flex: 1; margin: 0; padding-left: 4px; font: inherit; font-weight: 600; }
|
||||
.row { display: flex; align-items: center; gap: 3px; min-width: 0; }
|
||||
.file { display: flex; flex: 1; align-items: center; gap: 6px; min-width: 0; min-height: 28px; padding: 4px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
|
||||
.file:hover:not(:disabled) { background: var(--rs-hover-bg); }
|
||||
.file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.file:disabled { color: var(--rs-text-dim); }
|
||||
.file span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.status { color: var(--rs-text-dim); font-size: 11px; white-space: nowrap; }
|
||||
@media (max-width: 450px) { .status { display: none; } }
|
||||
</style>
|
||||
@@ -0,0 +1,62 @@
|
||||
// The Git feature. `loader.ts` imports this module at first need: the Source control pane, a Git tab, or the graph command.
|
||||
// It uses the host Git service directly. `src-tauri/src/git.rs` runs the `git` program for the workspace of the window.
|
||||
import { mount, unmount } from "svelte";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { gitApi } from "../../git/service.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||
import { GitState } from "./state.svelte.ts";
|
||||
import SourceControl from "./SourceControl.svelte";
|
||||
import GitDiff from "./GitDiff.svelte";
|
||||
import GitGraph from "./GitGraph.svelte";
|
||||
|
||||
export function start(context: FeatureContext): FeatureInstance {
|
||||
const state = new GitState();
|
||||
|
||||
async function loadDiff(path: string, staged: boolean) {
|
||||
const sequence = ++state.sequence;
|
||||
state.selected = { path, staged, text: tr("Loading diff…"), error: false };
|
||||
try {
|
||||
const text = await gitApi.diff(path, staged);
|
||||
if (state.disposed || sequence !== state.sequence) return;
|
||||
state.selected = { path, staged, text: text || tr("No text changes."), error: false };
|
||||
} catch (reason) {
|
||||
if (state.disposed || sequence !== state.sequence) return;
|
||||
state.selected = { path, staged, text: String(reason), error: true };
|
||||
}
|
||||
}
|
||||
|
||||
const views: Record<string, (target: HTMLElement) => Record<string, unknown>> = {
|
||||
"source-control": target => mount(SourceControl, { target, props: {
|
||||
git: state,
|
||||
showDiff: (path: string, staged: boolean) => { context.openView("diff"); void loadDiff(path, staged); },
|
||||
showGraph: () => context.openView("graph"),
|
||||
onWorkspaceChange: context.onWorkspaceChange,
|
||||
} }),
|
||||
diff: target => mount(GitDiff, { target, props: { git: state, openFile: context.openFile } }),
|
||||
graph: target => mount(GitGraph, { target, props: { git: state } }),
|
||||
};
|
||||
|
||||
return {
|
||||
mount(view, element) {
|
||||
const create = views[view];
|
||||
if (!create) throw new Error(tr("This view is unavailable."));
|
||||
const component = create(element);
|
||||
return () => unmount(component);
|
||||
},
|
||||
saveTabState(view) {
|
||||
if (view === "diff") return state.selected ? { path: state.selected.path, staged: state.selected.staged } : null;
|
||||
if (view === "graph") return { selectedId: state.history.selectedId, file: state.history.file };
|
||||
return undefined;
|
||||
},
|
||||
async restoreTabState(view, value) {
|
||||
const saved = value && typeof value === "object" ? value as Record<string, unknown> : null;
|
||||
if (!saved) return;
|
||||
if (view === "diff" && typeof saved.path === "string" && typeof saved.staged === "boolean") await loadDiff(saved.path, saved.staged);
|
||||
if (view === "graph") {
|
||||
state.history.selectedId = typeof saved.selectedId === "string" ? saved.selectedId : null;
|
||||
state.history.file = typeof saved.file === "string" ? saved.file : null;
|
||||
}
|
||||
},
|
||||
dispose() { state.disposed = true; state.sequence++; },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Pure Git helpers of the Git feature: change groups, labels, and the lanes of the commit graph.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { GitChange, GitGraph, GitGraphCommit } from "../../git/contracts.ts";
|
||||
|
||||
export function isConflict(change: GitChange): boolean {
|
||||
return change.index === "U" || change.worktree === "U" || ["AA", "DD"].includes(change.index + change.worktree);
|
||||
}
|
||||
|
||||
/** Staged changes and working tree changes. A conflict shows only with the working tree changes. */
|
||||
export function groups(changes: GitChange[]): { staged: GitChange[]; working: GitChange[] } {
|
||||
return {
|
||||
staged: changes.filter(change => !isConflict(change) && ![" ", "?", "!"].includes(change.index)),
|
||||
working: changes.filter(change => isConflict(change) || ![" ", "!"].includes(change.worktree)),
|
||||
};
|
||||
}
|
||||
|
||||
/** The paths to stage or unstage. A rename needs both its old and its new path. */
|
||||
export function pathsFor(changes: GitChange[]): string[] {
|
||||
return [...new Set(changes.flatMap(change => change.originalPath ? [change.originalPath, change.path] : [change.path]))];
|
||||
}
|
||||
|
||||
export function changeLabel(change: GitChange, staged: boolean): string {
|
||||
if (isConflict(change)) return tr("Conflict");
|
||||
const code = staged ? change.index : change.worktree;
|
||||
switch (code) {
|
||||
case "?": return tr("New");
|
||||
case "A": return tr("Added");
|
||||
case "M": return tr("Modified");
|
||||
case "D": return tr("Deleted");
|
||||
case "R": return tr("Renamed");
|
||||
case "C": return tr("Copied");
|
||||
case "T": return tr("Type changed");
|
||||
default: return code;
|
||||
}
|
||||
}
|
||||
|
||||
export type DiffLineKind = "add" | "remove" | "range" | "context";
|
||||
|
||||
export function diffLineKind(line: string): DiffLineKind {
|
||||
if (line.startsWith("+") && !line.startsWith("+++")) return "add";
|
||||
if (line.startsWith("-") && !line.startsWith("---")) return "remove";
|
||||
return line.startsWith("@@") ? "range" : "context";
|
||||
}
|
||||
|
||||
export interface GraphNode extends GitGraphCommit { row: number; lane: number; color: number }
|
||||
export interface GraphEdge { from: string; to: string; row: number; lane: number; parentLane: number; color: number; outside: boolean; endRow: number }
|
||||
|
||||
/** Lanes and colors for the commit graph. The six colors repeat, and lanes that are in use do not share a color. */
|
||||
export function graphLayout(history: GitGraph | null | undefined): { nodes: GraphNode[]; edges: GraphEdge[]; lanes: number } {
|
||||
const commits = history?.commits ?? [];
|
||||
const lanes: (string | null)[] = [];
|
||||
const nodes: GraphNode[] = [];
|
||||
const edges: Omit<GraphEdge, "endRow">[] = [];
|
||||
const colors = new Map<string, number>();
|
||||
let nextColor = 0;
|
||||
const ids = new Set(commits.map(commit => commit.id));
|
||||
const reserve = (id: string, preferredColor?: number) => {
|
||||
let lane = lanes.indexOf(id);
|
||||
if (lane < 0) {
|
||||
lane = lanes.indexOf(null);
|
||||
if (lane < 0) lane = lanes.length;
|
||||
lanes[lane] = id;
|
||||
if (preferredColor === undefined) {
|
||||
const activeColors = new Set(lanes.filter(value => value !== id && value !== null).map(value => colors.get(value!)));
|
||||
preferredColor = nextColor++;
|
||||
for (let offset = 0; offset < 6 && activeColors.has(preferredColor % 6); offset++) preferredColor = nextColor++;
|
||||
}
|
||||
colors.set(id, preferredColor % 6);
|
||||
}
|
||||
return lane;
|
||||
};
|
||||
let width = 1;
|
||||
for (const [row, commit] of commits.entries()) {
|
||||
const lane = reserve(commit.id);
|
||||
const color = colors.get(commit.id)!;
|
||||
nodes.push({ ...commit, row, lane, color });
|
||||
lanes[lane] = null;
|
||||
for (const [index, parent] of commit.parents.entries()) {
|
||||
const parentLane = reserve(parent, index === 0 ? color : undefined);
|
||||
edges.push({ from: commit.id, to: parent, row, lane, parentLane, color: index === 0 ? color : colors.get(parent)!, outside: !ids.has(parent) });
|
||||
}
|
||||
width = Math.max(width, lanes.length, lane + 1);
|
||||
}
|
||||
const rows = new Map(nodes.map(node => [node.id, node.row]));
|
||||
return { nodes, edges: edges.map(edge => ({ ...edge, endRow: rows.get(edge.to) ?? nodes.length })), lanes: width };
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// The shared state of one Git feature instance. The Source control pane, the diff tab, and the graph tab read it.
|
||||
|
||||
export interface DiffSelection {
|
||||
path: string;
|
||||
staged: boolean;
|
||||
text: string;
|
||||
error: boolean;
|
||||
}
|
||||
|
||||
export class GitState {
|
||||
/** The file of the diff tab. */
|
||||
selected = $state<DiffSelection | null>(null);
|
||||
/** The commit and the file of the graph tab. Tab transfers carry them. */
|
||||
history = $state<{ selectedId: string | null; file: string | null }>({ selectedId: null, file: null });
|
||||
/** Grows after each commit, push, or pull, so that the graph reads the history again. */
|
||||
historyVersion = $state(0);
|
||||
/** The diff request that may write `selected`. */
|
||||
sequence = 0;
|
||||
disposed = false;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Launch rules: a feature with a rule starts its instance as soon as the rule wants it, without a view or a command.
|
||||
// A feature without a rule loads at first need. `syncFeatures` in `src/lib/plugins/external.ts` applies the rules.
|
||||
import type { FeatureId } from "./catalog.ts";
|
||||
import { hasBackgroundSource, onBackgroundChange } from "./backgroundSettings.ts";
|
||||
|
||||
export interface LaunchRule {
|
||||
/** True when the feature also runs in browser windows. Other features stay out of them. */
|
||||
browserWindow: boolean;
|
||||
/** True when the rule also starts the feature in the settings window. */
|
||||
settingsWindow: boolean;
|
||||
/** True when the instance must run now. */
|
||||
wanted(): boolean;
|
||||
/** Run `listener` after each change that can change `wanted`. Returns the function that stops it. */
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
export const LAUNCH_RULES: Partial<Record<FeatureId, LaunchRule>> = {
|
||||
// Background starts at the start of a window when a folder or an image is selected, and at once when the user selects one.
|
||||
// The settings window shows the settings only, so the slideshow does not run there.
|
||||
background: { browserWindow: true, settingsWindow: false, wanted: () => hasBackgroundSource(), subscribe: onBackgroundChange },
|
||||
};
|
||||
|
||||
/** True when a feature runs in a window of this kind. */
|
||||
export function runsInWindow(id: FeatureId, window: { browserWindow: boolean }): boolean {
|
||||
return !window.browserWindow || !!LAUNCH_RULES[id]?.browserWindow;
|
||||
}
|
||||
|
||||
/** True when the launch rule of a feature wants its instance now in a window of this kind. */
|
||||
export function launchWanted(id: FeatureId, window: { settingsWindow: boolean }): boolean {
|
||||
const rule = LAUNCH_RULES[id];
|
||||
return !!rule && (!window.settingsWindow || rule.settingsWindow) && rule.wanted();
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Each feature module loads at most one time in each window. The host core never imports a feature module
|
||||
// statically. `pnpm check:features` makes sure of this in the build output.
|
||||
import { writable } from "svelte/store";
|
||||
import type { FeatureId } from "./catalog.ts";
|
||||
import type { FeatureModule } from "./types.ts";
|
||||
|
||||
const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
|
||||
git: () => import("./git/index.ts"),
|
||||
background: () => import("./background/index.ts"),
|
||||
terminal: () => import("./terminal/index.ts"),
|
||||
pdf: () => import("./pdf/index.ts"),
|
||||
pm: () => import("./pm/index.ts"),
|
||||
};
|
||||
|
||||
const modules = new Map<FeatureId, Promise<FeatureModule>>();
|
||||
|
||||
/** The last load error of each feature, for Settings → Features. */
|
||||
export const featureErrors = writable<Partial<Record<FeatureId, string>>>({});
|
||||
|
||||
function setError(id: FeatureId, message: string | undefined) {
|
||||
featureErrors.update(errors => {
|
||||
const next = { ...errors };
|
||||
if (message) next[id] = message; else delete next[id];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
/** Import the module of a feature. After a failure, the next call tries again. */
|
||||
export function loadFeature(id: FeatureId, load: () => Promise<FeatureModule> = imports[id]): Promise<FeatureModule> {
|
||||
let pending = modules.get(id);
|
||||
if (!pending) {
|
||||
pending = load().then(module => { setError(id, undefined); return module; }, reason => {
|
||||
modules.delete(id);
|
||||
setError(id, String(reason));
|
||||
throw reason;
|
||||
});
|
||||
modules.set(id, pending);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** True after the first load started in this window. Tests use it to prove that an off feature never loads. */
|
||||
export function featureRequested(id: FeatureId): boolean {
|
||||
return modules.has(id);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// The first start of a version with a new native feature. The switch takes the state of the old plugin package,
|
||||
// or the default of the feature when the feature does not follow its package (`followsPackage`).
|
||||
// `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing.
|
||||
// The first start also makes the `background` section from the old Background Slideshow settings (`backgroundSettings.ts`),
|
||||
// the `terminal` section from the localStorage key of the Terminal plugin (`terminalSettings.ts`), and the
|
||||
// `projectManagement` section and the tab view states from the kept Project Management settings (`pmSettings.ts`).
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { readSection, writeSection } from "../settings/store.ts";
|
||||
import { readAppearance } from "../theme/appearance.ts";
|
||||
import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "./catalog.ts";
|
||||
import { storedSwitches } from "./state.ts";
|
||||
import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts";
|
||||
import { LEGACY_TERMINAL_KEY, migrateTerminal, writeTerminal, type TerminalMigrationHost } from "./terminalSettings.ts";
|
||||
import { migrateProjectManagement, writeProjectManagement, type ProjectManagementMigrationHost } from "./pmSettings.ts";
|
||||
|
||||
/** What the host reports about one old plugin package. */
|
||||
export interface LegacyPlugin {
|
||||
id: string;
|
||||
installed: boolean;
|
||||
enabled: boolean;
|
||||
/** The kept plugin settings, or null. */
|
||||
settings: unknown;
|
||||
}
|
||||
|
||||
/** An installed package gives its enabled state. Without a package, or for a feature that does not follow its package, the default applies. */
|
||||
export function legacySwitch(entry: FeatureEntry, legacy: LegacyPlugin | undefined): boolean {
|
||||
return entry.followsPackage && legacy?.installed ? legacy.enabled : entry.defaultOn;
|
||||
}
|
||||
|
||||
export interface MigrationHost {
|
||||
read: () => unknown;
|
||||
write: (value: unknown) => Promise<void>;
|
||||
legacy: (ids: string[]) => Promise<LegacyPlugin[]>;
|
||||
}
|
||||
|
||||
const desktopHost: MigrationHost = {
|
||||
read: () => readSection("features"),
|
||||
write: value => writeSection("features", value),
|
||||
legacy: ids => invoke<LegacyPlugin[]>("features_legacy", { ids }),
|
||||
};
|
||||
|
||||
const desktopBackground: BackgroundMigrationHost = {
|
||||
missing: () => readSection("background") === undefined,
|
||||
hasImage: () => hasImage(readAppearance()),
|
||||
migrateFolder: async () => !!await invoke<string | null>("background_migrate"),
|
||||
write: writeBackground,
|
||||
};
|
||||
|
||||
const desktopProjectManagement: ProjectManagementMigrationHost = {
|
||||
missing: () => readSection("projectManagement") === undefined,
|
||||
write: writeProjectManagement,
|
||||
get storage() { return localStorage; },
|
||||
};
|
||||
|
||||
const desktopTerminal: TerminalMigrationHost = {
|
||||
missing: () => readSection("terminal") === undefined,
|
||||
legacy: () => localStorage.getItem(LEGACY_TERMINAL_KEY),
|
||||
write: writeTerminal,
|
||||
};
|
||||
|
||||
/**
|
||||
* Give each feature without a stored switch the state of its old package, and make a missing `background`, `terminal`,
|
||||
* or `projectManagement` section.
|
||||
* It runs before the first render. When the host cannot report the packages, nothing is written, so the next start tries again.
|
||||
* The `terminal` section needs no package report, so it migrates also then.
|
||||
*/
|
||||
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground,
|
||||
terminal: TerminalMigrationHost = desktopTerminal, projectManagement: ProjectManagementMigrationHost = desktopProjectManagement): Promise<FeatureId[]> {
|
||||
try { await migrateTerminal(terminal); }
|
||||
catch (reason) { console.error("RuneStone could not copy the old terminal settings.", reason); }
|
||||
const current = host.read();
|
||||
const stored = storedSwitches(current);
|
||||
const missing = FEATURES.filter(entry => stored[entry.id] === undefined);
|
||||
const backgroundOwner = featureEntry("background").owner;
|
||||
const backgroundMissing = background.missing();
|
||||
const pmOwner = featureEntry("pm").owner;
|
||||
const pmMissing = projectManagement.missing();
|
||||
const owners = [...new Set([...missing.map(entry => entry.owner), ...backgroundMissing ? [backgroundOwner] : [], ...pmMissing ? [pmOwner] : []])];
|
||||
if (!owners.length) return [];
|
||||
let legacy: LegacyPlugin[];
|
||||
try { legacy = await host.legacy(owners); }
|
||||
catch (reason) {
|
||||
console.error("RuneStone could not read the old plugin packages. The feature defaults apply.", reason);
|
||||
return [];
|
||||
}
|
||||
if (missing.length) {
|
||||
const next: Record<string, unknown> = current && typeof current === "object" && !Array.isArray(current) ? { ...current as Record<string, unknown> } : {};
|
||||
for (const entry of missing) next[entry.id] = legacySwitch(entry, legacy.find(item => item.id === entry.owner));
|
||||
await host.write(next);
|
||||
}
|
||||
if (backgroundMissing) await migrateBackground(legacy.find(item => item.id === backgroundOwner), background);
|
||||
if (pmMissing) await migrateProjectManagement(legacy.find(item => item.id === pmOwner), projectManagement);
|
||||
return missing.map(entry => entry.id);
|
||||
}
|
||||
|
||||
/** Workbench and Settings windows of the desktop app migrate. Browser windows start no feature, and the browser preview keeps the defaults. */
|
||||
export function migrateFeaturesOnStart(): Promise<unknown> {
|
||||
const browserWindow = new URLSearchParams(location.search).get("browserWindow") === "true";
|
||||
if (!isTauri() || browserWindow) return Promise.resolve();
|
||||
return migrateFeatures().catch(reason => console.error("The feature migration failed.", reason));
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
<script lang="ts">
|
||||
// One PDF tab: the toolbar, the status line, the password form, and all pages in one column that scrolls.
|
||||
// Only the pages near the visible area have a canvas and a text layer. The other pages are empty sheets.
|
||||
// The document and its worker live as long as the tab. `close` releases both.
|
||||
import { flushSync, onMount } from "svelte";
|
||||
import { message, t } from "$lib/i18n";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import type { PluginDocumentContext } from "$lib/plugins/sdk";
|
||||
import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine";
|
||||
import { MAX_ZOOM, MIN_ZOOM, PAGE_GAP, PAGE_MARGIN, RESIZE_SETTLE_MS, ZOOM_STEP, fitZoom, mostVisiblePage, nextRotation, outputScale, pageBoxes, pageNumber, pagesInRange, zoomFromText, zoomLevel, type PageSize } from "./model";
|
||||
|
||||
let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
|
||||
|
||||
type Status = { key: string; values?: Record<string, string | number>; alert?: boolean };
|
||||
/** One page that has a drawing, or waits for one. `key` names the zoom, the rotation, and the pixel ratio. */
|
||||
type Drawing = { key: string; done: boolean; cancel(): void };
|
||||
|
||||
let page = $state(1);
|
||||
let count = $state(0);
|
||||
let zoom = $state(1);
|
||||
let rotation = $state(0);
|
||||
let fit = $state(true);
|
||||
let sizes = $state.raw<PageSize[]>([]);
|
||||
let status = $state<Status>({ key: message("Loading PDF…") });
|
||||
let asking = $state<"needed" | "incorrect" | null>(null);
|
||||
let reloading = $state(false);
|
||||
let failed = $state(false);
|
||||
let scroller: HTMLDivElement;
|
||||
let sheets: HTMLDivElement[] = $state([]);
|
||||
let pageInput: HTMLInputElement;
|
||||
let passwordInput: HTMLInputElement | undefined = $state();
|
||||
|
||||
let disposed = false;
|
||||
let pdf: PDFDocumentProxy | undefined;
|
||||
let opened: OpenPdf | undefined;
|
||||
let answer: ((password: string) => void) | undefined;
|
||||
let generation = 0;
|
||||
const drawings = new Map<number, Drawing>();
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
let loading: Promise<void> = Promise.resolve();
|
||||
let closing: Promise<void> | undefined;
|
||||
// The place in the document: a page and the part of its height above the top of the visible area.
|
||||
let anchor = { index: 0, part: 0 };
|
||||
// The scroll position that the viewer set. A scroll event at this position keeps the page number.
|
||||
let settled = -1;
|
||||
let frame = 0;
|
||||
|
||||
const ready = $derived(count > 0);
|
||||
const boxes = $derived(pageBoxes(sizes, zoom, rotation));
|
||||
const zoomText = $derived(ready ? `${Math.round(zoom * 100)}%` : "—");
|
||||
|
||||
function fail(reason: unknown) {
|
||||
if (disposed) return;
|
||||
failed = true;
|
||||
status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true };
|
||||
}
|
||||
|
||||
const drawingKey = () => `${zoom}:${rotation}:${window.devicePixelRatio}`;
|
||||
|
||||
/** The status line names the current page when its drawing is complete. */
|
||||
function report() {
|
||||
if (disposed || failed || !pdf) return;
|
||||
const drawing = drawings.get(page);
|
||||
status = drawing?.done && drawing.key === drawingKey()
|
||||
? { key: message("Page {page} of {count}"), values: { page, count } }
|
||||
: { key: message("Loading page {page}…"), values: { page } };
|
||||
}
|
||||
|
||||
/** Draw one page. The jobs run one at a time. A cancelled job ends at its next step. */
|
||||
function draw(number: number, key: string) {
|
||||
let cancelled = false;
|
||||
let render: RenderTask | undefined;
|
||||
let text: TextLayer | undefined;
|
||||
const drawing: Drawing = { key, done: false, cancel() { cancelled = true; render?.cancel(); text?.cancel(); } };
|
||||
drawings.set(number, drawing);
|
||||
const source = pdf;
|
||||
queue = queue.then(async () => {
|
||||
if (cancelled || disposed || !source) return;
|
||||
const pdfPage = await source.getPage(number);
|
||||
const sheet = sheets[number - 1];
|
||||
if (cancelled || disposed || !sheet) return;
|
||||
const viewport = pdfPage.getViewport({ scale: zoom, rotation: (pdfPage.rotate + rotation) % 360 });
|
||||
const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, Math.floor(viewport.width * scale));
|
||||
canvas.height = Math.max(1, Math.floor(viewport.height * scale));
|
||||
canvas.setAttribute("role", "img");
|
||||
// The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N".
|
||||
canvas.setAttribute("aria-label", $t("PDF page {page}", { page: number }));
|
||||
const layer = document.createElement("div");
|
||||
layer.className = "textLayer";
|
||||
layer.style.setProperty("--total-scale-factor", String(viewport.scale));
|
||||
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
|
||||
await render.promise;
|
||||
if (cancelled || disposed) return;
|
||||
// The old drawing of the page stays until the new one is complete.
|
||||
sheet.replaceChildren(canvas, layer);
|
||||
text = new TextLayer({ textContentSource: pdfPage.streamTextContent(), container: layer, viewport });
|
||||
await text.render();
|
||||
if (cancelled || disposed) return;
|
||||
drawing.done = true;
|
||||
pdfPage.cleanup();
|
||||
report();
|
||||
}).catch(reason => { if (!cancelled && !disposed) fail(reason); });
|
||||
}
|
||||
|
||||
/** Draw the pages near the visible area, the current page first. Empty the pages that are far from it. */
|
||||
function refresh() {
|
||||
if (!pdf || disposed || scroller.clientWidth === 0) return;
|
||||
const key = drawingKey();
|
||||
const height = scroller.clientHeight;
|
||||
const wanted = pagesInRange(boxes, scroller.scrollTop - height, scroller.scrollTop + 2 * height);
|
||||
for (const [number, drawing] of drawings) {
|
||||
const keep = wanted.includes(number);
|
||||
if (keep && drawing.key === key) continue;
|
||||
drawing.cancel();
|
||||
drawings.delete(number);
|
||||
if (!keep) sheets[number - 1]?.replaceChildren();
|
||||
}
|
||||
for (const number of wanted.sort((a, b) => Math.abs(a - page) - Math.abs(b - page))) if (!drawings.has(number)) draw(number, key);
|
||||
report();
|
||||
}
|
||||
|
||||
/** Put the remembered place at the top of the visible area again, after the page boxes changed. */
|
||||
function restore() {
|
||||
flushSync();
|
||||
const box = boxes[anchor.index];
|
||||
if (!box || scroller.clientWidth === 0) return;
|
||||
scroller.scrollTop = Math.max(0, box.top + anchor.part * box.height);
|
||||
settled = scroller.scrollTop;
|
||||
refresh();
|
||||
}
|
||||
|
||||
function remember() {
|
||||
const box = boxes[page - 1];
|
||||
anchor = { index: page - 1, part: box ? (scroller.scrollTop - box.top) / box.height : 0 };
|
||||
}
|
||||
|
||||
function scrolled() {
|
||||
if (frame) return;
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = 0;
|
||||
if (disposed || !ready || scroller.clientWidth === 0) return;
|
||||
if (scroller.scrollTop !== settled) {
|
||||
settled = -1;
|
||||
page = mostVisiblePage(boxes, scroller.scrollTop, scroller.scrollTop + scroller.clientHeight);
|
||||
remember();
|
||||
}
|
||||
refresh();
|
||||
});
|
||||
}
|
||||
|
||||
/** Show the top of a page. */
|
||||
function go(value: number) {
|
||||
if (!pdf) return;
|
||||
page = pageNumber(value, pdf.numPages);
|
||||
pageInput.value = String(page);
|
||||
// The first page shows with the margin above it. Each other page shows with half of the gap above it.
|
||||
anchor = { index: page - 1, part: -(page === 1 ? PAGE_MARGIN : PAGE_GAP / 2) / (boxes[page - 1]?.height ?? 1) };
|
||||
restore();
|
||||
}
|
||||
|
||||
function applyFit() {
|
||||
if (fit && scroller.clientWidth > 0 && sizes.length) zoom = fitZoom(sizes, rotation, scroller.clientWidth - 2 * PAGE_MARGIN);
|
||||
}
|
||||
|
||||
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); restore(); }
|
||||
|
||||
function typedZoom(input: HTMLInputElement) {
|
||||
const value = zoomFromText(input.value);
|
||||
if (value !== null && Math.round(value * 100) !== Math.round(zoom * 100)) setZoom(value);
|
||||
input.value = zoomText;
|
||||
}
|
||||
|
||||
/** Read the size of each page after the first. Until then, a page has the size of the first page. */
|
||||
async function measure(source: PDFDocumentProxy, current: number) {
|
||||
const next = [...sizes];
|
||||
let changed = false;
|
||||
for (let number = 2; number <= source.numPages; number++) {
|
||||
const { width, height } = (await source.getPage(number)).getViewport({ scale: 1 });
|
||||
if (disposed || current !== generation) return;
|
||||
if (width !== next[number - 1].width || height !== next[number - 1].height) { next[number - 1] = { width, height }; changed = true; }
|
||||
}
|
||||
if (!changed) return;
|
||||
sizes = next;
|
||||
applyFit();
|
||||
restore();
|
||||
}
|
||||
|
||||
async function load() {
|
||||
failed = false;
|
||||
status = { key: message("Loading PDF…") };
|
||||
const bytes = await readBytes(file.path);
|
||||
if (disposed) return;
|
||||
opened = openPdf(bytes, (reason, next) => {
|
||||
if (disposed) return;
|
||||
answer = next;
|
||||
asking = reason;
|
||||
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
|
||||
queueMicrotask(() => passwordInput?.focus());
|
||||
});
|
||||
const source = await opened.promise;
|
||||
if (disposed) return;
|
||||
const current = ++generation;
|
||||
const { width, height } = (await source.getPage(1)).getViewport({ scale: 1 });
|
||||
if (disposed) return;
|
||||
pdf = source;
|
||||
sizes = Array.from({ length: source.numPages }, () => ({ width, height }));
|
||||
count = source.numPages;
|
||||
applyFit();
|
||||
go(page);
|
||||
report();
|
||||
void measure(source, current).catch(reason => { if (current === generation) fail(reason); });
|
||||
}
|
||||
|
||||
async function release() {
|
||||
generation++;
|
||||
for (const drawing of drawings.values()) drawing.cancel();
|
||||
drawings.clear();
|
||||
await queue;
|
||||
const current = opened;
|
||||
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0; sizes = [];
|
||||
await current?.close();
|
||||
}
|
||||
|
||||
async function reload() {
|
||||
if (reloading || disposed) return;
|
||||
reloading = true;
|
||||
try {
|
||||
await loading;
|
||||
await release();
|
||||
if (!disposed) await (loading = load());
|
||||
} catch (reason) { fail(reason); }
|
||||
finally { reloading = false; }
|
||||
}
|
||||
|
||||
function unlock(event: SubmitEvent) {
|
||||
event.preventDefault();
|
||||
if (!passwordInput || !answer) return;
|
||||
const value = passwordInput.value;
|
||||
passwordInput.value = "";
|
||||
asking = null;
|
||||
status = { key: message("Loading PDF…") };
|
||||
const next = answer;
|
||||
answer = undefined;
|
||||
next(value);
|
||||
}
|
||||
|
||||
/** Ctrl and the wheel change the zoom. The wheel alone scrolls the pages. */
|
||||
function wheel(event: WheelEvent) {
|
||||
if (!(event.ctrlKey || event.metaKey) || !ready || event.deltaY === 0) return;
|
||||
event.preventDefault();
|
||||
setZoom(event.deltaY < 0 ? zoom * 1.1 : zoom / 1.1);
|
||||
}
|
||||
|
||||
/** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
|
||||
export function close(): Promise<void> {
|
||||
if (closing) return closing;
|
||||
disposed = true;
|
||||
closing = release().then(() => loading).catch(() => {});
|
||||
return closing;
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
loading = load().catch(fail);
|
||||
// Fit-width pages follow the width of the tab. A tab that shows again draws at once. Later sizes wait until the size settles.
|
||||
let width = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const resized = () => { applyFit(); restore(); };
|
||||
const observer = new ResizeObserver(() => {
|
||||
const next = scroller.clientWidth;
|
||||
if (next === width) return;
|
||||
const shown = width === 0;
|
||||
width = next;
|
||||
clearTimeout(timer);
|
||||
if (next === 0) return;
|
||||
if (shown) resized();
|
||||
else timer = setTimeout(resized, RESIZE_SETTLE_MS);
|
||||
});
|
||||
observer.observe(scroller);
|
||||
scroller.addEventListener("wheel", wheel, { passive: false });
|
||||
return () => { observer.disconnect(); clearTimeout(timer); cancelAnimationFrame(frame); scroller.removeEventListener("wheel", wheel); void close(); };
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="pdf-viewer" aria-label={$t("PDF Viewer")}>
|
||||
<div class="toolbar" role="group" aria-label={$t("PDF controls")}>
|
||||
<IconButton icon="up" label={$t("Previous page")} disabled={!ready || page <= 1} onclick={() => go(page - 1)} />
|
||||
<input bind:this={pageInput} class="page" type="number" min="1" max={Math.max(count, 1)} value={page} disabled={!ready}
|
||||
aria-label={$t("Page number")} onchange={event => { if (Number(event.currentTarget.value) !== page) go(Number(event.currentTarget.value)); }}
|
||||
onkeydown={event => { if (event.key === "Enter") go(Number(event.currentTarget.value)); }} />
|
||||
<span class="count">/ {ready ? count : "—"}</span>
|
||||
<IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} />
|
||||
<span class="separator" aria-hidden="true"></span>
|
||||
<IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} />
|
||||
<input class="zoom" type="text" inputmode="decimal" value={zoomText} disabled={!ready} aria-label={$t("Zoom percent")}
|
||||
onfocus={event => event.currentTarget.select()} onchange={event => typedZoom(event.currentTarget)}
|
||||
onkeydown={event => { if (event.key === "Enter") typedZoom(event.currentTarget); }} />
|
||||
<IconButton icon="zoom-in" label={$t("Zoom in")} disabled={!ready || zoom >= MAX_ZOOM} onclick={() => setZoom(zoom * ZOOM_STEP)} />
|
||||
<IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; applyFit(); restore(); }} />
|
||||
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); applyFit(); restore(); }} />
|
||||
<IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} />
|
||||
</div>
|
||||
<p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p>
|
||||
{#if asking}
|
||||
<form class="password" onsubmit={unlock}>
|
||||
<label>{$t("PDF password")} <input bind:this={passwordInput} type="password" autocomplete="off" /></label>
|
||||
<button class="text-button" type="submit">{$t("Unlock")}</button>
|
||||
</form>
|
||||
{/if}
|
||||
<!-- The page area takes focus, so the keyboard scrolls the pages. The host gives it focus after a tab change by keyboard. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
|
||||
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF pages")} data-tab-focus onscroll={scrolled}>
|
||||
<div class="pages">
|
||||
{#each boxes as box, index (index)}
|
||||
<div bind:this={sheets[index]} class="sheet" data-page={index + 1} style:width={`${box.width}px`} style:height={`${box.height}px`}></div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; }
|
||||
/* The toolbar, the status line, and the password form are opaque, so a background image never hides them. */
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
|
||||
.page { box-sizing: border-box; width: 64px; height: 28px; margin-left: 4px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: right; }
|
||||
.page:disabled, .zoom:disabled { color: var(--rs-text-dim); }
|
||||
.count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; }
|
||||
.separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); }
|
||||
.zoom { box-sizing: border-box; width: 60px; height: 28px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: center; }
|
||||
.status { margin: 0; padding: 4px 12px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
|
||||
.status.alert { color: var(--rs-error); }
|
||||
.password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
|
||||
.password input { box-sizing: border-box; height: 28px; margin-left: 4px; padding: 2px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
.text-button:hover { background: var(--rs-bg-active); }
|
||||
/* The padding and the gap match PAGE_MARGIN and PAGE_GAP in model.ts. */
|
||||
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; background: var(--rs-workarea-editor-bg); }
|
||||
.scroll:focus-visible { outline-offset: -2px; }
|
||||
.pages { display: flex; flex-direction: column; align-items: center; gap: 12px; width: max-content; min-width: 100%; }
|
||||
/* A PDF page is paper: white in both themes. */
|
||||
.sheet { position: relative; flex: none; background: white; box-shadow: 0 2px 10px #0003; }
|
||||
.sheet :global(canvas) { display: block; width: 100%; height: 100%; }
|
||||
/* The text layer geometry follows the viewer styles of PDF.js 6 (Apache-2.0). See THIRD_PARTY_NOTICES.md. */
|
||||
.sheet :global(.textLayer) { position: absolute; inset: 0; overflow: clip; text-align: initial; line-height: 1; letter-spacing: normal; word-spacing: normal; text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 0; --min-font-size: 1; --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); --min-font-size-inv: calc(1 / var(--min-font-size)); }
|
||||
.sheet :global(.textLayer :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; }
|
||||
.sheet :global(.textLayer > :not(.markedContent)), .sheet :global(.markedContent span:not(.markedContent)) { z-index: 1; --font-height: 0; font-size: calc(var(--text-scale-factor) * var(--font-height)); --scale-x: 1; --rotate: 0deg; transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv)); }
|
||||
.sheet :global(.markedContent) { display: contents; }
|
||||
.sheet :global(.textLayer ::selection) { background: color-mix(in srgb, var(--rs-selection) 65%, transparent); color: transparent; }
|
||||
</style>
|
||||
@@ -0,0 +1,69 @@
|
||||
/// <reference types="vite/client" />
|
||||
// PDF.js for the PDF Viewer feature. The worker, the character maps, the standard fonts, and the WebAssembly image
|
||||
// decoders come from the app (`'self'`) as Vite assets, so a PDF never causes a network request.
|
||||
// Each open document has its own worker. `close` stops it.
|
||||
// The reference to the Vite types serves the unit test type check, which reaches this file through `loader.ts`.
|
||||
import { getDocument, PDFWorker, PasswordResponses, type PDFDocumentLoadingTask, type PDFDocumentProxy } from "pdfjs-dist/build/pdf.min.mjs";
|
||||
import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";
|
||||
|
||||
export { TextLayer, type PDFDocumentProxy, type RenderTask } from "pdfjs-dist/build/pdf.min.mjs";
|
||||
|
||||
// `build.assetsInlineLimit` in vite.config.js keeps these files out of the code, so each one is a file of the app.
|
||||
// The JPEG 2000 and JBIG2 decoders are the only WebAssembly files that PDF.js asks for with `useWorkerFetch: false`.
|
||||
// The viewer runs no PDF scripts (quickjs) and uses no ICC color profiles (qcms), as the PDF Viewer plugin did.
|
||||
const assets = import.meta.glob<string>([
|
||||
"/node_modules/pdfjs-dist/cmaps/*.bcmap",
|
||||
"/node_modules/pdfjs-dist/standard_fonts/*.{pfb,ttf}",
|
||||
"/node_modules/pdfjs-dist/wasm/{jbig2,openjpeg}.wasm",
|
||||
], { query: "?url", import: "default", eager: true });
|
||||
|
||||
const folders: Record<string, string> = { cMapUrl: "cmaps", standardFontDataUrl: "standard_fonts", wasmUrl: "wasm" };
|
||||
|
||||
/** The app URL of a PDF.js data file, or undefined for an unknown kind or file. */
|
||||
export function assetUrl(kind: string, filename: string): string | undefined {
|
||||
const folder = folders[kind];
|
||||
if (!folder || !/^[\w.-]+$/.test(filename)) return undefined;
|
||||
return assets[`/node_modules/pdfjs-dist/${folder}/${filename}`];
|
||||
}
|
||||
|
||||
/** PDF.js asks the window for its data files (`useWorkerFetch: false`). This class reads them from the app. */
|
||||
class AppBinaryDataFactory {
|
||||
async fetch({ kind, filename }: { kind: string; filename: string }): Promise<Uint8Array> {
|
||||
const url = assetUrl(kind, filename);
|
||||
if (!url) throw new Error(`PDF.js has no data file ${filename}.`);
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error(`PDF.js could not read ${filename}: ${response.status}.`);
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
}
|
||||
}
|
||||
|
||||
export interface OpenPdf {
|
||||
/** Resolves with the document after the password, if the file needs one. */
|
||||
promise: Promise<PDFDocumentProxy>;
|
||||
/** Stop the load or release the document, and stop the worker. Later calls return the same promise. */
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the bytes of a PDF in a new worker. PDF.js calls `onPassword` for a protected file, with "incorrect" after a
|
||||
* wrong password. The viewer calls `answer` with the next password.
|
||||
*/
|
||||
export function openPdf(data: Uint8Array, onPassword: (reason: "needed" | "incorrect", answer: (password: string) => void) => void): OpenPdf {
|
||||
const port = new Worker(workerUrl, { type: "module", name: "PDF.js" });
|
||||
const worker = PDFWorker.create({ port });
|
||||
const task: PDFDocumentLoadingTask = getDocument({
|
||||
data, worker, useWorkerFetch: false, BinaryDataFactory: AppBinaryDataFactory,
|
||||
useSystemFonts: false, isImageDecoderSupported: false, enableXfa: false,
|
||||
});
|
||||
task.onPassword = (answer: (password: string) => void, reason: number) => {
|
||||
onPassword(reason === PasswordResponses.INCORRECT_PASSWORD ? "incorrect" : "needed", answer);
|
||||
};
|
||||
let closing: Promise<void> | undefined;
|
||||
return {
|
||||
promise: task.promise,
|
||||
close: () => closing ??= (async () => {
|
||||
try { await task.destroy(); }
|
||||
finally { worker.destroy(); port.terminate(); }
|
||||
})(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// The PDF Viewer feature. `loader.ts` imports this module when the first PDF tab opens. The file tree marks PDF files
|
||||
// before that, through the document type of the catalog (`../pdfDocument.ts`).
|
||||
// Each tab reads its file with `workspace_read_bytes` (64 MiB at most) and has its own PDF.js worker.
|
||||
import { flushSync, mount, unmount } from "svelte";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { workspaceReadBytes } from "../../workspace/api.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||
import PdfViewer from "./PdfViewer.svelte";
|
||||
|
||||
export function start(_context: FeatureContext): FeatureInstance {
|
||||
const tabs = new Set<() => Promise<void>>();
|
||||
let stopped = false;
|
||||
return {
|
||||
mount() { throw new Error(tr("This view is unavailable.")); },
|
||||
mountDocument(type, element, file) {
|
||||
if (type !== "pdf") throw new Error(tr("This view is unavailable."));
|
||||
if (stopped) throw new Error(tr("This feature is off."));
|
||||
const viewer = mount(PdfViewer, { target: element, props: { file, readBytes: workspaceReadBytes } });
|
||||
flushSync();
|
||||
let closing: Promise<void> | undefined;
|
||||
// Release the document and stop its worker first. Then remove the component.
|
||||
const dispose = () => closing ??= viewer.close().then(() => unmount(viewer)).finally(() => { tabs.delete(dispose); });
|
||||
tabs.add(dispose);
|
||||
return dispose;
|
||||
},
|
||||
/** The host closes the PDF tabs first. Close what is left, so no worker stays. */
|
||||
async dispose() {
|
||||
stopped = true;
|
||||
await Promise.allSettled([...tabs].map(dispose => dispose()));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// The limits of the PDF Viewer: page numbers, zoom, and the size of the page canvas.
|
||||
|
||||
export const MIN_ZOOM = 0.25;
|
||||
export const MAX_ZOOM = 4;
|
||||
/** Each zoom step multiplies or divides the zoom by this factor. */
|
||||
export const ZOOM_STEP = 1.25;
|
||||
/** A redraw after a resize waits until the size did not change for this time. */
|
||||
export const RESIZE_SETTLE_MS = 150;
|
||||
|
||||
/** A whole page number from 1 to `count`. A value that is not a number gives page 1. */
|
||||
export function pageNumber(value: number, count: number): number {
|
||||
return Math.max(1, Math.min(count, Number.isFinite(value) ? Math.trunc(value) : 1));
|
||||
}
|
||||
|
||||
/** A zoom factor from 0.25 to 4. A value that is not a finite number gives 1. */
|
||||
export function zoomLevel(value: number): number {
|
||||
return Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, Number.isFinite(value) ? value : 1));
|
||||
}
|
||||
|
||||
/** The next clockwise rotation in degrees: 0, 90, 180, or 270. */
|
||||
export function nextRotation(rotation: number): number {
|
||||
return (rotation + 90) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pixel scale of the page canvas. It follows the device pixel ratio up to 2, and keeps each side at most
|
||||
* 8192 pixels and the area at most 16 million pixels, so a large page does not use too much memory.
|
||||
*/
|
||||
export function outputScale(width: number, height: number, deviceScale: number): number {
|
||||
return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height)));
|
||||
}
|
||||
|
||||
/** The space around the pages and between two pages, in CSS pixels. `PdfViewer.svelte` uses the same values in its styles. */
|
||||
export const PAGE_MARGIN = 16;
|
||||
export const PAGE_GAP = 12;
|
||||
|
||||
/** The size of a page at zoom 1, with the rotation of the file. */
|
||||
export interface PageSize { width: number; height: number }
|
||||
/** The place of a page in the column of pages, in whole CSS pixels. */
|
||||
export interface PageBox { top: number; width: number; height: number }
|
||||
|
||||
/** The zoom factor for typed text such as "150" or "150 %". Text that is not a number gives null. */
|
||||
export function zoomFromText(text: string): number | null {
|
||||
const value = Number(text.replace("%", "").replace(",", ".").trim());
|
||||
return text.trim() && Number.isFinite(value) && value > 0 ? zoomLevel(value / 100) : null;
|
||||
}
|
||||
|
||||
/** The zoom that fits the widest page in `available` pixels. */
|
||||
export function fitZoom(sizes: readonly PageSize[], rotation: number, available: number): number {
|
||||
const turned = rotation % 180 !== 0;
|
||||
const widest = Math.max(0, ...sizes.map(size => turned ? size.height : size.width));
|
||||
return zoomLevel(widest > 0 ? available / widest : 1);
|
||||
}
|
||||
|
||||
/** One box for each page, from the top of the column to the bottom. */
|
||||
export function pageBoxes(sizes: readonly PageSize[], zoom: number, rotation: number): PageBox[] {
|
||||
const turned = rotation % 180 !== 0;
|
||||
let top = PAGE_MARGIN;
|
||||
return sizes.map(size => {
|
||||
const width = Math.max(1, Math.floor((turned ? size.height : size.width) * zoom));
|
||||
const height = Math.max(1, Math.floor((turned ? size.width : size.height) * zoom));
|
||||
const box = { top, width, height };
|
||||
top += height + PAGE_GAP;
|
||||
return box;
|
||||
});
|
||||
}
|
||||
|
||||
/** The numbers of the pages that touch the range from `from` to `to`. */
|
||||
export function pagesInRange(boxes: readonly PageBox[], from: number, to: number): number[] {
|
||||
const pages: number[] = [];
|
||||
for (let index = 0; index < boxes.length; index++) {
|
||||
if (boxes[index].top >= to) break;
|
||||
if (boxes[index].top + boxes[index].height > from) pages.push(index + 1);
|
||||
}
|
||||
return pages;
|
||||
}
|
||||
|
||||
/** The number of the page that shows the most in the range from `from` to `to`. The first such page wins. */
|
||||
export function mostVisiblePage(boxes: readonly PageBox[], from: number, to: number): number {
|
||||
let page = 1, most = 0;
|
||||
for (let index = 0; index < boxes.length; index++) {
|
||||
const { top, height } = boxes[index];
|
||||
if (top >= to) break;
|
||||
const shown = Math.min(top + height, to) - Math.max(top, from);
|
||||
if (shown > most) { most = shown; page = index + 1; }
|
||||
}
|
||||
return page;
|
||||
}
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
// The minified build of PDF.js has the same exports as the package entry.
|
||||
declare module "pdfjs-dist/build/pdf.min.mjs" {
|
||||
export * from "pdfjs-dist";
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// The document identification of the PDF Viewer feature. It is in the main bundle, because the file tree marks
|
||||
// PDF files before the feature module loads. The document ID is the workspace path, so two files never share a tab.
|
||||
|
||||
/** The document ID of a PDF file: its path with forward slashes. Any letter case of the extension matches. */
|
||||
export function identifyPdf(path: string): { id: string } | null {
|
||||
return /\.pdf$/i.test(path) ? { id: path.replaceAll("\\", "/") } : null;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// The Project Management feature. `loader.ts` imports this module at the first use: the ribbon button, a board tab,
|
||||
// or a tab transfer from another window. The views are `planning` (All tasks) and `board-<hex of the board ID>`.
|
||||
// The storage code (`storage/`) and the domain code (`model/`) use no host module, so the skill helper can bundle them.
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { backgroundHub } from "../../plugins/backgrounds.ts";
|
||||
import { onProjectManagementChange, readProjectManagement, readViewStates, writeProjectManagement, writeViewStates } from "../pmSettings.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||
import { boardKey, isManagedBoard, readCatalog } from "./storage/catalog.ts";
|
||||
import { findLegacy, hasLegacy, type LegacyContent } from "./storage/legacy.ts";
|
||||
import { isHiddenCard } from "./storage/persistence.ts";
|
||||
import { message } from "./storage/message.ts";
|
||||
import type { BoardReference } from "./storage/board.ts";
|
||||
import { TaskStore } from "./model/store.ts";
|
||||
import { hostMenus } from "./ui/host.ts";
|
||||
import { mountPM, parseViewState, type PMViewState } from "./ui/ui.ts";
|
||||
import { hostWorkspace } from "./workspace.ts";
|
||||
import { boardOfView, boardViewId, PLANNING } from "./views.ts";
|
||||
|
||||
export function start(context: FeatureContext): FeatureInstance {
|
||||
const workspace = hostWorkspace(context.onWorkspaceChange);
|
||||
const preferences = readProjectManagement();
|
||||
const stopPreferences = onProjectManagementChange(() => Object.assign(preferences, readProjectManagement()));
|
||||
const states = new Map<string, PMViewState>(Object.entries(readViewStates()).map(([key, value]) => [key, parseViewState(value)]));
|
||||
const dirty = new Set<string>();
|
||||
let saveTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let disposed = false;
|
||||
const mounted = new Set<() => void>();
|
||||
/** The legacy data of each workspace root. A migration reads it again. */
|
||||
const legacy = new Map<string, Promise<LegacyContent>>();
|
||||
|
||||
const flush = () => {
|
||||
clearTimeout(saveTimer);
|
||||
if (!dirty.size) return;
|
||||
writeViewStates(Object.fromEntries([...dirty].map(key => [key, structuredClone(states.get(key))])));
|
||||
dirty.clear();
|
||||
};
|
||||
const persist = (id: string) => {
|
||||
if (disposed) return;
|
||||
dirty.add(id);
|
||||
clearTimeout(saveTimer);
|
||||
saveTimer = setTimeout(flush, 200);
|
||||
};
|
||||
const root = () => invoke<string | null>("workspace_last_path").catch(() => null);
|
||||
const legacyContent = async (fresh = false) => {
|
||||
const key = await root() ?? "";
|
||||
if (fresh) legacy.delete(key);
|
||||
let pending = legacy.get(key);
|
||||
if (!pending) {
|
||||
pending = findLegacy(workspace, () => { if (disposed) throw new Error(message("Project Management is off.")); });
|
||||
pending.catch(() => legacy.delete(key));
|
||||
legacy.set(key, pending);
|
||||
}
|
||||
return pending;
|
||||
};
|
||||
/** Copy the legacy boards, the root label file, and every legacy task note to `.runestone/pm/`, with backups. */
|
||||
const migrate = async () => {
|
||||
const store = new TaskStore(workspace, undefined, { legacy: true });
|
||||
try {
|
||||
await store.reload();
|
||||
const cards = store.tasks.filter(task => !isHiddenCard(task.path)).map(task => task.id);
|
||||
return await store.migrateStorage(cards);
|
||||
} finally {
|
||||
store.dispose();
|
||||
void legacyContent(true).catch(() => undefined);
|
||||
}
|
||||
};
|
||||
|
||||
const openBoard = async (path: string, from?: string) => {
|
||||
const snapshot = await readCatalog(workspace);
|
||||
const board = isManagedBoard(path) ? snapshot.value.boards.find(item => boardKey(item.value.id) === path) : undefined;
|
||||
if (!board) throw new Error(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);
|
||||
};
|
||||
|
||||
function mountView(view: string, element: HTMLElement) {
|
||||
const boardId = view === PLANNING ? null : boardOfView(view);
|
||||
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 });
|
||||
if (boardId) {
|
||||
void readCatalog(workspace).then(snapshot => {
|
||||
const board = snapshot.value.boards.find(item => item.value.id === boardId);
|
||||
if (board && !disposed) context.setViewTitle(view, board.name);
|
||||
}, () => undefined);
|
||||
}
|
||||
const cleanup = mountPM(element, store, {
|
||||
ui: hostMenus,
|
||||
backgrounds: backgroundHub,
|
||||
state: states.get(view),
|
||||
stateChanged: () => persist(view),
|
||||
preferences,
|
||||
savePreferences: value => writeProjectManagement(value),
|
||||
openBoard: (path, replace) => openBoard(path, replace ? view : undefined),
|
||||
openAll: replace => { if (replace) context.replaceView(view, PLANNING); else context.openView(PLANNING); },
|
||||
boardRenamed: name => { if (boardId) context.setViewTitle(view, name); },
|
||||
boardDeleted: () => { if (boardId) context.closeView(view); },
|
||||
watch: workspace.watch,
|
||||
legacy: { find: legacyContent, has: hasLegacy, migrate },
|
||||
});
|
||||
mounted.add(cleanup);
|
||||
return () => { mounted.delete(cleanup); cleanup(); };
|
||||
}
|
||||
|
||||
return {
|
||||
mount: mountView,
|
||||
async launch(view) {
|
||||
if (view !== PLANNING) { context.openView(view); return; }
|
||||
// The default board of the workspace is in the catalog. A missing, archived, or damaged default opens All tasks.
|
||||
try {
|
||||
const { value } = await readCatalog(workspace);
|
||||
const board = value.boards.find(item => item.value.id === value.defaultBoardId && !item.archived);
|
||||
if (board) { await openBoard(boardKey(board.value.id)); return; }
|
||||
} catch { /* All tasks shows the storage problem. */ }
|
||||
context.openView(PLANNING);
|
||||
},
|
||||
saveTabState: view => structuredClone(states.get(view) ?? {}),
|
||||
restoreTabState(view, value) {
|
||||
if (view !== PLANNING && !boardOfView(view)) throw new Error(message("This view is unavailable."));
|
||||
states.set(view, parseViewState(value));
|
||||
persist(view);
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
flush();
|
||||
stopPreferences();
|
||||
for (const cleanup of [...mounted]) cleanup();
|
||||
mounted.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { defaultBoard, type BoardDocument, type BoardList } from "../storage/board.ts";
|
||||
import type { Task } from "./model.ts";
|
||||
import { message } from "../storage/message.ts";
|
||||
|
||||
export interface TaskColumn {
|
||||
list?: BoardList;
|
||||
tasks: Task[];
|
||||
allowCreate?: boolean;
|
||||
}
|
||||
|
||||
/** Merge equal list names without changing the cards' board placements. */
|
||||
export function allTaskColumns(boards: BoardDocument[], tasks: Task[]): TaskColumn[] {
|
||||
const active = boards.filter(board => !board.archived);
|
||||
const columns = new Map<string, TaskColumn>();
|
||||
const assigned = new Set<string>();
|
||||
const append = (list: BoardList | undefined, members: Task[], allowCreate = false) => {
|
||||
const key = list ? `list:${list.name.trim().toLowerCase()}` : "unlisted";
|
||||
let column = columns.get(key);
|
||||
if (!column) {
|
||||
column = { list: list ? { id: allowCreate ? list.id : key, name: list.name, status: list.status, collapsed: false } : undefined, tasks: [], allowCreate };
|
||||
columns.set(key, column);
|
||||
}
|
||||
const included = new Set(column.tasks.map(task => task.id));
|
||||
for (const task of members) if (!included.has(task.id)) {
|
||||
column.tasks.push(task);
|
||||
included.add(task.id);
|
||||
}
|
||||
};
|
||||
for (const board of active) {
|
||||
const members = tasks.filter(task => Object.hasOwn(task.placements ?? {}, board.id));
|
||||
for (const task of members) assigned.add(task.id);
|
||||
for (const list of board.value.lists)
|
||||
append(list, members.filter(task => task.placements![board.id].listId === list.id));
|
||||
const unlisted = members.filter(task => !board.value.lists.some(list => list.id === task.placements![board.id].listId));
|
||||
if (unlisted.length) append(undefined, unlisted);
|
||||
}
|
||||
const standalone = tasks.filter(task => !assigned.has(task.id));
|
||||
if (standalone.length || !active.length) {
|
||||
for (const list of defaultBoard("all-tasks").lists)
|
||||
append(list, standalone.filter(task => task.status === list.status), true);
|
||||
}
|
||||
return [...columns.values()];
|
||||
}
|
||||
|
||||
export interface TaskBoardGroup {
|
||||
boardIds: string[];
|
||||
name: string;
|
||||
tasks: Task[];
|
||||
}
|
||||
|
||||
/** Keep shared cards once and name every board represented in this column. */
|
||||
export function allTaskGroups(boards: BoardDocument[], column: TaskColumn): TaskBoardGroup[] {
|
||||
const active = boards.filter(board => !board.archived);
|
||||
const groups = new Map<string, TaskBoardGroup>();
|
||||
for (const task of column.tasks) {
|
||||
const owners = active.filter(board => {
|
||||
const placement = task.placements?.[board.id];
|
||||
if (!placement) return false;
|
||||
const list = board.value.lists.find(list => list.id === placement.listId);
|
||||
return column.list
|
||||
? list?.name.trim().toLowerCase() === column.list.name.trim().toLowerCase()
|
||||
: !list;
|
||||
});
|
||||
const boardIds = owners.map(board => board.id);
|
||||
const key = JSON.stringify(boardIds);
|
||||
let group = groups.get(key);
|
||||
if (!group) {
|
||||
group = { boardIds, name: owners.length ? owners.map(board => board.name).join(" · ") : message("No active board"), tasks: [] };
|
||||
groups.set(key, group);
|
||||
}
|
||||
group.tasks.push(task);
|
||||
}
|
||||
return [...groups.values()].sort((a, b) => {
|
||||
const order = (group: TaskBoardGroup) => group.boardIds.length ? active.findIndex(board => board.id === group.boardIds[0]) : active.length;
|
||||
return order(a) - order(b);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export const backgroundPositions = ["center", "top left", "top", "top right", "left", "right", "bottom left", "bottom", "bottom right"] as const;
|
||||
export const backgroundSizes = ["cover", "contain", "auto"] as const;
|
||||
export interface BackgroundAppearance { overlay: number; position: typeof backgroundPositions[number]; size: typeof backgroundSizes[number] }
|
||||
export function parseBackground(value: unknown): BackgroundAppearance {
|
||||
const raw = value as Partial<BackgroundAppearance> | null;
|
||||
return { overlay: typeof raw?.overlay === "number" && Number.isFinite(raw.overlay) ? Math.max(-1, Math.min(1, raw.overlay)) : 0,
|
||||
position: backgroundPositions.includes(raw?.position as any) ? raw!.position! : "center",
|
||||
size: backgroundSizes.includes(raw?.size as any) ? raw!.size! : "cover" };
|
||||
}
|
||||
export function backgroundOverlay(value: number) {
|
||||
const color = value < 0 ? `rgba(255,255,255,${-value})` : `rgba(0,0,0,${value})`;
|
||||
return `linear-gradient(${color}, ${color})`;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export function headingEdit(value: string, selectionStart: number, selectionEnd: number) {
|
||||
const start = selectionStart === 0 ? 0 : value.lastIndexOf("\n", selectionStart - 1) + 1;
|
||||
const last = selectionEnd > selectionStart && value[selectionEnd - 1] === "\n"
|
||||
? selectionEnd - 1 : selectionEnd;
|
||||
const next = value.indexOf("\n", last);
|
||||
const end = next < 0 ? value.length : next;
|
||||
const edits: { start: number; removed: number; added: number }[] = [];
|
||||
let offset = start;
|
||||
const text = value.slice(start, end).split("\n").map(line => {
|
||||
const prefix = /^( {0,3})(#{1,6})(?:[\t ]+|$)/.exec(line);
|
||||
const removed = prefix?.[0].length ?? 0;
|
||||
const replacement = `${prefix?.[1] ?? ""}## `;
|
||||
edits.push({ start: offset, removed, added: replacement.length });
|
||||
offset += line.length + 1;
|
||||
return replacement + line.slice(removed);
|
||||
}).join("\n");
|
||||
const position = (original: number) => {
|
||||
let result = original;
|
||||
for (const edit of edits) {
|
||||
if (original < edit.start) break;
|
||||
result += original < edit.start + edit.removed
|
||||
? edit.added - (original - edit.start) : edit.added - edit.removed;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
return { start, end, text, selectionStart: position(selectionStart), selectionEnd: position(selectionEnd) };
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import MarkdownIt from "markdown-it";
|
||||
import { imagePath } from "../storage/images.ts";
|
||||
|
||||
const markdown = new MarkdownIt({ html: false, linkify: false, breaks: true });
|
||||
markdown.validateLink = (url) => /^(https?:|mailto:|#|pm-image:)/i.test(url);
|
||||
markdown.renderer.rules.link_open = (tokens, index, options, _env, self) => {
|
||||
const token = tokens[index];
|
||||
const href = String(token.attrGet("href") ?? "");
|
||||
if (!/^(https?:|mailto:|#)/i.test(href)) token.attrs = [];
|
||||
else {
|
||||
token.attrSet("target", "_blank");
|
||||
token.attrSet("rel", "noopener noreferrer");
|
||||
}
|
||||
return self.renderToken(tokens, index, options);
|
||||
};
|
||||
// Image sources come only from the validated workspace image store, never from Markdown URLs.
|
||||
markdown.renderer.rules.image = (tokens, index) => {
|
||||
const token = tokens[index];
|
||||
const id = String(token.attrGet("src") ?? "").replace(/^pm-image:/, "");
|
||||
const name = markdown.utils.escapeHtml(token.content || "Image");
|
||||
try {
|
||||
imagePath(id);
|
||||
return `<img data-pm-image="${id}" alt="${name}">`;
|
||||
} catch {
|
||||
return `<span class="pm-muted">Image: ${name} (use Add image to import)</span>`;
|
||||
}
|
||||
};
|
||||
|
||||
export function renderMarkdown(source: string): string {
|
||||
return markdown.render(source);
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import { message } from "../storage/message.ts";
|
||||
|
||||
export const statuses = ["todo", "doing", "done"] as const;
|
||||
export type Status = (typeof statuses)[number];
|
||||
export const priorities = ["highest", "high", "medium", "low", "lowest"] as const;
|
||||
export type PriorityLevels = 2 | 3 | 5;
|
||||
export function availablePriorities(levels: PriorityLevels): readonly Priority[] {
|
||||
return levels === 2 ? ["high", "low"] : levels === 3 ? ["high", "medium", "low"] : priorities;
|
||||
}
|
||||
export type Priority = (typeof priorities)[number];
|
||||
export const priorityNames: Record<Priority, string> = {
|
||||
highest: message("Highest"),
|
||||
high: message("High"),
|
||||
medium: message("Medium"),
|
||||
low: message("Low"),
|
||||
lowest: message("Lowest"),
|
||||
};
|
||||
export const statusNames: Record<Status, string> = {
|
||||
todo: message("To do"),
|
||||
doing: message("In progress"),
|
||||
done: message("Done"),
|
||||
};
|
||||
export const cardColors = {
|
||||
red: "#df7373",
|
||||
orange: "#d99554",
|
||||
amber: "#dda83e",
|
||||
yellow: "#c5ae4f",
|
||||
lime: "#a4bd58",
|
||||
green: "#63ad84",
|
||||
teal: "#4cafa6",
|
||||
cyan: "#53b8cf",
|
||||
blue: "#729fe0",
|
||||
indigo: "#8790df",
|
||||
purple: "#ac89d8",
|
||||
magenta: "#cb75c8",
|
||||
pink: "#d784b0",
|
||||
brown: "#b48b68",
|
||||
slate: "#8398ae",
|
||||
gray: "#a4a6ad",
|
||||
} as const;
|
||||
export interface Plan {
|
||||
start: string;
|
||||
end: string;
|
||||
}
|
||||
export interface Session {
|
||||
id: string;
|
||||
start: string;
|
||||
end: string;
|
||||
timeZone: string;
|
||||
}
|
||||
export interface TaskFields {
|
||||
createdAt?: string;
|
||||
title?: string;
|
||||
order?: string;
|
||||
color?: string;
|
||||
assignees?: string[];
|
||||
customFields?: { name: string; value: string }[];
|
||||
listId?: string | null;
|
||||
placements?: Record<string, { listId: string | null; order?: string }>;
|
||||
status: Status;
|
||||
tags: string[];
|
||||
labels?: string[];
|
||||
priority?: Priority | null;
|
||||
coverImage?: string | null;
|
||||
attachments?: { id: string; name: string }[];
|
||||
subtasks?: { id: string; title: string; done: boolean; taskId?: string }[];
|
||||
links?: { taskId: string; relation: "relates" | "blocks" | "blocked-by" }[];
|
||||
due?: { date: string };
|
||||
plan?: Plan;
|
||||
sessions: Session[];
|
||||
archived: boolean;
|
||||
}
|
||||
export interface Task extends TaskFields {
|
||||
id: string;
|
||||
path: string;
|
||||
title: string;
|
||||
body: string;
|
||||
source: string;
|
||||
}
|
||||
export interface Entry {
|
||||
name: string;
|
||||
rel_path: string;
|
||||
kind: string;
|
||||
}
|
||||
export interface Workspace {
|
||||
list(path?: string): Promise<Entry[]>;
|
||||
listMarkdown?(): Promise<string[]>;
|
||||
read(path: string): Promise<string>;
|
||||
readMany?(paths: string[]): Promise<{ path: string; source?: string; error?: string }[]>;
|
||||
readOptional?(path: string): Promise<string | null>;
|
||||
write(path: string, contents: string, expected: string): Promise<void>;
|
||||
create?(path: string, contents: string): Promise<void>;
|
||||
subscribe?(listener: () => void): () => void;
|
||||
}
|
||||
export function validDate(value: unknown): value is string {
|
||||
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value))
|
||||
return false;
|
||||
const date = new Date(`${value}T00:00:00Z`);
|
||||
return !isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
||||
}
|
||||
export function addDays(value: string, days: number): string {
|
||||
if (!validDate(value)) throw new Error(message("Enter a valid calendar date."));
|
||||
const date = new Date(`${value}T12:00:00Z`);
|
||||
date.setUTCDate(date.getUTCDate() + days);
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
export function dayDistance(start: string, end: string): number {
|
||||
return Math.round(
|
||||
(Date.parse(`${end}T12:00:00Z`) - Date.parse(`${start}T12:00:00Z`)) /
|
||||
86_400_000,
|
||||
);
|
||||
}
|
||||
export function localDay(date = new Date()): string {
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
||||
}
|
||||
export function localTime(instant: string): string {
|
||||
const date = new Date(instant);
|
||||
return `${localDay(date)}T${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
|
||||
}
|
||||
export function localInstant(value: string): string {
|
||||
const date = new Date(value);
|
||||
if (isNaN(date.getTime()) || localTime(date.toISOString()) !== value)
|
||||
throw new Error(message("Enter an existing local date and time."));
|
||||
return date.toISOString();
|
||||
}
|
||||
export function validateFields(fields: TaskFields): void {
|
||||
if (fields.createdAt !== undefined && (typeof fields.createdAt !== "string" ||
|
||||
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(fields.createdAt) ||
|
||||
!validDate(fields.createdAt.slice(0, 10)) || !Number.isFinite(Date.parse(fields.createdAt))))
|
||||
throw new Error(message("The card creation timestamp is invalid."));
|
||||
if (fields.attachments !== undefined && (!Array.isArray(fields.attachments) || fields.attachments.some(item => !item || typeof item.id !== "string" || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(item.id) || typeof item.name !== "string" || !item.name.trim() || item.name.length > 255) || new Set(fields.attachments.map(item => item.id)).size !== fields.attachments.length))
|
||||
throw new Error(message("Each image attachment needs a unique image ID and a name of 1 to 255 characters."));
|
||||
if (fields.priority !== undefined && fields.priority !== null && !priorities.includes(fields.priority))
|
||||
throw new Error(message("Choose a supported priority or No priority."));
|
||||
if (fields.coverImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(fields.coverImage))
|
||||
throw new Error(message("Choose an image from this card."));
|
||||
if (fields.subtasks !== undefined && (!Array.isArray(fields.subtasks) || fields.subtasks.some(item => !item || typeof item.id !== "string" || !item.id || typeof item.title !== "string" || !item.title.trim() || item.title.length > 200 || typeof item.done !== "boolean" || (item.taskId !== undefined && (typeof item.taskId !== "string" || !item.taskId))) || new Set(fields.subtasks.map(item => item.id)).size !== fields.subtasks.length))
|
||||
throw new Error(message("Each subtask needs a unique ID, a title, and a completion state."));
|
||||
if (fields.links !== undefined && (!Array.isArray(fields.links) || fields.links.some(item => !item || typeof item.taskId !== "string" || !item.taskId || !["relates", "blocks", "blocked-by"].includes(item.relation)) || new Set(fields.links.map(item => item.taskId)).size !== fields.links.length))
|
||||
throw new Error(message("Choose each linked card once and select its relationship."));
|
||||
if (
|
||||
fields.title !== undefined &&
|
||||
(typeof fields.title !== "string" ||
|
||||
!fields.title.trim() ||
|
||||
fields.title.length > 100 ||
|
||||
/[\x00-\x1f]/.test(fields.title))
|
||||
)
|
||||
throw new Error(message("Enter a card title of 1 to 100 characters."));
|
||||
const validOrder = (value: unknown) =>
|
||||
value === undefined ||
|
||||
(typeof value === "string" && /^[0-9a-z]*[1-9a-z]$/.test(value));
|
||||
if (!validOrder(fields.order))
|
||||
throw new Error(message("The card order is invalid. Refresh the board."));
|
||||
if (fields.placements !== undefined) {
|
||||
if (
|
||||
!fields.placements ||
|
||||
typeof fields.placements !== "object" ||
|
||||
Array.isArray(fields.placements)
|
||||
)
|
||||
throw new Error(message("Board placements must be a mapping."));
|
||||
for (const [id, placement] of Object.entries(fields.placements)) {
|
||||
if (
|
||||
!id.trim() ||
|
||||
!placement ||
|
||||
typeof placement !== "object" ||
|
||||
Array.isArray(placement) ||
|
||||
(placement.listId !== null &&
|
||||
(typeof placement.listId !== "string" || !placement.listId)) ||
|
||||
!validOrder(placement.order)
|
||||
)
|
||||
throw new Error(message("Each board placement needs a board ID and a valid list ID."));
|
||||
}
|
||||
}
|
||||
if (
|
||||
fields.color !== undefined &&
|
||||
(typeof fields.color !== "string" ||
|
||||
!Object.hasOwn(cardColors, fields.color))
|
||||
)
|
||||
throw new Error(message("Choose a supported card color."));
|
||||
if (
|
||||
fields.assignees !== undefined &&
|
||||
(!Array.isArray(fields.assignees) ||
|
||||
fields.assignees.some((name) => typeof name !== "string" || !name.trim()))
|
||||
)
|
||||
throw new Error(message("Assignments must contain names."));
|
||||
if (fields.customFields !== undefined) {
|
||||
if (
|
||||
!Array.isArray(fields.customFields) ||
|
||||
fields.customFields.some(
|
||||
(field) =>
|
||||
!field ||
|
||||
typeof field.name !== "string" ||
|
||||
!field.name.trim() ||
|
||||
typeof field.value !== "string",
|
||||
)
|
||||
)
|
||||
throw new Error(message("Each custom field needs a name and a text value."));
|
||||
const names = fields.customFields.map((field) =>
|
||||
field.name.trim().toLocaleLowerCase(),
|
||||
);
|
||||
if (new Set(names).size !== names.length)
|
||||
throw new Error(message("Use a different name for each custom field."));
|
||||
}
|
||||
if (
|
||||
fields.listId !== undefined &&
|
||||
fields.listId !== null &&
|
||||
(typeof fields.listId !== "string" || !fields.listId)
|
||||
)
|
||||
throw new Error(message("The task has an invalid list ID."));
|
||||
if (!statuses.includes(fields.status))
|
||||
throw new Error(message("Choose a supported task status."));
|
||||
if (
|
||||
!Array.isArray(fields.tags) ||
|
||||
fields.tags.some((tag) => typeof tag !== "string")
|
||||
)
|
||||
throw new Error(message("Tags must be text."));
|
||||
if (
|
||||
fields.labels !== undefined &&
|
||||
(!Array.isArray(fields.labels) ||
|
||||
fields.labels.some(
|
||||
(id) => typeof id !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(id),
|
||||
) ||
|
||||
new Set(fields.labels).size !== fields.labels.length)
|
||||
)
|
||||
throw new Error(message("Labels must contain unique saved label IDs."));
|
||||
if (fields.due && !validDate(fields.due.date))
|
||||
throw new Error(message("Enter a valid deadline date."));
|
||||
if (
|
||||
fields.plan &&
|
||||
(!validDate(fields.plan.start) ||
|
||||
!validDate(fields.plan.end) ||
|
||||
fields.plan.end <= fields.plan.start)
|
||||
) {
|
||||
throw new Error(message("The planned end must follow the start."));
|
||||
}
|
||||
const ids = new Set<string>();
|
||||
for (const session of fields.sessions) {
|
||||
const instant =
|
||||
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
|
||||
if (
|
||||
!session.id ||
|
||||
ids.has(session.id) ||
|
||||
!instant.test(session.start) ||
|
||||
!instant.test(session.end) ||
|
||||
!validDate(session.start.slice(0, 10)) ||
|
||||
!validDate(session.end.slice(0, 10)) ||
|
||||
!Number.isFinite(Date.parse(session.start)) ||
|
||||
!Number.isFinite(Date.parse(session.end)) ||
|
||||
Date.parse(session.end) <= Date.parse(session.start)
|
||||
)
|
||||
throw new Error(message("Each session needs a unique ID and a valid time range."));
|
||||
new Intl.DateTimeFormat("en", { timeZone: session.timeZone }).format();
|
||||
ids.add(session.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,880 @@
|
||||
import { readTask, editTask, adoptNote, split } from "../storage/notes.ts";
|
||||
import { createCard, readCards, cardOrigin, cardPath, fileIssue, migrateCards, parseCard, prepareCards } from "../storage/cards.ts";
|
||||
import { cardsFolder, cardsMarker, isHiddenCard, readOptional, saveDocument, storageRoot } from "../storage/persistence.ts";
|
||||
import { deletedCardsPath, readDeletedCards, recordCardDeletion } from "../storage/deleted-cards.ts";
|
||||
import { mapConcurrent, markdownPaths, readSources } from "../storage/scan.ts";
|
||||
import type { Task, TaskFields, Workspace } from "./model.ts";
|
||||
import { cardOrder, compareCards, orderBetween } from "../storage/order.ts";
|
||||
import { LabelStore, labelsPath, parseLabels, type LabelSnapshot, type SavedLabel } from "../storage/labels.ts";
|
||||
import {
|
||||
catalogPath,
|
||||
readCatalog,
|
||||
managedDocuments,
|
||||
isManagedBoard,
|
||||
createBoard,
|
||||
} from "../storage/catalog.ts";
|
||||
import { migrateStorage } from "../storage/migration.ts";
|
||||
import { format, message } from "../storage/message.ts";
|
||||
import {
|
||||
BoardStore,
|
||||
boardDocument,
|
||||
type BoardDocument,
|
||||
type BoardReference,
|
||||
} from "../storage/board.ts";
|
||||
|
||||
const workspaceTasks = new WeakMap<Workspace, Task[]>();
|
||||
|
||||
export interface TaskStoreOptions {
|
||||
/**
|
||||
* True (the default) also reads the visible Markdown notes of the legacy format: boards and task notes in the workspace.
|
||||
* The migration and the read-only skill helper use it. False reads only `.runestone/pm/`, and a save, a delete,
|
||||
* or a move reads only the changed files again. The native feature of RuneStone uses false.
|
||||
*/
|
||||
legacy?: boolean;
|
||||
}
|
||||
|
||||
const errorMessage = (error: unknown) => error instanceof Error ? error.message : String(error);
|
||||
/** The issue of a task ID that more than one note uses. `adopt()` looks for this issue. */
|
||||
const duplicateTaskIssue = (id: string) =>
|
||||
format(message("Duplicate task ID {id}: resolve the copied notes before editing them."), { id });
|
||||
|
||||
/** The files of `.runestone/pm/` that the hidden mode reads, with the problem of each file. */
|
||||
interface HiddenState {
|
||||
cards: Map<string, Task>;
|
||||
cardIssues: Map<string, string>;
|
||||
cardsError: string;
|
||||
catalog: { source: string | null; boards: BoardDocument[]; error: string };
|
||||
labels: { snapshot?: LabelSnapshot; error: string };
|
||||
deleted: { ids: Set<string>; error: string };
|
||||
}
|
||||
|
||||
export class TaskStore {
|
||||
tasks: Task[] = [];
|
||||
boards: BoardDocument[] = [];
|
||||
legacyBoards: BoardDocument[] = [];
|
||||
issues: string[] = [];
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
private disposed = false;
|
||||
private loaded = false;
|
||||
private revision = 0;
|
||||
private hidden?: HiddenState;
|
||||
readonly legacy: boolean;
|
||||
readonly workspace: Workspace;
|
||||
readonly board: BoardStore;
|
||||
readonly labels: LabelStore;
|
||||
constructor(workspace: Workspace, board?: BoardReference, options: TaskStoreOptions = {}) {
|
||||
this.workspace = workspace;
|
||||
this.legacy = options.legacy ?? true;
|
||||
this.tasks = workspaceTasks.get(workspace) ?? [];
|
||||
this.board = new BoardStore(workspace, board);
|
||||
this.labels = new LabelStore(workspace);
|
||||
}
|
||||
get scopedTasks() {
|
||||
const id = this.board.reference?.id;
|
||||
return id
|
||||
? this.board.available
|
||||
? this.tasks.filter((task) => Object.hasOwn(task.placements ?? {}, id))
|
||||
: []
|
||||
: this.tasks;
|
||||
}
|
||||
dispose() {
|
||||
this.disposed = true;
|
||||
}
|
||||
private check() {
|
||||
if (this.disposed)
|
||||
throw new Error(message("The Project Management view is closed. Reopen it before saving."));
|
||||
}
|
||||
/** Read all Project Management data again. */
|
||||
async reload(): Promise<void> {
|
||||
if (this.legacy) return this.reloadLegacy();
|
||||
this.check();
|
||||
const revision = ++this.revision;
|
||||
const previous = this.hidden?.cards ?? new Map(this.tasks.map((task) => [task.path, task]));
|
||||
const state: HiddenState = {
|
||||
cards: new Map(), cardIssues: new Map(), cardsError: "",
|
||||
catalog: { source: null, boards: [], error: "" }, labels: { error: "" }, deleted: { ids: new Set(), error: "" },
|
||||
};
|
||||
try {
|
||||
// Direct reads are necessary because the host hides .runestone from root listings.
|
||||
if ((await readOptional(this.workspace, cardsMarker)) !== null) {
|
||||
const paths = (await this.workspace.list(cardsFolder))
|
||||
.filter((entry) => entry.kind !== "folder" && isHiddenCard(entry.rel_path)).map((entry) => entry.rel_path);
|
||||
const sources = await readSources(this.workspace, paths);
|
||||
for (const path of paths) this.acceptCard(state, path, sources.get(path)!, previous.get(path));
|
||||
}
|
||||
} catch (error) {
|
||||
state.cardsError = errorMessage(error);
|
||||
}
|
||||
await Promise.all([this.readHiddenCatalog(state), this.readHiddenLabels(state), this.readHiddenDeleted(state)]);
|
||||
this.check();
|
||||
if (revision !== this.revision) return;
|
||||
this.hidden = state;
|
||||
this.publishHidden();
|
||||
}
|
||||
/**
|
||||
* Read only the changed files of `.runestone/pm/` again, for example after a watcher event.
|
||||
* Paths outside `.runestone/pm/` change nothing. A change of a folder, of the storage markers, or an unknown change
|
||||
* (`undefined`) reads everything again. The legacy mode always reads everything again.
|
||||
*/
|
||||
reloadPaths(paths?: readonly string[]): Promise<void> {
|
||||
return this.run(() => this.reloadFor(paths));
|
||||
}
|
||||
private async reloadFor(paths?: readonly string[]) {
|
||||
if (this.legacy || !this.hidden || !paths) return this.reload();
|
||||
const relevant = [...new Set(paths)].filter((path) => path === ".runestone" || path === storageRoot || path.startsWith(storageRoot + "/"));
|
||||
// A folder or the card marker can change many cards at once.
|
||||
if (relevant.some((path) => [".runestone", storageRoot, cardsFolder, cardsMarker].includes(path))) return this.reload();
|
||||
const cards = relevant.filter((path) => isHiddenCard(path) && path.lastIndexOf("/") === cardsFolder.length);
|
||||
const files = relevant.filter((path) => [catalogPath, labelsPath, deletedCardsPath].includes(path));
|
||||
// Images, drafts, backups, and the Git exclusion change no card, board, or label.
|
||||
if (!cards.length && !files.length) return;
|
||||
this.check();
|
||||
const state = this.hidden;
|
||||
++this.revision;
|
||||
const work: Promise<void>[] = [];
|
||||
if (cards.length) work.push((async () => {
|
||||
const sources = await readSources(this.workspace, cards);
|
||||
for (const path of cards) {
|
||||
const result = sources.get(path)!;
|
||||
// A missing file is a deleted card. The host reports another read error for it.
|
||||
if (result.source === undefined && (await readOptional(this.workspace, path)) === null) {
|
||||
state.cards.delete(path);
|
||||
state.cardIssues.delete(path);
|
||||
} else this.acceptCard(state, path, result, state.cards.get(path));
|
||||
}
|
||||
})());
|
||||
if (relevant.includes(catalogPath)) work.push(this.readHiddenCatalog(state));
|
||||
if (relevant.includes(labelsPath)) work.push(this.readHiddenLabels(state));
|
||||
if (relevant.includes(deletedCardsPath)) work.push(this.readHiddenDeleted(state));
|
||||
await Promise.all(work);
|
||||
this.check();
|
||||
if (this.hidden === state) this.publishHidden();
|
||||
}
|
||||
private acceptCard(state: HiddenState, path: string, result: { source?: string; error?: string }, cached?: Task) {
|
||||
try {
|
||||
if (result.error || result.source === undefined) throw new Error(result.error ?? message("The card is unavailable."));
|
||||
state.cards.set(path, cached?.source === result.source ? cached : parseCard(path, result.source));
|
||||
state.cardIssues.delete(path);
|
||||
} catch (error) {
|
||||
state.cards.delete(path);
|
||||
state.cardIssues.set(path, errorMessage(error));
|
||||
}
|
||||
}
|
||||
private async readHiddenCatalog(state: HiddenState) {
|
||||
try {
|
||||
const catalog = await readCatalog(this.workspace);
|
||||
state.catalog = { source: catalog.source, boards: managedDocuments(catalog.value, catalog.source ?? ""), error: "" };
|
||||
} catch (error) {
|
||||
// Do not expose boards as writable when hidden storage cannot be read.
|
||||
state.catalog = { source: null, boards: [], error: errorMessage(error) };
|
||||
}
|
||||
}
|
||||
private async readHiddenLabels(state: HiddenState) {
|
||||
try { state.labels = { snapshot: await this.labels.read(), error: "" }; }
|
||||
catch (error) { state.labels = { error: errorMessage(error) }; }
|
||||
}
|
||||
private async readHiddenDeleted(state: HiddenState) {
|
||||
try { state.deleted = { ids: new Set((await readDeletedCards(this.workspace)).ids), error: "" }; }
|
||||
catch (error) { state.deleted = { ids: new Set(), error: errorMessage(error) }; }
|
||||
}
|
||||
/** Make the public fields from the hidden files. One invalid card file hides all cards, as in the legacy mode. */
|
||||
private publishHidden() {
|
||||
const state = this.hidden!;
|
||||
const issues: string[] = [...[...state.cardIssues].map(([path, issue]) => fileIssue(path, issue))];
|
||||
if (state.cardsError) issues.push(format(message("Hidden cards: {error}"), { error: state.cardsError }));
|
||||
if (state.catalog.error) issues.push(format(message("Hidden Project Management storage: {error}"), { error: state.catalog.error }));
|
||||
if (state.labels.error) issues.push(format(message("Saved labels: {error}"), { error: state.labels.error }));
|
||||
if (state.deleted.error) issues.push(format(message("Deleted cards: {error}"), { error: state.deleted.error }));
|
||||
this.labels.load(state.labels.snapshot, state.labels.error);
|
||||
const blocked = !!(state.cardsError || state.cardIssues.size || state.deleted.error);
|
||||
this.tasks = blocked ? [] : [...state.cards.values()]
|
||||
.filter((task) => !state.deleted.ids.has(task.id))
|
||||
.sort((a, b) => a.title.localeCompare(b.title));
|
||||
this.boards = [...state.catalog.boards].sort((a, b) => a.name.localeCompare(b.name));
|
||||
this.legacyBoards = [];
|
||||
if (this.board.reference) {
|
||||
this.board.load(this.boards.find((board) => board.id === this.board.reference!.id));
|
||||
if (!this.board.available)
|
||||
issues.push(message("This board is missing, invalid, or duplicated. Task notes remain available in All tasks."));
|
||||
}
|
||||
this.issues = issues;
|
||||
workspaceTasks.set(this.workspace, this.tasks);
|
||||
this.loaded = true;
|
||||
}
|
||||
private async reloadLegacy(): Promise<void> {
|
||||
this.check();
|
||||
const revision = ++this.revision;
|
||||
const tasks: Task[] = [],
|
||||
issues: string[] = [];
|
||||
const boards: BoardDocument[] = [];
|
||||
const previous = new Map(this.tasks.map((task) => [task.path, task]));
|
||||
const paths = await markdownPaths(this.workspace, () => this.check());
|
||||
const sources = await readSources(this.workspace, paths);
|
||||
const documents = await mapConcurrent(paths, async (path) => {
|
||||
this.check();
|
||||
try {
|
||||
const result = sources.get(path)!;
|
||||
if (result.error || result.source === undefined) throw new Error(result.error ?? message("The file is unavailable."));
|
||||
const source = result.source;
|
||||
const cached = previous.get(path);
|
||||
if (cached?.source === source) return { task: cached };
|
||||
const board = boardDocument(source, path);
|
||||
return board ? { board } : { task: readTask(path, source) };
|
||||
} catch (error) {
|
||||
return { issue: fileIssue(path, errorMessage(error)) };
|
||||
}
|
||||
});
|
||||
for (const document of documents) {
|
||||
if (document.board) boards.push(document.board);
|
||||
if (document.task) tasks.push(document.task);
|
||||
if (document.issue) issues.push(document.issue);
|
||||
}
|
||||
try {
|
||||
const hidden = await readCards(this.workspace, previous);
|
||||
issues.push(...hidden.issues);
|
||||
if (hidden.issues.length) tasks.length = 0;
|
||||
for (const card of hidden.tasks) {
|
||||
const originals = tasks.filter((task) => task.id === card.id);
|
||||
const origin = originals.length ? cardOrigin(card.source) : undefined;
|
||||
for (const original of originals) {
|
||||
if (
|
||||
origin?.path === original.path &&
|
||||
origin.source === original.source
|
||||
)
|
||||
tasks.splice(tasks.indexOf(original), 1);
|
||||
else
|
||||
issues.push(format(
|
||||
message("The original card differs from hidden storage: {path}. Preserve both versions."),
|
||||
{ path: original.path },
|
||||
));
|
||||
}
|
||||
}
|
||||
tasks.push(...hidden.tasks);
|
||||
} catch (error) {
|
||||
issues.push(format(message("Hidden cards: {error}"), { error: errorMessage(error) }));
|
||||
// Block legacy edits when the hidden store cannot be checked for migrated IDs.
|
||||
tasks.length = 0;
|
||||
}
|
||||
let legacyBoards = [...boards];
|
||||
try {
|
||||
const catalog = await readCatalog(this.workspace);
|
||||
for (let index = boards.length - 1; index >= 0; index--)
|
||||
if (catalog.value.deletedBoardIds?.includes(boards[index].id))
|
||||
boards.splice(index, 1);
|
||||
legacyBoards = [...boards];
|
||||
for (const managed of catalog.value.boards) {
|
||||
const matches = boards.filter((board) => board.id === managed.value.id);
|
||||
for (const board of matches) {
|
||||
if (
|
||||
managed.original?.path === board.path &&
|
||||
managed.original.source === board.source
|
||||
)
|
||||
boards.splice(boards.indexOf(board), 1);
|
||||
else
|
||||
issues.push(format(
|
||||
message("The legacy board differs from hidden storage: {path}. Preserve both versions before cleanup."),
|
||||
{ path: board.path },
|
||||
));
|
||||
}
|
||||
}
|
||||
boards.push(...managedDocuments(catalog.value, catalog.source ?? ""));
|
||||
} catch (error) {
|
||||
issues.push(format(message("Hidden Project Management storage: {error}"), { error: errorMessage(error) }));
|
||||
// Do not expose legacy boards as writable when hidden storage cannot be read.
|
||||
boards.length = 0;
|
||||
}
|
||||
let labels: LabelSnapshot | undefined,
|
||||
labelError = "";
|
||||
try {
|
||||
labels = await this.labels.read();
|
||||
} catch (error) {
|
||||
labelError = errorMessage(error);
|
||||
issues.push(format(message("Saved labels: {error}"), { error: labelError }));
|
||||
}
|
||||
this.check();
|
||||
if (revision !== this.revision) return;
|
||||
this.labels.load(labels, labelError);
|
||||
this.legacyBoards = legacyBoards;
|
||||
const counts = new Map<string, number>();
|
||||
for (const task of tasks)
|
||||
counts.set(task.id, (counts.get(task.id) ?? 0) + 1);
|
||||
for (const [id, count] of counts)
|
||||
if (count > 1) issues.push(duplicateTaskIssue(id));
|
||||
let deletedIds = new Set<string>();
|
||||
try { deletedIds = new Set((await readDeletedCards(this.workspace)).ids); }
|
||||
catch (error) {
|
||||
issues.push(format(message("Deleted cards: {error}"), { error: errorMessage(error) }));
|
||||
tasks.length = 0;
|
||||
}
|
||||
this.check();
|
||||
if (revision !== this.revision) return;
|
||||
this.tasks = tasks
|
||||
.filter((task) => counts.get(task.id) === 1 && !deletedIds.has(task.id))
|
||||
.sort((a, b) => a.title.localeCompare(b.title));
|
||||
const boardCounts = new Map<string, number>();
|
||||
for (const board of boards)
|
||||
boardCounts.set(board.id, (boardCounts.get(board.id) ?? 0) + 1);
|
||||
for (const [id, count] of boardCounts)
|
||||
if (count > 1)
|
||||
issues.push(format(message("Duplicate board ID {id}: resolve the copied boards before editing them."), { id }));
|
||||
this.boards = boards
|
||||
.filter((board) => boardCounts.get(board.id) === 1)
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
if (this.board.reference) {
|
||||
this.board.load(
|
||||
this.boards.find((board) => board.id === this.board.reference!.id),
|
||||
);
|
||||
if (!this.board.available)
|
||||
issues.push(message("This board is missing, invalid, or duplicated. Task notes remain available in All tasks."));
|
||||
}
|
||||
this.issues = issues;
|
||||
workspaceTasks.set(this.workspace, this.tasks);
|
||||
this.loaded = true;
|
||||
}
|
||||
private run<T>(action: () => Promise<T>): Promise<T> {
|
||||
const result = this.queue.then(() => {
|
||||
this.check();
|
||||
return action();
|
||||
});
|
||||
this.queue = result.catch(() => {});
|
||||
return result;
|
||||
}
|
||||
save(
|
||||
task: Task,
|
||||
patch: Partial<TaskFields> & { body?: string },
|
||||
applyListStatus = false,
|
||||
): Promise<void> {
|
||||
return this.run(() => this.saveTask(task, patch, applyListStatus));
|
||||
}
|
||||
deleteCard(task: Task): Promise<void> {
|
||||
return this.run(async () => {
|
||||
await this.reloadFor([task.path]);
|
||||
const current = this.tasks.find(item => item.id === task.id && item.path === task.path);
|
||||
if (!current || current.source !== task.source)
|
||||
throw new Error(message("The card changed or is unavailable. Refresh before deleting it."));
|
||||
await recordCardDeletion(this.workspace, task.id);
|
||||
await this.reloadFor([deletedCardsPath]);
|
||||
});
|
||||
}
|
||||
unlinkIncoming(targetId: string, sources: Task[]): Promise<void> {
|
||||
if (!sources.length) return Promise.resolve();
|
||||
return this.run(async () => {
|
||||
await this.reloadFor(sources.map(source => source.path));
|
||||
const current = sources.map(source => {
|
||||
const found = this.tasks.find(task => task.id === source.id && task.path === source.path);
|
||||
if (found && !found.links?.some(link => link.taskId === targetId)) return undefined;
|
||||
if (!found || found.source !== source.source)
|
||||
throw new Error(message("A linked card changed. Refresh before removing its link."));
|
||||
return found;
|
||||
});
|
||||
for (const source of current) {
|
||||
if (!source) continue;
|
||||
await this.saveTask(source, { links: source.links?.filter(link => link.taskId !== targetId) }, false, undefined, true);
|
||||
}
|
||||
});
|
||||
}
|
||||
private async saveTask(
|
||||
task: Task,
|
||||
patch: Partial<TaskFields> & { body?: string },
|
||||
applyListStatus: boolean,
|
||||
beforeId?: string | null,
|
||||
reloaded = false,
|
||||
placementBoardId = this.board.reference?.id,
|
||||
): Promise<void> {
|
||||
if (!reloaded) await this.reloadFor([task.path]);
|
||||
const current = this.tasks.find(
|
||||
(item) => item.id === task.id && item.path === task.path,
|
||||
);
|
||||
if (!current || current.source !== task.source)
|
||||
throw new Error(message("The task changed or has a duplicate ID. Cancel, refresh, and review the note before saving."));
|
||||
const next = { ...patch };
|
||||
if (Object.hasOwn(next, "listId")) {
|
||||
if (this.board.archived)
|
||||
throw new Error(message("Restore this board before moving cards."));
|
||||
const listId = next.listId ?? null;
|
||||
const list = this.board.value.lists.find((list) => list.id === listId);
|
||||
if (listId !== null && !list)
|
||||
throw new Error(message("This list no longer exists. Refresh the board."));
|
||||
const previousList = this.board.listFor(task);
|
||||
if (applyListStatus && listId !== (previousList?.id ?? null)) {
|
||||
if (list?.status) next.status = list.status;
|
||||
else if (previousList?.status === "done" && task.status === "done") next.status = "todo";
|
||||
}
|
||||
const id = this.board.reference?.id;
|
||||
if (id) {
|
||||
if (!this.board.available)
|
||||
throw new Error(message("The board is unavailable. Reopen it before saving."));
|
||||
const placement = { ...task.placements?.[id], listId };
|
||||
if (
|
||||
listId !== (this.board.listFor(task)?.id ?? null) ||
|
||||
beforeId !== undefined
|
||||
)
|
||||
placement.order = this.position(task, listId, beforeId);
|
||||
next.placements = { ...task.placements, [id]: placement };
|
||||
} else if (
|
||||
beforeId !== undefined ||
|
||||
(list?.status && task.status !== list.status)
|
||||
) {
|
||||
next.order = this.position(task, listId, beforeId);
|
||||
}
|
||||
next.listId = undefined;
|
||||
}
|
||||
if (next.status !== undefined && next.status !== task.status) {
|
||||
const placements = { ...(next.placements ?? task.placements) };
|
||||
for (const board of this.boards) {
|
||||
if (board.id === placementBoardId) continue;
|
||||
const placement = placements[board.id];
|
||||
const listId = board.value.defaults[next.status];
|
||||
if (
|
||||
!placement ||
|
||||
listId === null ||
|
||||
placement.listId === listId ||
|
||||
!board.value.lists.some((list) => list.id === listId)
|
||||
)
|
||||
continue;
|
||||
const cards = this.tasks
|
||||
.filter(
|
||||
(card) =>
|
||||
card.id !== task.id &&
|
||||
card.archived === task.archived &&
|
||||
card.placements?.[board.id]?.listId === listId,
|
||||
)
|
||||
.sort((a, b) => compareCards(a, b, board.id));
|
||||
const last = cards.at(-1);
|
||||
placements[board.id] = {
|
||||
...placement,
|
||||
listId,
|
||||
order: orderBetween(last ? cardOrder(last, board.id) : undefined),
|
||||
};
|
||||
next.placements = placements;
|
||||
}
|
||||
}
|
||||
const source = editTask(task, next);
|
||||
await saveDocument(this.workspace, task.path, source, task.source);
|
||||
this.accept(task.path, source);
|
||||
}
|
||||
private accept(path: string, source: string) {
|
||||
++this.revision;
|
||||
if (this.hidden && isHiddenCard(path)) {
|
||||
this.hidden.cards.set(path, readTask(path, source)!);
|
||||
this.hidden.cardIssues.delete(path);
|
||||
this.publishHidden();
|
||||
return;
|
||||
}
|
||||
this.tasks = [
|
||||
...this.tasks.filter((task) => task.path !== path),
|
||||
readTask(path, source)!,
|
||||
].sort((a, b) => a.title.localeCompare(b.title));
|
||||
workspaceTasks.set(this.workspace, this.tasks);
|
||||
}
|
||||
cardsInList(listId: string | null, archived = false): Task[] {
|
||||
return this.scopedTasks
|
||||
.filter(
|
||||
(task) =>
|
||||
task.archived === archived &&
|
||||
(this.board.listFor(task)?.id ?? null) === listId,
|
||||
)
|
||||
.sort((a, b) => compareCards(a, b, this.board.reference?.id));
|
||||
}
|
||||
archiveList(listId: string): Promise<void> {
|
||||
return this.run(async () => {
|
||||
await this.reloadFor(this.cardsInList(listId).map(task => task.path));
|
||||
if (!this.board.editable || !this.board.value.lists.some((list) => list.id === listId))
|
||||
throw new Error(message("The list is unavailable. Refresh the board."));
|
||||
if (this.issues.length)
|
||||
throw new Error(format(message("Resolve workspace issues before archiving cards: {issues}"), { issues: this.issues.join(" ") }));
|
||||
for (const task of this.cardsInList(listId)) {
|
||||
const source = editTask(task, { archived: true });
|
||||
await saveDocument(this.workspace, task.path, source, task.source);
|
||||
this.accept(task.path, source);
|
||||
}
|
||||
});
|
||||
}
|
||||
private position(
|
||||
task: Task | undefined,
|
||||
listId: string | null,
|
||||
beforeId?: string | null,
|
||||
): string {
|
||||
const cards = this.cardsInList(listId, task?.archived).filter(
|
||||
(card) => card.id !== task?.id,
|
||||
);
|
||||
const index =
|
||||
beforeId == null
|
||||
? cards.length
|
||||
: cards.findIndex((card) => card.id === beforeId);
|
||||
if (index < 0) throw new Error(message("The target card moved. Refresh the board."));
|
||||
const id = this.board.reference?.id;
|
||||
return orderBetween(
|
||||
index > 0 ? cardOrder(cards[index - 1], id) : undefined,
|
||||
index < cards.length ? cardOrder(cards[index], id) : undefined,
|
||||
);
|
||||
}
|
||||
async createOrLink(title: string, fields: TaskFields): Promise<void> {
|
||||
const path = title.trim().replaceAll("\\", "/").replace(/^\.\//, "");
|
||||
if (!/\.(md|markdown|mdown)$/i.test(path)) return this.create(title, fields, "");
|
||||
if (/^(?:[a-z]+:|\/)/i.test(path) || path.split("/").some(part => !part || part === "." || part === ".."))
|
||||
throw new Error(message("Use a relative Markdown path inside this workspace."));
|
||||
const added = await this.adopt(path);
|
||||
const task = this.tasks.find(item => item.id === added.id && item.path === added.path);
|
||||
if (!task) throw new Error(message("The linked card is unavailable. Refresh the board."));
|
||||
if (this.board.reference) await this.moveTask(task, fields.listId ?? null);
|
||||
}
|
||||
create(title: string, fields: TaskFields, body: string, destinationId?: string): Promise<void> {
|
||||
return this.run(async () => {
|
||||
if (!this.workspace.create)
|
||||
throw new Error(message("This RuneStone version cannot create plugin notes. Add an existing note or install the host bridge."));
|
||||
if (!this.loaded) await this.reload();
|
||||
++this.revision;
|
||||
if (destinationId !== undefined) await this.reloadFor([catalogPath]);
|
||||
const destination = destinationId === undefined ? undefined : this.boards.find(board => board.id === destinationId && !board.archived);
|
||||
if (destinationId !== undefined && !destination) throw new Error(message("Choose an available, active board for this card."));
|
||||
const id = destination?.id ?? this.board.reference?.id;
|
||||
if (id && !destination && !this.board.available)
|
||||
throw new Error(message("The board is unavailable. Reopen it before saving."));
|
||||
// Named-board creation reads the current board without a workspace scan.
|
||||
await this.board.reload();
|
||||
if (this.board.archived)
|
||||
throw new Error(message("Restore this board before adding cards."));
|
||||
const targetBoard = destination?.value ?? this.board.value;
|
||||
const listId =
|
||||
fields.listId === undefined
|
||||
? targetBoard.defaults[fields.status]
|
||||
: fields.listId;
|
||||
if (
|
||||
id &&
|
||||
listId !== null &&
|
||||
!targetBoard.lists.some((list) => list.id === listId)
|
||||
)
|
||||
throw new Error(message("This list no longer exists. Refresh the board."));
|
||||
const lastGlobalCard = this.tasks
|
||||
.filter(
|
||||
(task) =>
|
||||
task.status === fields.status && task.archived === fields.archived,
|
||||
)
|
||||
.sort((a, b) => compareCards(a, b))
|
||||
.at(-1);
|
||||
const lastDestinationCard = destination && id
|
||||
? this.tasks.filter(task => !task.archived && task.placements?.[id]?.listId === listId)
|
||||
.sort((a, b) => compareCards(a, b, id)).at(-1)
|
||||
: undefined;
|
||||
const placementOrder = destination && id
|
||||
? orderBetween(lastDestinationCard ? cardOrder(lastDestinationCard, id) : undefined)
|
||||
: this.position(undefined, listId);
|
||||
const note = await createCard(
|
||||
this.workspace,
|
||||
title,
|
||||
{
|
||||
...fields,
|
||||
order:
|
||||
fields.order ??
|
||||
orderBetween(
|
||||
lastGlobalCard ? cardOrder(lastGlobalCard) : undefined,
|
||||
),
|
||||
listId: undefined,
|
||||
...(id
|
||||
? {
|
||||
placements: {
|
||||
[id]: { listId, order: placementOrder },
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
body,
|
||||
);
|
||||
this.accept(note.path, note.source);
|
||||
});
|
||||
}
|
||||
openSubtask(parentId: string, subtaskId: string): Promise<Task> {
|
||||
return this.run(async () => {
|
||||
await this.reloadFor([cardPath(parentId)]);
|
||||
const parent = this.tasks.find(task => task.id === parentId);
|
||||
const item = parent?.subtasks?.find(item => item.id === subtaskId);
|
||||
if (!parent || !item) throw new Error(message("The subtask is unavailable. Refresh the board."));
|
||||
if (item.taskId) {
|
||||
const target = this.tasks.find(task => task.id === item.taskId);
|
||||
if (!target) throw new Error(message("The subtask card is unavailable. Refresh the board."));
|
||||
return target;
|
||||
}
|
||||
// A stable ID lets a retry recover after the child saves but the parent fails.
|
||||
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(["subtask", parent.id, item.id])));
|
||||
const id = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("");
|
||||
let target = this.tasks.find(task => task.id === id);
|
||||
if (!target) {
|
||||
const placements = Object.fromEntries(Object.keys(parent.placements ?? {}).map(boardId => {
|
||||
const board = this.boards.find(board => board.id === boardId);
|
||||
return [boardId, { listId: board?.value.defaults[item.done ? "done" : "todo"] ?? null }];
|
||||
}));
|
||||
const note = await createCard(this.workspace, item.title, {
|
||||
status: item.done ? "done" : "todo", tags: [], sessions: [], archived: false, placements,
|
||||
}, "", id);
|
||||
this.accept(note.path, note.source);
|
||||
target = this.tasks.find(task => task.path === cardPath(id));
|
||||
}
|
||||
await this.saveTask(parent, { subtasks: parent.subtasks!.map(subtask => subtask.id === subtaskId ? { ...subtask, taskId: id } : subtask) }, false);
|
||||
return target!;
|
||||
});
|
||||
}
|
||||
moveTask(
|
||||
task: Task,
|
||||
listId: string | null,
|
||||
beforeId?: string | null,
|
||||
): Promise<void> {
|
||||
return this.run(() => this.saveTask(task, { listId }, true, beforeId));
|
||||
}
|
||||
removeFromBoard(task: Task): Promise<void> {
|
||||
const id = this.board.reference?.id;
|
||||
if (!id)
|
||||
return Promise.reject(new Error(message("Open a board before removing a card.")));
|
||||
const placements = { ...task.placements };
|
||||
delete placements[id];
|
||||
return this.save(task, { placements });
|
||||
}
|
||||
saveToBoard(task: Task, destinationId: string, listId: string | null, patch: Partial<TaskFields> & { body?: string }): Promise<void> {
|
||||
return this.run(async () => {
|
||||
await this.reloadFor([task.path]);
|
||||
const destination = this.boards.find(board => board.id === destinationId);
|
||||
if (!destination || destination.archived || (listId !== null && !destination.value.lists.some(list => list.id === listId)))
|
||||
throw new Error(message("The destination board or list is unavailable. Refresh the board."));
|
||||
if (this.board.reference && (!this.board.available || this.board.archived)) throw new Error(message("Open an available, active board before moving a card."));
|
||||
const placements = { ...task.placements };
|
||||
if (this.board.reference) delete placements[this.board.reference.id];
|
||||
const last = this.tasks.filter(item => item.id !== task.id && item.placements?.[destinationId]?.listId === listId).sort((a, b) => compareCards(a, b, destinationId)).at(-1);
|
||||
placements[destinationId] = { listId, order: orderBetween(last ? cardOrder(last, destinationId) : undefined) };
|
||||
const { listId: ignoredList, status: ignoredStatus, ...details } = patch;
|
||||
const destinationList = destination.value.lists.find(list => list.id === listId);
|
||||
const previousList = destination.value.lists.find(list => list.id === task.placements?.[destinationId]?.listId);
|
||||
const status = destinationList?.status ?? (previousList?.status === "done" && task.status === "done" ? "todo" : task.status);
|
||||
await this.saveTask(task, { ...details, status, placements }, false, undefined, true, destinationId);
|
||||
});
|
||||
}
|
||||
transferTask(
|
||||
task: Task,
|
||||
destinationId: string,
|
||||
listId: string | null,
|
||||
): Promise<void> {
|
||||
return this.run(async () => {
|
||||
await this.reloadFor([task.path]);
|
||||
const sourceId = this.board.reference?.id;
|
||||
if (!sourceId || !this.board.available || this.board.archived)
|
||||
throw new Error(message("Open an available, active board before moving a card."));
|
||||
const current = this.tasks.find(
|
||||
(item) => item.id === task.id && item.path === task.path,
|
||||
);
|
||||
if (!current || current.source !== task.source)
|
||||
throw new Error(message("The card changed. Cancel, refresh, and review it before moving."));
|
||||
if (!Object.hasOwn(current.placements ?? {}, sourceId))
|
||||
throw new Error(message("This card no longer belongs to the source board."));
|
||||
if (sourceId === destinationId)
|
||||
throw new Error(message("Choose a different destination board."));
|
||||
const destination = this.boards.find((board) => board.id === destinationId);
|
||||
if (!destination || destination.archived)
|
||||
throw new Error(message("The destination board is unavailable or archived. Choose another board."));
|
||||
if (listId !== null && !destination.value.lists.some((list) => list.id === listId))
|
||||
throw new Error(message("The destination list no longer exists. Choose another list."));
|
||||
const last = this.tasks
|
||||
.filter((card) => card.id !== task.id && card.archived === task.archived &&
|
||||
Object.hasOwn(card.placements ?? {}, destinationId) &&
|
||||
(destination.value.lists.some((list) => list.id === card.placements![destinationId].listId)
|
||||
? card.placements![destinationId].listId : null) === listId)
|
||||
.sort((a, b) => compareCards(a, b, destinationId)).at(-1);
|
||||
const placements = { ...current.placements };
|
||||
delete placements[sourceId];
|
||||
placements[destinationId] = {
|
||||
...placements[destinationId],
|
||||
listId,
|
||||
order: orderBetween(last ? cardOrder(last, destinationId) : undefined),
|
||||
};
|
||||
// One guarded write changes membership without synchronizing other boards.
|
||||
const source = editTask(current, { placements });
|
||||
await saveDocument(this.workspace, current.path, source, current.source);
|
||||
this.accept(current.path, source);
|
||||
});
|
||||
}
|
||||
changeBoard(change: () => Promise<void>, reload = true): Promise<void> {
|
||||
return this.run(async () => {
|
||||
await change();
|
||||
// The hidden mode reads only the catalog again. The saved board then keeps the current catalog text.
|
||||
if (this.hidden) await this.reloadFor([catalogPath]);
|
||||
else if (reload) await this.reload();
|
||||
else this.boards = this.boards.map(board => board.id === this.board.reference?.id
|
||||
? { ...board, value: this.board.value } : board);
|
||||
});
|
||||
}
|
||||
saveLabels(
|
||||
labels: SavedLabel[],
|
||||
expected: string | null | undefined,
|
||||
): Promise<void> {
|
||||
return this.run(async () => {
|
||||
this.labels.checkSave(labels, expected);
|
||||
const removed = new Set(parseLabels(expected ?? null).labels
|
||||
.filter((label) => !labels.some((next) => next.id === label.id)).map((label) => label.id));
|
||||
if (removed.size) {
|
||||
await this.reloadFor([labelsPath]);
|
||||
if (this.labels.source !== expected)
|
||||
throw new Error(message("Saved labels changed. Refresh before deleting labels."));
|
||||
if (this.issues.length)
|
||||
throw new Error(format(message("Resolve workspace issues before deleting labels: {issues}"), { issues: this.issues.join(" ") }));
|
||||
// Keep definitions until every guarded card write succeeds, so a retry is safe.
|
||||
for (const task of this.tasks)
|
||||
if (task.labels?.some((id) => removed.has(id))) {
|
||||
const source = editTask(task, { labels: task.labels.filter((id) => !removed.has(id)) });
|
||||
await saveDocument(this.workspace, task.path, source, task.source);
|
||||
this.accept(task.path, source);
|
||||
}
|
||||
}
|
||||
await this.labels.save(labels, expected, true);
|
||||
++this.revision;
|
||||
if (this.hidden) await this.reloadFor([labelsPath]);
|
||||
});
|
||||
}
|
||||
createBoard(name: string) {
|
||||
return this.run(async () => {
|
||||
const reference = await createBoard(this.workspace, name);
|
||||
await this.reloadFor([catalogPath]);
|
||||
return reference;
|
||||
});
|
||||
}
|
||||
migrateStorage(cardIds: string[] = []) {
|
||||
return this.run(async () => {
|
||||
await this.reload();
|
||||
if (this.issues.length)
|
||||
throw new Error(format(message("Resolve the workspace issues before migration: {issues}"), { issues: this.issues.join(" ") }));
|
||||
const selected = cardIds.map((id) => {
|
||||
const task = this.tasks.find((task) => task.id === id);
|
||||
if (!task)
|
||||
throw new Error(message("A selected card is unavailable. Refresh before migration."));
|
||||
return task;
|
||||
});
|
||||
const result = await migrateStorage(
|
||||
this.workspace,
|
||||
this.legacyBoards,
|
||||
selected,
|
||||
);
|
||||
await this.reload();
|
||||
return result;
|
||||
});
|
||||
}
|
||||
renameBoard(
|
||||
name: string,
|
||||
rename?: (document: BoardReference, name: string) => Promise<string>,
|
||||
): Promise<void> {
|
||||
return this.run(async () => {
|
||||
await this.reloadFor([catalogPath]);
|
||||
if (!this.board.editable)
|
||||
throw new Error(message("Open an available board before renaming it."));
|
||||
const reference = this.board.reference!;
|
||||
if (isManagedBoard(reference.path)) {
|
||||
await this.board.manage({ name });
|
||||
await this.reloadFor([catalogPath]);
|
||||
return;
|
||||
}
|
||||
if (!rename) throw new Error(message("Migrate this board before renaming it."));
|
||||
const path = await rename({ ...reference }, name.trim());
|
||||
reference.path = path;
|
||||
await this.reload();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Add a note to Project Management and return its card. The legacy mode adds the properties to the note itself.
|
||||
* The hidden mode leaves the note unchanged: it copies a plain note into a new private card, and it migrates a
|
||||
* legacy task note with a backup. The card then gets a placement on the open board.
|
||||
*/
|
||||
adopt(path: string): Promise<Task> {
|
||||
if (!this.legacy) return this.run(() => this.adoptHidden(path));
|
||||
return this.run(async () => {
|
||||
if (!/\.(md|markdown|mdown)$/i.test(path))
|
||||
throw new Error(message("Choose a Markdown note from this workspace."));
|
||||
await this.reload();
|
||||
const id = this.board.reference?.id;
|
||||
if (id && !this.board.available)
|
||||
throw new Error(message("The board is unavailable. Reopen it before adding a note."));
|
||||
if (this.board.archived)
|
||||
throw new Error(message("Restore this board before adding cards."));
|
||||
const source = await this.workspace.read(path);
|
||||
let next = adoptNote(path, source);
|
||||
const task = readTask(path, next)!;
|
||||
if (
|
||||
this.tasks.some(
|
||||
(other) => other.id === task.id && other.path !== path,
|
||||
) ||
|
||||
this.issues.includes(duplicateTaskIssue(task.id))
|
||||
)
|
||||
throw new Error(message("Resolve this task's duplicate ID before adding it."));
|
||||
if (id && !Object.hasOwn(task.placements ?? {}, id))
|
||||
next = editTask(task, {
|
||||
placements: {
|
||||
...task.placements,
|
||||
[id]: {
|
||||
listId: this.board.value.defaults[task.status],
|
||||
order: this.position(
|
||||
task,
|
||||
this.board.value.defaults[task.status],
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
if (next !== source)
|
||||
await saveDocument(this.workspace, path, next, source);
|
||||
await this.reload();
|
||||
const added = this.tasks.find(item => item.path === path);
|
||||
if (!added) throw new Error(message("The linked card is unavailable. Refresh the board."));
|
||||
return added;
|
||||
});
|
||||
}
|
||||
private async adoptHidden(path: string): Promise<Task> {
|
||||
if (!/\.(md|markdown|mdown)$/i.test(path))
|
||||
throw new Error(message("Choose a Markdown note from this workspace."));
|
||||
const id = this.board.reference?.id;
|
||||
if (id && !this.board.available)
|
||||
throw new Error(message("The board is unavailable. Reopen it before adding a note."));
|
||||
if (this.board.archived)
|
||||
throw new Error(message("Restore this board before adding cards."));
|
||||
let card: Task | undefined;
|
||||
if (isHiddenCard(path)) {
|
||||
await this.reloadFor([path]);
|
||||
card = this.tasks.find(task => task.path === path);
|
||||
if (!card) throw new Error(message("The linked card is unavailable. Refresh the board."));
|
||||
} else {
|
||||
const source = await this.workspace.read(path);
|
||||
const note = readTask(path, source);
|
||||
if (note) {
|
||||
// A task note of the legacy format keeps its ID. The migration copies it with a backup.
|
||||
await this.reloadFor([cardPath(note.id)]);
|
||||
card = this.tasks.find(task => task.id === note.id);
|
||||
if (!card) {
|
||||
await migrateCards(this.workspace, [note]);
|
||||
await this.reloadFor([cardPath(note.id)]);
|
||||
card = this.tasks.find(task => task.id === note.id);
|
||||
}
|
||||
if (!card) throw new Error(message("The linked card is unavailable. Refresh the board."));
|
||||
} else {
|
||||
const { doc, body, match, newline } = split(source);
|
||||
if (doc.has("runestone_pm"))
|
||||
throw new Error(message("This document already contains Project Management data and cannot become a task."));
|
||||
const cardId = crypto.randomUUID();
|
||||
const last = this.tasks.filter(task => task.status === "todo" && !task.archived).sort((a, b) => compareCards(a, b)).at(-1);
|
||||
doc.set("runestone_pm", {
|
||||
schema: 1, id: cardId, kind: "task",
|
||||
title: path.split("/").at(-1)!.replace(/\.(md|markdown|mdown)$/i, ""),
|
||||
createdAt: new Date().toISOString(),
|
||||
order: orderBetween(last ? cardOrder(last) : undefined),
|
||||
status: "todo", tags: [], sessions: [], archived: false,
|
||||
});
|
||||
const copy = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`;
|
||||
const target = cardPath(cardId);
|
||||
parseCard(target, copy);
|
||||
await prepareCards(this.workspace);
|
||||
await saveDocument(this.workspace, target, copy, null);
|
||||
this.accept(target, copy);
|
||||
card = this.tasks.find(task => task.path === target)!;
|
||||
}
|
||||
}
|
||||
if (id && !Object.hasOwn(card.placements ?? {}, id)) {
|
||||
const listId = this.board.value.defaults[card.status];
|
||||
await this.saveTask(card, { placements: { ...card.placements, [id]: { listId, order: this.position(card, listId) } } }, false, undefined, true);
|
||||
const placed = card.id;
|
||||
card = this.tasks.find(task => task.id === placed)!;
|
||||
}
|
||||
return card;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { BackgroundAppearance } from "./background.ts";
|
||||
|
||||
/** One background frame. It has the shape of `BackgroundFrame` in `src/lib/plugins/backgroundContracts.ts`. */
|
||||
export interface BackgroundFrame extends BackgroundAppearance {
|
||||
url: string;
|
||||
blurredUrl?: string;
|
||||
previous?: BackgroundAppearance & { url: string; blurredUrl?: string };
|
||||
transitionMs?: number;
|
||||
}
|
||||
/** The part of the host background hub (`backgroundHub` in `src/lib/plugins/backgrounds.ts`) that the boards read. */
|
||||
export interface PMBackgroundApi {
|
||||
get(target: string): BackgroundFrame | null;
|
||||
subscribe(listener: (target: string) => void): () => void;
|
||||
}
|
||||
|
||||
function sameImage(a: BackgroundAppearance & { url: string; blurredUrl?: string }, b: BackgroundAppearance & { url: string; blurredUrl?: string }) {
|
||||
return a.url === b.url && a.blurredUrl === b.blurredUrl && a.overlay === b.overlay && a.position === b.position && a.size === b.size;
|
||||
}
|
||||
|
||||
function sameFrame(a: BackgroundFrame, b: BackgroundFrame | null | undefined) {
|
||||
return !!b && sameImage(a, b) && (a.transitionMs ?? 0) === (b.transitionMs ?? 0)
|
||||
&& (a.previous ? !!b.previous && sameImage(a.previous, b.previous) : !b.previous);
|
||||
}
|
||||
|
||||
export function watchBackground(
|
||||
target: string,
|
||||
api: PMBackgroundApi | undefined,
|
||||
saved: () => Promise<BackgroundFrame | null>,
|
||||
apply: (frame: BackgroundFrame | null) => void,
|
||||
) {
|
||||
let revision = 0;
|
||||
let closed = false;
|
||||
async function refresh() {
|
||||
if (closed) return;
|
||||
const current = ++revision;
|
||||
try {
|
||||
const frame = api?.get(target) ?? (target !== "pm-all" ? api?.get("pm-all") : null) ?? await saved();
|
||||
// A shared slideshow uses the host image coordinates across every pane.
|
||||
if (!closed && current === revision) apply(frame && sameFrame(frame, api?.get("app")) ? null : frame);
|
||||
} catch {
|
||||
if (!closed && current === revision) apply(null);
|
||||
}
|
||||
}
|
||||
const unsubscribe = api?.subscribe(changed => {
|
||||
if (changed === target || changed === "pm-all" || changed === "app") void refresh();
|
||||
});
|
||||
return {
|
||||
refresh,
|
||||
dispose() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
++revision;
|
||||
unsubscribe?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Workspace } from "./model.ts";
|
||||
import { boardKey, readCatalog } from "../storage/catalog.ts";
|
||||
import { boardDocument } from "../storage/board.ts";
|
||||
|
||||
/**
|
||||
* The board that opens first in this workspace: the `pm-board:` key of a saved board, the path of a legacy Markdown board,
|
||||
* or undefined for All tasks. Settings → Project Management writes `defaultBoardId` and `defaultBoardPath` of the catalog.
|
||||
*/
|
||||
export async function defaultBoardPath(workspace: Workspace): Promise<string | undefined> {
|
||||
const snapshot = await readCatalog(workspace);
|
||||
if (typeof snapshot.value.defaultBoardId !== "string") return;
|
||||
const board = snapshot.value.boards.find(board => board.value.id === snapshot.value.defaultBoardId);
|
||||
if (board) return board.archived ? undefined : boardKey(board.value.id);
|
||||
if (snapshot.value.deletedBoardIds?.includes(snapshot.value.defaultBoardId)) return;
|
||||
const path = snapshot.value.defaultBoardPath;
|
||||
if (typeof path !== "string" || path.startsWith(".") || path.includes("\\") || path.split("/").some(part => !part || part === "..")) return;
|
||||
try {
|
||||
const legacy = boardDocument(await workspace.read(path), path);
|
||||
return legacy?.id === snapshot.value.defaultBoardId && !legacy.archived ? path : undefined;
|
||||
} catch { return; }
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
import { statuses, type Status, type Task, type Workspace } from "../model/model.ts";
|
||||
import { Document } from "yaml";
|
||||
import { split } from "./notes.ts";
|
||||
import {
|
||||
isManagedBoard,
|
||||
readCatalog,
|
||||
managedDocuments,
|
||||
writeCatalog,
|
||||
validateName,
|
||||
} from "./catalog.ts";
|
||||
import { message } from "./message.ts";
|
||||
|
||||
export interface BoardReference {
|
||||
id: string;
|
||||
path: string;
|
||||
}
|
||||
export interface BoardDocument extends BoardReference {
|
||||
name: string;
|
||||
value: Board;
|
||||
source: string;
|
||||
archived?: boolean;
|
||||
}
|
||||
export interface BoardList {
|
||||
id: string;
|
||||
name: string;
|
||||
status: Status | null;
|
||||
collapsed: boolean;
|
||||
maxCards?: number;
|
||||
}
|
||||
export interface Board {
|
||||
schema: 1;
|
||||
kind: "board";
|
||||
id: string;
|
||||
lists: BoardList[];
|
||||
backgroundImage?: string | null;
|
||||
backgroundAppearance?: import("../model/background.ts").BackgroundAppearance;
|
||||
defaults: Record<Status, string | null>;
|
||||
}
|
||||
export function defaultBoard(id: string = crypto.randomUUID()): Board {
|
||||
return {
|
||||
schema: 1,
|
||||
kind: "board",
|
||||
id,
|
||||
lists: [
|
||||
{ id: "todo", name: 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" },
|
||||
};
|
||||
}
|
||||
export function parseBoard(source: string): Board {
|
||||
const value = split(source).doc.toJS({ maxAliasCount: 50 }).runestone_pm;
|
||||
if (
|
||||
!value ||
|
||||
value.schema !== 1 ||
|
||||
value.kind !== "board" ||
|
||||
typeof value.id !== "string" ||
|
||||
!value.id.trim() ||
|
||||
!Array.isArray(value.lists) ||
|
||||
!value.defaults
|
||||
)
|
||||
throw new Error(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 (
|
||||
!list ||
|
||||
typeof list.id !== "string" ||
|
||||
!list.id ||
|
||||
ids.has(list.id) ||
|
||||
typeof list.name !== "string" ||
|
||||
!list.name.trim() ||
|
||||
list.name.length > 80 ||
|
||||
(list.status !== null && !statuses.includes(list.status)) ||
|
||||
typeof list.collapsed !== "boolean" ||
|
||||
(list.maxCards !== undefined && (!Number.isSafeInteger(list.maxCards) || list.maxCards < 1))
|
||||
)
|
||||
throw new Error(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(message("The board has an invalid default list."));
|
||||
return value;
|
||||
}
|
||||
export function boardDocument(
|
||||
source: string,
|
||||
path: string,
|
||||
): BoardDocument | null {
|
||||
const value = split(source).doc.toJS({ maxAliasCount: 50 }).runestone_pm;
|
||||
if (value?.kind !== "board") return null;
|
||||
const board = parseBoard(source);
|
||||
return {
|
||||
id: board.id,
|
||||
path,
|
||||
name: path
|
||||
.split("/")
|
||||
.at(-1)!
|
||||
.replace(/\.(md|markdown|mdown)$/i, ""),
|
||||
value: board,
|
||||
source,
|
||||
};
|
||||
}
|
||||
export function newBoardSource(): string {
|
||||
return `---\n${new Document({ runestone_pm: defaultBoard() }).toString({ lineWidth: 0 })}---\n`;
|
||||
}
|
||||
export class BoardStore {
|
||||
value = defaultBoard("all-tasks");
|
||||
name: string = message("All tasks");
|
||||
available = true;
|
||||
archived = false;
|
||||
private source: string | null = null;
|
||||
private workspace: Workspace;
|
||||
readonly reference?: BoardReference;
|
||||
constructor(workspace: Workspace, reference?: BoardReference) {
|
||||
this.workspace = workspace;
|
||||
this.reference = reference ? { ...reference } : undefined;
|
||||
}
|
||||
get editable() {
|
||||
return (
|
||||
!!this.reference &&
|
||||
this.available &&
|
||||
!this.archived &&
|
||||
this.source !== null
|
||||
);
|
||||
}
|
||||
async reload() {
|
||||
if (!this.reference) return;
|
||||
if (!isManagedBoard(this.reference.path) && this.workspace.readOptional) {
|
||||
const snapshot = await readCatalog(this.workspace);
|
||||
if (snapshot.value.deletedBoardIds?.includes(this.reference.id)) {
|
||||
this.load();
|
||||
throw new Error(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,
|
||||
);
|
||||
if (managed) {
|
||||
const current = await this.workspace.readOptional(this.reference.path);
|
||||
if (
|
||||
managed.original?.path !== this.reference.path ||
|
||||
(current !== null && current !== managed.original.source)
|
||||
)
|
||||
throw new Error(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,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (isManagedBoard(this.reference.path)) {
|
||||
const snapshot = await readCatalog(this.workspace);
|
||||
this.load(
|
||||
managedDocuments(snapshot.value, snapshot.source ?? "").find(
|
||||
(board) => board.id === this.reference!.id,
|
||||
),
|
||||
);
|
||||
if (!this.available)
|
||||
throw new Error(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(message("The board changed. Reopen it from navigation."));
|
||||
this.load(document);
|
||||
}
|
||||
load(document?: BoardDocument) {
|
||||
if (!this.reference) return;
|
||||
this.available = !!document;
|
||||
this.source = document?.source ?? null;
|
||||
if (document) {
|
||||
this.reference.path = document.path;
|
||||
this.value = document.value;
|
||||
this.name = document.name;
|
||||
this.archived = document.archived ?? false;
|
||||
}
|
||||
}
|
||||
listFor(
|
||||
task: Pick<Task, "listId" | "status" | "placements">,
|
||||
): BoardList | undefined {
|
||||
const id = this.reference
|
||||
? (task.placements?.[this.reference.id]?.listId ??
|
||||
(task.listId !== undefined ? task.listId : null))
|
||||
: this.value.defaults[task.status];
|
||||
return this.value.lists.find((list) => list.id === id);
|
||||
}
|
||||
async update(change: (board: Board) => void) {
|
||||
if (!this.editable)
|
||||
throw new Error(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(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(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(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(message("The board is unavailable."));
|
||||
change(board.value);
|
||||
this.source = await writeCatalog(
|
||||
this.workspace,
|
||||
snapshot.value,
|
||||
expected,
|
||||
);
|
||||
this.value = board.value;
|
||||
return;
|
||||
}
|
||||
const current = await this.workspace.read(this.reference!.path);
|
||||
if (current !== expected)
|
||||
throw new Error(message("The board changed. Refresh before editing its lists."));
|
||||
const next = structuredClone(this.value);
|
||||
change(next);
|
||||
const { doc, body, newline, match } = split(expected!);
|
||||
for (const key of ["lists", "defaults", "backgroundImage", "backgroundAppearance"] as const)
|
||||
if (next[key] !== undefined) doc.setIn(["runestone_pm", key], next[key]);
|
||||
const source = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`;
|
||||
parseBoard(source);
|
||||
await this.workspace.write(this.reference!.path, source, expected!);
|
||||
this.source = source;
|
||||
this.value = next;
|
||||
}
|
||||
async deleteBoard() {
|
||||
if (!this.reference || !this.available || this.source === null)
|
||||
throw new Error(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(message("This board was already deleted. Refresh Project Management."));
|
||||
if (isManagedBoard(path)) {
|
||||
if (snapshot.source !== this.source)
|
||||
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(message("The board is unavailable. Refresh Project Management."));
|
||||
} else {
|
||||
if (snapshot.value.boards.some((board) => board.value.id === id))
|
||||
throw new Error(message("This board moved to hidden storage. Refresh before deleting."));
|
||||
if ((await this.workspace.read(path)) !== this.source)
|
||||
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.
|
||||
snapshot.value.deletedBoardIds = [...(snapshot.value.deletedBoardIds ?? []), id];
|
||||
await writeCatalog(this.workspace, snapshot.value, snapshot.source);
|
||||
this.load();
|
||||
}
|
||||
async manage(patch: { name?: string; archived?: boolean }) {
|
||||
if (
|
||||
!this.reference ||
|
||||
!isManagedBoard(this.reference.path) ||
|
||||
!this.available
|
||||
)
|
||||
throw new Error(message("Migrate this board before managing hidden storage."));
|
||||
const snapshot = await readCatalog(this.workspace);
|
||||
if (snapshot.source !== this.source)
|
||||
throw new Error(message("The board changed. Refresh before saving."));
|
||||
const board = snapshot.value.boards.find(
|
||||
(item) => item.value.id === this.reference!.id,
|
||||
)!;
|
||||
if (patch.name !== undefined) {
|
||||
validateName(patch.name);
|
||||
if (
|
||||
snapshot.value.boards.some(
|
||||
(item) =>
|
||||
item !== board &&
|
||||
item.name.toLocaleLowerCase() ===
|
||||
patch.name!.trim().toLocaleLowerCase(),
|
||||
)
|
||||
)
|
||||
throw new Error(message("A board with this name already exists."));
|
||||
board.name = patch.name.trim();
|
||||
}
|
||||
if (patch.archived !== undefined) board.archived = patch.archived;
|
||||
this.source = await writeCatalog(
|
||||
this.workspace,
|
||||
snapshot.value,
|
||||
snapshot.source,
|
||||
);
|
||||
this.name = board.name;
|
||||
this.archived = board.archived ?? false;
|
||||
}
|
||||
async add(name: string, status: Status | null) {
|
||||
await this.update((board) => {
|
||||
this.checkName(board, name);
|
||||
board.lists.push({
|
||||
id: crypto.randomUUID(),
|
||||
name: name.trim(),
|
||||
status,
|
||||
collapsed: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
async edit(id: string, name: string, status: Status | null) {
|
||||
await this.update((board) => {
|
||||
this.checkName(board, name, id);
|
||||
const list = this.requireList(board, id);
|
||||
list.name = name.trim();
|
||||
list.status = status;
|
||||
});
|
||||
}
|
||||
async collapse(id: string) {
|
||||
await this.update((board) => {
|
||||
const list = this.requireList(board, id);
|
||||
list.collapsed = !list.collapsed;
|
||||
});
|
||||
}
|
||||
async setLimit(id: string, maximum?: number) {
|
||||
if (maximum !== undefined && (!Number.isSafeInteger(maximum) || maximum < 1))
|
||||
throw new Error(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;
|
||||
else list.maxCards = maximum;
|
||||
});
|
||||
}
|
||||
async move(id: string, index: number) {
|
||||
await this.update((board) => {
|
||||
const list = this.requireList(board, id);
|
||||
board.lists = board.lists.filter((item) => item.id !== id);
|
||||
board.lists.splice(
|
||||
Math.max(0, Math.min(index, board.lists.length)),
|
||||
0,
|
||||
list,
|
||||
);
|
||||
});
|
||||
}
|
||||
async remove(id: string) {
|
||||
await this.update((board) => {
|
||||
this.requireList(board, id);
|
||||
board.lists = board.lists.filter((list) => list.id !== id);
|
||||
for (const status of statuses)
|
||||
if (board.defaults[status] === id) board.defaults[status] = null;
|
||||
});
|
||||
}
|
||||
private requireList(board: Board, id: string) {
|
||||
const list = board.lists.find((item) => item.id === id);
|
||||
if (!list)
|
||||
throw new Error(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(message("Enter a list name of 1 to 80 characters."));
|
||||
if (
|
||||
board.lists.some(
|
||||
(list) =>
|
||||
list.id !== except &&
|
||||
list.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
|
||||
)
|
||||
)
|
||||
throw new Error(message("A list with this name already exists."));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { readTask, newTask, split } from "./notes.ts";
|
||||
import type { Task, TaskFields, Workspace } from "../model/model.ts";
|
||||
import { backupFile, type OriginalFile } from "./catalog.ts";
|
||||
import { legacyPosition } from "./order.ts";
|
||||
import { mapConcurrent, readSources } from "./scan.ts";
|
||||
import {
|
||||
cardsFolder,
|
||||
cardsMarker,
|
||||
isHiddenCard,
|
||||
readOptional,
|
||||
saveDocument,
|
||||
} from "./persistence.ts";
|
||||
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) =>
|
||||
byte.toString(16).padStart(2, "0"),
|
||||
).join("");
|
||||
return `${cardsFolder}/${key}.md`;
|
||||
}
|
||||
export function cardOrigin(source: string): OriginalFile | undefined {
|
||||
const origin = split(source).doc.toJS({
|
||||
maxAliasCount: 50,
|
||||
}).runestone_pm_origin;
|
||||
if (origin === undefined) return;
|
||||
if (
|
||||
!origin ||
|
||||
typeof origin.path !== "string" ||
|
||||
typeof origin.source !== "string" ||
|
||||
typeof origin.backup !== "string" ||
|
||||
origin.path.startsWith(".") ||
|
||||
origin.path.includes("\\") ||
|
||||
origin.path
|
||||
.split("/")
|
||||
.some((part: string) => !part || part === "." || part === "..") ||
|
||||
origin.backup !== `.runestone/pm/backups/${origin.path}`
|
||||
)
|
||||
throw new Error(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. */
|
||||
export function parseCard(path: string, source: string): Task {
|
||||
cardOrigin(source);
|
||||
const task = readTask(path, source);
|
||||
if (!task || cardPath(task.id) !== path)
|
||||
throw new Error(message("The hidden card ID does not match its storage path."));
|
||||
return task;
|
||||
}
|
||||
export async function prepareCards(workspace: Workspace) {
|
||||
const marker = await readOptional(workspace, cardsMarker);
|
||||
if (marker !== null) return;
|
||||
try {
|
||||
await saveDocument(workspace, cardsMarker, "*\n", null);
|
||||
} catch (error) {
|
||||
if ((await readOptional(workspace, cardsMarker)) !== "*\n") throw error;
|
||||
}
|
||||
}
|
||||
export async function readCards(
|
||||
workspace: Workspace,
|
||||
previous: ReadonlyMap<string, Task> = new Map(),
|
||||
): Promise<{ tasks: Task[]; issues: string[] }> {
|
||||
const tasks: Task[] = [],
|
||||
issues: string[] = [];
|
||||
// Direct reads are necessary because the host hides .runestone from root listings.
|
||||
if (
|
||||
!workspace.readOptional ||
|
||||
(await workspace.readOptional(cardsMarker)) === null
|
||||
)
|
||||
return { tasks, issues };
|
||||
const entries = (await workspace.list(cardsFolder)).filter(
|
||||
(entry) => entry.kind !== "folder" && isHiddenCard(entry.rel_path),
|
||||
);
|
||||
const sources = await readSources(workspace, entries.map(entry => entry.rel_path));
|
||||
const documents = await mapConcurrent(entries, async (entry) => {
|
||||
try {
|
||||
const result = sources.get(entry.rel_path)!;
|
||||
if (result.error || result.source === undefined) throw new Error(result.error ?? 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: fileIssue(entry.rel_path, error instanceof Error ? error.message : String(error)),
|
||||
};
|
||||
}
|
||||
});
|
||||
for (const document of documents) {
|
||||
if (document.task) tasks.push(document.task);
|
||||
if (document.issue) issues.push(document.issue);
|
||||
}
|
||||
return { tasks, issues };
|
||||
}
|
||||
export async function createCard(
|
||||
workspace: Workspace,
|
||||
title: string,
|
||||
fields: TaskFields,
|
||||
body: string,
|
||||
id: string = crypto.randomUUID(),
|
||||
) {
|
||||
// The storage name is independent of the title, so punctuation and duplicate titles are safe.
|
||||
const note = newTask(id, { ...fields, title: title.trim() }, body, id);
|
||||
const path = cardPath(id);
|
||||
await prepareCards(workspace);
|
||||
await saveDocument(workspace, path, note.source, null);
|
||||
return { path, source: note.source };
|
||||
}
|
||||
export async function migrateCards(workspace: Workspace, tasks: Task[]) {
|
||||
for (const task of tasks) {
|
||||
if (isHiddenCard(task.path)) continue;
|
||||
if ((await workspace.read(task.path)) !== task.source)
|
||||
throw new Error(
|
||||
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(
|
||||
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(
|
||||
format(message("The note already contains a migration record: {path}. Review it before migration."), { path: task.path }),
|
||||
);
|
||||
}
|
||||
for (const task of tasks) {
|
||||
if (isHiddenCard(task.path)) continue;
|
||||
const original = await backupFile(workspace, task.path, task.source);
|
||||
const path = cardPath(task.id);
|
||||
if ((await readOptional(workspace, path)) !== null) continue;
|
||||
const { doc, body, newline, match } = split(task.source);
|
||||
doc.set("runestone_pm_origin", original);
|
||||
if (task.order === undefined)
|
||||
doc.setIn(["runestone_pm", "order"], legacyPosition(task.path));
|
||||
for (const [id, placement] of Object.entries(task.placements ?? {}))
|
||||
if (placement.order === undefined)
|
||||
doc.setIn(
|
||||
["runestone_pm", "placements", id, "order"],
|
||||
legacyPosition(task.path),
|
||||
);
|
||||
const source = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`;
|
||||
const copied = readTask(path, source)!;
|
||||
if (
|
||||
copied.id !== task.id ||
|
||||
copied.title !== task.title ||
|
||||
copied.body !== task.body
|
||||
)
|
||||
throw new Error(
|
||||
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(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(
|
||||
format(message("The saved card check failed: {path}. Keep the original."), { path: task.path }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { Document } from "yaml";
|
||||
import {
|
||||
defaultBoard,
|
||||
parseBoard,
|
||||
type Board,
|
||||
type BoardDocument,
|
||||
} from "./board.ts";
|
||||
import type { Workspace } from "../model/model.ts";
|
||||
import { readOptional, saveDocument } from "./persistence.ts";
|
||||
import { format, message } from "./message.ts";
|
||||
|
||||
export const catalogPath = ".runestone/pm/workspace.json";
|
||||
export const boardKey = (id: string) => `pm-board:${id}`;
|
||||
export const isManagedBoard = (path: string) => path.startsWith("pm-board:");
|
||||
export interface OriginalFile {
|
||||
path: string;
|
||||
source: string;
|
||||
backup: string;
|
||||
}
|
||||
export interface ManagedBoard {
|
||||
name: string;
|
||||
value: Board;
|
||||
archived?: boolean;
|
||||
original?: OriginalFile;
|
||||
}
|
||||
export interface Catalog {
|
||||
schema: 1;
|
||||
boards: ManagedBoard[];
|
||||
deletedBoardIds?: string[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
export function boardMarkdown(value: Board): string {
|
||||
return `---\n${new Document({ runestone_pm: value }).toString({ lineWidth: 0 })}---\n`;
|
||||
}
|
||||
export function validateName(name: string) {
|
||||
if (!name.trim() || name.trim().length > 100 || /[\x00-\x1f]/.test(name))
|
||||
throw new Error(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(message("The Project Management storage format is unsupported. Restore a backup or update Project Management."));
|
||||
const ids = new Set<string>();
|
||||
if (
|
||||
data.deletedBoardIds !== undefined &&
|
||||
(!Array.isArray(data.deletedBoardIds) ||
|
||||
data.deletedBoardIds.some((id: unknown) => typeof id !== "string" || !id.trim()) ||
|
||||
new Set(data.deletedBoardIds).size !== data.deletedBoardIds.length)
|
||||
)
|
||||
throw new Error(message("The deleted board record is invalid."));
|
||||
for (const board of data.boards) {
|
||||
if (!board || typeof board.name !== "string")
|
||||
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(message("Project Management storage contains duplicate board IDs."));
|
||||
ids.add(board.value.id);
|
||||
if (data.deletedBoardIds?.includes(board.value.id))
|
||||
throw new Error(message("A deleted board still has an active storage entry."));
|
||||
if (board.archived !== undefined && typeof board.archived !== "boolean")
|
||||
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(message("The board migration record is invalid."));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
export async function readCatalog(workspace: Workspace) {
|
||||
const source = await readOptional(workspace, catalogPath);
|
||||
return { source, value: parseCatalog(source) };
|
||||
}
|
||||
export async function writeCatalog(
|
||||
workspace: Workspace,
|
||||
value: Catalog,
|
||||
expected: string | null,
|
||||
) {
|
||||
if (!workspace.readOptional)
|
||||
throw new Error(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);
|
||||
return source;
|
||||
}
|
||||
export function managedDocuments(
|
||||
value: Catalog,
|
||||
source: string,
|
||||
): BoardDocument[] {
|
||||
return value.boards.map((board) => ({
|
||||
id: board.value.id,
|
||||
path: boardKey(board.value.id),
|
||||
name: board.name,
|
||||
value: board.value,
|
||||
archived: board.archived,
|
||||
source,
|
||||
}));
|
||||
}
|
||||
export async function createBoard(workspace: Workspace, name: string) {
|
||||
validateName(name);
|
||||
const snapshot = await readCatalog(workspace);
|
||||
if (
|
||||
snapshot.value.boards.some(
|
||||
(board) =>
|
||||
board.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
|
||||
)
|
||||
)
|
||||
throw new Error(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);
|
||||
return { id: value.id, path: boardKey(value.id) };
|
||||
}
|
||||
export async function backupFile(
|
||||
workspace: Workspace,
|
||||
path: string,
|
||||
source: string,
|
||||
): Promise<OriginalFile> {
|
||||
if (
|
||||
path.startsWith(".") ||
|
||||
path.includes("\\") ||
|
||||
path.split("/").some((part) => !part || part === ".." || part === ".")
|
||||
)
|
||||
throw new Error(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(
|
||||
format(message("The backup differs from {path}. Preserve both versions before migration."), { path }),
|
||||
);
|
||||
if ((await workspace.read(backup)) !== source)
|
||||
throw new Error(format(message("The backup check failed for {path}."), { path }));
|
||||
return { path, source, backup };
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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";
|
||||
|
||||
export async function readDeletedCards(workspace: Workspace) {
|
||||
const source = await readOptional(workspace, deletedCardsPath);
|
||||
if (source === null) return { source, ids: [] as string[] };
|
||||
const value = JSON.parse(source);
|
||||
if (value?.schema !== 1 || !Array.isArray(value.ids) ||
|
||||
value.ids.some((id: unknown) => typeof id !== "string" || !id.trim()) ||
|
||||
new Set(value.ids).size !== value.ids.length)
|
||||
throw new Error(message("The deleted card record is invalid. Restore it before editing cards."));
|
||||
return { source, ids: value.ids as string[] };
|
||||
}
|
||||
|
||||
/** Keep a deletion record so saved legacy notes cannot restore deleted cards. */
|
||||
export async function recordCardDeletion(workspace: Workspace, id: string) {
|
||||
const snapshot = await readDeletedCards(workspace);
|
||||
if (snapshot.ids.includes(id)) return;
|
||||
await saveDocument(workspace, deletedCardsPath,
|
||||
JSON.stringify({ schema: 1, ids: [...snapshot.ids, id] }, null, 2) + "\n", snapshot.source);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { Workspace } from "../model/model.ts";
|
||||
import { readOptional, saveDocument } from "./persistence.ts";
|
||||
import { message } from "./message.ts";
|
||||
import { imagePath, parseImage } from "./images.ts";
|
||||
|
||||
const invalidDraft = () => new Error(message("The description draft is invalid. Preserve it before recovery."));
|
||||
const sameImages = (a: ReadonlyMap<string, string>, b: ReadonlyMap<string, string>) =>
|
||||
a.size === b.size && [...a].every(([id, data]) => b.get(id) === data);
|
||||
|
||||
/**
|
||||
* A draft is separate from the saved card and uses compare-and-write protection.
|
||||
* A second file keeps the data of the images that only the draft uses. Thus a text change does not write the images again.
|
||||
* The image folder gets an image only from a save of the description or the card. A discarded draft keeps an empty image record, so no image file stays behind.
|
||||
*/
|
||||
export class DescriptionDraft {
|
||||
private source: string | null = null;
|
||||
private imageSource: string | null = null;
|
||||
private images: ReadonlyMap<string, string> = new Map();
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
readonly path: string;
|
||||
readonly imagesPath: string;
|
||||
private workspace: Workspace;
|
||||
constructor(workspace: Workspace, id: string) {
|
||||
this.workspace = workspace;
|
||||
const key = Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join("");
|
||||
this.path = `.runestone/pm/drafts/${key}.json`;
|
||||
this.imagesPath = `.runestone/pm/drafts/${key}.images.json`;
|
||||
}
|
||||
async load(): Promise<string | null> {
|
||||
this.source = await readOptional(this.workspace, this.path);
|
||||
if (this.source === null) return null;
|
||||
const value = JSON.parse(this.source);
|
||||
if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string"))
|
||||
throw invalidDraft();
|
||||
return value.body;
|
||||
}
|
||||
/** The image data of the draft, by image ID. A draft of an earlier version has no image record. Call this before `save`. */
|
||||
async loadImages(): Promise<Map<string, string>> {
|
||||
this.images = new Map();
|
||||
this.imageSource = await readOptional(this.workspace, this.imagesPath);
|
||||
if (this.imageSource === null) return new Map();
|
||||
const value = JSON.parse(this.imageSource);
|
||||
if (value?.schema !== 1 || typeof value.images !== "object" || value.images === null || Array.isArray(value.images))
|
||||
throw invalidDraft();
|
||||
const images = new Map<string, string>();
|
||||
for (const [id, data] of Object.entries(value.images)) {
|
||||
try { imagePath(id); images.set(id, parseImage(JSON.stringify({ schema: 1, data }))); }
|
||||
catch { throw invalidDraft(); }
|
||||
}
|
||||
this.images = images;
|
||||
return new Map(images);
|
||||
}
|
||||
/** Save the text of the draft and the data of the images that only the draft uses. A `null` body discards the draft and its images. */
|
||||
save(body: string | null, images: ReadonlyMap<string, string> = new Map()): Promise<void> {
|
||||
const write = this.queue.then(async () => {
|
||||
const next = body === null ? new Map<string, string>() : images;
|
||||
// Keep the old and the new image data until the text is saved, so that each saved reference has its data.
|
||||
await this.saveImages(new Map([...this.images, ...next]));
|
||||
const source = JSON.stringify({ schema: 1, body }) + "\n";
|
||||
if (source !== this.source && !(body === null && this.source === null)) {
|
||||
await saveDocument(this.workspace, this.path, source, this.source);
|
||||
this.source = source;
|
||||
}
|
||||
await this.saveImages(next);
|
||||
});
|
||||
this.queue = write.catch(() => {});
|
||||
return write;
|
||||
}
|
||||
private async saveImages(images: ReadonlyMap<string, string>) {
|
||||
if (sameImages(images, this.images) || (!images.size && this.imageSource === null)) return;
|
||||
const sorted = [...images].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
||||
const source = JSON.stringify({ schema: 1, images: Object.fromEntries(sorted) }) + "\n";
|
||||
await saveDocument(this.workspace, this.imagesPath, source, this.imageSource);
|
||||
this.imageSource = source;
|
||||
this.images = new Map(images);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
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 = [
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
];
|
||||
const idPattern =
|
||||
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||
export const imageFolder = `${storageRoot}/images`;
|
||||
export function imagePath(id: string) {
|
||||
if (!new RegExp(`^${idPattern}$`).test(id))
|
||||
throw new Error(message("The image ID is invalid."));
|
||||
return `${imageFolder}/${id}.json`;
|
||||
}
|
||||
export function imageReferences(body: string) {
|
||||
return [
|
||||
...body.matchAll(
|
||||
new RegExp(`!\\[([^\\]\\r\\n]*)\\]\\(pm-image:(${idPattern})\\)`, "g"),
|
||||
),
|
||||
].map((match) => ({
|
||||
id: match[2],
|
||||
name: match[1] || "Pasted image",
|
||||
markdown: match[0],
|
||||
index: match.index,
|
||||
}));
|
||||
}
|
||||
export function imageMarkdown(name: string, id: string) {
|
||||
imagePath(id);
|
||||
return `![${name.replace(/[\[\]\r\n\\]/g, " ").trim() || "Pasted image"}](pm-image:${id})`;
|
||||
}
|
||||
export function parseImage(source: string): string {
|
||||
if (source.length > Math.ceil(maxImageBytes / 3) * 4 + 256)
|
||||
throw new Error(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(message("The saved image is invalid."));
|
||||
const match =
|
||||
/^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec(
|
||||
value.data,
|
||||
);
|
||||
if (
|
||||
!match ||
|
||||
match[2].length % 4 !== 0 ||
|
||||
atob(match[2]).length > maxImageBytes
|
||||
)
|
||||
throw new Error(message("The saved image is invalid or exceeds 50 MiB."));
|
||||
return value.data;
|
||||
}
|
||||
/** Write the pending images that `body`, `attachments`, or `ids` refer to. Returns the IDs of the written images. */
|
||||
export async function saveImages(
|
||||
workspace: Workspace,
|
||||
body: string,
|
||||
pending: ReadonlyMap<string, string>,
|
||||
attachments: TaskFields["attachments"] = [],
|
||||
ids: string[] = [],
|
||||
) {
|
||||
const saved: string[] = [];
|
||||
for (const id of new Set([...[...imageReferences(body), ...attachments].map((image) => image.id), ...ids])) {
|
||||
const data = pending.get(id);
|
||||
if (!data) continue;
|
||||
const source = JSON.stringify({ schema: 1, data }) + "\n";
|
||||
parseImage(source);
|
||||
const path = imagePath(id);
|
||||
// Retrying a failed card save reuses its complete image files.
|
||||
const previous = await workspace.readOptional?.(path);
|
||||
if (previous !== source) await saveDocument(workspace, path, source, null);
|
||||
saved.push(id);
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
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";
|
||||
export interface SavedLabel {
|
||||
id: string;
|
||||
name: string;
|
||||
color: keyof typeof cardColors;
|
||||
archived?: boolean;
|
||||
}
|
||||
export interface LabelSnapshot {
|
||||
source: string | null;
|
||||
labels: SavedLabel[];
|
||||
legacy?: boolean;
|
||||
}
|
||||
export function defaultLabels(): SavedLabel[] {
|
||||
return [
|
||||
{ id: "bug", name: "Bug", color: "red" },
|
||||
{ id: "feature", name: "Feature", color: "blue" },
|
||||
{ id: "improvement", name: "Improvement", color: "green" },
|
||||
];
|
||||
}
|
||||
export function validateLabels(
|
||||
labels: unknown,
|
||||
): asserts labels is SavedLabel[] {
|
||||
if (!Array.isArray(labels)) throw new Error(message("Saved labels must be a list."));
|
||||
const ids = new Set<string>(),
|
||||
names = new Set<string>();
|
||||
for (const label of labels) {
|
||||
if (
|
||||
!label ||
|
||||
typeof label !== "object" ||
|
||||
Array.isArray(label) ||
|
||||
typeof label.id !== "string" ||
|
||||
!/^[a-zA-Z0-9_-]{1,100}$/.test(label.id) ||
|
||||
ids.has(label.id)
|
||||
)
|
||||
throw new Error(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(message("Enter a label name of 1 to 80 characters."));
|
||||
const name = label.name.trim().toLocaleLowerCase();
|
||||
if (names.has(name))
|
||||
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(message("Choose a supported label color."));
|
||||
if (label.archived !== undefined && typeof label.archived !== "boolean")
|
||||
throw new Error(message("The label archive state must be true or false."));
|
||||
ids.add(label.id);
|
||||
names.add(name);
|
||||
}
|
||||
}
|
||||
export function parseLabels(source: string | null): LabelSnapshot {
|
||||
if (source === null) return { source, labels: defaultLabels() };
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(source);
|
||||
} catch {
|
||||
throw new Error(message("Fix the saved labels file before editing labels."));
|
||||
}
|
||||
if (
|
||||
!data ||
|
||||
typeof data !== "object" ||
|
||||
Array.isArray(data) ||
|
||||
data.schema !== 1
|
||||
)
|
||||
throw new Error(message("The saved labels file has an unsupported schema."));
|
||||
validateLabels(data.labels);
|
||||
return { source, labels: data.labels };
|
||||
}
|
||||
|
||||
export class LabelStore {
|
||||
value: SavedLabel[] = [];
|
||||
source: string | null | undefined;
|
||||
error = "";
|
||||
legacy = false;
|
||||
readonly workspace: Workspace;
|
||||
constructor(workspace: Workspace) {
|
||||
this.workspace = workspace;
|
||||
}
|
||||
async read(): Promise<LabelSnapshot> {
|
||||
const source = await readOptional(this.workspace, labelsPath);
|
||||
if (source !== null) return parseLabels(source);
|
||||
const legacy = await readOptional(this.workspace, legacyLabelsPath);
|
||||
return { ...parseLabels(legacy), legacy: legacy !== null };
|
||||
}
|
||||
load(snapshot?: LabelSnapshot, error = "") {
|
||||
this.value = snapshot?.labels ?? [];
|
||||
this.source = snapshot?.source;
|
||||
this.error = error;
|
||||
this.legacy = snapshot?.legacy ?? false;
|
||||
}
|
||||
checkSave(labels: SavedLabel[], expected: string | null | undefined): asserts expected is string | null {
|
||||
if (this.legacy)
|
||||
throw new Error(message("Use the workspace migration tool before editing legacy labels. See the Project Management development guide."));
|
||||
if (!this.workspace.readOptional)
|
||||
throw new Error(message("Update RuneStone to use hidden Project Management storage."));
|
||||
if (expected === undefined || this.error)
|
||||
throw new Error(message("Saved labels are unavailable. Refresh before editing labels."));
|
||||
validateLabels(labels);
|
||||
}
|
||||
async save(labels: SavedLabel[], expected: string | null | undefined, allowDelete = false) {
|
||||
this.checkSave(labels, expected);
|
||||
const previous = parseLabels(expected!);
|
||||
if (
|
||||
!allowDelete && previous.labels.some(
|
||||
(label) => !labels.some((next) => next.id === label.id),
|
||||
)
|
||||
)
|
||||
throw new Error(message("Archive unused labels to preserve existing cards."));
|
||||
const data = expected === null ? { schema: 1 } : JSON.parse(expected);
|
||||
const source =
|
||||
JSON.stringify(
|
||||
{
|
||||
...data,
|
||||
labels: labels.map((label) => ({
|
||||
...label,
|
||||
name: label.name.trim(),
|
||||
})),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n";
|
||||
await saveDocument(this.workspace, labelsPath, source, expected);
|
||||
this.load(parseLabels(source));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// The legacy format: boards and task notes in visible Markdown files, and the root label file.
|
||||
// The native feature reads only `.runestone/pm/`. When it opens a workspace that still has data in the legacy format,
|
||||
// it offers the migration (`migrateStorage` in `migration.ts`), and it migrates only after the user chooses it.
|
||||
import type { Workspace } from "../model/model.ts";
|
||||
import { readCatalog } from "./catalog.ts";
|
||||
import { cardPath } from "./cards.ts";
|
||||
import { readDeletedCards } from "./deleted-cards.ts";
|
||||
import { labelsPath, legacyLabelsPath } from "./labels.ts";
|
||||
import { split } from "./notes.ts";
|
||||
import { cardsFolder, readOptional } from "./persistence.ts";
|
||||
import { markdownPaths, readSources } from "./scan.ts";
|
||||
|
||||
/** The legacy data that the migration has not copied to `.runestone/pm/` yet. */
|
||||
export interface LegacyContent {
|
||||
/** The paths of board notes. */
|
||||
boards: string[];
|
||||
/** The paths of task notes. */
|
||||
cards: string[];
|
||||
/** The paths of notes with invalid Project Management properties. The migration reports them. */
|
||||
invalid: string[];
|
||||
/** True when `runestone-pm-labels.json` exists and `.runestone/pm/labels.json` does not. */
|
||||
labels: boolean;
|
||||
}
|
||||
|
||||
/** The YAML properties at the start of a note, up to a line that starts with `runestone_pm:`. The closing line stops it. */
|
||||
const properties = /^---[ \t]*\r?\n(?:(?!(?:---|\.\.\.)[ \t]*\r?\n)[^\n]*\n)*?runestone_pm[ \t]*:/;
|
||||
|
||||
/** True when the YAML properties of a note can contain Project Management data. It needs no YAML parse. */
|
||||
export function mentionsProjectData(source: string): boolean {
|
||||
return properties.test(source.charCodeAt(0) === 0xfeff ? source.slice(1) : source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the legacy data of a workspace. Only notes that name `runestone_pm` in their properties get a YAML parse.
|
||||
* A board or a card that the migration copied, or that the user deleted, does not count.
|
||||
*/
|
||||
export async function findLegacy(workspace: Workspace, check: () => void = () => {}): Promise<LegacyContent> {
|
||||
const result: LegacyContent = { boards: [], cards: [], invalid: [], labels: false };
|
||||
const paths = await markdownPaths(workspace, check);
|
||||
const found: { path: string; kind: "board" | "task"; id: string }[] = [];
|
||||
// One batch at a time, so the texts of all notes are never in memory together.
|
||||
for (let offset = 0; offset < paths.length; offset += 64) {
|
||||
const sources = await readSources(workspace, paths.slice(offset, offset + 64));
|
||||
check();
|
||||
for (const [path, file] of sources) {
|
||||
if (file.source === undefined || !mentionsProjectData(file.source)) continue;
|
||||
try {
|
||||
const value = split(file.source).doc.toJS({ maxAliasCount: 50 }).runestone_pm;
|
||||
if (value === undefined) continue;
|
||||
if (!value || typeof value.id !== "string" || !value.id.trim() || (value.kind !== "board" && value.kind !== "task")) throw new Error("Invalid data.");
|
||||
found.push({ path, kind: value.kind, id: value.id });
|
||||
} catch { result.invalid.push(path); }
|
||||
}
|
||||
}
|
||||
let saved = new Set<string>(), deletedBoards = new Set<string>(), deletedCards = new Set<string>();
|
||||
try {
|
||||
const catalog = await readCatalog(workspace);
|
||||
saved = new Set(catalog.value.boards.map(board => board.value.id));
|
||||
deletedBoards = new Set(catalog.value.deletedBoardIds ?? []);
|
||||
} catch { /* The migration reports a damaged catalog. */ }
|
||||
try { deletedCards = new Set((await readDeletedCards(workspace)).ids); } catch { /* The migration reports it. */ }
|
||||
let cards = new Set<string>();
|
||||
if (found.some(item => item.kind === "task")) {
|
||||
try { cards = new Set((await workspace.list(cardsFolder)).map(entry => entry.rel_path)); } catch { /* No card folder yet. */ }
|
||||
}
|
||||
for (const item of found) {
|
||||
if (item.kind === "board" && !saved.has(item.id) && !deletedBoards.has(item.id)) result.boards.push(item.path);
|
||||
if (item.kind === "task" && !cards.has(cardPath(item.id)) && !deletedCards.has(item.id)) result.cards.push(item.path);
|
||||
}
|
||||
result.labels = (await readOptional(workspace, legacyLabelsPath)) !== null && (await readOptional(workspace, labelsPath)) === null;
|
||||
for (const list of [result.boards, result.cards, result.invalid]) list.sort();
|
||||
return result;
|
||||
}
|
||||
|
||||
/** True when the workspace has legacy data to migrate. */
|
||||
export function hasLegacy(content: LegacyContent): boolean {
|
||||
return content.boards.length > 0 || content.cards.length > 0 || content.invalid.length > 0 || content.labels;
|
||||
}
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import type { Workspace, Task } from "../model/model.ts";
|
||||
import { migrateCards, readCards, cardOrigin } from "./cards.ts";
|
||||
import type { BoardDocument } from "./board.ts";
|
||||
import {
|
||||
backupFile,
|
||||
readCatalog,
|
||||
writeCatalog,
|
||||
isManagedBoard,
|
||||
type OriginalFile,
|
||||
} from "./catalog.ts";
|
||||
import { labelsPath, legacyLabelsPath, parseLabels } from "./labels.ts";
|
||||
import {
|
||||
readOptional,
|
||||
saveDocument,
|
||||
ensurePrivateStorage,
|
||||
} from "./persistence.ts";
|
||||
import { format, message } from "./message.ts";
|
||||
|
||||
/** Retain originals until the user checks the boards and removes the listed files. */
|
||||
export async function migrateStorage(
|
||||
workspace: Workspace,
|
||||
boards: BoardDocument[],
|
||||
cards: Task[] = [],
|
||||
) {
|
||||
if (!workspace.readOptional || !workspace.create)
|
||||
throw new Error(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);
|
||||
const savedLabels = await readOptional(workspace, labelsPath);
|
||||
if (legacyLabels !== null) parseLabels(legacyLabels);
|
||||
if (savedLabels !== null) parseLabels(savedLabels);
|
||||
// Validate every source before creating backups or publishing any changes.
|
||||
for (const board of legacy) {
|
||||
if (snapshot.value.deletedBoardIds?.includes(board.id))
|
||||
throw new Error(message("This board was deleted. Refresh Project Management before migration."));
|
||||
if ((await workspace.read(board.path)) !== board.source)
|
||||
throw new Error(
|
||||
format(message("The board changed: {path}. Refresh before migration."), { path: board.path }),
|
||||
);
|
||||
const existing = snapshot.value.boards.find(
|
||||
(item) => item.value.id === board.id,
|
||||
);
|
||||
if (
|
||||
existing &&
|
||||
(existing.original?.path !== board.path ||
|
||||
existing.original.source !== board.source)
|
||||
)
|
||||
throw new Error(
|
||||
format(message("A different board already uses the ID from {path}."), { path: board.path }),
|
||||
);
|
||||
}
|
||||
if (legacyLabels !== null && savedLabels !== null) {
|
||||
const original = JSON.parse(savedLabels).original;
|
||||
if (
|
||||
original?.path !== legacyLabelsPath ||
|
||||
original?.source !== legacyLabels
|
||||
)
|
||||
throw new Error(message("Hidden labels and legacy labels both exist. Resolve their differences before migration."));
|
||||
}
|
||||
await ensurePrivateStorage(workspace);
|
||||
let changed = false;
|
||||
for (const board of legacy) {
|
||||
if (snapshot.value.boards.some((item) => item.value.id === board.id))
|
||||
continue;
|
||||
const original = await backupFile(workspace, board.path, board.source);
|
||||
snapshot.value.boards.push({
|
||||
name: board.name,
|
||||
value: board.value,
|
||||
original,
|
||||
});
|
||||
changed = true;
|
||||
}
|
||||
const labelBackup =
|
||||
legacyLabels !== null && savedLabels === null
|
||||
? await backupFile(workspace, legacyLabelsPath, legacyLabels)
|
||||
: undefined;
|
||||
for (const board of legacy)
|
||||
if ((await workspace.read(board.path)) !== board.source)
|
||||
throw new Error(
|
||||
format(message("The board changed: {path}. Refresh before migration."), { path: board.path }),
|
||||
);
|
||||
if (legacyLabels !== (await readOptional(workspace, legacyLabelsPath)))
|
||||
throw new Error(message("Legacy labels changed. Refresh before migration."));
|
||||
if (changed) await writeCatalog(workspace, snapshot.value, snapshot.source);
|
||||
if (labelBackup) {
|
||||
const source =
|
||||
JSON.stringify(
|
||||
{ ...JSON.parse(legacyLabels!), original: labelBackup },
|
||||
null,
|
||||
2,
|
||||
) + "\n";
|
||||
await saveDocument(workspace, labelsPath, source, null);
|
||||
if ((await workspace.read(labelsPath)) !== source)
|
||||
throw new Error(message("The saved label check failed. Retry migration."));
|
||||
}
|
||||
const saved = await readCatalog(workspace);
|
||||
for (const board of legacy) {
|
||||
const entry = saved.value.boards.find((item) => item.value.id === board.id);
|
||||
const expected = snapshot.value.boards.find(
|
||||
(item) => item.value.id === board.id,
|
||||
);
|
||||
if (
|
||||
entry?.original?.source !== board.source ||
|
||||
JSON.stringify(entry) !== JSON.stringify(expected)
|
||||
)
|
||||
throw new Error(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(
|
||||
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(
|
||||
format(message("The original changed: {path}. Keep both versions."), { path: file.path }),
|
||||
);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
export async function migrationFiles(
|
||||
workspace: Workspace,
|
||||
): Promise<OriginalFile[]> {
|
||||
const snapshot = await readCatalog(workspace);
|
||||
const files = snapshot.value.boards.flatMap((board) =>
|
||||
board.original ? [board.original] : [],
|
||||
);
|
||||
const labels = await readOptional(workspace, labelsPath);
|
||||
if (labels !== null) {
|
||||
parseLabels(labels);
|
||||
const original = JSON.parse(labels).original;
|
||||
if (
|
||||
original &&
|
||||
typeof original.path === "string" &&
|
||||
typeof original.source === "string" &&
|
||||
typeof original.backup === "string"
|
||||
)
|
||||
files.push(original);
|
||||
}
|
||||
const cards = await readCards(workspace);
|
||||
if (cards.issues.length) throw new Error(cards.issues.join(" "));
|
||||
for (const task of cards.tasks) {
|
||||
const original = cardOrigin(task.source);
|
||||
if (original) files.push(original);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { Document, isMap, parseDocument } from "yaml";
|
||||
import { isHiddenCard } from "./persistence.ts";
|
||||
import {
|
||||
validateFields,
|
||||
type Task,
|
||||
type TaskFields,
|
||||
type Status,
|
||||
type Session,
|
||||
} from "../model/model.ts";
|
||||
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(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(message("Fix invalid or unsupported YAML properties before editing this note."));
|
||||
if (!isMap(doc.contents))
|
||||
throw new Error(message("Note properties must be a YAML mapping."));
|
||||
return {
|
||||
match,
|
||||
doc,
|
||||
body: match ? source.slice(match[0].length) : source,
|
||||
newline: source.includes("\r\n") ? "\r\n" : "\n",
|
||||
};
|
||||
}
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
export function readTask(path: string, source: string): Task | null {
|
||||
const { doc, body } = split(source);
|
||||
const metadata = doc.toJS({ maxAliasCount: 50 });
|
||||
const pm: unknown = metadata.runestone_pm;
|
||||
if (pm === undefined) return null;
|
||||
if (record(pm) && pm.kind === "board") return null;
|
||||
if (
|
||||
!record(pm) ||
|
||||
pm.schema !== 1 ||
|
||||
pm.kind !== "task" ||
|
||||
typeof pm.id !== "string" ||
|
||||
!pm.id.trim()
|
||||
) {
|
||||
throw new Error(message("This note has an unsupported Project Management schema, kind, or ID."));
|
||||
}
|
||||
if (pm.archived !== undefined && typeof pm.archived !== "boolean")
|
||||
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(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(message("The plan needs a start and an exclusive end date."));
|
||||
if (
|
||||
pm.sessions !== undefined &&
|
||||
(!Array.isArray(pm.sessions) ||
|
||||
pm.sessions.some(
|
||||
(value) =>
|
||||
!record(value) ||
|
||||
typeof value.id !== "string" ||
|
||||
typeof value.start !== "string" ||
|
||||
typeof value.end !== "string" ||
|
||||
typeof value.timeZone !== "string",
|
||||
))
|
||||
) {
|
||||
throw new Error(message("Sessions need an ID, start, end, and time zone."));
|
||||
}
|
||||
const task: Task = {
|
||||
id: pm.id,
|
||||
createdAt: pm.createdAt as string | undefined,
|
||||
path,
|
||||
title:
|
||||
pm.title === undefined
|
||||
? (isHiddenCard(path) &&
|
||||
record(metadata.runestone_pm_origin) &&
|
||||
typeof metadata.runestone_pm_origin.path === "string"
|
||||
? metadata.runestone_pm_origin.path
|
||||
: path
|
||||
)
|
||||
.split("/")
|
||||
.at(-1)!
|
||||
.replace(/\.(md|markdown|mdown)$/i, "")
|
||||
: (pm.title as string),
|
||||
order: pm.order as string | undefined,
|
||||
body,
|
||||
source,
|
||||
status: pm.status as Status,
|
||||
listId: pm.listId as string | null | undefined,
|
||||
placements: pm.placements as Task["placements"],
|
||||
tags: (pm.tags ?? []) as string[],
|
||||
labels: pm.labels as Task["labels"],
|
||||
priority: pm.priority as Task["priority"],
|
||||
coverImage: pm.coverImage as Task["coverImage"],
|
||||
attachments: pm.attachments as Task["attachments"],
|
||||
subtasks: pm.subtasks as Task["subtasks"],
|
||||
links: pm.links as Task["links"],
|
||||
color: pm.color as Task["color"],
|
||||
assignees: pm.assignees as Task["assignees"],
|
||||
customFields: pm.customFields as Task["customFields"],
|
||||
due: pm.due as Task["due"],
|
||||
plan: pm.plan as Task["plan"],
|
||||
sessions: (pm.sessions ?? []) as Session[],
|
||||
archived: pm.archived === true,
|
||||
};
|
||||
validateFields({ ...task, title: pm.title as string | undefined });
|
||||
return task;
|
||||
}
|
||||
|
||||
// Update individual YAML nodes so unknown keys and comments remain in the document.
|
||||
export function editTask(
|
||||
task: Task,
|
||||
patch: Partial<TaskFields> & { body?: string },
|
||||
): string {
|
||||
const fields = { ...task, title: undefined, ...patch };
|
||||
if (Object.hasOwn(patch, "createdAt") && patch.createdAt !== task.createdAt)
|
||||
throw new Error(message("The card creation timestamp cannot change."));
|
||||
validateFields(fields);
|
||||
const { doc, match, newline } = split(task.source);
|
||||
for (const key of [
|
||||
"title",
|
||||
"order",
|
||||
"listId",
|
||||
"placements",
|
||||
"status",
|
||||
"tags",
|
||||
"labels",
|
||||
"priority",
|
||||
"coverImage",
|
||||
"attachments",
|
||||
"subtasks",
|
||||
"links",
|
||||
"color",
|
||||
"assignees",
|
||||
"customFields",
|
||||
"due",
|
||||
"plan",
|
||||
"sessions",
|
||||
"archived",
|
||||
] as const) {
|
||||
if (!Object.hasOwn(patch, key)) continue;
|
||||
const value = patch[key];
|
||||
if (value === undefined) {
|
||||
doc.deleteIn(["runestone_pm", key]);
|
||||
continue;
|
||||
}
|
||||
if (key === "due" || key === "plan") {
|
||||
for (const [name, child] of Object.entries(value as object))
|
||||
doc.setIn(["runestone_pm", key, name], child);
|
||||
} else doc.setIn(["runestone_pm", key], value);
|
||||
}
|
||||
const bom = match?.[1] ?? "";
|
||||
const yaml = doc.toString({ lineWidth: 0 }).replaceAll("\n", newline);
|
||||
const closing = match?.[4].replace(/^\r?\n/, "") ?? `---${newline}`;
|
||||
return `${bom}---${newline}${yaml}${closing}${patch.body ?? task.body}`;
|
||||
}
|
||||
export function newTask(
|
||||
title: string,
|
||||
fields: TaskFields,
|
||||
body = "",
|
||||
id: string = crypto.randomUUID(),
|
||||
): { path: string; source: string } {
|
||||
title = title.trim();
|
||||
if (
|
||||
!title ||
|
||||
title.length > 100 ||
|
||||
/[<>:"/\\|?*\x00-\x1f]/.test(title) ||
|
||||
/[. ]$/.test(title) ||
|
||||
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(title)
|
||||
)
|
||||
throw new Error(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() },
|
||||
});
|
||||
return {
|
||||
path: `Projects/Inbox/${title}.md`,
|
||||
source: `---\n${doc.toString({ lineWidth: 0 })}---\n${body}`,
|
||||
};
|
||||
}
|
||||
export function adoptNote(path: string, source: string): string {
|
||||
if (readTask(path, source)) return source;
|
||||
const { doc, body, match, newline } = split(source);
|
||||
if (doc.has("runestone_pm"))
|
||||
throw new Error(message("This document already contains Project Management data and cannot become a task."));
|
||||
doc.set("runestone_pm", {
|
||||
schema: 1,
|
||||
id: crypto.randomUUID(),
|
||||
kind: "task",
|
||||
createdAt: new Date().toISOString(),
|
||||
status: "todo",
|
||||
tags: [],
|
||||
sessions: [],
|
||||
archived: false,
|
||||
});
|
||||
return `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { Task } from "../model/model.ts";
|
||||
import { message } from "./message.ts";
|
||||
|
||||
const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
const encode = (text: string) =>
|
||||
text
|
||||
.split("")
|
||||
.map((char) => char.charCodeAt(0).toString(16).padStart(4, "0"))
|
||||
.join("");
|
||||
|
||||
export function cardOrder(task: Task, boardId?: string): string {
|
||||
const saved = boardId ? task.placements?.[boardId]?.order : task.order;
|
||||
// Old notes keep filename order. Title edits do not change their positions.
|
||||
const position = saved ?? legacyPosition(task.path);
|
||||
// The ID breaks ties when separate windows choose the same position.
|
||||
return position + "i" + encode(task.id) + "8";
|
||||
}
|
||||
|
||||
export function legacyPosition(path: string): string {
|
||||
return encode(path.split("/").at(-1)!.toLowerCase()) + "0000" + encode(path);
|
||||
}
|
||||
|
||||
export function compareCards(a: Task, b: Task, boardId?: string): number {
|
||||
const left = cardOrder(a, boardId),
|
||||
right = cardOrder(b, boardId);
|
||||
return left < right ? -1 : left > right ? 1 : 0;
|
||||
}
|
||||
|
||||
export function orderBetween(lower?: string, upper?: string): string {
|
||||
if (lower !== undefined && upper !== undefined && lower >= upper)
|
||||
throw new Error(message("The card order changed. Refresh the board."));
|
||||
let result = "";
|
||||
for (let index = 0; ; index++) {
|
||||
const low =
|
||||
index < (lower?.length ?? 0) ? digits.indexOf(lower![index]) : 0;
|
||||
const high =
|
||||
upper === undefined ? digits.length : digits.indexOf(upper[index]);
|
||||
if (high - low > 1) return result + digits[Math.floor((low + high) / 2)];
|
||||
result += digits[low];
|
||||
if (low < high) upper = undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { Workspace } from "../model/model.ts";
|
||||
import { message } from "./message.ts";
|
||||
|
||||
export const storageRoot = ".runestone/pm";
|
||||
export const privateRulesPath = `${storageRoot}/.gitignore`;
|
||||
export const cardsFolder = `${storageRoot}/cards`;
|
||||
export const cardsMarker = `${cardsFolder}/.gitignore`;
|
||||
export const isHiddenCard = (path: string) =>
|
||||
path.startsWith(cardsFolder + "/") && /\.md$/i.test(path);
|
||||
|
||||
/** Install the local exclusion before publishing any private Project Management data. */
|
||||
export async function ensurePrivateStorage(workspace: Workspace) {
|
||||
if (!workspace.readOptional || !workspace.create)
|
||||
throw new Error(message("Update RuneStone to use hidden Project Management storage."));
|
||||
const expected = await workspace.readOptional(privateRulesPath);
|
||||
const rules = expected
|
||||
?.split(/\r?\n/)
|
||||
.filter((line) => line && !line.startsWith("#"));
|
||||
if (rules?.at(-1) === "*") return;
|
||||
const source =
|
||||
(expected ? expected + (expected.endsWith("\n") ? "" : "\n") : "") +
|
||||
"# RuneStone Project Management local data\n*\n";
|
||||
if (expected === null) {
|
||||
try {
|
||||
await workspace.create(privateRulesPath, source);
|
||||
} catch (error) {
|
||||
if ((await workspace.readOptional(privateRulesPath)) !== source)
|
||||
throw error;
|
||||
}
|
||||
} else await workspace.write(privateRulesPath, source, expected);
|
||||
if ((await workspace.readOptional(privateRulesPath)) !== source)
|
||||
throw new Error(message("The Project Management Git exclusion changed. Retry before saving private data."));
|
||||
}
|
||||
|
||||
/** Older hosts cannot discover hidden files through the root listing. */
|
||||
export async function readOptional(
|
||||
workspace: Workspace,
|
||||
path: string,
|
||||
): Promise<string | null> {
|
||||
if (workspace.readOptional) return workspace.readOptional(path);
|
||||
const entries = await workspace.list();
|
||||
if (entries.some((entry) => entry.rel_path === path))
|
||||
return workspace.read(path);
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function saveDocument(
|
||||
workspace: Workspace,
|
||||
path: string,
|
||||
source: string,
|
||||
expected: string | null,
|
||||
) {
|
||||
if (path.startsWith(storageRoot + "/") && path !== privateRulesPath)
|
||||
await ensurePrivateStorage(workspace);
|
||||
if (expected === null) {
|
||||
if (!workspace.create)
|
||||
throw new Error(message("Update RuneStone to create Project Management storage."));
|
||||
await workspace.create(path, source);
|
||||
} else await workspace.write(path, source, expected);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
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;
|
||||
|
||||
/** Read bounded batches while retaining each file's failure and conflict evidence. */
|
||||
export async function readSources(workspace: Workspace, paths: string[]) {
|
||||
const results = new Map<string, { source?: string; error?: string }>();
|
||||
if (workspace.readMany) {
|
||||
for (let offset = 0; offset < paths.length; offset += 64) {
|
||||
const batch = paths.slice(offset, offset + 64);
|
||||
const rows = await workspace.readMany(batch);
|
||||
for (const path of batch) {
|
||||
const row = rows.find(row => row.path === path);
|
||||
results.set(path, row && (typeof row.source === "string" || row.error) ? row : { error: message("The batch did not return this file.") });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
await mapConcurrent(paths, async path => {
|
||||
try { results.set(path, { source: await workspace.read(path) }); }
|
||||
catch (error) { results.set(path, { error: error instanceof Error ? error.message : String(error) }); }
|
||||
});
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function mapConcurrent<T, R>(
|
||||
items: readonly T[],
|
||||
visit: (item: T) => Promise<R>,
|
||||
): Promise<R[]> {
|
||||
const results = new Array<R>(items.length);
|
||||
let next = 0;
|
||||
const workers = Array.from(
|
||||
{ length: Math.min(scanConcurrency, items.length) },
|
||||
async () => {
|
||||
while (next < items.length) {
|
||||
const index = next++;
|
||||
results[index] = await visit(items[index]);
|
||||
}
|
||||
},
|
||||
);
|
||||
// Drain every worker before returning or reporting a failed directory read.
|
||||
const settled = await Promise.allSettled(workers);
|
||||
const failed = settled.find((result) => result.status === "rejected");
|
||||
if (failed?.status === "rejected") throw failed.reason;
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function markdownPaths(
|
||||
workspace: Workspace,
|
||||
check: () => void,
|
||||
): Promise<string[]> {
|
||||
check();
|
||||
if (workspace.listMarkdown) {
|
||||
const paths = await workspace.listMarkdown();
|
||||
check();
|
||||
return paths;
|
||||
}
|
||||
const files: string[] = [];
|
||||
let folders = [""];
|
||||
while (folders.length) {
|
||||
const listings = await mapConcurrent(folders, async (path) => {
|
||||
check();
|
||||
return workspace.list(path);
|
||||
});
|
||||
folders = [];
|
||||
for (const entries of listings) {
|
||||
check();
|
||||
for (const entry of entries) {
|
||||
if (
|
||||
entry.name.startsWith(".") ||
|
||||
entry.rel_path.startsWith(".runestone/")
|
||||
)
|
||||
continue;
|
||||
if (entry.kind === "folder") folders.push(entry.rel_path);
|
||||
else if (/\.(md|markdown|mdown)$/i.test(entry.name))
|
||||
files.push(entry.rel_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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) {
|
||||
const choices = new Map<HTMLSelectElement, { trigger: HTMLButtonElement; update(): void }>();
|
||||
let menu: { close(): void } | undefined;
|
||||
let owner: HTMLSelectElement | undefined;
|
||||
const close = () => { menu?.close(); menu = undefined; owner = undefined; };
|
||||
const sync = () => {
|
||||
for (const [select, choice] of choices) {
|
||||
if (!root.contains(select)) {
|
||||
if (owner === select) close();
|
||||
choices.delete(select);
|
||||
} else choice.update();
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(sync);
|
||||
observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["disabled", "label", "selected"] });
|
||||
return {
|
||||
use(select: HTMLSelectElement) {
|
||||
const existing = choices.get(select);
|
||||
if (existing) { existing.update(); return existing.trigger; }
|
||||
const label = select.getAttribute("aria-label") ?? select.closest("label")?.firstChild?.textContent?.trim() ?? tr("Choose");
|
||||
const trigger = document.createElement("button");
|
||||
trigger.type = "button";
|
||||
trigger.className = "pm-button pm-choice-button";
|
||||
trigger.setAttribute("aria-label", label);
|
||||
trigger.setAttribute("aria-haspopup", "menu");
|
||||
const text = document.createElement("span"); text.className = "pm-choice-label";
|
||||
const icon = document.createElement("span"); icon.className = "pm-icon";
|
||||
icon.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>';
|
||||
trigger.append(text, icon);
|
||||
const update = () => {
|
||||
const value = select.selectedOptions[0]?.textContent ?? tr("Choose");
|
||||
if (text.textContent !== value) text.textContent = value;
|
||||
if (trigger.disabled !== select.disabled) trigger.disabled = select.disabled;
|
||||
};
|
||||
trigger.onclick = () => {
|
||||
close(); update(); trigger.focus({ preventScroll: true });
|
||||
const bounds = trigger.getBoundingClientRect(); owner = select;
|
||||
menu = ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: trigger.closest<HTMLElement>("dialog, [popover]") ?? undefined,
|
||||
items: Array.from(select.options).map(option => ({ label: option.textContent ?? "", radio: true,
|
||||
checked: option.selected, disabled: option.disabled, run: () => {
|
||||
select.value = option.value;
|
||||
select.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
sync();
|
||||
} })) });
|
||||
};
|
||||
trigger.onkeydown = event => {
|
||||
if (["ArrowDown", "ArrowUp"].includes(event.key)) { event.preventDefault(); trigger.click(); }
|
||||
};
|
||||
select.hidden = true;
|
||||
select.after(trigger);
|
||||
select.addEventListener("change", update);
|
||||
choices.set(select, { trigger, update }); update();
|
||||
return trigger;
|
||||
},
|
||||
close,
|
||||
update(select: HTMLSelectElement) { choices.get(select)?.update(); },
|
||||
dispose() { close(); observer.disconnect(); choices.clear(); },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { cardColors } from "../model/model.ts";
|
||||
import { message, tr } from "../../../i18n/index.ts";
|
||||
|
||||
/** 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",
|
||||
blue: "#0066ff", indigo: "#5533ff", purple: "#aa00ff", magenta: "#ff00cc",
|
||||
pink: "#ff4080", brown: "#a65316", slate: "#527da3", gray: "#858585",
|
||||
};
|
||||
|
||||
export function swatchForeground(hex: string) {
|
||||
const channels = hex.slice(1).match(/../g)!.map(value => {
|
||||
const channel = parseInt(value, 16) / 255;
|
||||
return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
|
||||
});
|
||||
const luminance = channels[0] * 0.2126 + channels[1] * 0.7152 + channels[2] * 0.0722;
|
||||
return (luminance + 0.05) / 0.05 > 1.05 / (luminance + 0.05) ? "#000000" : "#ffffff";
|
||||
}
|
||||
|
||||
export function createColorPalette(
|
||||
name: string,
|
||||
initial: string,
|
||||
change: (value: string) => void,
|
||||
allowNone = false,
|
||||
palette: Record<keyof typeof cardColors, string> = cardColors,
|
||||
) {
|
||||
const element = document.createElement("fieldset");
|
||||
element.className = "pm-color-palette pm-wide";
|
||||
element.setAttribute("role", "radiogroup");
|
||||
element.setAttribute("aria-label", name);
|
||||
const legend = document.createElement("legend");
|
||||
legend.textContent = name;
|
||||
const choices = document.createElement("div");
|
||||
choices.className = "pm-color-choices";
|
||||
const current = document.createElement("span");
|
||||
current.className = "pm-color-name";
|
||||
current.setAttribute("aria-hidden", "true");
|
||||
const group = "pm-colors-" + crypto.randomUUID();
|
||||
const inputs: HTMLInputElement[] = [];
|
||||
const values = [...(allowNone ? [""] : []), ...Object.keys(cardColors)];
|
||||
let selected = initial;
|
||||
const set = (value: string) => {
|
||||
selected = value;
|
||||
for (const input of inputs) input.checked = input.value === value;
|
||||
current.textContent = colorName(value);
|
||||
};
|
||||
for (const value of values) {
|
||||
const input = document.createElement("input");
|
||||
input.type = "radio";
|
||||
input.name = group;
|
||||
input.value = value;
|
||||
input.className = "pm-color-swatch";
|
||||
input.setAttribute("aria-label", colorName(value));
|
||||
input.title = colorName(value);
|
||||
if (value) {
|
||||
input.style.setProperty(
|
||||
"--pm-swatch-color",
|
||||
palette[value as keyof typeof cardColors],
|
||||
);
|
||||
input.style.setProperty("--pm-swatch-foreground", swatchForeground(palette[value as keyof typeof cardColors]));
|
||||
} else input.classList.add("pm-no-color");
|
||||
input.onchange = () => {
|
||||
if (!input.checked) return;
|
||||
set(value);
|
||||
change(value);
|
||||
};
|
||||
inputs.push(input);
|
||||
choices.append(input);
|
||||
}
|
||||
element.append(legend, choices, current);
|
||||
set(initial);
|
||||
return { element, value: () => selected, set };
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { tooltip } from "./host.ts";
|
||||
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", 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"></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");
|
||||
status.setAttribute("role", "status");
|
||||
status.setAttribute("aria-live", "polite");
|
||||
let current = -1;
|
||||
let matches: { from: number; to: number }[] = [];
|
||||
let returnStart = 0, returnEnd = 0;
|
||||
const highlights = document.createElement("div");
|
||||
highlights.className = "pm-description-find-highlights";
|
||||
highlights.setAttribute("aria-hidden", "true"); highlights.hidden = true;
|
||||
textarea.parentElement!.append(highlights);
|
||||
function paint() {
|
||||
highlights.replaceChildren();
|
||||
highlights.hidden = element.hidden || !matches.length;
|
||||
if (highlights.hidden) return;
|
||||
const style = getComputedStyle(textarea);
|
||||
for (const property of ["font", "line-height", "padding", "letter-spacing", "tab-size"])
|
||||
highlights.style.setProperty(property, style.getPropertyValue(property));
|
||||
let end = 0;
|
||||
for (const [index, match] of matches.entries()) {
|
||||
highlights.append(document.createTextNode(textarea.value.slice(end, match.from)));
|
||||
const mark = document.createElement("mark"); mark.textContent = textarea.value.slice(match.from, match.to);
|
||||
if (index === current) mark.className = "pm-description-find-current";
|
||||
highlights.append(mark); end = match.to;
|
||||
}
|
||||
highlights.append(document.createTextNode(textarea.value.slice(end)));
|
||||
}
|
||||
function option(label: string) {
|
||||
const wrapper = document.createElement("label");
|
||||
const checkbox = document.createElement("input"); checkbox.type = "checkbox";
|
||||
checkbox.onchange = refresh;
|
||||
wrapper.append(checkbox, document.createTextNode(label)); options.append(wrapper);
|
||||
return checkbox;
|
||||
}
|
||||
const matchCase = option(tr("Match case"));
|
||||
const wholeWord = option(tr("Whole word"));
|
||||
const regex = option(tr("Regex"));
|
||||
options.append(status);
|
||||
function close() {
|
||||
hide();
|
||||
textarea.focus({ preventScroll: true });
|
||||
textarea.setSelectionRange(returnStart, returnEnd);
|
||||
}
|
||||
function hide() { element.hidden = highlights.hidden = true; }
|
||||
function action(label: string, path: string, run: () => void) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button"; button.className = "rs-find-button pm-icon-button";
|
||||
button.setAttribute("aria-label", label);
|
||||
button.innerHTML = `<span class="pm-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="${path}"/></svg></span>`;
|
||||
tooltip(button, label);
|
||||
button.onclick = run; actions.append(button);
|
||||
return button;
|
||||
}
|
||||
const previous = action(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 ? tr("{current} of {total}", { current: current < 0 ? 0 : current + 1, total: matches.length }) : tr("No matches")) : "";
|
||||
}
|
||||
function refresh() {
|
||||
current = -1; matches = [];
|
||||
input.setAttribute("aria-invalid", "false"); status.classList.remove("rs-find-error");
|
||||
if (input.value) {
|
||||
try {
|
||||
const pattern = regex.checked ? input.value : input.value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const expression = new RegExp(wholeWord.checked ? `\\b(?:${pattern})\\b` : pattern, `gmu${matchCase.checked ? "" : "i"}`);
|
||||
for (const match of textarea.value.matchAll(expression)) {
|
||||
if (match[0].length) matches.push({ from: match.index, to: match.index + match[0].length });
|
||||
}
|
||||
} catch {
|
||||
input.setAttribute("aria-invalid", "true"); status.classList.add("rs-find-error");
|
||||
}
|
||||
}
|
||||
previous.disabled = following.disabled = !matches.length;
|
||||
if (input.getAttribute("aria-invalid") === "true") status.textContent = tr("Invalid expression");
|
||||
else announce();
|
||||
paint();
|
||||
}
|
||||
function next(backward = false) {
|
||||
if (!matches.length) return;
|
||||
current = current < 0 ? (backward ? matches.length - 1 : 0) : (current + (backward ? -1 : 1) + matches.length) % matches.length;
|
||||
const match = matches[current];
|
||||
returnStart = match.from; returnEnd = match.to;
|
||||
textarea.setSelectionRange(match.from, match.to);
|
||||
// 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}`;
|
||||
mirror.textContent = textarea.value.slice(0, match.from);
|
||||
const marker = document.createElement("span"); marker.textContent = textarea.value.slice(match.from, match.to);
|
||||
mirror.append(marker); document.body.append(mirror);
|
||||
const dialog = textarea.closest("dialog");
|
||||
if (dialog) dialog.scrollTop += textarea.getBoundingClientRect().top + marker.offsetTop - dialog.getBoundingClientRect().top - dialog.clientHeight / 2;
|
||||
mirror.remove(); announce(); paint();
|
||||
}
|
||||
input.oninput = refresh;
|
||||
element.addEventListener("keydown", event => {
|
||||
if (event.key === "Escape" || event.key === "Enter" && event.target === input) {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (event.key === "Escape") close(); else next(event.shiftKey);
|
||||
}
|
||||
});
|
||||
textarea.addEventListener("input", refresh);
|
||||
return {
|
||||
element,
|
||||
open() {
|
||||
if (element.hidden) {
|
||||
returnStart = textarea.selectionStart; returnEnd = textarea.selectionEnd;
|
||||
const selected = textarea.value.slice(returnStart, returnEnd);
|
||||
if (selected && !selected.includes("\n")) input.value = selected;
|
||||
refresh();
|
||||
}
|
||||
element.hidden = false; paint(); element.scrollIntoView({ block: "nearest" }); input.focus(); input.select();
|
||||
},
|
||||
close,
|
||||
hide,
|
||||
dispose() { textarea.removeEventListener("input", refresh); highlights.remove(); },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import { tooltip } from "./host.ts";
|
||||
import type { createCardImages } from "./images-ui.ts";
|
||||
import { renderMarkdown } from "../model/markdown.ts";
|
||||
import { headingEdit } from "../model/description-format.ts";
|
||||
import { createDescriptionFind } from "./description-find.ts";
|
||||
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", 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></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", 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", tr("Description preview"));
|
||||
const toolbar = document.createElement("div");
|
||||
toolbar.className = "pm-description-toolbar";
|
||||
toolbar.setAttribute("role", "group");
|
||||
toolbar.setAttribute("aria-label", tr("Markdown formatting"));
|
||||
textarea.spellcheck = true;
|
||||
const resize = () => {
|
||||
if (source.hidden || !textarea.isConnected) return;
|
||||
textarea.style.height = "auto";
|
||||
textarea.style.height = `${Math.max(150, textarea.scrollHeight + 2)}px`;
|
||||
};
|
||||
let width = 0;
|
||||
let resizeFrame = 0;
|
||||
const observer = new ResizeObserver(() => {
|
||||
if (textarea.clientWidth && textarea.clientWidth !== width) {
|
||||
width = textarea.clientWidth;
|
||||
cancelAnimationFrame(resizeFrame);
|
||||
resizeFrame = requestAnimationFrame(resize);
|
||||
}
|
||||
});
|
||||
observer.observe(element);
|
||||
let disposed = false;
|
||||
let revision = 0;
|
||||
let editing = !textarea.value.trim();
|
||||
let original = textarea.value;
|
||||
let pending = false;
|
||||
const unsaved = document.createElement("span");
|
||||
unsaved.className = "pm-description-unsaved";
|
||||
unsaved.textContent = tr("Unsaved changes");
|
||||
unsaved.hidden = true;
|
||||
unsaved.setAttribute("aria-live", "polite");
|
||||
function insert(before: string, after: string, placeholder: string) {
|
||||
const start = textarea.selectionStart;
|
||||
const selection = textarea.value.slice(start, textarea.selectionEnd) || placeholder;
|
||||
textarea.setRangeText(before + selection + after, start, textarea.selectionEnd, "end");
|
||||
textarea.setSelectionRange(start + before.length, start + before.length + selection.length);
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
textarea.focus();
|
||||
}
|
||||
const formatting = [
|
||||
control(message("Heading"), () => {
|
||||
const edit = headingEdit(textarea.value, textarea.selectionStart, textarea.selectionEnd);
|
||||
const direction = textarea.selectionDirection;
|
||||
textarea.setRangeText(edit.text, edit.start, edit.end, "preserve");
|
||||
textarea.setSelectionRange(edit.selectionStart, edit.selectionEnd, direction);
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
textarea.focus();
|
||||
}),
|
||||
control(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 = 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", tr("View image {name}", { name: image.alt }));
|
||||
image.removeAttribute("title");
|
||||
trigger.onclick = () => images.showImage(image, trigger);
|
||||
image.replaceWith(trigger);
|
||||
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(tr("Cannot display image: {name}", { name: image.alt }));
|
||||
} catch {
|
||||
if (!disposed && current === revision)
|
||||
fail(tr("Cannot load image: {name}", { name: image.alt }));
|
||||
}
|
||||
}
|
||||
}
|
||||
const edit = control(message("Edit"), () => {
|
||||
if (!persistence) original = textarea.value;
|
||||
editing = true;
|
||||
update();
|
||||
textarea.focus();
|
||||
resize();
|
||||
});
|
||||
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 ? tr("Edit Markdown") : tr("Preview");
|
||||
toggle.setAttribute("aria-pressed", String(source.hidden));
|
||||
if (source.hidden) void render();
|
||||
updateLoading();
|
||||
if (!source.hidden) textarea.focus();
|
||||
});
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "pm-description-actions";
|
||||
const finish = async (cancel: boolean) => {
|
||||
if (images.isLoading() || pending) return;
|
||||
pending = true; updateLoading();
|
||||
try {
|
||||
if (cancel) {
|
||||
textarea.value = persistence ? await persistence.cancel() : original;
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
} else await persistence?.save();
|
||||
original = textarea.value;
|
||||
unsaved.hidden = true;
|
||||
editing = false;
|
||||
pending = false;
|
||||
update();
|
||||
edit.focus();
|
||||
} catch { /* The card editor shows the persistence error. */ }
|
||||
finally { pending = false; updateLoading(); }
|
||||
};
|
||||
const cancel = control(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 ?? "";
|
||||
item.setAttribute("aria-label", name);
|
||||
item.removeAttribute("title");
|
||||
item.classList.add("pm-icon-button");
|
||||
for (const child of [...item.childNodes])
|
||||
if (child.nodeType === Node.TEXT_NODE) child.remove();
|
||||
tooltip(item, name);
|
||||
}
|
||||
toolbar.setAttribute("role", "toolbar");
|
||||
toolbar.append(...formatting, images.addControl, toggle);
|
||||
header.append(heading, unsaved, edit);
|
||||
const surface = document.createElement("div");
|
||||
surface.className = "pm-description-surface";
|
||||
surface.append(toolbar, source);
|
||||
const content = document.createElement("div"); content.id = `pm-description-${crypto.randomUUID()}`;
|
||||
toggleSection.setAttribute("aria-controls", content.id);
|
||||
toggleSection.onclick = () => {
|
||||
content.hidden = !content.hidden;
|
||||
toggleSection.setAttribute("aria-expanded", String(!content.hidden));
|
||||
edit.hidden = content.hidden || editing;
|
||||
if (!content.hidden) resize();
|
||||
};
|
||||
content.append(find.element, surface, preview, images.element, actions);
|
||||
element.append(header, content);
|
||||
function updateLoading() {
|
||||
edit.disabled = toggle.disabled = cancel.disabled = apply.disabled = images.isLoading() || pending;
|
||||
images.addControl.disabled = images.isLoading() || pending || !!source.hidden;
|
||||
for (const button of formatting) button.disabled = images.isLoading() || pending || !!source.hidden;
|
||||
}
|
||||
function update() {
|
||||
find.hide();
|
||||
edit.hidden = editing || content.hidden;
|
||||
toolbar.hidden = actions.hidden = !editing;
|
||||
source.hidden = !editing;
|
||||
images.setEditing(editing);
|
||||
preview.hidden = editing;
|
||||
toggle.lastChild!.textContent = tr("Preview");
|
||||
toggle.setAttribute("aria-pressed", "false");
|
||||
updateLoading();
|
||||
if (!editing) void render();
|
||||
else { cancelAnimationFrame(resizeFrame); resizeFrame = requestAnimationFrame(resize); }
|
||||
}
|
||||
const onInput = () => {
|
||||
unsaved.hidden = textarea.value === original;
|
||||
resize();
|
||||
if (document.activeElement === textarea) {
|
||||
const style = getComputedStyle(textarea);
|
||||
const mirror = document.createElement("div");
|
||||
mirror.style.cssText = `position:fixed;visibility:hidden;pointer-events:none;white-space:pre-wrap;overflow-wrap:break-word;box-sizing:border-box;width:${textarea.clientWidth}px;font:${style.font};line-height:${style.lineHeight};padding:${style.padding}`;
|
||||
mirror.textContent = textarea.value.slice(0, textarea.selectionEnd);
|
||||
const marker = document.createElement("span"); marker.textContent = "\u200b"; mirror.append(marker);
|
||||
document.body.append(mirror);
|
||||
const caret = textarea.getBoundingClientRect().top + marker.offsetTop + parseFloat(style.lineHeight);
|
||||
mirror.remove();
|
||||
const dialog = textarea.closest("dialog");
|
||||
const bottomSpace = parseFloat(style.paddingBottom);
|
||||
if (dialog && caret + bottomSpace > dialog.getBoundingClientRect().bottom - 50) dialog.scrollTop += caret + bottomSpace - dialog.getBoundingClientRect().bottom + 50;
|
||||
}
|
||||
if (!preview.hidden) void render();
|
||||
};
|
||||
textarea.addEventListener("input", onInput);
|
||||
element.addEventListener("keydown", (event) => {
|
||||
if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "f") {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
content.hidden = false; toggleSection.setAttribute("aria-expanded", "true");
|
||||
if (!editing) { editing = true; update(); }
|
||||
if (source.hidden) toggle.click();
|
||||
find.open();
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape" && !find.element.hidden) {
|
||||
event.preventDefault(); event.stopPropagation(); find.close(); return;
|
||||
}
|
||||
if (event.key === "Escape" && editing && !element.querySelector("dialog[open], :popover-open")) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
editing = false;
|
||||
update();
|
||||
edit.focus();
|
||||
}
|
||||
});
|
||||
update();
|
||||
return {
|
||||
element,
|
||||
updateLoading,
|
||||
resize,
|
||||
restoreDraft(body: string) {
|
||||
textarea.value = body;
|
||||
unsaved.hidden = body === original;
|
||||
// Keep the saved description visible until the user opens the draft.
|
||||
if (editing) resize();
|
||||
},
|
||||
saved(body: string) { original = body; unsaved.hidden = textarea.value === body; },
|
||||
dispose() { disposed = true; find.dispose(); cancelAnimationFrame(resizeFrame); observer.disconnect(); revision++; textarea.removeEventListener("input", onInput); },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
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", tr("Add card details"));
|
||||
const search = document.createElement("input");
|
||||
search.type = "search";
|
||||
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 = tr("No matching details.");
|
||||
empty.hidden = true;
|
||||
panel.append(search, choices, empty);
|
||||
trigger.popoverTargetElement = panel;
|
||||
trigger.setAttribute("aria-haspopup", "dialog");
|
||||
trigger.setAttribute("aria-controls", panel.id);
|
||||
trigger.setAttribute("aria-expanded", "false");
|
||||
const close = () => {
|
||||
if (panel.matches(":popover-open")) panel.hidePopover();
|
||||
};
|
||||
const position = () => {
|
||||
if (!panel.matches(":popover-open")) return;
|
||||
const anchor = trigger.getBoundingClientRect();
|
||||
panel.style.maxHeight = `${window.innerHeight - 24}px`;
|
||||
const bounds = panel.getBoundingClientRect();
|
||||
panel.style.left = `${Math.max(12, Math.min(anchor.left, window.innerWidth - bounds.width - 12))}px`;
|
||||
panel.style.top = `${Math.max(12, Math.min(anchor.bottom + 6, window.innerHeight - bounds.height - 12))}px`;
|
||||
};
|
||||
const entries: { row: HTMLElement; name: string }[] = [];
|
||||
function filter() {
|
||||
for (const entry of entries)
|
||||
entry.row.hidden = !entry.name
|
||||
.toLocaleLowerCase()
|
||||
.includes(search.value.trim().toLocaleLowerCase());
|
||||
empty.hidden = entries.some((entry) => !entry.row.hidden);
|
||||
position();
|
||||
}
|
||||
search.oninput = filter;
|
||||
panel.onkeydown = (event) => {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
close();
|
||||
trigger.focus();
|
||||
} else if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) {
|
||||
if (
|
||||
event.target === search &&
|
||||
(event.key === "Home" || event.key === "End")
|
||||
)
|
||||
return;
|
||||
const buttons = entries
|
||||
.filter((entry) => !entry.row.hidden)
|
||||
.map((entry) => entry.row.querySelector("button")!);
|
||||
const index = buttons.indexOf(
|
||||
document.activeElement as HTMLButtonElement,
|
||||
);
|
||||
const next =
|
||||
event.key === "Home"
|
||||
? 0
|
||||
: event.key === "End"
|
||||
? buttons.length - 1
|
||||
: event.key === "ArrowDown"
|
||||
? (index + 1) % buttons.length
|
||||
: index < 0
|
||||
? buttons.length - 1
|
||||
: (index + buttons.length - 1) % buttons.length;
|
||||
event.preventDefault();
|
||||
buttons[next]?.focus();
|
||||
} else if (event.key === "Enter" && event.target === search) {
|
||||
event.preventDefault();
|
||||
entries
|
||||
.find((entry) => !entry.row.hidden)
|
||||
?.row.querySelector("button")
|
||||
?.click();
|
||||
}
|
||||
};
|
||||
panel.addEventListener("beforetoggle", (event) => {
|
||||
if ((event as ToggleEvent).newState === "open") {
|
||||
search.value = "";
|
||||
filter();
|
||||
}
|
||||
});
|
||||
panel.addEventListener("toggle", () => {
|
||||
const open = panel.matches(":popover-open");
|
||||
trigger.setAttribute("aria-expanded", String(open));
|
||||
if (open) {
|
||||
position();
|
||||
if (!panel.contains(document.activeElement)) search.focus();
|
||||
}
|
||||
});
|
||||
window.addEventListener("resize", position);
|
||||
document.addEventListener("scroll", position, true);
|
||||
return {
|
||||
element: panel,
|
||||
add(button: HTMLButtonElement, detail: string) {
|
||||
button.className = "rs-picker-row";
|
||||
button.querySelector(".pm-icon")?.classList.add("rs-picker-icon");
|
||||
const row = document.createElement("div");
|
||||
row.className = "pm-detail-choice";
|
||||
const hint = document.createElement("span");
|
||||
hint.id = `pm-detail-hint-${crypto.randomUUID()}`;
|
||||
hint.textContent = detail;
|
||||
hint.className = "pm-detail-hint rs-picker-hint";
|
||||
button.setAttribute("aria-describedby", hint.id);
|
||||
button.setAttribute("aria-label", button.textContent ?? "");
|
||||
const action = button.onclick;
|
||||
button.onclick = (event) => {
|
||||
close();
|
||||
action?.call(button, event);
|
||||
};
|
||||
const text = document.createElement("span");
|
||||
for (const child of [...button.childNodes]) if (!(child instanceof Element && child.classList.contains("pm-icon"))) text.append(child);
|
||||
text.append(hint);
|
||||
button.append(text);
|
||||
row.append(button);
|
||||
choices.append(row);
|
||||
entries.push({ row, name: button.textContent ?? "" });
|
||||
},
|
||||
dispose() {
|
||||
close();
|
||||
window.removeEventListener("resize", position);
|
||||
document.removeEventListener("scroll", position, true);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// The host layer of the Project Management interface: the shared action menu, the shared tooltip, and the shared action
|
||||
// icons of RuneStone. The interface builds plain DOM. A Svelte version is a later card.
|
||||
import { showActionMenu, type MenuOptions } from "../../../ui/managedActionMenu.ts";
|
||||
import { attachTooltip } from "../../../ui/tooltip.ts";
|
||||
export { actionIcons, type ActionIcon } from "../../../ui/actionIcons.ts";
|
||||
export type { ActionMenuItem } from "../../../ui/actionMenu.ts";
|
||||
|
||||
/** The menus that the interface opens. Tests can give their own. */
|
||||
export interface MenuHost {
|
||||
showActionMenu(options: MenuOptions): { close(): void };
|
||||
}
|
||||
|
||||
export const hostMenus: MenuHost = { showActionMenu: options => showActionMenu(options) };
|
||||
|
||||
/** The attribute that gives a control its tooltip text. */
|
||||
export const TOOLTIP = "data-pm-tooltip";
|
||||
|
||||
/** Give a control the shared tooltip. The text can change later through the attribute. */
|
||||
export function tooltip<T extends HTMLElement>(control: T, text: string): T {
|
||||
control.setAttribute(TOOLTIP, text);
|
||||
return control;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach the shared tooltip to each control in `root` with `data-pm-tooltip`, also to controls that a render adds later.
|
||||
* A removed control loses its tooltip. Returns the function that removes all tooltips.
|
||||
*/
|
||||
export function mountTooltips(root: HTMLElement): () => void {
|
||||
const attached = new Map<HTMLElement, () => void>();
|
||||
const attach = (node: Node) => {
|
||||
if (!(node instanceof HTMLElement)) return;
|
||||
const controls = node.matches(`[${TOOLTIP}]`) ? [node, ...node.querySelectorAll<HTMLElement>(`[${TOOLTIP}]`)] : node.querySelectorAll<HTMLElement>(`[${TOOLTIP}]`);
|
||||
for (const control of controls) {
|
||||
if (attached.has(control)) continue;
|
||||
attached.set(control, attachTooltip(control, () => control.getAttribute(TOOLTIP) ?? ""));
|
||||
}
|
||||
};
|
||||
const sweep = () => {
|
||||
for (const [control, detach] of attached) {
|
||||
if (control.isConnected && root.contains(control)) continue;
|
||||
detach();
|
||||
attached.delete(control);
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(records => {
|
||||
sweep();
|
||||
for (const record of records) for (const node of record.addedNodes) attach(node);
|
||||
});
|
||||
observer.observe(root, { childList: true, subtree: true });
|
||||
attach(root);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
for (const detach of attached.values()) detach();
|
||||
attached.clear();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
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,
|
||||
imagePath,
|
||||
imageReferences,
|
||||
imageTypes,
|
||||
maxImageBytes,
|
||||
parseImage,
|
||||
saveImages,
|
||||
} from "../storage/images.ts";
|
||||
import { workspaceDownloadImage } from "../../../workspace/api.ts";
|
||||
import { copiedImage } from "../../../workspace/copiedImage.ts";
|
||||
import { mayAnimate, pastedImageSource } from "../../../workspace/media.ts";
|
||||
|
||||
async function fileDataUrl(file: File) {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
let binary = "";
|
||||
for (let offset = 0; offset < bytes.length; offset += 8192)
|
||||
binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
|
||||
return `data:${file.type};base64,${btoa(binary)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The original of a copied web image. The RuneStone browser keeps the bytes of the image that it copied.
|
||||
* For a copy from another browser, download the original of a format with frames.
|
||||
* Undefined keeps the still copy. "refused" means that the website did not give the original.
|
||||
*/
|
||||
async function webImage(source: string): Promise<{ data: string; type: string } | "refused" | undefined> {
|
||||
const data = await copiedImage(source) ?? (mayAnimate(source) ? await workspaceDownloadImage(source).catch(() => "") : undefined);
|
||||
if (data === undefined) return undefined;
|
||||
if (!data) return "refused";
|
||||
const type = /^data:([^;]+);/.exec(data)?.[1] ?? "";
|
||||
return imageTypes.includes(type) ? { data, type } : undefined;
|
||||
}
|
||||
|
||||
/** 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,
|
||||
initialAttachments: TaskFields["attachments"] = [],
|
||||
) {
|
||||
const attachments = structuredClone(initialAttachments);
|
||||
const element = document.createElement("div");
|
||||
element.className = "pm-card-images pm-wide";
|
||||
const hint = document.createElement("p");
|
||||
hint.className = "pm-muted";
|
||||
hint.id = `pm-image-hint-${crypto.randomUUID()}`;
|
||||
hint.textContent = 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";
|
||||
error.setAttribute("role", "alert");
|
||||
const gallery = document.createElement("div");
|
||||
gallery.className = "pm-image-gallery";
|
||||
gallery.setAttribute("role", "group");
|
||||
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", tr("Insert images in description"));
|
||||
const add = control(message("Add image"), () => input.click());
|
||||
const attachmentInput = input.cloneNode() as HTMLInputElement;
|
||||
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", tr("Image attachments"));
|
||||
const attachmentsElement = document.createElement("section"); attachmentsElement.className = "pm-attachments pm-wide";
|
||||
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);
|
||||
const pending = new Map<string, string>();
|
||||
const loaded = new Map<string, Promise<string>>();
|
||||
let viewer: HTMLDialogElement | undefined;
|
||||
let viewerObserver: ResizeObserver | undefined;
|
||||
let idleTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let disposed = false,
|
||||
loading = false,
|
||||
saving = false,
|
||||
revision = 0;
|
||||
function updateControls() {
|
||||
description.disabled = add.disabled = attach.disabled = loading || saving;
|
||||
[...element.querySelectorAll("button"), ...attachmentsElement.querySelectorAll("button")].forEach((button) => {
|
||||
button.disabled = loading || saving;
|
||||
});
|
||||
}
|
||||
function showImage(source: HTMLImageElement, trigger: HTMLButtonElement) {
|
||||
if (viewer || disposed || !source.complete || !source.naturalWidth) return;
|
||||
const dialog = document.createElement("dialog");
|
||||
dialog.className = "pm-image-viewer";
|
||||
viewer = dialog;
|
||||
const header = document.createElement("div");
|
||||
header.className = "pm-image-viewer-header";
|
||||
const title = document.createElement("h2");
|
||||
title.id = `pm-image-title-${crypto.randomUUID()}`;
|
||||
title.textContent = source.alt;
|
||||
dialog.setAttribute("aria-labelledby", title.id);
|
||||
const frame = document.createElement("div");
|
||||
frame.className = "pm-image-frame";
|
||||
const full = document.createElement("img");
|
||||
full.src = source.src;
|
||||
full.alt = source.alt;
|
||||
frame.append(full);
|
||||
const size = control(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(tr("Close image"), () => dialog.close());
|
||||
header.append(title, size, close);
|
||||
dialog.append(header, frame);
|
||||
const placeControls = () => {
|
||||
if (!dialog.open) return;
|
||||
const bounds = full.getBoundingClientRect();
|
||||
const actual = frame.classList.contains("pm-image-actual");
|
||||
const width = actual ? dialog.clientWidth - 16 : Math.min(dialog.clientWidth - 16, Math.max(320, bounds.width - 16));
|
||||
header.style.width = `${width}px`;
|
||||
header.style.left = `${Math.max(8, (dialog.clientWidth - width) / 2)}px`;
|
||||
header.style.right = "auto";
|
||||
header.style.top = `${actual ? 8 : Math.max(8, bounds.top + 8)}px`;
|
||||
};
|
||||
const observer = new ResizeObserver(placeControls);
|
||||
viewerObserver = observer;
|
||||
observer.observe(full);
|
||||
observer.observe(frame);
|
||||
full.onload = placeControls;
|
||||
dialog.onclose = () => {
|
||||
clearTimeout(idleTimer);
|
||||
observer.disconnect();
|
||||
viewerObserver = undefined;
|
||||
dialog.remove();
|
||||
viewer = undefined;
|
||||
if (!disposed && trigger.isConnected) trigger.focus({ preventScroll: true });
|
||||
};
|
||||
// Keep the viewer outside the gallery, 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;
|
||||
dialog.addEventListener("pointerdown", (event) => {
|
||||
outsidePointer = event.isPrimary && event.button === 0 && outside(event.target);
|
||||
event.stopPropagation();
|
||||
});
|
||||
dialog.addEventListener("pointercancel", () => { outsidePointer = false; });
|
||||
dialog.addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
if (outsidePointer && outside(event.target)) dialog.close();
|
||||
outsidePointer = false;
|
||||
});
|
||||
dialog.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
dialog.close();
|
||||
}
|
||||
});
|
||||
dialog.addEventListener("cancel", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
dialog.close();
|
||||
});
|
||||
dialog.showModal();
|
||||
placeControls();
|
||||
// Focus the surface first, so 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);
|
||||
}
|
||||
async function render() {
|
||||
const current = ++revision;
|
||||
gallery.replaceChildren();
|
||||
attachmentGallery.replaceChildren();
|
||||
for (const ref of [...imageReferences(description.value), ...attachments]) {
|
||||
const attached = !("index" in ref);
|
||||
const figure = document.createElement("figure");
|
||||
const caption = document.createElement("figcaption");
|
||||
const name = document.createElement("span");
|
||||
name.textContent = ref.name;
|
||||
name.title = ref.name;
|
||||
caption.append(
|
||||
name,
|
||||
removeControl(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 }));
|
||||
return;
|
||||
}
|
||||
const references = imageReferences(description.value);
|
||||
const match = references.find(
|
||||
(item) => item.id === ref.id && item.index === ref.index,
|
||||
);
|
||||
if (!match) return;
|
||||
description.setRangeText(
|
||||
"",
|
||||
match.index,
|
||||
match.index + match.markdown.length,
|
||||
"preserve",
|
||||
);
|
||||
description.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
description.focus();
|
||||
}),
|
||||
);
|
||||
const image = document.createElement("img");
|
||||
image.alt = ref.name;
|
||||
image.loading = "lazy";
|
||||
const thumbnail = document.createElement("button");
|
||||
thumbnail.type = "button";
|
||||
thumbnail.className = "pm-image-thumbnail";
|
||||
thumbnail.setAttribute("aria-label", 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");
|
||||
failure.className = "pm-error";
|
||||
failure.setAttribute("role", "alert");
|
||||
const fail = () => {
|
||||
thumbnail.remove();
|
||||
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);
|
||||
(attached ? attachmentGallery : gallery).append(figure);
|
||||
updateControls();
|
||||
let data = pending.get(ref.id);
|
||||
try {
|
||||
if (!data) {
|
||||
let promise = loaded.get(ref.id);
|
||||
if (!promise) {
|
||||
promise = workspace.read(imagePath(ref.id)).then(parseImage);
|
||||
loaded.set(ref.id, promise);
|
||||
}
|
||||
data = await promise;
|
||||
}
|
||||
if (disposed || current !== revision) return;
|
||||
image.src = data;
|
||||
} catch {
|
||||
if (!disposed && current === revision) fail();
|
||||
}
|
||||
}
|
||||
}
|
||||
/** `source` is the web address of the original of a copied image. `files` holds its still copy. */
|
||||
async function addFiles(files: File[], attachOnly = false, source?: string) {
|
||||
if (disposed || loading || description.disabled || !files.length) return;
|
||||
loading = true;
|
||||
updateControls();
|
||||
changed(true);
|
||||
error.textContent = "";
|
||||
attachmentError.textContent = "";
|
||||
const start = description.selectionStart,
|
||||
end = description.selectionEnd;
|
||||
try {
|
||||
const staged: { id: string; name: string; data: string }[] = [];
|
||||
let refused = false;
|
||||
for (const file of files) {
|
||||
// A browser copies only the first frame of a web image. The original keeps all of its frames.
|
||||
const web = source ? await webImage(source) : undefined;
|
||||
refused ||= web === "refused";
|
||||
const original = typeof web === "object" ? web : undefined;
|
||||
if (!original && !imageTypes.includes(file.type))
|
||||
throw new Error(message("Use a PNG, JPEG, GIF, or WebP image."));
|
||||
if (!original && !file.size)
|
||||
throw new Error(message("The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file."));
|
||||
if (!original && file.size > maxImageBytes)
|
||||
throw new Error(message("Use an image between 1 byte and 50 MiB."));
|
||||
const data = original?.data ?? await fileDataUrl(file);
|
||||
const name = original ? `${(file.name || "image").replace(/\.\w+$/, "")}.${original.type.slice(6)}` : file.name;
|
||||
// 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(message("The image cannot be read. Copy it again or choose another file."));
|
||||
});
|
||||
staged.push({
|
||||
id: crypto.randomUUID(),
|
||||
name: (name || tr("Pasted image")).slice(0, 255),
|
||||
data,
|
||||
});
|
||||
}
|
||||
if (disposed) return;
|
||||
for (const image of staged) pending.set(image.id, image.data);
|
||||
if (attachOnly) attachments.push(...staged.map(({ id, name }) => ({ id, name })));
|
||||
else {
|
||||
const markdown = staged.map((image) => imageMarkdown(image.name, image.id)).join("\n");
|
||||
description.setRangeText(`\n${markdown}\n`, start, end, "end");
|
||||
}
|
||||
description.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
if (refused) error.textContent = tr("The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.");
|
||||
} catch (reason) {
|
||||
if (!disposed)
|
||||
(attachOnly ? attachmentError : error).textContent = errorText(reason);
|
||||
} finally {
|
||||
loading = false;
|
||||
if (!disposed) {
|
||||
updateControls();
|
||||
changed(false);
|
||||
(attachOnly ? attach : description).focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
const paste = (event: ClipboardEvent) => {
|
||||
const files = Array.from(event.clipboardData?.files ?? []).filter((file) =>
|
||||
file.type.startsWith("image/"),
|
||||
);
|
||||
if (!files.length) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// Read the HTML now. The clipboard data is empty after the paste event.
|
||||
const source = files.length === 1 ? pastedImageSource(event.clipboardData?.getData("text/html") ?? "") : undefined;
|
||||
void addFiles(files, false, source);
|
||||
};
|
||||
const dragOver = (event: DragEvent) => {
|
||||
if (event.dataTransfer?.types.includes("Files")) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
};
|
||||
const drop = (event: DragEvent) => {
|
||||
const files = Array.from(event.dataTransfer?.files ?? []);
|
||||
if (!files.length) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void addFiles(files);
|
||||
};
|
||||
description.addEventListener("dragover", dragOver);
|
||||
description.addEventListener("drop", drop);
|
||||
description.addEventListener("paste", paste);
|
||||
description.addEventListener("input", render);
|
||||
input.onchange = () => {
|
||||
void addFiles(Array.from(input.files ?? []));
|
||||
input.value = "";
|
||||
};
|
||||
attachmentInput.onchange = () => {
|
||||
void addFiles(Array.from(attachmentInput.files ?? []), true);
|
||||
attachmentInput.value = "";
|
||||
};
|
||||
void render();
|
||||
return {
|
||||
element,
|
||||
attachmentsElement,
|
||||
addControl: add,
|
||||
value: () => structuredClone(attachments),
|
||||
references: () => [...imageReferences(description.value), ...attachments],
|
||||
setEditing(value: boolean) { element.hidden = !value; },
|
||||
showImage,
|
||||
async resolveImage(id: string) {
|
||||
const data = pending.get(id);
|
||||
if (data) return data;
|
||||
let promise = loaded.get(id);
|
||||
if (!promise) {
|
||||
promise = workspace.read(imagePath(id)).then(parseImage);
|
||||
loaded.set(id, promise);
|
||||
}
|
||||
return promise;
|
||||
},
|
||||
isLoading: () => loading,
|
||||
setSaving(value: boolean) {
|
||||
saving = value;
|
||||
updateControls();
|
||||
},
|
||||
/** Write the images of `body`, of the attachments, and of `ids`, for example the card cover. */
|
||||
async save(body: string, ids: string[] = []) {
|
||||
for (const id of await saveImages(workspace, body, pending, attachments, ids)) {
|
||||
// The image file now holds the data, so the description draft does not keep it.
|
||||
const data = pending.get(id);
|
||||
if (!data) continue;
|
||||
loaded.set(id, Promise.resolve(data));
|
||||
pending.delete(id);
|
||||
}
|
||||
},
|
||||
/** The data of the unsaved images that `body` refers to. The description draft keeps it. */
|
||||
draftImages: (body: string) => new Map(imageReferences(body).flatMap(ref => {
|
||||
const data = pending.get(ref.id);
|
||||
return data ? [[ref.id, data] as const] : [];
|
||||
})),
|
||||
/** Add the image data of a restored description draft, and show the images of the restored text. */
|
||||
restore(images: ReadonlyMap<string, string>) {
|
||||
for (const [id, data] of images) if (!pending.has(id)) pending.set(id, data);
|
||||
void render();
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
clearTimeout(idleTimer);
|
||||
viewerObserver?.disconnect();
|
||||
viewerObserver = undefined;
|
||||
viewer?.remove(); viewer = undefined;
|
||||
revision++;
|
||||
// Keep the pending image data. A draft save that is in progress after a close still needs it.
|
||||
loaded.clear();
|
||||
description.removeEventListener("paste", paste);
|
||||
description.removeEventListener("input", render);
|
||||
description.removeEventListener("dragover", dragOver);
|
||||
description.removeEventListener("drop", drop);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
import { type LabelStore, type SavedLabel } from "../storage/labels.ts";
|
||||
import { actionIcons, tooltip } from "./host.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,
|
||||
text = "",
|
||||
className = "",
|
||||
) {
|
||||
const element = document.createElement(tag);
|
||||
element.textContent = text;
|
||||
element.className = className;
|
||||
return element;
|
||||
}
|
||||
function control(text: string, action: () => void) {
|
||||
const button = node("button", text, "pm-button");
|
||||
button.type = "button";
|
||||
button.onclick = action;
|
||||
return button;
|
||||
}
|
||||
export function labelBadge(label?: SavedLabel, id = "") {
|
||||
const badge = node(
|
||||
"span",
|
||||
label?.name ?? tr("Unavailable label"),
|
||||
"pm-label-badge",
|
||||
);
|
||||
if (label)
|
||||
badge.style.setProperty("--pm-label-color", labelColors[label.color]);
|
||||
badge.setAttribute("aria-label", label
|
||||
? tr(label.archived ? "{name}, {color}, archived" : "{name}, {color}", { name: label.name, color: colorName(label.color) })
|
||||
: tr("Unavailable label: {id}", { id }));
|
||||
return badge;
|
||||
}
|
||||
|
||||
export function createLabelPicker(
|
||||
catalog: LabelStore,
|
||||
initial: string[],
|
||||
manage: () => void,
|
||||
quickAccess = false,
|
||||
) {
|
||||
const element = node("section", "", "pm-label-picker pm-wide");
|
||||
element.setAttribute("aria-label", 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", 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", 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", tr(quickAccess ? "Labels" : "Add labels"));
|
||||
toggle.append(plus, toggleText);
|
||||
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 = 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", tr("Available labels"));
|
||||
const hint = node("p", "", "pm-muted");
|
||||
const manageButton = control(tr("Manage labels"), () => {
|
||||
close();
|
||||
toggle.focus();
|
||||
manage();
|
||||
});
|
||||
manageButton.className = "pm-label-manage rs-picker-row";
|
||||
const manageIcon = node("span", "", "pm-icon rs-picker-icon");
|
||||
manageIcon.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 3h8l10 10-8 8L3 11z"/><circle cx="7.5" cy="7.5" r="1"/></svg>';
|
||||
manageButton.prepend(manageIcon);
|
||||
panel.append(search, choices, hint, manageButton);
|
||||
chips.append(toggle);
|
||||
element.append(chips, panel);
|
||||
const position = () => {
|
||||
if (!panel.matches(":popover-open")) return;
|
||||
const anchor = (quickAccess ? toggle : chips).getBoundingClientRect();
|
||||
const gap = 6,
|
||||
margin = 12;
|
||||
panel.style.maxHeight = `${window.innerHeight - margin * 2}px`;
|
||||
const bounds = panel.getBoundingClientRect();
|
||||
const below = window.innerHeight - anchor.bottom - margin - gap;
|
||||
const above = anchor.top - margin - gap;
|
||||
const useBelow = below >= bounds.height || below >= above;
|
||||
panel.style.maxHeight = `${Math.max(0, useBelow ? below : above)}px`;
|
||||
const height = panel.getBoundingClientRect().height;
|
||||
panel.style.left = `${Math.max(margin, Math.min(anchor.left, window.innerWidth - bounds.width - margin))}px`;
|
||||
panel.style.top = `${Math.max(margin, useBelow ? anchor.bottom + gap : anchor.top - height - gap)}px`;
|
||||
};
|
||||
const scroll = (event: Event) => {
|
||||
if (!panel.contains(event.target as Node)) position();
|
||||
};
|
||||
const stop = () => {
|
||||
window.removeEventListener("resize", position);
|
||||
document.removeEventListener("scroll", scroll, true);
|
||||
};
|
||||
function close() {
|
||||
if (panel.matches(":popover-open")) panel.hidePopover();
|
||||
stop();
|
||||
}
|
||||
function open() {
|
||||
if (panel.matches(":popover-open")) return;
|
||||
panel.showPopover();
|
||||
}
|
||||
panel.addEventListener("beforetoggle", (event) => {
|
||||
const expanded = (event as ToggleEvent).newState === "open";
|
||||
toggle.setAttribute("aria-expanded", String(expanded));
|
||||
if (!expanded) stop();
|
||||
});
|
||||
panel.addEventListener("toggle", (event) => {
|
||||
if (
|
||||
(event as ToggleEvent).newState !== "open" ||
|
||||
!panel.matches(":popover-open")
|
||||
)
|
||||
return;
|
||||
position();
|
||||
window.addEventListener("resize", position);
|
||||
document.addEventListener("scroll", scroll, true);
|
||||
if (!panel.contains(document.activeElement))
|
||||
search.focus({ preventScroll: true });
|
||||
});
|
||||
const drawChoices = () => {
|
||||
choices.replaceChildren();
|
||||
const matches = catalog.value.filter(
|
||||
(label) =>
|
||||
!label.archived &&
|
||||
!selected.has(label.id) &&
|
||||
label.name
|
||||
.toLocaleLowerCase()
|
||||
.includes(search.value.trim().toLocaleLowerCase()),
|
||||
);
|
||||
matches.forEach((label, index) => {
|
||||
const row = control("", () => {
|
||||
selected.add(label.id);
|
||||
drawChips();
|
||||
drawChoices();
|
||||
const remaining = choices.querySelectorAll<HTMLButtonElement>("button");
|
||||
(remaining[Math.min(index, remaining.length - 1)] ?? search).focus({
|
||||
preventScroll: true,
|
||||
});
|
||||
});
|
||||
row.className = "pm-label-option rs-picker-row";
|
||||
row.setAttribute("aria-label", tr("Add label {name}", { name: label.name }));
|
||||
row.append(labelBadge(label));
|
||||
choices.append(row);
|
||||
});
|
||||
hint.textContent =
|
||||
localize(catalog.error) ||
|
||||
(matches.length
|
||||
? ""
|
||||
: search.value.trim()
|
||||
? tr("No matching labels.")
|
||||
: tr("No available labels."));
|
||||
hint.hidden = !hint.textContent;
|
||||
manageButton.disabled = catalog.source === undefined;
|
||||
position();
|
||||
};
|
||||
function drawChips() {
|
||||
for (const chip of [...chips.children]) if (chip !== toggle) chip.remove();
|
||||
for (const id of selected) {
|
||||
const label = catalog.value.find((label) => label.id === id);
|
||||
const chip = labelBadge(label, id);
|
||||
const remove = control("×", () => {
|
||||
selected.delete(id);
|
||||
drawChips();
|
||||
drawChoices();
|
||||
toggle.focus();
|
||||
});
|
||||
remove.setAttribute("aria-label", 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);
|
||||
}
|
||||
toggleText.hidden = !quickAccess && selected.size > 0;
|
||||
toggle.classList.toggle("pm-label-add-compact", !quickAccess && selected.size > 0);
|
||||
position();
|
||||
}
|
||||
search.oninput = drawChoices;
|
||||
search.onkeydown = (event) => {
|
||||
if (event.key === "Enter") event.preventDefault();
|
||||
if (event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
choices.querySelector<HTMLButtonElement>("button")?.focus();
|
||||
}
|
||||
};
|
||||
choices.onkeydown = (event) => {
|
||||
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
const rows = [...choices.querySelectorAll<HTMLButtonElement>("button")];
|
||||
const index = rows.indexOf(event.target as HTMLButtonElement);
|
||||
rows[
|
||||
event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : (index + (event.key === "ArrowDown" ? 1 : rows.length - 1)) % rows.length
|
||||
]?.focus();
|
||||
};
|
||||
element.onkeydown = (event) => {
|
||||
if (event.key === "Escape" && panel.matches(":popover-open")) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
close();
|
||||
toggle.focus();
|
||||
}
|
||||
};
|
||||
const refresh = () => {
|
||||
for (const id of selected)
|
||||
if (known.has(id) && !catalog.value.some((label) => label.id === id)) selected.delete(id);
|
||||
catalog.value.forEach((label) => known.add(label.id));
|
||||
drawChips();
|
||||
drawChoices();
|
||||
};
|
||||
refresh();
|
||||
return { element, trigger: toggle, refresh, open, dispose: close, value: () => [...selected] };
|
||||
}
|
||||
|
||||
export function createLabelManager(
|
||||
catalog: LabelStore,
|
||||
save: (
|
||||
labels: SavedLabel[],
|
||||
expected: string | null | undefined,
|
||||
) => Promise<void>,
|
||||
close: () => void,
|
||||
) {
|
||||
const dialog = node("dialog", "", "pm-editor pm-label-manager");
|
||||
dialog.setAttribute("aria-label", 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", 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", 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", tr("Name"), "pm-field");
|
||||
const name = node("input");
|
||||
name.value = label.name;
|
||||
name.required = true;
|
||||
name.maxLength = 80;
|
||||
nameWrap.append(name);
|
||||
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 = () => {
|
||||
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", 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 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", 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, deleteName());
|
||||
fields.append(nameWrap, remove, color.element);
|
||||
row.append(legend, fields, state);
|
||||
rows.append(row);
|
||||
update();
|
||||
return name;
|
||||
};
|
||||
const add = control(tr("New label"), () => {
|
||||
const label: SavedLabel = {
|
||||
id: crypto.randomUUID(),
|
||||
name: "",
|
||||
color: "blue",
|
||||
};
|
||||
draft.push(label);
|
||||
addRow(label).focus();
|
||||
});
|
||||
draft.forEach(addRow);
|
||||
const actions = node("div", "", "pm-editor-actions");
|
||||
const cancel = control(tr("Cancel"), () => {
|
||||
if (!saving) dialog.close();
|
||||
});
|
||||
const submit = control(tr("Save labels"), () => {});
|
||||
submit.type = "submit";
|
||||
submit.classList.add("pm-primary");
|
||||
actions.append(cancel, submit);
|
||||
form.append(
|
||||
node("h2", tr("Manage labels")),
|
||||
node(
|
||||
"p",
|
||||
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",
|
||||
tr("When you save, RuneStone removes each deleted label from all cards."),
|
||||
"pm-muted",
|
||||
),
|
||||
error,
|
||||
actions,
|
||||
);
|
||||
dialog.append(form);
|
||||
form.onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
if (saving) return;
|
||||
saving = true;
|
||||
const controls = form.querySelectorAll<
|
||||
HTMLInputElement | HTMLButtonElement | HTMLSelectElement
|
||||
>("input,button,select");
|
||||
controls.forEach((control) => {
|
||||
control.disabled = true;
|
||||
});
|
||||
try {
|
||||
await save(draft, expected);
|
||||
if (dialog.isConnected) dialog.close();
|
||||
} catch (reason) {
|
||||
error.textContent = errorText(reason);
|
||||
} finally {
|
||||
saving = false;
|
||||
controls.forEach((control) => {
|
||||
control.disabled = false;
|
||||
});
|
||||
}
|
||||
};
|
||||
dialog.oncancel = (event) => {
|
||||
if (saving) event.preventDefault();
|
||||
};
|
||||
dialog.onclose = () => {
|
||||
dialog.remove();
|
||||
close();
|
||||
};
|
||||
return dialog;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
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"/>',
|
||||
high: '<path d="m6 11 6-6 6 6M6 19l6-6 6 6"/>',
|
||||
medium: '<path d="M5 9h14M5 15h14"/>',
|
||||
lowest: '<path d="m6 3 6 6 6-6M6 9l6 6 6-6M6 15l6 6 6-6"/>',
|
||||
low: '<path d="m6 5 6 6 6-6M6 13l6 6 6-6"/>',
|
||||
};
|
||||
export function setPriorityAppearance(node: HTMLElement, value: Priority | null) {
|
||||
node.dataset.priority = value ?? "none";
|
||||
const icon = node.querySelector(".pm-icon");
|
||||
if (icon) icon.innerHTML = `<svg viewBox="0 0 24 24" aria-hidden="true">${value ? priorityIcons[value] : '<path d="M6 21V3M6 4h13l-3 5 3 5H6"/>'}</svg>`;
|
||||
}
|
||||
|
||||
/** The priority control of card details. The shared host menu shows the choices. */
|
||||
export function createPriorityPicker(
|
||||
trigger: HTMLButtonElement,
|
||||
initial: Priority | null,
|
||||
levels: PriorityLevels = 3,
|
||||
ui: MenuHost,
|
||||
) {
|
||||
let value = initial;
|
||||
let changed = false;
|
||||
trigger.setAttribute("aria-haspopup", "menu");
|
||||
const update = () => {
|
||||
trigger.lastChild!.textContent = value ? 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: 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;
|
||||
trigger.onkeydown = event => { if (["ArrowDown", "ArrowUp"].includes(event.key)) { event.preventDefault(); open(); } };
|
||||
update();
|
||||
return {
|
||||
value: () => value,
|
||||
changed: () => changed,
|
||||
open,
|
||||
dispose() { menu?.close(); },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import type { Task, TaskFields } from "../model/model.ts";
|
||||
import type { BoardDocument } from "../storage/board.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[],
|
||||
control: (name: string, action: () => void) => HTMLButtonElement,
|
||||
removeControl: (name: string, action: () => void) => HTMLButtonElement,
|
||||
boards: BoardDocument[],
|
||||
open: (target: { taskId?: string; subtaskId?: string }) => void,
|
||||
useSharedChoices?: (select: HTMLSelectElement) => void,
|
||||
) {
|
||||
const element = document.createElement("section"); element.className = "pm-relations pm-wide";
|
||||
const subtasks = structuredClone(task?.subtasks ?? []);
|
||||
for (const item of subtasks) {
|
||||
const target = tasks.find(task => task.id === item.taskId);
|
||||
if (target) { item.title = target.title; item.done = target.status === "done"; }
|
||||
}
|
||||
const links = structuredClone(task?.links ?? []);
|
||||
const removedIncoming = new Map<string, Task>();
|
||||
const cardRow = (target: Task | undefined, title: string, action: () => void, relation?: string) => {
|
||||
const button = document.createElement("button"); button.type = "button"; button.className = "pm-related-card";
|
||||
button.setAttribute("aria-label", tr("Open {name}", { name: title })); button.onclick = action;
|
||||
const name = document.createElement("span"); name.className = "pm-related-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 placementText(board?.name, position.listId === null ? null : list?.name);
|
||||
});
|
||||
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(priorityLabel(target?.priority ?? null)));
|
||||
setPriorityAppearance(priority, target?.priority ?? null);
|
||||
metadata.append(placement, priority); button.append(name, metadata);
|
||||
return button;
|
||||
};
|
||||
const section = (name: string) => {
|
||||
const root = document.createElement("section"); root.className = "pm-relation-section";
|
||||
const header = document.createElement("div"); header.className = "pm-relation-heading";
|
||||
const heading = document.createElement("h3");
|
||||
const toggle = document.createElement("button"); toggle.type = "button"; toggle.className = "pm-section-toggle";
|
||||
toggle.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>';
|
||||
const label = document.createElement("span"); label.textContent = name; toggle.append(label);
|
||||
toggle.setAttribute("aria-expanded", "true");
|
||||
const content = document.createElement("div"); content.id = `pm-relations-${crypto.randomUUID()}`;
|
||||
toggle.setAttribute("aria-controls", content.id);
|
||||
toggle.onclick = () => { content.hidden = !content.hidden; toggle.setAttribute("aria-expanded", String(!content.hidden)); };
|
||||
heading.append(toggle); header.append(heading); root.append(header, content); element.append(root);
|
||||
return { header, content, toggle, expand() { content.hidden = false; toggle.setAttribute("aria-expanded", "true"); } };
|
||||
};
|
||||
const sub = section(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 = () => {
|
||||
count.textContent = subtasks.length ? `${subtasks.filter(item => item.done).length}/${subtasks.length}` : "";
|
||||
rows.replaceChildren();
|
||||
for (const item of subtasks) {
|
||||
const row = document.createElement("div"); row.className = "pm-relation-row";
|
||||
const target = tasks.find(task => task.id === item.taskId);
|
||||
const done = document.createElement("input"); done.type = "checkbox"; done.checked = target ? target.status === "done" : item.done;
|
||||
done.disabled = !!item.taskId;
|
||||
done.setAttribute("aria-label", 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(tr("Delete subtask {name}", { name: item.title }), () => { subtasks.splice(subtasks.indexOf(item), 1); render(); }));
|
||||
rows.append(row);
|
||||
}
|
||||
};
|
||||
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(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(tr("Create subtask"), () => {
|
||||
if (!draft.value.trim()) return;
|
||||
subtasks.push({ id: crypto.randomUUID(), title: draft.value.trim(), done: false }); render(); dismiss();
|
||||
});
|
||||
add.disabled = true;
|
||||
draft.oninput = () => add.disabled = !draft.value.trim();
|
||||
draft.onkeydown = event => {
|
||||
if (event.key === "Enter") { event.preventDefault(); add.click(); }
|
||||
if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); dismiss(); }
|
||||
};
|
||||
addRow.append(draft, add, removeControl(tr("Cancel subtask"), dismiss));
|
||||
sub.header.append(reveal); sub.content.append(rows, addRow);
|
||||
|
||||
const linkedSection = section(tr("Linked cards"));
|
||||
const linked = document.createElement("div");
|
||||
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", 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", 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)
|
||||
&& !(item.links?.some(link => link.taskId === task?.id) && !removedIncoming.has(item.id))
|
||||
&& item.title.toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase()));
|
||||
const drawChoices = () => {
|
||||
choices.replaceChildren();
|
||||
const matches = candidates();
|
||||
for (const item of matches) {
|
||||
const row = document.createElement("button"); row.type = "button"; row.className = "rs-picker-row";
|
||||
row.setAttribute("aria-label", 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";
|
||||
const title = document.createElement("span"); title.textContent = item.title;
|
||||
const hint = document.createElement("span"); hint.className = "rs-picker-hint";
|
||||
hint.textContent = Object.entries(item.placements ?? {}).map(([id, position]) => {
|
||||
const board = boards.find(board => board.id === id);
|
||||
return 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;
|
||||
links.push({ taskId: item.id, relation: relation.value as NonNullable<TaskFields["links"]>[number]["relation"] });
|
||||
drawLinks(); search.focus({ preventScroll: true });
|
||||
};
|
||||
choices.append(row);
|
||||
}
|
||||
resultStatus.textContent = matches.length ? "" : search.value.trim() ? tr("No matching cards.") : tr("No available cards to link.");
|
||||
resultStatus.hidden = matches.length > 0;
|
||||
choices.hidden = matches.length === 0;
|
||||
};
|
||||
const drawLinks = () => {
|
||||
linked.replaceChildren();
|
||||
for (const item of links) {
|
||||
const row = document.createElement("div"); row.className = "pm-relation-row";
|
||||
const target = tasks.find(candidate => candidate.id === item.taskId);
|
||||
const text = cardRow(target, target?.title ?? tr("Unavailable card"), () => open({ taskId: item.taskId }), names[item.relation]);
|
||||
text.disabled = !target;
|
||||
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);
|
||||
}
|
||||
// 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" ? 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 }), tr("Subtask of"))); linked.append(row);
|
||||
}
|
||||
drawChoices();
|
||||
};
|
||||
const linkEditor = document.createElement("div"); linkEditor.className = "pm-link-editor"; linkEditor.hidden = true;
|
||||
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 => {
|
||||
if (event.key === "Enter") { event.preventDefault(); choices.querySelector<HTMLButtonElement>("button")?.click(); }
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
const rows = choices.querySelectorAll<HTMLButtonElement>("button");
|
||||
rows[event.key === "ArrowDown" ? 0 : rows.length - 1]?.focus();
|
||||
}
|
||||
};
|
||||
choices.onkeydown = event => {
|
||||
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
const rows = [...choices.querySelectorAll<HTMLButtonElement>("button")];
|
||||
const index = rows.indexOf(event.target as HTMLButtonElement);
|
||||
if (event.key === "ArrowUp" && index === 0) { search.focus(); return; }
|
||||
rows[event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : (index + (event.key === "ArrowDown" ? 1 : rows.length - 1)) % rows.length]?.focus();
|
||||
};
|
||||
linkEditor.addEventListener("keydown", event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); dismissLink(); } });
|
||||
const linkRow = document.createElement("div"); linkRow.className = "pm-relation-row"; linkRow.append(search, relation, removeControl(tr("Cancel linked card"), dismissLink));
|
||||
useSharedChoices?.(relation);
|
||||
linkEditor.append(linkRow, choices, resultStatus); linkedSection.header.append(revealLink); linkedSection.content.append(linked, linkEditor);
|
||||
render(); drawLinks();
|
||||
return { element, focus: () => sub.toggle.focus(), removedIncoming: () => [...removedIncoming.values()], value: () => ({ subtasks: subtasks.map(item => ({ ...item, title: item.title.trim() })), links }) };
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,169 @@
|
||||
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", tr("Selected tags"));
|
||||
const label = document.createElement("label");
|
||||
label.className = "pm-field";
|
||||
label.textContent = tr("Add a tag");
|
||||
const input = document.createElement("input");
|
||||
input.type = "text";
|
||||
input.autocomplete = "off";
|
||||
input.placeholder = tr("Type a tag and press Enter");
|
||||
input.setAttribute("role", "combobox");
|
||||
input.setAttribute("aria-autocomplete", "list");
|
||||
input.setAttribute("aria-expanded", "false");
|
||||
const suggestions = document.createElement("div");
|
||||
suggestions.className = "pm-tag-suggestions rs-picker";
|
||||
suggestions.id = "pm-tags-" + crypto.randomUUID();
|
||||
suggestions.setAttribute("role", "listbox");
|
||||
suggestions.setAttribute("aria-label", 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 = 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);
|
||||
|
||||
const normalize = (tag: string) => tag.trim().toLocaleLowerCase();
|
||||
const known = new Map<string, string>();
|
||||
for (const tag of [...initial, ...existing])
|
||||
if (tag.trim() && !known.has(normalize(tag)))
|
||||
known.set(normalize(tag), tag.trim());
|
||||
let selected = [...new Set(initial.map(normalize).filter(Boolean))].map(
|
||||
(key) => known.get(key)!,
|
||||
);
|
||||
let matches: string[] = [],
|
||||
active = -1;
|
||||
const hide = () => {
|
||||
suggestions.hidden = true;
|
||||
input.setAttribute("aria-expanded", "false");
|
||||
input.removeAttribute("aria-activedescendant");
|
||||
active = -1;
|
||||
};
|
||||
const highlight = () => {
|
||||
[...suggestions.children].forEach((option, index) =>
|
||||
option.setAttribute("aria-selected", String(index === active)),
|
||||
);
|
||||
if (active >= 0)
|
||||
input.setAttribute(
|
||||
"aria-activedescendant",
|
||||
suggestions.children[active].id,
|
||||
);
|
||||
else input.removeAttribute("aria-activedescendant");
|
||||
if (active >= 0) suggestions.children[active].scrollIntoView({ block: "nearest" });
|
||||
};
|
||||
const add = (value: string) => {
|
||||
const key = normalize(value);
|
||||
if (key && !selected.some((tag) => normalize(tag) === key)) {
|
||||
const tag = known.get(key) ?? value.trim();
|
||||
known.set(key, tag);
|
||||
selected.push(tag);
|
||||
renderChips();
|
||||
}
|
||||
input.value = "";
|
||||
hide();
|
||||
};
|
||||
const suggest = () => {
|
||||
const query = normalize(input.value);
|
||||
matches = query
|
||||
? [...known.values()]
|
||||
.filter(
|
||||
(tag) =>
|
||||
normalize(tag).includes(query) &&
|
||||
!selected.some((value) => normalize(value) === normalize(tag)),
|
||||
)
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.slice(0, 8)
|
||||
: [];
|
||||
suggestions.replaceChildren();
|
||||
active = -1;
|
||||
matches.forEach((tag, index) => {
|
||||
const option = document.createElement("div");
|
||||
option.textContent = tag;
|
||||
option.className = "rs-picker-row";
|
||||
option.id = suggestions.id + "-" + index;
|
||||
option.setAttribute("role", "option");
|
||||
option.onpointerdown = (event) => event.preventDefault();
|
||||
option.onclick = () => {
|
||||
add(tag);
|
||||
input.focus();
|
||||
};
|
||||
suggestions.append(option);
|
||||
});
|
||||
suggestions.hidden = matches.length === 0;
|
||||
input.setAttribute("aria-expanded", String(!suggestions.hidden));
|
||||
highlight();
|
||||
};
|
||||
function renderChips() {
|
||||
chips.replaceChildren();
|
||||
for (const tag of selected) {
|
||||
const chip = document.createElement("span");
|
||||
chip.className = "pm-tag-chip";
|
||||
chip.setAttribute("role", "listitem");
|
||||
const text = document.createElement("span");
|
||||
text.textContent = tag;
|
||||
const remove = document.createElement("button");
|
||||
remove.type = "button";
|
||||
remove.textContent = "×";
|
||||
remove.setAttribute("aria-label", tr("Remove tag {name}", { name: tag }));
|
||||
remove.onclick = () => {
|
||||
selected = selected.filter((value) => value !== tag);
|
||||
renderChips();
|
||||
input.focus();
|
||||
suggest();
|
||||
};
|
||||
chip.append(text, remove);
|
||||
chips.append(chip);
|
||||
}
|
||||
}
|
||||
input.oninput = suggest;
|
||||
input.onfocus = suggest;
|
||||
input.onblur = hide;
|
||||
input.onkeydown = (event) => {
|
||||
if (event.isComposing || event.keyCode === 229) return;
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
add(active >= 0 && !suggestions.hidden ? matches[active] : input.value);
|
||||
} else if (
|
||||
(event.key === "ArrowDown" || event.key === "ArrowUp") &&
|
||||
matches.length
|
||||
) {
|
||||
event.preventDefault();
|
||||
if (suggestions.hidden) suggest();
|
||||
if (!matches.length) return;
|
||||
active =
|
||||
event.key === "ArrowDown"
|
||||
? (active + 1) % matches.length
|
||||
: (active <= 0 ? matches.length : active) - 1;
|
||||
highlight();
|
||||
} else if (["Home", "End"].includes(event.key) && !suggestions.hidden && active >= 0) {
|
||||
event.preventDefault(); active = event.key === "Home" ? 0 : matches.length - 1; highlight();
|
||||
} else if (event.key === "Escape" && !suggestions.hidden) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
hide();
|
||||
}
|
||||
};
|
||||
renderChips();
|
||||
return {
|
||||
element,
|
||||
value() {
|
||||
add(input.value);
|
||||
return [...selected];
|
||||
},
|
||||
clear() {
|
||||
selected = [];
|
||||
input.value = "";
|
||||
hide();
|
||||
renderChips();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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
@@ -0,0 +1,21 @@
|
||||
// The view IDs of Project Management. They are the same as in the plugin, so saved tab states and tab transfers between
|
||||
// the plugin and the feature keep their boards. The catalog (`../catalog.ts`) has the same board pattern.
|
||||
|
||||
/** All tasks, or the default board when the ribbon button opens it. */
|
||||
export const PLANNING = "planning";
|
||||
const BOARD_VIEW = /^board-((?:[0-9a-f]{2})+)$/;
|
||||
|
||||
/** The view ID of a board: `board-` and the UTF-8 bytes of the board ID in hexadecimal. */
|
||||
export function boardViewId(id: string): string {
|
||||
return "board-" + Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
/** The board ID of a board view ID, or null for another view. */
|
||||
export function boardOfView(view: string): string | null {
|
||||
const hex = BOARD_VIEW.exec(view)?.[1];
|
||||
if (!hex) return null;
|
||||
try {
|
||||
const id = new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(hex.match(/../g)!, pair => parseInt(pair, 16)));
|
||||
return id.trim() && boardViewId(id) === view ? id : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// The workspace of the storage code (`model/model.ts`), on the host workspace commands of this window.
|
||||
// Writes and creations tell the other views of this window at once. The file watcher reports the same paths later,
|
||||
// also for changes from other windows and programs.
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { workspaceList, workspaceRead, workspaceReadMany, workspaceWrite } from "../../workspace/api.ts";
|
||||
import { notifyPluginWorkspace } from "../../plugins/external.ts";
|
||||
import type { Workspace } from "./model/model.ts";
|
||||
|
||||
/** A workspace with a subscription that reports the changed paths. */
|
||||
export interface FeatureWorkspace extends Workspace {
|
||||
/** Run `listener` after each change. `paths` is undefined when the change is unknown. */
|
||||
watch(listener: (paths?: readonly string[]) => void): () => void;
|
||||
}
|
||||
|
||||
export function hostWorkspace(onChange: (listener: (paths?: readonly string[]) => void) => () => void): FeatureWorkspace {
|
||||
return {
|
||||
list: path => workspaceList(path ?? ""),
|
||||
listMarkdown: () => invoke<string[]>("workspace_list_markdown"),
|
||||
read: workspaceRead,
|
||||
readMany: workspaceReadMany,
|
||||
readOptional: path => invoke<string | null>("workspace_read", { rel: path, missingOk: true }),
|
||||
write: async (path, contents, expected) => { await workspaceWrite(path, contents, expected); notifyPluginWorkspace([path]); },
|
||||
create: async (path, contents) => { await invoke<void>("workspace_create", { rel: path, kind: "file", contents }); notifyPluginWorkspace([path]); },
|
||||
subscribe: listener => onChange(() => listener()),
|
||||
watch: onChange,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// The board list of Project Management, read from `.runestone/pm/workspace.json` without the feature code.
|
||||
// Appearance → Background lists the boards for its targets, and Settings → Project Management chooses the default board.
|
||||
// It reads JSON only. The feature code (`src/lib/features/pm/storage/catalog.ts`) owns the full format and validation.
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { workspaceWrite } from "../workspace/api.ts";
|
||||
import { message } from "../i18n/index.ts";
|
||||
|
||||
export const BOARD_CATALOG_PATH = ".runestone/pm/workspace.json";
|
||||
|
||||
export interface BoardSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
archived: boolean;
|
||||
}
|
||||
|
||||
export interface BoardCatalog {
|
||||
/** The boards in the order of the file. */
|
||||
boards: BoardSummary[];
|
||||
/** The board that opens first, or null for All tasks. */
|
||||
defaultBoardId: string | null;
|
||||
/** The file text, or null when the file does not exist. */
|
||||
source: string | null;
|
||||
}
|
||||
|
||||
/** Reads one workspace file, or gives null when the file does not exist. */
|
||||
export type ReadOptional = (path: string) => Promise<string | null>;
|
||||
/** Replaces one workspace file when its text is still `expected`. */
|
||||
export type WriteExpected = (path: string, contents: string, expected: string) => Promise<void>;
|
||||
|
||||
const desktopRead: ReadOptional = path => invoke<string | null>("workspace_read", { rel: path, missingOk: true });
|
||||
const desktopWrite: WriteExpected = (path, contents, expected) => workspaceWrite(path, contents, expected);
|
||||
|
||||
function record(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
||||
}
|
||||
|
||||
/** The boards of the file text. A missing file has no boards. A damaged file throws. */
|
||||
export function parseBoardCatalog(source: string | null): BoardCatalog {
|
||||
if (source === null) return { boards: [], defaultBoardId: null, source };
|
||||
const data = record(JSON.parse(source));
|
||||
if (!data || data.schema !== 1 || !Array.isArray(data.boards)) throw new Error(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);
|
||||
if (!board || !value || typeof value.id !== "string" || !value.id.trim() || typeof board.name !== "string") continue;
|
||||
if (boards.some(item => item.id === value.id)) continue;
|
||||
boards.push({ id: value.id, name: board.name.trim() || value.id, archived: board.archived === true });
|
||||
}
|
||||
return { boards, defaultBoardId: typeof data.defaultBoardId === "string" ? data.defaultBoardId : null, source };
|
||||
}
|
||||
|
||||
/** Read the board list of the workspace of this window. */
|
||||
export async function readBoardCatalog(read: ReadOptional = desktopRead): Promise<BoardCatalog> {
|
||||
return parseBoardCatalog(await read(BOARD_CATALOG_PATH));
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the default board of the workspace: a board ID, or null for All tasks. Other keys of the file stay.
|
||||
* The write fails when another window changed the file after the read.
|
||||
*/
|
||||
export async function writeDefaultBoard(id: string | null, read: ReadOptional = desktopRead, write: WriteExpected = desktopWrite): Promise<void> {
|
||||
const source = await read(BOARD_CATALOG_PATH);
|
||||
const catalog = parseBoardCatalog(source);
|
||||
if (source === null) {
|
||||
if (id === null) return;
|
||||
throw new Error(message("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}`;
|
||||
await write(BOARD_CATALOG_PATH, JSON.stringify(data, null, 2) + "\n", source);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// The settings of the Project Management feature: the `projectManagement` section of the settings file, and the view
|
||||
// state of each Project Management tab in localStorage.
|
||||
// This file is in the main bundle, because Settings → Project Management and the first-start migration need it
|
||||
// without the board interface code.
|
||||
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
|
||||
import type { LegacyPlugin } from "./migration.ts";
|
||||
|
||||
export type PriorityLevels = 2 | 3 | 5;
|
||||
export const PRIORITY_LEVELS: readonly PriorityLevels[] = [2, 3, 5];
|
||||
|
||||
export interface ProjectManagementSettings {
|
||||
/** The priority choices of a card: 2 (High and Low), 3 (High, Medium, and Low), or 5 (Highest through Lowest). */
|
||||
priorityLevels: PriorityLevels;
|
||||
}
|
||||
|
||||
export const DEFAULT_PROJECT_MANAGEMENT: Readonly<ProjectManagementSettings> = Object.freeze({ priorityLevels: 3 });
|
||||
/**
|
||||
* The view state of each tab: the view, the period, the search, collapsed lists, and scroll positions.
|
||||
* The keys are the view IDs, `planning` for All tasks and `board-<hex>` for a board. RuneStone can lose these values without harm.
|
||||
*/
|
||||
export const VIEW_STATES_KEY = "runestone.pm.viewStates";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
/** Valid settings from any value. Invalid fields take the defaults. */
|
||||
export function normalizeProjectManagement(value: unknown): ProjectManagementSettings {
|
||||
const levels = record(value).priorityLevels;
|
||||
return { priorityLevels: levels === 2 || levels === 5 ? levels : 3 };
|
||||
}
|
||||
|
||||
export function readProjectManagement(): ProjectManagementSettings {
|
||||
return normalizeProjectManagement(readSection("projectManagement"));
|
||||
}
|
||||
|
||||
/** Save the settings. Keys of a newer version stay. */
|
||||
export function writeProjectManagement(next: ProjectManagementSettings): Promise<void> {
|
||||
return writeSection("projectManagement", { ...record(readSection("projectManagement")), ...normalizeProjectManagement(next) });
|
||||
}
|
||||
|
||||
/** Run `listener` after each change of the settings in any window. Returns the function that stops it. */
|
||||
export function onProjectManagementChange(listener: () => void): () => void {
|
||||
return onSettingsChange("projectManagement", listener);
|
||||
}
|
||||
|
||||
/** The saved view states. An unreadable value gives none. */
|
||||
export function readViewStates(storage: Pick<Storage, "getItem"> = localStorage): Record<string, unknown> {
|
||||
try { return record(JSON.parse(storage.getItem(VIEW_STATES_KEY) ?? "null")); } catch { return {}; }
|
||||
}
|
||||
|
||||
/** Save the view states of some tabs. The other tabs keep their states. */
|
||||
export function writeViewStates(changes: Record<string, unknown>, storage: Pick<Storage, "getItem" | "setItem"> = localStorage): void {
|
||||
try { storage.setItem(VIEW_STATES_KEY, JSON.stringify({ ...readViewStates(storage), ...changes })); }
|
||||
catch { /* View state is harmless to lose. */ }
|
||||
}
|
||||
|
||||
/** The host side of the first-start migration of the `projectManagement` section and the view states. */
|
||||
export interface ProjectManagementMigrationHost {
|
||||
/** True when the settings file has no `projectManagement` section. */
|
||||
missing(): boolean;
|
||||
write(value: ProjectManagementSettings): Promise<void>;
|
||||
storage: Pick<Storage, "getItem" | "setItem">;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the `projectManagement` section from the kept settings of the Project Management plugin
|
||||
* (`plugin-data/runestone.pm/settings.json`), and copy its view states to localStorage when localStorage has none.
|
||||
* The plugin files stay unchanged. Without a section to make, nothing is written.
|
||||
*/
|
||||
export async function migrateProjectManagement(legacy: LegacyPlugin | undefined, host: ProjectManagementMigrationHost): Promise<ProjectManagementSettings | null> {
|
||||
if (!host.missing()) return null;
|
||||
const kept = record(legacy?.settings);
|
||||
const views = record(kept.viewStates);
|
||||
try {
|
||||
if (Object.keys(views).length && host.storage.getItem(VIEW_STATES_KEY) === null) host.storage.setItem(VIEW_STATES_KEY, JSON.stringify(views));
|
||||
} catch (reason) { console.error("RuneStone could not copy the Project Management view states.", reason); }
|
||||
const value = normalizeProjectManagement(kept);
|
||||
await host.write(value);
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// A feature in the workbench of one window. Its views, commands, and document types come from the static catalog, so the
|
||||
// navigation buttons, the command palette, and the file tree show them without the feature code. The first mount,
|
||||
// restore, or action command loads the feature module and starts one instance for this window.
|
||||
// A view pattern of the catalog makes a view for each matching ID on request (`patternView`), also before the module loads.
|
||||
// A launch rule (`launch.ts`) can also start the instance at once.
|
||||
import { tr } from "../i18n/index.ts";
|
||||
import type { Dispose, PluginCommand, PluginDocumentContext, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
|
||||
import type { FeatureEntry } from "./catalog.ts";
|
||||
import { loadFeature } from "./loader.ts";
|
||||
import type { FeatureContext, FeatureInstance, FeatureModule } from "./types.ts";
|
||||
|
||||
export class FeatureSession {
|
||||
readonly controller = new AbortController();
|
||||
readonly views = new Map<string, PluginView>();
|
||||
readonly documentTypes = new Map<string, PluginDocumentType>();
|
||||
readonly commands = new Map<string, PluginCommand>();
|
||||
readonly entry: FeatureEntry;
|
||||
private context: FeatureContext;
|
||||
private load: () => Promise<FeatureModule>;
|
||||
private instance?: Promise<FeatureInstance>;
|
||||
private ready?: FeatureInstance;
|
||||
/** The IDs of the views that a view pattern made. Only these take a title from the feature. */
|
||||
private patterned = new Set<string>();
|
||||
|
||||
constructor(entry: FeatureEntry, context: FeatureContext, load: () => Promise<FeatureModule> = () => loadFeature(entry.id)) {
|
||||
this.entry = entry;
|
||||
this.context = context;
|
||||
this.load = load;
|
||||
for (const info of entry.views) {
|
||||
this.views.set(info.id, {
|
||||
id: info.id, get title() { return info.title(); }, placement: info.placement, icon: info.icon,
|
||||
navigation: !!info.navigation, launcher: false,
|
||||
mount: element => this.mountView(info.id, element),
|
||||
saveTabState: () => this.ready?.saveTabState?.(info.id),
|
||||
restoreTabState: async state => { await (await this.running()).restoreTabState?.(info.id, state); },
|
||||
...info.launch ? { launch: async () => {
|
||||
const instance = await this.running();
|
||||
if (instance.launch) await instance.launch(info.id); else context.openView(info.id);
|
||||
} } : {},
|
||||
});
|
||||
}
|
||||
for (const info of entry.documentTypes) {
|
||||
this.documentTypes.set(info.id, {
|
||||
id: info.id, get title() { return info.title(); }, icon: info.icon, extensions: [...info.extensions], content: info.content,
|
||||
identify: (path, source) => info.identify(path, source),
|
||||
mount: (element, document) => this.mountDocument(info.id, element, document),
|
||||
});
|
||||
}
|
||||
for (const info of entry.commands) {
|
||||
const view = info.view;
|
||||
this.commands.set(info.id, { id: info.id, get title() { return info.title(); }, icon: info.icon,
|
||||
run: view ? () => context.openView(view) : async () => { await (await this.running()).run?.(info.id); } });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The view with this ID: a catalog view, or a new editor view when a view pattern of the catalog matches the ID.
|
||||
* A new view keeps the title of the pattern until the feature gives one.
|
||||
*/
|
||||
patternView(id: string): PluginView | undefined {
|
||||
const existing = this.views.get(id);
|
||||
if (existing || this.controller.signal.aborted) return existing;
|
||||
const pattern = this.entry.viewPatterns?.find(item => item.match.test(id));
|
||||
if (!pattern) return undefined;
|
||||
const view: PluginView = {
|
||||
id, title: pattern.title(), placement: "editor", icon: pattern.icon, navigation: false, launcher: false,
|
||||
mount: element => this.mountView(id, element),
|
||||
saveTabState: () => this.ready?.saveTabState?.(id),
|
||||
restoreTabState: async state => { await (await this.running()).restoreTabState?.(id, state); },
|
||||
};
|
||||
this.views.set(id, view);
|
||||
this.patterned.add(id);
|
||||
return view;
|
||||
}
|
||||
|
||||
/** Give a view of a view pattern its title. Returns true when the title changed. */
|
||||
setViewTitle(id: string, title: string): boolean {
|
||||
const view = this.patterned.has(id) ? this.views.get(id) : this.patternView(id);
|
||||
if (!view || !this.patterned.has(id) || !title.trim() || view.title === title) return false;
|
||||
view.title = title;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The instance of this window. A failed load leaves no instance, so a later call tries again. */
|
||||
private running(): Promise<FeatureInstance> {
|
||||
if (this.controller.signal.aborted) return Promise.reject(new Error(tr("This feature is off.")));
|
||||
this.instance ??= this.load().then(module => {
|
||||
if (this.controller.signal.aborted) throw new Error(tr("This feature is off."));
|
||||
return this.ready = module.start(this.context);
|
||||
}).catch(reason => { this.instance = undefined; throw reason; });
|
||||
return this.instance;
|
||||
}
|
||||
|
||||
private async mountView(id: string, element: HTMLElement): Promise<Dispose> {
|
||||
return (await this.running()).mount(id, element);
|
||||
}
|
||||
|
||||
private async mountDocument(type: string, element: HTMLElement, document: PluginDocumentContext): Promise<Dispose> {
|
||||
const instance = await this.running();
|
||||
if (!instance.mountDocument) throw new Error(tr("This view is unavailable."));
|
||||
return instance.mountDocument(type, element, document);
|
||||
}
|
||||
|
||||
/** Mount a view, or with `document`, a document of the document type `id`. */
|
||||
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<Dispose> {
|
||||
const view = document ? this.documentTypes.get(id) : this.patternView(id);
|
||||
if (!view) throw new Error(tr("This view is unavailable."));
|
||||
const dispose = document ? await (view as PluginDocumentType).mount(element, document) : await (view as PluginView).mount(element, { surface: "view" });
|
||||
return async () => {
|
||||
if (typeof dispose === "function") await dispose();
|
||||
element.replaceChildren();
|
||||
};
|
||||
}
|
||||
|
||||
async launch(id: string) {
|
||||
const view = this.views.get(id);
|
||||
if (view?.launch) await view.launch();
|
||||
else this.context.openView(id);
|
||||
}
|
||||
|
||||
/** Load the module and start the instance now, without a view. Later calls use the same instance. */
|
||||
async start(): Promise<void> { await this.running(); }
|
||||
|
||||
/** The instance of this window, for a feature with a surface that is not a view, such as the terminal panel. */
|
||||
loadInstance(): Promise<FeatureInstance> { return this.running(); }
|
||||
|
||||
/** True after the instance started. */
|
||||
get started(): boolean { return this.instance !== undefined; }
|
||||
|
||||
async run(id: string) {
|
||||
const command = this.commands.get(id);
|
||||
if (!command) throw new Error(tr("This command is unavailable."));
|
||||
await command.run();
|
||||
}
|
||||
|
||||
async dropTab(_data: string): Promise<void> { throw new Error(tr("This feature cannot receive this tab.")); }
|
||||
|
||||
/** Stop the instance. The host closes the views of the feature first. */
|
||||
async stop() {
|
||||
this.controller.abort();
|
||||
const instance = this.ready ?? await this.instance?.catch(() => undefined);
|
||||
this.ready = undefined;
|
||||
this.instance = undefined;
|
||||
await instance?.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// The feature switches: the `features` section of the settings file, for example `{ "git": true }`.
|
||||
// A missing key means that the migration from the old plugin package has not run for that feature yet.
|
||||
import { readable } from "svelte/store";
|
||||
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
|
||||
import { FEATURES, type FeatureId } from "./catalog.ts";
|
||||
|
||||
export type FeatureSwitches = Record<FeatureId, boolean>;
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
/** The stored switches of the known features. Other keys are ignored. */
|
||||
export function storedSwitches(value: unknown): Partial<FeatureSwitches> {
|
||||
const stored = record(value);
|
||||
const result: Partial<FeatureSwitches> = {};
|
||||
for (const { id } of FEATURES) if (typeof stored[id] === "boolean") result[id] = stored[id];
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The switches with the default of each feature that has no stored value. */
|
||||
export function switchesFrom(value: unknown): FeatureSwitches {
|
||||
const stored = storedSwitches(value);
|
||||
return Object.fromEntries(FEATURES.map(entry => [entry.id, stored[entry.id] ?? entry.defaultOn])) as FeatureSwitches;
|
||||
}
|
||||
|
||||
export function readSwitches(): FeatureSwitches {
|
||||
return switchesFrom(readSection("features"));
|
||||
}
|
||||
|
||||
/** The switches in this window. Changes from other windows arrive through `settings-changed`. */
|
||||
export const featureSwitches = readable<FeatureSwitches>(readSwitches(), set => {
|
||||
// The settings can load after this module, so read them again for the first subscriber.
|
||||
set(readSwitches());
|
||||
return onSettingsChange("features", () => set(readSwitches()));
|
||||
});
|
||||
|
||||
/** Turn one feature on or off. Keys of unknown features stay, so a newer version keeps its values. */
|
||||
export function setFeature(id: FeatureId, on: boolean): Promise<void> {
|
||||
return writeSection("features", { ...record(readSection("features")), [id]: on });
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<script lang="ts">
|
||||
// Keeps the panel props as state, so `update` from the host reaches the panel.
|
||||
import { untrack } from "svelte";
|
||||
import type { TerminalAction, TerminalProps } from "../terminalHost";
|
||||
import type { TerminalSessions } from "./sessions";
|
||||
import TerminalDock from "./TerminalDock.svelte";
|
||||
let { initial, sessions }: { initial: TerminalProps; sessions: TerminalSessions } = $props();
|
||||
let dockProps = $state<TerminalProps>(untrack(() => initial));
|
||||
let dock: TerminalDock;
|
||||
export function update(value: TerminalProps) { dockProps = value; }
|
||||
export async function command(action: Exclude<TerminalAction, "toggle">) { await dock.command(action); }
|
||||
</script>
|
||||
<TerminalDock bind:this={dock} {...dockProps} {sessions} />
|
||||
@@ -0,0 +1,290 @@
|
||||
<script lang="ts">
|
||||
// The terminal panel: a ribbon, the panes of the active group side by side, and a session rail when more than one session runs.
|
||||
// A split adds a pane to the group of the active session. Close ends all sessions of the panel, and the next show starts a new one.
|
||||
import { onMount, tick, untrack } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { showActionMenu, type MenuHandle } from "$lib/ui/managedActionMenu";
|
||||
import type { ActionMenuItem } from "$lib/ui/actionMenu";
|
||||
import { keys } from "$lib/ui/shortcuts";
|
||||
import { workspaceRead } from "$lib/workspace/api";
|
||||
import { TERMINAL_KEYS, type TerminalAction } from "../terminalKeys";
|
||||
import { onTerminalChange, readTerminal, writeTerminal, type TerminalSettings } from "../terminalSettings";
|
||||
import type { TerminalProps } from "../terminalHost";
|
||||
import { directoryCommand, fileCommand, parseTasks, pickProfile, remember, type ShellProfile, type TerminalControl } from "./model";
|
||||
import type { TerminalSessions } from "./sessions";
|
||||
import TerminalPicker from "./TerminalPicker.svelte";
|
||||
import TerminalPane, { type PaneState } from "./TerminalPane.svelte";
|
||||
|
||||
type Session = { id: string; group: string; title: string; state: PaneState; profile: ShellProfile; directory: string; weight: number; command?: string };
|
||||
type Picker = { title: string; items: { label: string; detail?: string; value: string }[]; onPick: (value: string) => void; empty?: string };
|
||||
let { cwd, visible, maximized = false, standalone = false, onClose, onMaximize = () => {}, activeFile = false, onRunFile, getSelection = () => "", onConfigureTasks, onOpenSettings, sessions: shells }:
|
||||
TerminalProps & { sessions: TerminalSessions } = $props();
|
||||
let sessions = $state<Session[]>([]);
|
||||
let profiles = $state<ShellProfile[]>([]);
|
||||
let settings = $state<TerminalSettings>(readTerminal());
|
||||
let activeId = $state("");
|
||||
let loading = $state(true);
|
||||
let error = $state("");
|
||||
let railWidth = $state(205);
|
||||
let picker = $state<Picker | null>(null);
|
||||
let closing = $state(false);
|
||||
let restartOnShow = false;
|
||||
let recentCommands = $state<string[]>([]);
|
||||
let recentDirectories = $state<string[]>([]);
|
||||
let menu: MenuHandle | undefined;
|
||||
let menuAnchor: HTMLElement | undefined;
|
||||
let profileAnchor: HTMLDivElement;
|
||||
let moreAnchor: HTMLDivElement;
|
||||
let panes: HTMLDivElement;
|
||||
let sequence = 0;
|
||||
let stopResize: (() => void) | undefined;
|
||||
let ready: Promise<void> = Promise.resolve();
|
||||
const controls = new Map<string, TerminalControl>();
|
||||
const active = $derived(sessions.find(session => session.id === activeId));
|
||||
const group = $derived(sessions.filter(session => session.group === active?.group));
|
||||
const totalWeight = $derived(group.reduce((sum, session) => sum + session.weight, 0));
|
||||
|
||||
function report(reason: unknown) { error = String(reason); }
|
||||
function stateLabel(state: PaneState) {
|
||||
if (state.kind === "exited") return state.code === null ? $t("Exited") : $t("Exited ({code})", { code: state.code });
|
||||
if (state.kind === "starting") return $t("Starting");
|
||||
return state.kind === "running" ? $t("Running") : $t("Failed");
|
||||
}
|
||||
function defaultProfile() { return pickProfile(profiles, settings.defaultProfile); }
|
||||
export function addSession(profile = defaultProfile(), split = false, command?: string, title?: string) {
|
||||
if (!profile || closing) return;
|
||||
const id = crypto.randomUUID();
|
||||
const next: Session = { id, group: split && active ? active.group : id, title: title || `${profile.title} ${++sequence}`, state: { kind: "starting" }, profile,
|
||||
directory: split && active ? active.directory : cwd, weight: 1, command };
|
||||
if (split) for (const member of group) member.weight = 1;
|
||||
sessions = [...sessions, next]; activeId = id;
|
||||
recentDirectories = remember(recentDirectories, next.directory);
|
||||
}
|
||||
function killSession(id: string) {
|
||||
const previous = sessions.findIndex(session => session.id === id);
|
||||
const sibling = sessions.find(session => session.group === sessions[previous]?.group && session.id !== id);
|
||||
sessions = sessions.filter(session => session.id !== id);
|
||||
if (activeId === id) activeId = sibling?.id || sessions[Math.max(0, previous - 1)]?.id || "";
|
||||
void tick().then(() => controls.get(activeId)?.focus());
|
||||
}
|
||||
async function closeDock() {
|
||||
if (closing) return;
|
||||
closing = true;
|
||||
closeMenu(); picker = null;
|
||||
try {
|
||||
await ready;
|
||||
// Mount the pending panes before their sessions close.
|
||||
await tick();
|
||||
const results = await Promise.allSettled(sessions.map(session => shells.close(session.id)));
|
||||
const failures = results.filter(result => result.status === "rejected");
|
||||
if (failures.length) throw new Error(failures.map(result => String(result.reason)).join("\n"));
|
||||
sessions = []; activeId = "";
|
||||
restartOnShow = true;
|
||||
onClose();
|
||||
} catch (reason) { report(reason); }
|
||||
finally { closing = false; }
|
||||
}
|
||||
function select(id: string) { activeId = id; }
|
||||
function closeMenu() { menu?.close(); menu = undefined; }
|
||||
function showMenu(anchor: HTMLElement, items: ActionMenuItem[], name: string) {
|
||||
const same = menu?.open && menuAnchor === anchor;
|
||||
closeMenu(); if (same) return;
|
||||
menuAnchor = anchor;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
menu = showActionMenu({ x: bounds.right - 430, y: bounds.bottom + 4, items, label: name }, shells.signal);
|
||||
}
|
||||
function profileMenu() {
|
||||
showMenu(profileAnchor, [
|
||||
{ label: tr("New terminal"), icon: "plus", shortcut: keys(TERMINAL_KEYS.new), run: () => addSession() },
|
||||
{ label: tr("New terminal window"), icon: "external", shortcut: keys(TERMINAL_KEYS.window), run: () => void shells.openWindow().catch(report) },
|
||||
{ label: tr("Split terminal"), icon: "column", shortcut: keys(TERMINAL_KEYS.split), disabled: !active, run: () => addSession(active?.profile, true) },
|
||||
{ separator: true },
|
||||
...profiles.map(profile => ({ label: profile.title, icon: "code" as const, title: profile.kind === "node" ? tr("A Node.js REPL with a local inspector. Attach an external debugger to it.") : undefined, run: () => addSession(profile) })),
|
||||
{ label: tr("Split terminal with profile"), icon: "column", disabled: !active, children: profiles.map(profile => ({ label: profile.title, icon: "code", run: () => addSession(profile, true) })) },
|
||||
{ separator: true },
|
||||
{ label: tr("Terminal settings"), icon: "settings", disabled: !onOpenSettings, run: () => onOpenSettings?.() },
|
||||
{ label: tr("Select the default profile"), icon: "select", run: () => picker = { title: tr("Select the default terminal profile"), items: profiles.filter(profile => profile.kind !== "node").map(profile => ({ label: profile.title, value: profile.id, detail: profile.id === defaultProfile()?.id ? tr("Default") : undefined })), onPick: value => persist({ ...settings, defaultProfile: value }) } },
|
||||
{ separator: true },
|
||||
{ label: tr("Run a task…"), icon: "task", run: () => void runTask() },
|
||||
{ label: tr("Configure tasks…"), icon: "code", disabled: !onConfigureTasks, run: () => void onConfigureTasks?.().catch(report) },
|
||||
], tr("Terminal profiles"));
|
||||
}
|
||||
function persist(next: TerminalSettings) {
|
||||
settings = { ...next };
|
||||
void writeTerminal(next).catch(report);
|
||||
}
|
||||
async function runFile() {
|
||||
const target = active;
|
||||
if (!target || !onRunFile) return;
|
||||
try { const path = await onRunFile(); if (path) controls.get(target.id)?.send(fileCommand(path, target.profile.kind)); } catch (reason) { report(reason); }
|
||||
}
|
||||
function runSelection() {
|
||||
const text = getSelection();
|
||||
if (!text) { error = tr("Select text in the editor first."); return; }
|
||||
controls.get(activeId)?.send(text);
|
||||
}
|
||||
function historyPicker(kind: "commands" | "directories") {
|
||||
const target = active;
|
||||
if (!target) return;
|
||||
picker = { title: kind === "commands" ? tr("Run a recent command") : tr("Go to a recent folder"),
|
||||
items: (kind === "commands" ? recentCommands : recentDirectories).map(value => ({ label: value, value })),
|
||||
empty: kind === "commands" ? tr("No commands yet. Shell commands show after the next prompt.") : tr("No folders yet."),
|
||||
onPick: value => { try { controls.get(target.id)?.send(kind === "commands" ? value : directoryCommand(value, target.profile.kind)); } catch (reason) { report(reason); } } };
|
||||
}
|
||||
async function runTask() {
|
||||
try {
|
||||
const tasks = parseTasks(await workspaceRead(".runestone/tasks.json"));
|
||||
picker = { title: tr("Run a task"), items: tasks.map((task, index) => ({ label: task.label, detail: task.command, value: String(index) })), empty: tr("No tasks yet. Choose Configure tasks… to add one."), onPick: index => {
|
||||
const task = tasks[Number(index)];
|
||||
const profile = task.profile ? profiles.find(profile => profile.id === task.profile) : defaultProfile();
|
||||
if (!profile) { error = tr("The profile of this task is not installed: {profile}", { profile: task.profile ?? "" }); return; }
|
||||
addSession(profile, false, task.command, task.label);
|
||||
} };
|
||||
} catch (reason) { error = tr("RuneStone cannot read .runestone/tasks.json. Use Configure tasks… to make or change it. {error}", { error: String(reason) }); }
|
||||
}
|
||||
function moreMenu() {
|
||||
showMenu(moreAnchor, [
|
||||
{ label: tr("Scroll to the previous command"), icon: "up", shortcut: keys(TERMINAL_KEYS.previous), disabled: !active, run: () => controls.get(activeId)?.scrollCommand(-1) },
|
||||
{ label: tr("Scroll to the next command"), icon: "down", shortcut: keys(TERMINAL_KEYS.next), disabled: !active, run: () => controls.get(activeId)?.scrollCommand(1) },
|
||||
{ label: tr("Clear the terminal"), icon: "clear", disabled: !active, run: () => controls.get(activeId)?.clear() },
|
||||
{ label: tr("Run the active file"), icon: "code", disabled: !active || !activeFile, run: () => void runFile() },
|
||||
{ label: tr("Run selected text"), icon: "select", disabled: !active || !activeFile, run: runSelection },
|
||||
{ label: tr("Start dictation"), icon: "comment", disabled: !active, title: tr("Start Windows voice typing in the focused terminal"), run: () => { controls.get(activeId)?.focus(); void shells.dictation().catch(report); } },
|
||||
{ separator: true },
|
||||
{ label: tr("Go to a recent folder…"), icon: "external", shortcut: keys(TERMINAL_KEYS.directories), disabled: !active, run: () => historyPicker("directories") },
|
||||
{ label: tr("Run a recent command…"), icon: "task", shortcut: keys(TERMINAL_KEYS.commands), disabled: !active, run: () => historyPicker("commands") },
|
||||
], tr("Terminal actions"));
|
||||
}
|
||||
export async function command(action: Exclude<TerminalAction, "toggle">) {
|
||||
await ready;
|
||||
if (action === "new") addSession();
|
||||
else if (action === "split") addSession(active?.profile || defaultProfile(), !!active);
|
||||
else if (action === "window") void shells.openWindow().catch(report);
|
||||
else if (action === "previous" || action === "next") controls.get(activeId)?.scrollCommand(action === "previous" ? -1 : 1);
|
||||
else historyPicker(action);
|
||||
}
|
||||
function beginResize(event: PointerEvent, update: (x: number) => void) {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault(); stopResize?.();
|
||||
const move = (event: PointerEvent) => update(event.clientX);
|
||||
stopResize = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", stop); window.removeEventListener("pointercancel", stop); stopResize = undefined; };
|
||||
const stop = () => stopResize?.();
|
||||
window.addEventListener("pointermove", move); window.addEventListener("pointerup", stop); window.addEventListener("pointercancel", stop);
|
||||
}
|
||||
function resizeRail(event: PointerEvent) { const x = event.clientX, width = railWidth; beginResize(event, next => railWidth = Math.min(340, Math.max(140, width + x - next))); }
|
||||
function resizeSplit(event: PointerEvent, session: Session) {
|
||||
const index = group.indexOf(session), previous = group[index - 1];
|
||||
if (!previous) return;
|
||||
const x = event.clientX, before = previous.weight, after = session.weight, width = panes.clientWidth, total = totalWeight;
|
||||
beginResize(event, next => { const change = (next - x) / width * total; previous.weight = Math.min(before + after - .15, Math.max(.15, before + change)); session.weight = before + after - previous.weight; });
|
||||
}
|
||||
function paneLeft(session: Session) { return group.slice(0, group.indexOf(session)).reduce((sum, item) => sum + item.weight, 0) / totalWeight * 100; }
|
||||
onMount(() => {
|
||||
let disposed = false;
|
||||
ready = shells.profiles().then(found => {
|
||||
if (disposed) return;
|
||||
profiles = found;
|
||||
if (profiles.length) addSession(); else error = tr("RuneStone found no supported shells on PATH.");
|
||||
}).catch(report).finally(() => loading = false);
|
||||
// Settings → Terminal and other windows change the settings. Open sessions take the new font, scrollback, and cursor.
|
||||
const stopSettings = onTerminalChange(() => { settings = readTerminal(); });
|
||||
return () => { disposed = true; stopSettings(); closeMenu(); stopResize?.(); };
|
||||
});
|
||||
$effect(() => { if (!visible) { closeMenu(); picker = null; } });
|
||||
$effect(() => {
|
||||
if (visible) untrack(() => {
|
||||
if (restartOnShow) { restartOnShow = false; addSession(); }
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="dock" style:--rail="{railWidth}px">
|
||||
<header class="ribbon">
|
||||
<span class="label" title={cwd}>{$t("Terminal")}</span><span class="directory" title={active?.directory || cwd}>{active?.directory || cwd}</span>
|
||||
<div class="actions">
|
||||
{#if sessions.length === 1 && active}<span class="single-session" title={`${active.title} · ${stateLabel(active.state)}`}>{active.profile.title}</span>{/if}
|
||||
<IconButton icon="plus" label={$t("New terminal")} disabled={loading || !profiles.length} onclick={() => addSession()} />
|
||||
<div bind:this={profileAnchor}><IconButton icon="chevron-down" label={$t("Terminal profiles and tasks")} disabled={loading} onclick={profileMenu} /></div>
|
||||
<IconButton icon="split" label={$t("Split terminal ({shortcut})", { shortcut: keys(TERMINAL_KEYS.split) })} disabled={!active} onclick={() => addSession(active?.profile, true)} />
|
||||
<div bind:this={moreAnchor}><IconButton icon="more" label={$t("More terminal actions")} onclick={moreMenu} /></div>
|
||||
<IconButton icon="trash" label={$t("Kill terminal")} disabled={!active} onclick={() => killSession(activeId)} />
|
||||
{#if !standalone}<IconButton icon={maximized ? "restore" : "maximize"} label={maximized ? $t("Restore panel") : $t("Maximize panel")} onclick={onMaximize} />{/if}
|
||||
<IconButton icon="close" label={standalone ? $t("Close terminal window") : $t("Close terminal (end all sessions)")} disabled={closing} onclick={() => void closeDock()} />
|
||||
</div>
|
||||
</header>
|
||||
{#if error}<div class="error" role="alert"><span>{error}</span><IconButton icon="close" label={$t("Dismiss the terminal error")} onclick={() => error = ""} /></div>{/if}
|
||||
<div class="body">
|
||||
<div class="panes" bind:this={panes}>
|
||||
{#each sessions as session (session.id)}
|
||||
<div class="pane" class:shown={session.group === active?.group} class:focused={session.id === activeId}
|
||||
style:left="{session.group === active?.group ? paneLeft(session) : 0}%" style:width="{session.group === active?.group ? session.weight / totalWeight * 100 : 100}%">
|
||||
{#if group.length > 1 && session.group === active?.group}<div class="pane-label">{session.title}</div>{/if}
|
||||
<TerminalPane id={session.id} {cwd} directory={session.directory} profile={session.profile} {settings} sessions={shells}
|
||||
active={visible && session.group === active?.group} focused={session.id === activeId} onFocus={() => activeId = session.id}
|
||||
onState={state => { session.state = state; if (state.kind === "running" && session.command) { controls.get(session.id)?.send(session.command); session.command = undefined; } }}
|
||||
onControl={control => { if (control) controls.set(session.id, control); else controls.delete(session.id); }}
|
||||
onCommand={command => recentCommands = remember(recentCommands, command)}
|
||||
onDirectory={directory => { session.directory = directory; recentDirectories = remember(recentDirectories, directory); }} />
|
||||
{#if session.group === active?.group && group.indexOf(session) > 0}
|
||||
<div class="split-gutter" role="separator" aria-label={$t("Resize split terminals")} aria-orientation="vertical" onpointerdown={event => resizeSplit(event, session)}></div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{#if !sessions.length}<div class="empty"><p>{loading ? $t("Finding the installed shells…") : $t("No terminal sessions.")}</p><button disabled={loading || !profiles.length} onclick={() => addSession()}>{$t("Start a terminal")}</button></div>{/if}
|
||||
</div>
|
||||
{#if sessions.length > 1}
|
||||
<div class="gutter" role="separator" aria-orientation="vertical" aria-label={$t("Resize terminal list")} onpointerdown={resizeRail}></div>
|
||||
<nav class="rail" aria-label={$t("Terminal list")}>
|
||||
{#each sessions as session (session.id)}
|
||||
<div class="item" data-session={session.id} class:active={session.id === activeId} class:grouped={sessions.filter(item => item.group === session.group).length > 1}>
|
||||
<button class="pick" aria-pressed={session.id === activeId} title={`${session.title} · ${stateLabel(session.state)} · ${session.directory}`} onclick={() => select(session.id)}
|
||||
onkeydown={event => {
|
||||
if (event.key === "Delete") { event.preventDefault(); killSession(session.id); }
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); const next = sessions[(sessions.indexOf(session) + (event.key === "ArrowDown" ? 1 : sessions.length - 1)) % sessions.length]; activeId = next.id; (event.currentTarget.closest("nav")?.querySelector(`[data-session="${next.id}"] .pick`) as HTMLButtonElement)?.focus(); }
|
||||
}}><span class="shell-icon" aria-hidden="true">›_</span><span class="session-name">{session.title}<small>{stateLabel(session.state)}</small></span></button>
|
||||
<div class="row-actions">
|
||||
<IconButton icon="split" label={$t("Split {title}", { title: session.title })} onclick={() => { activeId = session.id; addSession(session.profile, true); }} />
|
||||
<IconButton icon="trash" label={$t("Kill {title} ({shortcut})", { title: session.title, shortcut: keys("Delete") })} onclick={() => killSession(session.id)} />
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</nav>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{#if picker}<TerminalPicker {...picker} onClose={() => picker = null} />{/if}
|
||||
<style>
|
||||
.dock { display: flex; flex-direction: column; height: 100%; min-height: 0; container-type: inline-size; }
|
||||
.ribbon { display: flex; flex-wrap: wrap; align-items: center; gap: 0 10px; flex: 0 0 auto; min-height: var(--rs-titlebar-height, 36px); padding: 0 8px; background: var(--rs-image-sidebar-bg, color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent)); }
|
||||
.label { font-size: 13px; color: var(--rs-text-strong); }
|
||||
.directory { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rs-text-dim); font-size: 12px; }
|
||||
.actions, .row-actions { display: flex; align-items: center; flex-shrink: 0; }
|
||||
.actions { flex-wrap: wrap; max-width: 100%; }
|
||||
.single-session { max-width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; color: var(--rs-text-dim); margin-right: 6px; }
|
||||
.body { display: flex; flex: 1; min-height: 0; }
|
||||
.panes { flex: 1; position: relative; min-width: 0; min-height: 0; }
|
||||
.pane { display: flex; flex-direction: column; position: absolute; top: 0; bottom: 0; visibility: hidden; min-width: 0; overflow: hidden; }
|
||||
.pane.shown { visibility: visible; }
|
||||
.pane :global(.term) { flex: 1; min-height: 0; height: auto; }
|
||||
.pane-label { flex: 0 0 23px; padding: 3px 10px; font-size: 11px; color: var(--rs-text-dim); border-top: 1px solid transparent; background: var(--rs-image-editor-bg, color-mix(in srgb, var(--rs-bg) 90%, transparent)); }
|
||||
.focused .pane-label { color: var(--rs-text-strong); border-top-color: var(--rs-accent); }
|
||||
.split-gutter { position: absolute; top: 0; bottom: 0; left: 0; width: 4px; cursor: col-resize; background: var(--rs-border); }
|
||||
.gutter { flex: 0 0 4px; cursor: col-resize; }
|
||||
.gutter:hover, .split-gutter:hover { background: var(--rs-accent); }
|
||||
.rail { flex: 0 0 var(--rail); width: var(--rail); overflow: auto; padding: 4px; border-left: 1px solid var(--rs-border); background: var(--rs-image-sidebar-bg, color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent)); }
|
||||
.item { display: flex; align-items: center; min-width: 0; border-left: 2px solid transparent; border-radius: var(--rs-control-radius); }
|
||||
.item.grouped { border-left-color: var(--rs-border); }
|
||||
.item.active { background: var(--rs-image-control-hover-bg, color-mix(in srgb, var(--rs-bg-active) 92%, transparent)); border-left-color: var(--rs-accent); }
|
||||
.pick { display: flex; align-items: center; gap: 7px; flex: 1; min-width: 0; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); text-align: left; padding: 5px; }
|
||||
.shell-icon { color: var(--rs-text-dim); }
|
||||
.session-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
small { display: block; font-size: 10px; color: var(--rs-text-dim); }
|
||||
.row-actions { visibility: hidden; }
|
||||
.item:hover .row-actions, .item:focus-within .row-actions, .item.active .row-actions { visibility: visible; }
|
||||
.error { padding: 3px 4px 3px 12px; display: flex; align-items: center; gap: 8px; color: var(--rs-error); font-size: 12px; border-bottom: 1px solid var(--rs-border); }
|
||||
.error span { flex: 1; }
|
||||
.empty button { background: var(--rs-bg-active); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 4px 8px; }
|
||||
.empty { height: 100%; padding: 20px; color: var(--rs-text-dim); background: var(--rs-image-editor-bg, color-mix(in srgb, var(--rs-bg) 90%, transparent)); }
|
||||
@container (max-width: 700px) { .rail { flex-basis: 150px; width: 150px; } .row-actions { display: none; } .directory, .single-session { display: none; } .label { flex: 1; } }
|
||||
</style>
|
||||
@@ -0,0 +1,259 @@
|
||||
<script lang="ts" module>
|
||||
/** The state of one shell. `code` is the exit code, when the shell gave one. */
|
||||
export type PaneState = { kind: "starting" | "running" | "failed" } | { kind: "exited"; code: number | null };
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
// One xterm and its shell. Input before the shell starts waits in a buffer, xterm's answers to start-up queries included.
|
||||
// OSC 133 marks the prompts for command scrolling. OSC 633 reports the folder and the last command (src-tauri/src/pty.rs).
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { Terminal, type IMarker } from "@xterm/xterm";
|
||||
import { onMount } from "svelte";
|
||||
import { tr } from "$lib/i18n";
|
||||
import { terminalShortcut } from "../terminalKeys";
|
||||
import type { TerminalSettings } from "../terminalSettings";
|
||||
import { terminalTypography } from "./typography";
|
||||
import { terminalTheme, watchTerminalAppearance } from "./theme";
|
||||
import type { ShellProfile, TerminalControl } from "./model";
|
||||
import type { TerminalSessions } from "./sessions";
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
cwd: string;
|
||||
active: boolean;
|
||||
focused: boolean;
|
||||
profile: ShellProfile;
|
||||
directory: string;
|
||||
settings: TerminalSettings;
|
||||
sessions: TerminalSessions;
|
||||
onFocus: () => void;
|
||||
onControl: (control: TerminalControl | null) => void;
|
||||
onCommand: (command: string) => void;
|
||||
onDirectory: (directory: string) => void;
|
||||
onState: (state: PaneState) => void;
|
||||
};
|
||||
|
||||
let { id, cwd, active, focused, profile, directory, settings, sessions, onFocus, onControl, onCommand, onDirectory, onState }: Props = $props();
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let focusTerminal: (() => void) | undefined = $state();
|
||||
let instance = $state.raw<Terminal>();
|
||||
let resizeTerminal: (() => void) | undefined;
|
||||
|
||||
$effect(() => { if (active && focused && !document.activeElement?.closest(".rail")) focusTerminal?.(); });
|
||||
$effect(() => {
|
||||
if (instance) {
|
||||
instance.options.fontSize = settings.fontSize;
|
||||
instance.options.scrollback = settings.scrollback;
|
||||
instance.options.cursorBlink = settings.cursorBlink;
|
||||
requestAnimationFrame(() => resizeTerminal?.());
|
||||
}
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
if (!host) return;
|
||||
const theme = terminalTheme(host);
|
||||
host.style.setProperty("--rs-terminal-selection", theme.selectionBackground!);
|
||||
const term = new Terminal({
|
||||
scrollback: settings.scrollback,
|
||||
...terminalTypography(host),
|
||||
fontSize: settings.fontSize,
|
||||
cursorBlink: settings.cursorBlink,
|
||||
allowProposedApi: true,
|
||||
allowTransparency: true,
|
||||
theme,
|
||||
});
|
||||
const fit = new FitAddon();
|
||||
term.loadAddon(fit);
|
||||
term.open(host);
|
||||
instance = term;
|
||||
let disposed = false;
|
||||
let opened = false;
|
||||
let exited = false;
|
||||
const pendingInput: string[] = [];
|
||||
let writes = Promise.resolve();
|
||||
const fail = (reason: unknown) => {
|
||||
if (!disposed) term.writeln(`\r\n${String(reason)}`);
|
||||
};
|
||||
let selectionRevision = 0;
|
||||
const selection = term.onSelectionChange(() => { selectionRevision++; });
|
||||
const copySelection = (clearAfterCopy = false) => {
|
||||
const text = term.getSelection();
|
||||
if (!text) return;
|
||||
const revision = selectionRevision;
|
||||
void navigator.clipboard.writeText(text).then(() => {
|
||||
if (clearAfterCopy && !disposed && selectionRevision === revision) term.clearSelection();
|
||||
}).catch(fail);
|
||||
};
|
||||
const copyOnRightClick = (event: MouseEvent) => {
|
||||
if (!term.hasSelection()) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
copySelection(true);
|
||||
};
|
||||
// Copy the selected text before xterm prepares its own context menu.
|
||||
host.addEventListener("contextmenu", copyOnRightClick, true);
|
||||
term.attachCustomKeyEventHandler(event => {
|
||||
const copy = (event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === "c";
|
||||
if (copy && (term.hasSelection() || event.shiftKey)) {
|
||||
if (event.type === "keydown") {
|
||||
event.preventDefault();
|
||||
copySelection();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return !terminalShortcut(event);
|
||||
});
|
||||
const resize = () => {
|
||||
if (disposed || !host?.clientWidth || !host?.clientHeight) return;
|
||||
fit.fit();
|
||||
if (opened && !exited) void sessions.resize(id, term.cols, term.rows).catch(fail);
|
||||
};
|
||||
const stopAppearance = watchTerminalAppearance(host, () => {
|
||||
if (disposed || !host) return;
|
||||
const theme = terminalTheme(host);
|
||||
if (host.style.getPropertyValue("--rs-terminal-selection") !== theme.selectionBackground) {
|
||||
host.style.setProperty("--rs-terminal-selection", theme.selectionBackground!);
|
||||
}
|
||||
term.options.theme = theme;
|
||||
Object.assign(term.options, terminalTypography(host));
|
||||
resize();
|
||||
});
|
||||
resizeTerminal = resize;
|
||||
focusTerminal = () => { resize(); term.focus(); };
|
||||
const send = (data: string) => {
|
||||
if (exited || disposed) return;
|
||||
if (!opened) { pendingInput.push(data); return; }
|
||||
writes = writes.then(() => sessions.write(id, data)).catch(fail);
|
||||
};
|
||||
const onData = term.onData(send);
|
||||
let markers: IMarker[] = [];
|
||||
let prompt: { marker: IMarker; column: number } | undefined;
|
||||
const promptParser = term.parser.registerOscHandler(133, data => {
|
||||
if (data === "A") {
|
||||
const marker = term.registerMarker(0);
|
||||
if (marker) markers = [...markers.filter(item => !item.isDisposed), marker].slice(-1000);
|
||||
}
|
||||
if (data === "B") {
|
||||
prompt?.marker.dispose();
|
||||
const marker = term.registerMarker(0);
|
||||
prompt = marker ? { marker, column: term.buffer.active.cursorX } : undefined;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
const integration = term.parser.registerOscHandler(633, data => {
|
||||
const separator = data.indexOf(";");
|
||||
const type = data.slice(0, separator), value = data.slice(separator + 1);
|
||||
try {
|
||||
if (type === "Cwd") onDirectory(value);
|
||||
if (type === "RSCwd" || type === "RSCommand") {
|
||||
const decoded = new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0)));
|
||||
if (type === "RSCwd") onDirectory(decoded); else onCommand(decoded);
|
||||
}
|
||||
} catch { /* Ignore shell integration output that is not valid. */ }
|
||||
return true;
|
||||
});
|
||||
// Command Prompt has no history hook, so the pane reads the command line from the screen at Enter.
|
||||
const keys = term.onKey(({ domEvent }) => {
|
||||
if (profile.kind !== "cmd" || domEvent.key !== "Enter" || !prompt || prompt.marker.isDisposed) return;
|
||||
const buffer = term.buffer.active;
|
||||
let command = "";
|
||||
for (let line = prompt.marker.line; line <= buffer.baseY + buffer.cursorY; line++) {
|
||||
command += buffer.getLine(line)?.translateToString(true, line === prompt.marker.line ? prompt.column : 0) || "";
|
||||
}
|
||||
if (command.trim()) onCommand(command);
|
||||
prompt.marker.dispose(); prompt = undefined;
|
||||
});
|
||||
onControl({
|
||||
focus: () => { resize(); term.focus(); },
|
||||
clear: () => { markers.forEach(marker => marker.dispose()); markers = []; term.clear(); term.focus(); },
|
||||
scrollCommand: direction => {
|
||||
const lines = markers.filter(marker => !marker.isDisposed).map(marker => marker.line);
|
||||
const current = term.buffer.active.viewportY;
|
||||
const target = direction < 0 ? lines.reverse().find(line => line < current) : lines.find(line => line > current);
|
||||
if (target !== undefined) term.scrollToLine(target); else if (direction > 0) term.scrollToBottom();
|
||||
},
|
||||
send: (text, execute = true) => {
|
||||
if (exited) return;
|
||||
term.paste(text.replace(/\r?\n/g, "\r"));
|
||||
if (execute) send("\r");
|
||||
term.focus();
|
||||
},
|
||||
});
|
||||
const start = async () => {
|
||||
try {
|
||||
resize();
|
||||
// The host sends output from the start, because shells and agents can print at once.
|
||||
await sessions.open(id, {
|
||||
cwd, cols: term.cols, rows: term.rows, profile: profile.id, directory,
|
||||
onData: data => { if (!disposed) term.write(data); },
|
||||
onExit: code => {
|
||||
if (disposed) return;
|
||||
exited = true;
|
||||
onState({ kind: "exited", code });
|
||||
term.writeln(`\r\n[${code === null ? tr("Process exited") : tr("Process exited with code {code}", { code })}]`);
|
||||
},
|
||||
});
|
||||
opened = true;
|
||||
if (disposed) { await sessions.close(id); return; }
|
||||
for (const data of pendingInput.splice(0)) {
|
||||
writes = writes.then(() => sessions.write(id, data)).catch(fail);
|
||||
}
|
||||
if (!exited) onState({ kind: "running" });
|
||||
resize();
|
||||
if (active && focused) term.focus();
|
||||
} catch (reason) {
|
||||
fail(reason);
|
||||
if (!disposed) onState({ kind: "failed" });
|
||||
}
|
||||
};
|
||||
void start();
|
||||
const observer = new ResizeObserver(resize);
|
||||
observer.observe(host);
|
||||
return () => {
|
||||
disposed = true;
|
||||
focusTerminal = undefined;
|
||||
instance = undefined;
|
||||
resizeTerminal = undefined;
|
||||
onControl(null);
|
||||
observer.disconnect();
|
||||
stopAppearance();
|
||||
onData.dispose();
|
||||
selection.dispose();
|
||||
host?.removeEventListener("contextmenu", copyOnRightClick, true);
|
||||
promptParser.dispose(); integration.dispose(); keys.dispose();
|
||||
void sessions.close(id).catch(() => {});
|
||||
term.dispose();
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="term" data-cwd={directory} bind:this={host} onfocusin={onFocus}></div>
|
||||
|
||||
<style>
|
||||
.term {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
padding: 4px;
|
||||
background: var(--rs-image-editor-bg, color-mix(in srgb, var(--rs-bg) 90%, transparent));
|
||||
}
|
||||
|
||||
.term :global(.xterm),
|
||||
.term :global(.xterm-viewport) {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.term :global(.xterm-viewport) {
|
||||
/* Whole terminal rows can leave a gap above the bottom edge. */
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
/* The DOM renderer blends the selection on its transparent black base first. */
|
||||
.term :global(.xterm .xterm-selection div) {
|
||||
background-color: var(--rs-terminal-selection) !important;
|
||||
}
|
||||
|
||||
/* xterm marks selected glyphs as top decorations with opaque fills. */
|
||||
.term :global(.xterm-rows .xterm-decoration-top) {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,46 @@
|
||||
<script lang="ts">
|
||||
// A filter list for tasks, recent commands, recent folders, and profiles. It uses the shared picker rows of menu.css.
|
||||
import { onMount, tick } from "svelte";
|
||||
import { t } from "$lib/i18n";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { keys } from "$lib/ui/shortcuts";
|
||||
let { title, items, onPick, onClose, empty }: {
|
||||
title: string; items: { label: string; detail?: string; value: string }[];
|
||||
onPick: (value: string) => void; onClose: () => void; empty?: string;
|
||||
} = $props();
|
||||
let query = $state("");
|
||||
let selected = $state(0);
|
||||
let dialog: HTMLDialogElement;
|
||||
let input: HTMLInputElement;
|
||||
const listId = $props.id();
|
||||
const matches = $derived(items.filter(item => `${item.label} ${item.detail || ""}`.toLowerCase().includes(query.toLowerCase())));
|
||||
async function pick(value?: string) { if (value !== undefined) { const choose = onPick; onClose(); await tick(); choose(value); } }
|
||||
onMount(() => { dialog.showModal(); input.focus(); });
|
||||
</script>
|
||||
<dialog class="rs-picker" bind:this={dialog} oncancel={onClose} aria-label={title}>
|
||||
<header>{title}<IconButton icon="close" label={$t("Close the list")} onclick={onClose} /></header>
|
||||
<input bind:this={input} bind:value={query} role="combobox" aria-expanded="true" aria-controls={listId} aria-activedescendant={matches[selected] ? `${listId}-${selected}` : undefined} aria-autocomplete="list" aria-label={title} placeholder={$t("Type to filter…")} oninput={() => selected = 0} onkeydown={event => {
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
|
||||
dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
if (event.key === "Enter") { event.preventDefault(); void pick(matches[selected]?.value); }
|
||||
}} />
|
||||
<div class="results" id={listId} role="listbox" aria-label={$t("{title}: choices", { title })}>
|
||||
{#each matches as item, index}
|
||||
<button class="rs-picker-row" id={`${listId}-${index}`} role="option" aria-selected={index === selected} data-index={index} onclick={() => void pick(item.value)}><span class="entry-label">{item.label}{#if item.detail}<small class="rs-picker-hint">{item.detail}</small>{/if}</span></button>
|
||||
{/each}
|
||||
{#if !matches.length}<p>{query ? $t("No entries match the filter.") : empty ?? $t("No entries yet.")}</p>{/if}
|
||||
</div>
|
||||
<footer>{$t("{up} {down} select · {enter} choose · {escape} close", { up: "↑", down: "↓", enter: keys("Enter"), escape: keys("Escape") })}</footer>
|
||||
</dialog>
|
||||
<style>
|
||||
dialog { margin-top: 12vh; width: min(640px, 85vw); }
|
||||
dialog::backdrop { background: var(--rs-scrim); }
|
||||
header { display: flex; align-items: center; justify-content: space-between; padding: 8px 16px; }
|
||||
input { width: 100%; box-sizing: border-box; padding: var(--rs-menu-row-padding); min-height: var(--rs-menu-row-height); background: var(--rs-bg); color: var(--rs-text-strong); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
.results { max-height: 50vh; overflow: auto; }
|
||||
.entry-label { min-width: 0; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
footer, p { color: var(--rs-text-dim); }
|
||||
footer { padding: var(--rs-menu-row-padding); border-top: 1px solid var(--rs-border); font-size: var(--rs-settings-description-size); }
|
||||
</style>
|
||||
@@ -0,0 +1,36 @@
|
||||
// The Terminal feature. `loader.ts` imports this module at the first use of a terminal panel:
|
||||
// the Terminal button, a terminal shortcut, or a terminal window. Settings → Terminal does not load it.
|
||||
// It starts shells through the `pty_*` commands of src-tauri/src/pty.rs (`transport.ts`).
|
||||
import { flushSync, mount, unmount } from "svelte";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { TerminalInstance, TerminalMount } from "../terminalHost.ts";
|
||||
import type { FeatureContext } from "../types.ts";
|
||||
import { TerminalSessions } from "./sessions.ts";
|
||||
import { desktopTransport } from "./transport.ts";
|
||||
import TerminalBridge from "./TerminalBridge.svelte";
|
||||
// The xterm styles load with the feature chunk.
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
|
||||
export function start(_context: FeatureContext): TerminalInstance {
|
||||
const sessions = new TerminalSessions(desktopTransport);
|
||||
const docks = new Set<() => Promise<void>>();
|
||||
return {
|
||||
mount() { throw new Error(tr("This view is unavailable.")); },
|
||||
mountDock(element, props): TerminalMount {
|
||||
if (sessions.stopped) throw new Error(tr("This feature is off."));
|
||||
const instance = mount(TerminalBridge, { target: element, props: { initial: props, sessions } });
|
||||
flushSync();
|
||||
let stopping: Promise<void> | undefined;
|
||||
const dispose = () => stopping ??= unmount(instance).then(() => { docks.delete(dispose); });
|
||||
docks.add(dispose);
|
||||
return { update: value => instance.update(value), command: action => instance.command(action), dispose };
|
||||
},
|
||||
/** Remove the panels, then stop the shells that are left. Panels close their own sessions when they unmount. */
|
||||
async dispose() {
|
||||
const results = await Promise.allSettled([...docks].map(dispose => dispose()));
|
||||
await sessions.closeAll();
|
||||
const errors = results.filter(result => result.status === "rejected");
|
||||
if (errors.length) throw new Error(errors.map(result => String(result.reason)).join("\n"));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Shell commands, tasks, and history of the terminal panel. Plain functions, so the unit tests run them without a DOM.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
|
||||
export type ShellKind = "powershell" | "bash" | "cmd" | "node";
|
||||
/** A shell that `pty_profiles` found (src-tauri/src/pty.rs). */
|
||||
export type ShellProfile = { id: string; title: string; kind: ShellKind };
|
||||
/** The controls of one terminal pane for the panel. */
|
||||
export type TerminalControl = { focus(): void; clear(): void; scrollCommand(direction: -1 | 1): void; send(text: string, execute?: boolean): void };
|
||||
/** One task of `.runestone/tasks.json`. */
|
||||
export type TerminalTask = { label: string; command: string; profile?: string };
|
||||
|
||||
/** The profile of a new terminal: the default profile when it exists, then the first shell that is not Node.js. */
|
||||
export function pickProfile(profiles: readonly ShellProfile[], preferred: string): ShellProfile | undefined {
|
||||
return profiles.find(profile => profile.id === preferred) || profiles.find(profile => profile.kind !== "node") || profiles[0];
|
||||
}
|
||||
|
||||
/** Quote a path for a shell, so that the shell does not expand it. */
|
||||
export function quoteShell(value: string, kind: ShellKind): string {
|
||||
if (/[\r\n\0]/.test(value)) throw new Error(tr("A path cannot contain line breaks or null characters."));
|
||||
if (kind === "cmd") {
|
||||
// Command Prompt expands % and ! also between quotes. Refuse the path instead of running another path.
|
||||
if (/["%!]/.test(value)) throw new Error(tr("Use PowerShell for a path with quotes, % or !."));
|
||||
return `"${value}"`;
|
||||
}
|
||||
if (kind === "bash") return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
return `'${value.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
/** The command that goes to a folder in a shell. */
|
||||
export function directoryCommand(path: string, kind: ShellKind): string {
|
||||
if (kind === "node") return `process.chdir(${JSON.stringify(path)})`;
|
||||
const normalized = kind === "bash" ? path.replaceAll("\\", "/") : path;
|
||||
return `${kind === "powershell" ? "Set-Location -LiteralPath" : kind === "cmd" ? "cd /d" : "cd --"} ${quoteShell(normalized, kind)}`;
|
||||
}
|
||||
|
||||
/** The command that runs a file in a shell. The file extension selects the program. */
|
||||
export function fileCommand(path: string, kind: ShellKind): string {
|
||||
if (kind === "node") throw new Error(tr("Select a shell terminal to run files. The debug terminal is a Node.js REPL."));
|
||||
const ext = path.split(".").pop()?.toLowerCase();
|
||||
const quoted = quoteShell(kind === "bash" ? path.replaceAll("\\", "/") : path, kind);
|
||||
const runner = ext === "py" ? "python" : ["js", "mjs", "cjs"].includes(ext || "") ? "node"
|
||||
: ext === "ps1" ? "powershell -NoLogo -File" : ext === "sh" ? "bash" : ext === "rb" ? "ruby"
|
||||
: ext === "bat" || ext === "cmd" ? "cmd /c" : ext === "exe" ? "" : null;
|
||||
if (runner === null) throw new Error(tr("RuneStone cannot run this file type. Use Run selected text, or add a task."));
|
||||
return `${runner || (kind === "powershell" ? "&" : "")}${runner || kind === "powershell" ? " " : ""}${quoted}`;
|
||||
}
|
||||
|
||||
/** The tasks of `.runestone/tasks.json`. Each task must be valid before the panel offers one. */
|
||||
export function parseTasks(text: string): TerminalTask[] {
|
||||
const value = JSON.parse(text);
|
||||
if (!Array.isArray(value?.tasks)) throw new Error(tr("The tasks file needs a \"tasks\" array."));
|
||||
return value.tasks.map((task: unknown) => {
|
||||
if (!task || typeof task !== "object" || !("label" in task) || typeof task.label !== "string" || !task.label.trim()
|
||||
|| !("command" in task) || typeof task.command !== "string" || !task.command.trim()
|
||||
|| ("profile" in task && typeof task.profile !== "string")) throw new Error(tr("Each task needs a label, a command, and an optional profile ID."));
|
||||
return task as TerminalTask;
|
||||
});
|
||||
}
|
||||
|
||||
/** Put a value first in a history list without duplicates. The list keeps 100 values. */
|
||||
export function remember(items: string[], value: string): string[] {
|
||||
return value.trim() ? [value, ...items.filter(item => item !== value)].slice(0, 100) : items;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// The shell sessions of one Terminal instance. The panes call this layer, and this layer calls the host (`transport.ts`).
|
||||
// A close waits for the start of its shell, so a close cannot leave a late shell running.
|
||||
// `closeAll` runs when Terminal goes off or the window closes the feature.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { ShellProfile } from "./model.ts";
|
||||
|
||||
/** What a pane asks for when it starts a shell. `id` is the pane ID. The host uses it as the session ID. */
|
||||
export interface PtyRequest { id: string; cwd: string; cols: number; rows: number; profile?: string; directory?: string }
|
||||
|
||||
/** The host commands of the terminal (`pty_*` in src-tauri/src/pty.rs). Tests give a fake transport. */
|
||||
export interface PtyTransport {
|
||||
/** Start a shell. `onData` gets the raw output bytes and `onExit` the exit code, from the start on. */
|
||||
open(request: PtyRequest, onData: (data: Uint8Array) => void, onExit: (code: number | null) => void): Promise<void>;
|
||||
write(id: string, data: string): Promise<void>;
|
||||
resize(id: string, cols: number, rows: number): Promise<void>;
|
||||
close(id: string): Promise<void>;
|
||||
profiles(): Promise<ShellProfile[]>;
|
||||
openWindow(): Promise<void>;
|
||||
dictation(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface OpenOptions extends Omit<PtyRequest, "id"> {
|
||||
/** Raw output. A UTF-8 character can be split between two calls. */
|
||||
onData(data: Uint8Array): void;
|
||||
onExit?(code: number | null): void;
|
||||
}
|
||||
|
||||
export class TerminalSessions {
|
||||
private readonly transport: PtyTransport;
|
||||
private readonly controller = new AbortController();
|
||||
/** The sessions whose shell started and did not exit. */
|
||||
private readonly live = new Set<string>();
|
||||
private readonly opening = new Map<string, Promise<void>>();
|
||||
private readonly closing = new Map<string, Promise<void>>();
|
||||
/** Pane IDs that closed. A closed ID cannot start again. */
|
||||
private readonly closed = new Set<string>();
|
||||
|
||||
constructor(transport: PtyTransport) { this.transport = transport; }
|
||||
|
||||
/** Aborts when the instance stops. Menus of the panel close then. */
|
||||
get signal(): AbortSignal { return this.controller.signal; }
|
||||
get stopped(): boolean { return this.controller.signal.aborted; }
|
||||
|
||||
private check() { if (this.stopped) throw new Error(tr("This feature is off.")); }
|
||||
|
||||
/** Start a shell for pane `id`. */
|
||||
open(id: string, options: OpenOptions): Promise<void> {
|
||||
try {
|
||||
this.check();
|
||||
if (this.closed.has(id)) throw new Error(tr("This terminal is closed."));
|
||||
if (this.live.has(id) || this.opening.has(id)) throw new Error(tr("This terminal is already running."));
|
||||
} catch (reason) { return Promise.reject(reason); }
|
||||
let exited = false;
|
||||
const active = () => !this.closed.has(id) && !this.stopped;
|
||||
const { onData, onExit, ...request } = options;
|
||||
const pending = Promise.resolve().then(() => this.transport.open({ id, ...request },
|
||||
data => { if (active()) onData(data); },
|
||||
code => {
|
||||
if (exited) return;
|
||||
exited = true;
|
||||
this.live.delete(id);
|
||||
if (active()) onExit?.(code);
|
||||
})).then(() => { if (!exited) this.live.add(id); });
|
||||
this.opening.set(id, pending);
|
||||
void pending.finally(() => this.opening.delete(id)).catch(() => {});
|
||||
return pending;
|
||||
}
|
||||
|
||||
private session(id: string) {
|
||||
this.check();
|
||||
if (!this.live.has(id)) throw new Error(tr("This terminal is not running."));
|
||||
}
|
||||
|
||||
async write(id: string, data: string): Promise<void> { this.session(id); await this.transport.write(id, data); }
|
||||
async resize(id: string, cols: number, rows: number): Promise<void> { this.session(id); await this.transport.resize(id, cols, rows); }
|
||||
|
||||
/** Stop the shell of pane `id`. Later calls return the same promise until the close ends. */
|
||||
close(id: string): Promise<void> {
|
||||
this.closed.add(id);
|
||||
const pending = this.closing.get(id);
|
||||
if (pending) return pending;
|
||||
if (!this.live.has(id) && !this.opening.has(id)) return Promise.resolve();
|
||||
const close = Promise.resolve(this.opening.get(id)).catch(() => {})
|
||||
.then(() => this.live.has(id) ? this.transport.close(id) : undefined)
|
||||
.then(() => { this.live.delete(id); })
|
||||
.finally(() => this.closing.delete(id));
|
||||
this.closing.set(id, close);
|
||||
return close;
|
||||
}
|
||||
|
||||
profiles(): Promise<ShellProfile[]> {
|
||||
try { this.check(); } catch (reason) { return Promise.reject(reason); }
|
||||
return this.transport.profiles();
|
||||
}
|
||||
openWindow(): Promise<void> {
|
||||
try { this.check(); } catch (reason) { return Promise.reject(reason); }
|
||||
return this.transport.openWindow();
|
||||
}
|
||||
dictation(): Promise<void> {
|
||||
try { this.check(); } catch (reason) { return Promise.reject(reason); }
|
||||
return this.transport.dictation();
|
||||
}
|
||||
|
||||
/** Stop all sessions. Starts that are in progress finish first, then close. Later opens fail. */
|
||||
async closeAll(): Promise<void> {
|
||||
this.controller.abort();
|
||||
await Promise.allSettled([...this.opening.values()]);
|
||||
const results = await Promise.allSettled([...this.live, ...this.closing.keys()].map(id => this.close(id)));
|
||||
const errors = results.filter(result => result.status === "rejected");
|
||||
if (errors.length) throw new Error(errors.map(result => String(result.reason)).join("\n"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// The terminal colors come from the theme tokens. The 16 ANSI colors use the `--rs-ansi-*` tokens of
|
||||
// src/lib/theme/roles.ts, so the theme editor and custom themes change them. xterm needs hex colors.
|
||||
import type { ITheme } from "@xterm/xterm";
|
||||
import { ANSI_COLORS } from "../../theme/roles.ts";
|
||||
|
||||
/** The highest alpha of the selection, so the selected text stays readable on every background. */
|
||||
export const SELECTION_ALPHA = Math.floor(255 * 0.65);
|
||||
|
||||
type Key = Exclude<keyof ITheme, "extendedAnsi" | "background">;
|
||||
const capitalize = (name: string) => name[0].toUpperCase() + name.slice(1);
|
||||
|
||||
/** The token of each xterm color, and the highest alpha of the color when it has one. */
|
||||
export const TERMINAL_TOKENS: readonly { key: Key; token: string; maxAlpha?: number }[] = [
|
||||
{ key: "foreground", token: "var(--rs-text)" },
|
||||
{ key: "cursor", token: "var(--rs-accent)" },
|
||||
{ key: "cursorAccent", token: "var(--rs-bg)" },
|
||||
{ key: "selectionBackground", token: "var(--rs-selection)", maxAlpha: SELECTION_ALPHA },
|
||||
{ key: "selectionForeground", token: "var(--rs-selection-text, var(--rs-text))" },
|
||||
...ANSI_COLORS.map(color => ({ key: color as Key, token: `var(--rs-ansi-${color})` })),
|
||||
...ANSI_COLORS.map(color => ({ key: `bright${capitalize(color)}` as Key, token: `var(--rs-ansi-bright-${color})` })),
|
||||
];
|
||||
|
||||
/** The xterm theme. `resolve` turns a CSS color into a hex color, with the alpha capped at `maxAlpha`. The background is transparent. */
|
||||
export function terminalColors(resolve: (css: string, maxAlpha: number) => string): ITheme {
|
||||
const theme: ITheme = { background: "#00000000" };
|
||||
for (const { key, token, maxAlpha = 255 } of TERMINAL_TOKENS) theme[key] = resolve(token, maxAlpha);
|
||||
return theme;
|
||||
}
|
||||
|
||||
/** The xterm theme for the tokens that apply to `element`. */
|
||||
export function terminalTheme(element: HTMLElement): ITheme {
|
||||
const probe = document.createElement("span");
|
||||
probe.style.display = "none";
|
||||
element.append(probe);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = canvas.height = 1;
|
||||
const context = canvas.getContext("2d", { willReadFrequently: true })!;
|
||||
try {
|
||||
return terminalColors((value, maxAlpha) => {
|
||||
probe.style.color = value;
|
||||
context.clearRect(0, 0, 1, 1);
|
||||
const resolved = getComputedStyle(probe).color;
|
||||
context.fillStyle = resolved;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
const alpha = context.getImageData(0, 0, 1, 1).data[3];
|
||||
if (maxAlpha < 255) {
|
||||
// Paint the color opaque, so premultiplied alpha does not change the hue.
|
||||
context.fillStyle = `rgb(from ${resolved} r g b / 1)`;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
}
|
||||
const channels = [...context.getImageData(0, 0, 1, 1).data];
|
||||
channels[3] = Math.min(alpha, maxAlpha);
|
||||
return "#" + channels.map(byte => byte.toString(16).padStart(2, "0")).join("");
|
||||
});
|
||||
} finally {
|
||||
probe.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `update` in the next frame after a theme change: the `runestone-theme-changed` event of `applyAppearance`,
|
||||
* or a change of a class, style, or theme attribute of `element` or its parents. Returns the function that stops it.
|
||||
*/
|
||||
export function watchTerminalAppearance(element: HTMLElement, update: () => void): () => void {
|
||||
let frame = 0;
|
||||
const queue = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(update);
|
||||
};
|
||||
const observer = new MutationObserver(queue);
|
||||
for (let node: HTMLElement | null = element; node; node = node.parentElement) {
|
||||
observer.observe(node, { attributes: true, attributeFilter: ["class", "style", "data-theme", "data-palette"] });
|
||||
}
|
||||
observer.observe(document.head, { childList: true, subtree: true, characterData: true });
|
||||
window.addEventListener("runestone-theme-changed", queue);
|
||||
return () => { observer.disconnect(); window.removeEventListener("runestone-theme-changed", queue); cancelAnimationFrame(frame); };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// The desktop side of the terminal: the `pty_*` commands of src-tauri/src/pty.rs.
|
||||
// Each shell sends its output over a channel to this webview only. Output arrives as raw bytes (an ArrayBuffer),
|
||||
// and the exit as `{ exit: code }`. The host checks that each session belongs to the calling window.
|
||||
import { Channel, invoke } from "@tauri-apps/api/core";
|
||||
import type { ShellProfile } from "./model.ts";
|
||||
import type { PtyTransport } from "./sessions.ts";
|
||||
|
||||
/**
|
||||
* The ID of this page load. At the first start in a new page, the host closes the sessions that an earlier page
|
||||
* of the same window left, for example before a reload. Every panel of this page uses the same ID.
|
||||
*/
|
||||
const page = crypto.randomUUID();
|
||||
|
||||
export const desktopTransport: PtyTransport = {
|
||||
open: (request, onData, onExit) => {
|
||||
const channel = new Channel<ArrayBuffer | { exit: number | null }>(message => {
|
||||
if (message instanceof ArrayBuffer) onData(new Uint8Array(message));
|
||||
else if (message && typeof message === "object" && "exit" in message) onExit(message.exit);
|
||||
});
|
||||
return invoke<void>("pty_open", { ...request, page, channel });
|
||||
},
|
||||
write: (id, data) => invoke<void>("pty_write", { id, data }),
|
||||
resize: (id, cols, rows) => invoke<void>("pty_resize", { id, cols, rows }),
|
||||
close: id => invoke<void>("pty_close", { id }),
|
||||
profiles: () => invoke<ShellProfile[]>("pty_profiles"),
|
||||
openWindow: () => invoke<void>("pty_new_window", { id: crypto.randomUUID() }),
|
||||
dictation: () => invoke<void>("pty_dictation"),
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { ITerminalOptions } from "@xterm/xterm";
|
||||
|
||||
/** The code font of the theme, so the terminal and the code editor use the same font and weight. */
|
||||
export function terminalTypography(element: HTMLElement): Pick<ITerminalOptions, "fontFamily" | "fontWeight" | "fontWeightBold"> {
|
||||
const style = getComputedStyle(element);
|
||||
const weight = Number(style.getPropertyValue("--rs-code-font-weight").trim() || 300);
|
||||
return {
|
||||
fontFamily: style.getPropertyValue("--rs-font-mono").trim() || '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace',
|
||||
fontWeight: (Number.isFinite(weight) && weight >= 100 && weight <= 900 ? weight : 300) as ITerminalOptions["fontWeight"],
|
||||
fontWeightBold: 600,
|
||||
};
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
// The xterm style sheet. Vite bundles it with the feature chunk. The unit test type check has no Vite types, so it needs this declaration.
|
||||
declare module "@xterm/xterm/css/xterm.css";
|
||||
@@ -0,0 +1,48 @@
|
||||
// The contract between the hosts of the terminal panel (the workbench and the terminal window) and the Terminal feature.
|
||||
// This file is in the main bundle. It loads no feature code: `terminalInstance` loads the module at first use.
|
||||
import { featureInstance } from "../plugins/external.ts";
|
||||
import type { TerminalAction } from "./terminalKeys.ts";
|
||||
import type { FeatureInstance } from "./types.ts";
|
||||
|
||||
export type { TerminalAction } from "./terminalKeys.ts";
|
||||
|
||||
/** What the host gives to the terminal panel. */
|
||||
export interface TerminalProps {
|
||||
/** The workspace folder. A new terminal starts there. */
|
||||
cwd: string;
|
||||
visible: boolean;
|
||||
maximized?: boolean;
|
||||
/** True in a terminal window, which has no maximize control. */
|
||||
standalone?: boolean;
|
||||
/** The panel closed all its sessions. */
|
||||
onClose: () => void;
|
||||
onMaximize?: () => void;
|
||||
/** True when the active tab is a text file that Run active file can run. */
|
||||
activeFile?: boolean;
|
||||
/** Save the active file and return its absolute path, or null. */
|
||||
onRunFile?: () => Promise<string | null>;
|
||||
/** The selected text of the editor. */
|
||||
getSelection?: () => string;
|
||||
/** Open `.runestone/tasks.json`, and make it first when it does not exist. */
|
||||
onConfigureTasks?: () => Promise<void>;
|
||||
/** Open Settings, where Settings → Terminal is. */
|
||||
onOpenSettings?: () => void;
|
||||
}
|
||||
|
||||
/** One terminal panel in a host element. */
|
||||
export interface TerminalMount {
|
||||
update(props: TerminalProps): void;
|
||||
command(action: Exclude<TerminalAction, "toggle">): Promise<void>;
|
||||
/** Close the sessions of the panel and remove it. */
|
||||
dispose(): Promise<void>;
|
||||
}
|
||||
|
||||
/** The instance of the Terminal feature in one window. */
|
||||
export interface TerminalInstance extends FeatureInstance {
|
||||
mountDock(element: HTMLElement, props: TerminalProps): TerminalMount;
|
||||
}
|
||||
|
||||
/** Load the Terminal feature if necessary and return its instance in this window. Fails while Terminal is off. */
|
||||
export async function terminalInstance(): Promise<TerminalInstance> {
|
||||
return await featureInstance("terminal") as TerminalInstance;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// The shortcuts of the Terminal feature. This file is in the main bundle, because the workbench routes the keys
|
||||
// and Help lists them while the feature code is not loaded yet.
|
||||
import { message } from "../i18n/index.ts";
|
||||
|
||||
/** The actions of a terminal shortcut. "toggle" shows or hides the terminal panel. */
|
||||
export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories";
|
||||
export type TerminalKeyEvent = Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">;
|
||||
|
||||
/** The terminal action of a key event, or null. Backquote and Digit5 match the physical key on each keyboard layout. */
|
||||
export function terminalShortcut(event: TerminalKeyEvent): TerminalAction | null {
|
||||
if (!event.ctrlKey && !event.metaKey) return null;
|
||||
if (event.code === "Backquote" || event.key === "`") return event.shiftKey ? event.altKey ? "window" : "new" : "toggle";
|
||||
if (event.shiftKey && event.code === "Digit5" && !event.altKey) return "split";
|
||||
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "j") return "toggle";
|
||||
if (!event.shiftKey && !event.altKey && event.key === "ArrowUp") return "previous";
|
||||
if (!event.shiftKey && !event.altKey && event.key === "ArrowDown") return "next";
|
||||
if (!event.shiftKey && event.altKey && event.key.toLowerCase() === "r") return "commands";
|
||||
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "g") return "directories";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The written combination of each action, for menus and Help. `keys()` in `src/lib/ui/shortcuts.ts` gives the label. */
|
||||
export const TERMINAL_KEYS = {
|
||||
toggle: "Mod+J",
|
||||
new: "Mod+Shift+`",
|
||||
window: "Mod+Shift+Alt+`",
|
||||
split: "Mod+Shift+5",
|
||||
previous: "Mod+ArrowUp",
|
||||
next: "Mod+ArrowDown",
|
||||
commands: "Mod+Alt+R",
|
||||
directories: "Mod+G",
|
||||
} as const satisfies Record<TerminalAction, string>;
|
||||
|
||||
/** The Terminal rows of Help. They show only while Terminal is on. */
|
||||
export const TERMINAL_SHORTCUTS: readonly { label: string; keys: string }[] = [
|
||||
{ label: message("Show or hide the terminal"), keys: TERMINAL_KEYS.toggle },
|
||||
{ label: message("New terminal"), keys: TERMINAL_KEYS.new },
|
||||
{ label: message("New terminal window"), keys: TERMINAL_KEYS.window },
|
||||
{ label: message("Split terminal"), keys: TERMINAL_KEYS.split },
|
||||
{ label: message("Scroll to the previous command"), keys: TERMINAL_KEYS.previous },
|
||||
{ label: message("Scroll to the next command"), keys: TERMINAL_KEYS.next },
|
||||
{ label: message("Run a recent command"), keys: TERMINAL_KEYS.commands },
|
||||
{ label: message("Go to a recent folder"), keys: TERMINAL_KEYS.directories },
|
||||
{ label: message("Copy the selected output"), keys: "Mod+Shift+C" },
|
||||
];
|
||||
@@ -0,0 +1,76 @@
|
||||
// The settings of the Terminal feature: the `terminal` section of the settings file.
|
||||
// This file is in the main bundle, because Settings → Terminal and the first-start migration need it without xterm.
|
||||
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
|
||||
|
||||
export interface TerminalSettings {
|
||||
/** The profile of a new terminal. An empty value or an unknown profile selects the first shell that is not Node.js. */
|
||||
defaultProfile: string;
|
||||
/** From 9 to 28 pixels. */
|
||||
fontSize: number;
|
||||
/** From 100 to 100,000 lines. */
|
||||
scrollback: number;
|
||||
cursorBlink: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_TERMINAL: Readonly<TerminalSettings> = Object.freeze({ defaultProfile: "", fontSize: 13, scrollback: 10000, cursorBlink: true });
|
||||
export const FONT_SIZE = { min: 9, max: 28 } as const;
|
||||
export const SCROLLBACK = { min: 100, max: 100000 } as const;
|
||||
/** The localStorage key of the Terminal plugin. The first start copies it into the `terminal` section and keeps it. */
|
||||
export const LEGACY_TERMINAL_KEY = "runestone.terminal";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
const limit = (value: unknown, range: { min: number; max: number }, fallback: number) =>
|
||||
typeof value === "number" && Number.isFinite(value) ? Math.min(range.max, Math.max(range.min, Math.round(value))) : fallback;
|
||||
|
||||
/** Valid settings from any value. Invalid fields take the defaults. */
|
||||
export function normalizeTerminal(value: unknown): TerminalSettings {
|
||||
const raw = record(value);
|
||||
return {
|
||||
defaultProfile: typeof raw.defaultProfile === "string" ? raw.defaultProfile : DEFAULT_TERMINAL.defaultProfile,
|
||||
fontSize: limit(raw.fontSize, FONT_SIZE, DEFAULT_TERMINAL.fontSize),
|
||||
scrollback: limit(raw.scrollback, SCROLLBACK, DEFAULT_TERMINAL.scrollback),
|
||||
cursorBlink: typeof raw.cursorBlink === "boolean" ? raw.cursorBlink : DEFAULT_TERMINAL.cursorBlink,
|
||||
};
|
||||
}
|
||||
|
||||
export function readTerminal(): TerminalSettings {
|
||||
return normalizeTerminal(readSection("terminal"));
|
||||
}
|
||||
|
||||
/** Save the settings. Keys of a newer version stay. */
|
||||
export function writeTerminal(next: TerminalSettings): Promise<void> {
|
||||
return writeSection("terminal", { ...record(readSection("terminal")), ...normalizeTerminal(next) });
|
||||
}
|
||||
|
||||
/** Run `listener` after each change of the terminal settings in any window. Returns the function that stops it. */
|
||||
export function onTerminalChange(listener: () => void): () => void {
|
||||
return onSettingsChange("terminal", listener);
|
||||
}
|
||||
|
||||
/** The host side of the first-start migration of the `terminal` section. */
|
||||
export interface TerminalMigrationHost {
|
||||
/** True when the settings file has no `terminal` section. */
|
||||
missing(): boolean;
|
||||
/** The value of the old localStorage key, or null. */
|
||||
legacy(): string | null;
|
||||
write(value: TerminalSettings): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the `terminal` section from the localStorage key of the Terminal plugin. The old key stays, so an older version keeps it.
|
||||
* Without an old key, nothing is written and the defaults apply. Returns the written settings, or null.
|
||||
*/
|
||||
export async function migrateTerminal(host: TerminalMigrationHost): Promise<TerminalSettings | null> {
|
||||
if (!host.missing()) return null;
|
||||
let raw: string | null;
|
||||
try { raw = host.legacy(); } catch { return null; }
|
||||
if (raw === null) return null;
|
||||
let parsed: unknown;
|
||||
try { parsed = JSON.parse(raw); } catch { parsed = null; }
|
||||
const value = normalizeTerminal(parsed);
|
||||
await host.write(value);
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { Dispose, PluginDocumentContext } from "../plugins/sdk.ts";
|
||||
|
||||
/** The host services that a running feature gets. A feature also uses other host modules directly. */
|
||||
export interface FeatureContext {
|
||||
/** Open a view of this feature, as a tab or in the side pane. */
|
||||
openView(id: string): void;
|
||||
/** Open a workspace file in the editor. */
|
||||
openFile(path: string): Promise<void>;
|
||||
/**
|
||||
* Run `listener` after each change in the workspace. `paths` lists the changed workspace paths, also in `.runestone/`.
|
||||
* Without `paths`, the change is unknown, and the feature reads its data again. Returns the function that stops it.
|
||||
*/
|
||||
onWorkspaceChange(listener: (paths?: readonly string[]) => void): () => void;
|
||||
/** Give a view of a view pattern its title, for example the name of a board. Its tabs show the title. */
|
||||
setViewTitle(id: string, title: string): void;
|
||||
/** Close the tabs of a view. */
|
||||
closeView(id: string): void;
|
||||
/** Show the view `next` in the tab of the view `current`. The tab keeps its place and its pin. */
|
||||
replaceView(current: string, next: string): void;
|
||||
}
|
||||
|
||||
/** One running copy of a feature in one window. */
|
||||
export interface FeatureInstance {
|
||||
mount(view: string, element: HTMLElement): Dispose | Promise<Dispose>;
|
||||
/**
|
||||
* Show a document of a catalog document type in `element`. `document.path` follows a rename of the file.
|
||||
* The returned function removes the document and stops its work, for example a worker.
|
||||
*/
|
||||
mountDocument?(type: string, element: HTMLElement, document: PluginDocumentContext): Dispose | Promise<Dispose>;
|
||||
/** Open a view with `launch` in the catalog. The feature chooses the view, for example the default board. */
|
||||
launch?(view: string): void | Promise<void>;
|
||||
/** Run a command of the catalog that has no view. */
|
||||
run?(command: string): void | Promise<void>;
|
||||
/** The state of a tab for a transfer to another window. */
|
||||
saveTabState?(view: string): unknown;
|
||||
restoreTabState?(view: string, state: unknown): void | Promise<void>;
|
||||
/** Stop all work. The host unmounts the views first. */
|
||||
dispose(): void | Promise<void>;
|
||||
}
|
||||
|
||||
/** The module that `loader.ts` imports at first need. */
|
||||
export interface FeatureModule {
|
||||
start(context: FeatureContext): FeatureInstance;
|
||||
/** Show the settings of the feature in `element`, also in a window where the feature does not run. */
|
||||
mountSettings?(element: HTMLElement): Dispose;
|
||||
}
|
||||
Reference in New Issue
Block a user