Files
RuneStone/src/lib/plugins/PluginManager.svelte
T
Knotty Wyvern 5bd616d7fd Give themes named color roles, theme data files, and file format 3
Phase 5a-1 and 5a-2.

- roles.ts names 51 color roles. One derivation rule fills the roles
  that a theme does not give, for all themes. tokens.css keeps only the
  root defaults, without theme blocks.
- Each built-in theme is one data file in src/lib/theme/themes/. No code
  outside the theme data names a theme ID. characterThemes.ts is gone.
- New roles: link, focus, on-accent, highlight, scrim, the syntax roles,
  and 16 terminal (ANSI) roles. Stray colors in components use the roles.
- contrast.ts checks each theme against the readability rules of
  docs/ui-color.md. The tests mark the known palette failures as todo,
  and a second test fails when a known failure starts to pass.
- Theme files use schema 3 with a mode and an optional built-in base.
  A short file gets the missing colors and fonts from the base. Schema 1
  and 2 files still import. Old syntax names convert on import.
- Docs: ui-color.md, plugin-development.md (theme tokens), ui-design.md,
  guides/themes.md, and UI-041 and UI-042 in design-decisions.md.

The applied colors stay the same for every built-in theme, except three
small changes: the conflict line uses the warn color, the Write
highlight uses the highlight role, and two dialog backdrops use the
scrim role.

pnpm check passes. pnpm test: 447 pass, 31 todo, 0 fail. Full smoke
suite: 93 passed, 2 known. appearance/palettes read the old syntax
names and passed 3 of 3 times after the fix. workspace/manageTemplates
failed one time and passed on retry.
2026-10-28 15:50:45 -07:00

239 lines
17 KiB
Svelte

<script lang="ts">
import { t } from "$lib/i18n";
import { onDestroy } from "svelte";
import { invoke, isTauri } from "@tauri-apps/api/core";
import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { builtInPackages, installedPlugins, externalErrors, pluginServiceError, restartPlugins, refreshPlugins, setPluginEnabled } from "./external";
import type { Candidate, RemovalPlan, InstalledPlugin } from "./sdk";
const desktop = isTauri();
const installDateFormat = new Intl.DateTimeFormat(undefined, {
year: "numeric", month: "short", day: "numeric",
hour: "numeric", minute: "2-digit", second: "2-digit", timeZoneName: "short",
});
let busy = $state(false);
let error = $state("");
let message = $state("");
let candidates = $state<Candidate[]>([]);
let selected = $state<string[]>([]);
let plan = $state<RemovalPlan | null>(null);
let gitForm = $state(false);
let gitUrl = $state("");
let gitTag = $state("");
let gitToken = $state("");
let disposed = false;
let modal: HTMLDialogElement | undefined = $state();
let cancelButton: HTMLButtonElement | undefined = $state();
let previous: HTMLElement | null = null;
const external = $derived($installedPlugins.plugins);
const hasUpdates = $derived(candidates.some(candidate => external.some(plugin => plugin.manifest.id === candidate.manifest?.id)));
$effect(() => {
if (modal && (plan || candidates.length || gitForm)) {
if (!modal.open) { previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; modal.showModal(); }
if (!busy) cancelButton?.focus();
}
});
function tokens() { return [...candidates.map(item => item.token), ...(plan ? [plan.token] : [])]; }
async function cancel() {
if (busy) return;
const pending = tokens();
plan = null; candidates = []; selected = []; gitForm = false; gitToken = "";
modal?.close(); previous?.focus();
if (pending.length) await invoke("plugins_cancel", { tokens: pending }).catch(reason => error = String(reason));
}
onDestroy(() => { disposed = true; gitToken = ""; const pending = tokens(); if (pending.length) void invoke("plugins_cancel", { tokens: pending }).catch(() => {}); });
async function run(action: () => Promise<void>) {
busy = true; error = ""; message = "";
try { await action(); } catch (reason) { error = String(reason); }
finally { busy = false; }
}
async function choose() {
await run(async () => {
candidates = await invoke<Candidate[]>("plugins_choose");
selected = candidates.filter(item => !item.error && item.manifest).map(item => item.token);
});
}
async function install(enabled: boolean) {
await run(async () => {
const result = await invoke<{ name: string; error: string | null }[]>("plugins_install", { tokens: selected, enabled });
message = result.filter(item => !item.error).map(item => $t("{name}: package applied.", { name: item.name })).join(" ");
error = result.filter(item => item.error).map(item => `${item.name}: ${item.error}`).join("\n");
await invoke("plugins_cancel", { tokens: candidates.map(item => item.token) });
candidates = []; selected = []; await refreshPlugins(); previous?.focus();
});
}
async function fromGit() {
await run(async () => {
try {
const result = await invoke<Candidate[]>("plugins_from_git", { url: gitUrl.trim(), tag: gitTag.trim(), token: gitToken || null });
if (disposed) { await invoke("plugins_cancel", { tokens: result.map(item => item.token) }); return; }
candidates = result;
selected = result.filter(item => !item.error && item.manifest).map(item => item.token);
gitForm = false;
} finally { gitToken = ""; }
});
}
async function toggle(id: string, enabled: boolean, hash?: string) {
await run(async () => {
await setPluginEnabled(id, enabled, hash);
message = $t("Changes saved.");
});
}
async function prepare(plugin: InstalledPlugin) {
await run(async () => { plan = await invoke<RemovalPlan>("plugins_prepare_remove", { id: plugin.manifest.id }); });
}
async function remove() {
if (!plan) return;
const current = plan;
await run(async () => {
try { await invoke("plugins_remove", { token: current.token }); message = $t("{name} uninstalled. Settings and workspace documents were kept.", { name: current.plugin.manifest.name }); }
finally { plan = null; await refreshPlugins(); previous?.focus(); }
});
}
async function reveal(id?: string) { await run(async () => { await invoke("plugins_reveal", { id: id ?? null }); }); }
function trap(event: KeyboardEvent) {
event.stopPropagation();
if (event.repeat && (event.key === "Enter" || event.key === " ")) event.preventDefault();
if (event.key !== "Tab" || !modal) return;
const controls = [...modal.querySelectorAll<HTMLElement>("button:not(:disabled),input:not(:disabled),select:not(:disabled)")];
const first = controls[0], last = controls.at(-1);
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
}
</script>
<h2>{$t("Plug-ins")}</h2>
<p>{$t("Install a plugin ZIP file or get a release from a Git repository link.")}</p>
<p>{$t("To update a plugin, select its new ZIP or release link. Its settings and enabled state stay the same.")}</p>
<div class="toolbar">
<button disabled={!desktop || busy} onclick={() => choose()}><Icon icon="file-plus" />{$t("Install plugin ZIP")}</button>
<button disabled={!desktop || busy} onclick={() => { error = ""; gitForm = true; }}><Icon icon="link" />{$t("Install from Git link")}</button>
<IconButton icon="folder-open" label={$t("Open plugins folder")} disabled={!desktop || busy} onclick={() => reveal()} />
<button disabled={!desktop || busy} onclick={() => run(refreshPlugins)}><Icon icon="refresh" />{$t("Refresh")}</button>
</div>
{#if $installedPlugins.root}<p class="path">{$installedPlugins.root}</p>{/if}
{#if !desktop}<p>{$t("Installation requires the RuneStone desktop app.")}</p>{/if}
{#if $pluginServiceError}<p class="error" role="alert">{$pluginServiceError}</p>{/if}
<h3>{$t("Installed plugins")}</h3>
<p class="note">{$t("Plugins run with RuneStone's access. Only enable code you trust.")}</p>
{#if !external.length}<p>{$t("No plugins installed.")}</p>{/if}
{#each external as plugin (plugin.manifest.id)}
<div class="card">
<div class="row">
<div class="plugin-copy"><label for={`external-${plugin.manifest.id}`}>{plugin.manifest.name}</label><p>{plugin.manifest.description}</p><small>{plugin.manifest.author} · {plugin.manifest.version} · {$t("Full app access")}</small>
<div class="status">
<span class="badge">{builtInPackages.includes(plugin.manifest.id) ? $t("Included with RuneStone") : plugin.removal ? $t("Removal incomplete") : plugin.enabled ? $t("Enabled") : $t("Disabled")}</span>
<span class="note">
{#if plugin.installedAt != null}
{$t("Installed")} <time datetime={new Date(plugin.installedAt).toISOString()}>{installDateFormat.format(plugin.installedAt)}</time>
{:else}
{$t("Install date unknown")}
{/if}
</span>
</div>
</div>
<div class="controls">
<input id={`external-${plugin.manifest.id}`} type="checkbox" role="switch" checked={builtInPackages.includes(plugin.manifest.id) || plugin.enabled} disabled={busy || plugin.removal || builtInPackages.includes(plugin.manifest.id)} onchange={event => { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} />
<IconButton icon="folder-open" label={$t("Show files")} disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)} />
{#if plugin.removal}
<button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = $t("Plugin file cleanup completed."); })}><Icon icon="refresh" />{$t("Retry cleanup")}</button>
{:else}
<span class="danger"><IconButton icon="trash" label={$t("Uninstall")} disabled={busy} onclick={() => prepare(plugin)} /></span>
{/if}
</div>
</div>
{#if plugin.manifest.id === "runestone.browser"}<p class="note">{$t("Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.")}</p>{/if}
{#if plugin.manifest.id === "runestone.table-formulas"}<p class="note">{$t("Table Formulas is now built in. You can remove this old package. Your formulas stay in your files. To turn formulas on or off, go to Settings → General.")}</p>{/if}
{#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if}
</div>
{/each}
{#if $restartPlugins.length}<p class="note" role="status">{$t("Restart RuneStone to clear all code from plugins that stopped in this window.")}</p>{/if}
{#if error}<p class="error" role="alert">{error}</p>{/if}
{#if message}<p class="saved" role="status">{message}</p>{/if}
{#if candidates.length || plan || gitForm}
<dialog bind:this={modal} aria-labelledby="plugin-dialog-title" onkeydown={trap} oncancel={event => { event.preventDefault(); event.stopPropagation(); void cancel(); }}>
{#if gitForm}
<h2 id="plugin-dialog-title">{$t("Install from Git link")}</h2>
<p>{$t("Get a Gitea release ZIP, then review it before installation. Git-link installation is an experimental feature.")}</p>
<form onsubmit={event => { event.preventDefault(); if (!busy) void fromGit(); }}>
<label class="field">{$t("Repository link")}<input type="url" required bind:value={gitUrl} disabled={busy} placeholder="https://host/owner/repository" /></label>
<label class="field">{$t("Release tag (optional)")}<input bind:value={gitTag} disabled={busy} placeholder={$t("Latest release")} maxlength="200" /></label>
<label class="field">{$t("Access token (optional)")}<input type="password" bind:value={gitToken} disabled={busy} autocomplete="off" /></label>
<p class="note">{$t("Private repositories need a token with read access. RuneStone does not save the token.")}</p>
{#if gitUrl.trim().startsWith("http:")}<p class="note">{$t("HTTP sends the token and package without encryption. Use it only for a trusted local server.")}</p>{/if}
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer><button type="button" bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button type="submit" disabled={busy || !gitUrl.trim()}><Icon icon="link" />{busy ? $t("Downloading…") : $t("Review release")}</button></footer>
</form>
{:else if plan}
<h2 id="plugin-dialog-title">{$t("Uninstall {name}?", { name: plan.plugin.manifest.name })}</h2>
<p>{plan.plugin.manifest.author} · {plan.plugin.manifest.version}</p>
<p class="path">{plan.plugin.path}</p>
<p>{$t("This stops the plugin in every window and permanently deletes its installed folder. Settings, source packages, and workspace documents stay intact.")}</p>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer>
<button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button>
<button disabled={busy} onclick={async () => { const current = plan; await cancel(); if (current) await toggle(current.plugin.manifest.id, false); }}>{$t("Disable instead")}</button>
<button class="danger" disabled={busy} onclick={event => { if (event.detail < 2) void remove(); }}>{busy ? $t("Removing…") : $t("Uninstall and delete files")}</button>
</footer>
{:else}
<h2 id="plugin-dialog-title">{$t("Review plugin installation")}</h2>
<p>{$t("Plugins run with RuneStone's access. Only enable code you trust.")}</p>
{#each candidates as candidate (candidate.token)}
<div class="candidate">
<label><input type="checkbox" bind:group={selected} value={candidate.token} disabled={busy || !!candidate.error} />{candidate.manifest?.name ?? $t("Invalid package")}</label>
{#if candidate.manifest}<p>{candidate.manifest.author} · {candidate.manifest.version}</p><p>{candidate.manifest.description}</p><p class="path">{$t("Destination: {path}", { path: `${$installedPlugins.root}\\${candidate.manifest.id}` })}</p>{/if}
{#each external.filter(plugin => plugin.manifest.id === candidate.manifest?.id) as installed}
<p>{$t("Update {current} → {next}. Settings and enabled state stay the same.", { current: installed.manifest.version, next: candidate.manifest!.version })}</p>
{/each}
<p class="path">{$t("Source: {path}", { path: candidate.source })}</p>
{#if candidate.error}<p class="error">{candidate.error}</p>{/if}
</div>
{/each}
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button disabled={busy || !selected.length} onclick={() => install(false)}>{$t(hasUpdates ? "Apply packages" : "Install")}</button>{#if !hasUpdates}<button disabled={busy || !selected.length} onclick={() => install(true)}>{$t("Install and enable")}</button>{/if}</footer>
{/if}
</dialog>
{/if}
<style>
h2 { margin: 0; font-size: var(--rs-settings-heading-size); color: var(--rs-text-strong); }
h3 { font-size: 13px; margin: var(--rs-settings-section-gap) 0 8px; }
p { margin: 6px 0 10px; color: var(--rs-text-dim); line-height: 1.45; }
button { display: inline-flex; align-items: center; justify-content: center; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); padding: 4px 8px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
button:hover:not(:disabled) { background: var(--rs-bg-active); }
button:disabled { opacity: .5; }
.toolbar, footer { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); }
.card { border-bottom: 1px solid var(--rs-border); }
.row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: var(--rs-settings-row-padding) 0; }
.plugin-copy { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.row p { margin: 3px 0; font-size: var(--rs-settings-description-size); }
label { font-weight: 500; }
.path { overflow-wrap: anywhere; font-size: 11px; }
small, .badge, .note { color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); }
.status { display: flex; flex-wrap: wrap; align-items: center; gap: 2px 8px; margin-top: 3px; }
.controls { display: flex; flex: 0 0 auto; align-items: center; gap: 4px; }
.controls .danger { display: flex; }
.controls .danger :global(.icon-btn) { color: var(--rs-error); }
.error { color: var(--rs-error); white-space: pre-wrap; }
.saved { color: var(--rs-ok); min-height: 20px; }
.danger { color: var(--rs-error); }
input[role=switch] { appearance: none; width: 38px; height: 22px; flex: 0 0 38px; margin: 0 4px 0 0; border-radius: 20px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); cursor: pointer; }
input[role=switch]::before { content: ""; display: block; width: 16px; height: 16px; margin: 2px; background: var(--rs-text); border-radius: 50%; }
input[role=switch]:checked { background: var(--rs-accent); border-color: var(--rs-accent); }
input[role=switch]:checked::before { transform: translateX(16px); background: var(--rs-bg); }
dialog { width: min(650px, 90vw); max-height: 85vh; padding: 16px; color: var(--rs-text); background: var(--rs-bg); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
dialog::backdrop { background: var(--rs-scrim); }
footer { justify-content: flex-end; margin-top: var(--rs-settings-section-gap); }
.candidate { padding: var(--rs-settings-row-padding) 0; border-bottom: 1px solid var(--rs-border); }
.candidate label { display: flex; gap: 8px; }
input[type=checkbox] { accent-color: var(--rs-accent); }
.field { display: flex; flex-direction: column; gap: 6px; margin: 10px 0; }
.field input { min-width: 0; min-height: var(--rs-settings-control-height); padding: 4px 8px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
@media (max-width: 420px) {
.row { flex-wrap: wrap; }
.plugin-copy { flex-basis: 100%; }
.controls { margin-left: auto; }
}
</style>