Make Git a native feature with an off switch

- Add the native feature runtime in src/lib/features/: the catalog, the switches, the first-start migration, the loader, and the feature sessions.
- Add Settings → Features and the features settings section.
- Add features_legacy. It reads the old plugin packages and changes nothing.
- Move Git from the plugin into src/lib/features/git/, on host internals.
- Remove api.git, the git contribution key, and the SDK Git types.
- Add pnpm check:features. It fails when a feature module loads at start.
- Update the tests, the menu inventory, the docs, and UI-055.
This commit is contained in:
Knotty Wyvern
2026-10-29 15:51:21 -07:00
parent 58f77b2e9f
commit d3218b2501
68 changed files with 2068 additions and 324 deletions
+68
View File
@@ -0,0 +1,68 @@
// 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, and commands.
// 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 { PluginView } from "../plugins/sdk.ts";
export type FeatureId = "git";
/** 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;
}
/** A command of a feature. The command palette lists it. */
export interface FeatureCommandInfo {
id: string;
title: () => string;
icon?: PluginView["icon"];
/** The view that the command opens. */
view: string;
}
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;
views: readonly FeatureViewInfo[];
commands: readonly FeatureCommandInfo[];
}
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,
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" }],
},
];
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);
}
+20
View File
@@ -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>
+39
View File
@@ -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-bg-active); }
.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>
+244
View File
@@ -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-bg-active); }
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-bg-active); }
.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>
+201
View File
@@ -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("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-bg-active); }
.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-bg-active); }
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-bg-active); }
.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>
+62
View File
@@ -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++; },
};
}
+86
View File
@@ -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 };
}
+20
View File
@@ -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;
}
+41
View File
@@ -0,0 +1,41 @@
// 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"),
};
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);
}
+60
View File
@@ -0,0 +1,60 @@
// The first start of a version with a new native feature. The switch takes the state of the old plugin package.
// `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing.
import { invoke, isTauri } from "@tauri-apps/api/core";
import { readSection, writeSection } from "../settings/store.ts";
import { FEATURES, type FeatureEntry, type FeatureId } from "./catalog.ts";
import { storedSwitches } from "./state.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, the default of the feature applies. */
export function legacySwitch(entry: FeatureEntry, legacy: LegacyPlugin | undefined): boolean {
return 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 }),
};
/**
* Give each feature without a stored switch the state of its old package. It runs before the first render.
* When the host cannot report the packages, nothing is written, so the next start tries again.
*/
export async function migrateFeatures(host: MigrationHost = desktopHost): Promise<FeatureId[]> {
const current = host.read();
const stored = storedSwitches(current);
const missing = FEATURES.filter(entry => stored[entry.id] === undefined);
if (!missing.length) return [];
let legacy: LegacyPlugin[];
try { legacy = await host.legacy(missing.map(entry => entry.owner)); }
catch (reason) {
console.error("RuneStone could not read the old plugin packages. The feature defaults apply.", reason);
return [];
}
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);
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));
}
+81
View File
@@ -0,0 +1,81 @@
// A feature in the workbench of one window. Its views and commands come from the static catalog, so the
// navigation buttons and the command palette show them without the feature code. The first mount,
// restore, or command loads the feature module and starts one instance for this window.
import { tr } from "../i18n/index.ts";
import type { Dispose, PluginCommand, 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;
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); },
});
}
for (const info of entry.commands) {
this.commands.set(info.id, { id: info.id, get title() { return info.title(); }, icon: info.icon, run: () => context.openView(info.view) });
}
}
/** 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);
}
async mount(id: string, element: HTMLElement): Promise<Dispose> {
const view = this.views.get(id);
if (!view) throw new Error(tr("This view is unavailable."));
const dispose = await view.mount(element);
return async () => {
if (typeof dispose === "function") await dispose();
element.replaceChildren();
};
}
async launch(id: string) { this.context.openView(id); }
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();
}
}
+41
View File
@@ -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 });
}
+26
View File
@@ -0,0 +1,26 @@
import type { Dispose } 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. Returns the function that stops it. */
onWorkspaceChange(listener: () => void): () => void;
}
/** One running copy of a feature in one window. */
export interface FeatureInstance {
mount(view: string, element: HTMLElement): Dispose | Promise<Dispose>;
/** 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;
}
+64 -2
View File
@@ -1,2 +1,64 @@
// The Git types are part of the public plugin SDK (packages/plugin-sdk/src/git.ts).
export type { GitApi, GitChange, GitCommitDetails, GitCommitFile, GitGraph, GitGraphCommit, GitLineInfo, GitStatus } from "../plugins/sdk.ts";
// The Git types of the host. `src-tauri/src/git.rs` runs the `git` program for the workspace of the window.
// The Git feature (`src/lib/features/git/`) and the blame line of the editor use them.
export interface GitChange {
path: string;
originalPath?: string;
index: string;
worktree: string;
}
export interface GitStatus {
available: boolean;
repository: boolean;
branch: string | null;
changes: GitChange[];
}
export interface GitLineInfo {
commit: string;
author: string;
/** The author date in ISO 8601 format. */
date: string;
summary: string;
}
export interface GitApi {
status(): Promise<GitStatus>;
diff(path: string, staged: boolean): Promise<string>;
stage(paths: string[]): Promise<void>;
unstage(paths: string[]): Promise<void>;
commit(message: string): Promise<void>;
push(): Promise<void>;
pull(): Promise<void>;
graph(): Promise<GitGraph>;
commitDetails(commit: string): Promise<GitCommitDetails>;
commitDiff(commit: string, path: string): Promise<string>;
blame(path: string, line: number): Promise<GitLineInfo | null>;
}
export interface GitGraphCommit {
id: string;
parents: string[];
refs: string[];
summary: string;
author: string;
date: string;
}
export interface GitGraph {
commits: GitGraphCommit[];
}
export interface GitCommitFile {
path: string;
originalPath?: string;
status: string;
}
export interface GitCommitDetails {
id: string;
parents: string[];
author: string;
date: string;
message: string;
files: GitCommitFile[];
}
+72
View File
@@ -3443,6 +3443,78 @@ export const messageRows: [string, string, string, string][] = [
["Install the browser engine to see the browser bookmarks.", "Installez le moteur du navigateur pour voir les signets du navigateur.", "ブラウザーのブックマークを表示するには、ブラウザーエンジンをインストールしてください。", "安装浏览器引擎后即可查看浏览器书签。"],
["The other browser settings show after the engine is installed.", "Les autres paramètres du navigateur s’affichent une fois le moteur installé.", "その他のブラウザー設定は、エンジンのインストール後に表示されます。", "安装引擎后将显示其他浏览器设置。"],
["Engine", "Moteur", "エンジン", "引擎"],
["Features", "Fonctionnalités", "機能", "功能"],
["Turn off the features that you do not use. A feature that is off does not load, and its controls do not show.", "Désactivez les fonctionnalités que vous n’utilisez pas. Une fonctionnalité désactivée ne se charge pas et ses commandes ne s’affichent pas.", "使わない機能はオフにします。オフの機能は読み込まれず、そのコントロールも表示されません。", "关闭不使用的功能。已关闭的功能不会加载,其控件也不会显示。"],
["{name} could not load: {error}", "Impossible de charger {name} : {error}", "{name} を読み込めませんでした: {error}", "无法加载 {name}:{error}"],
["This feature is off.", "Cette fonctionnalité est désactivée.", "この機能はオフです。", "此功能已关闭。"],
["This view is unavailable.", "Cette vue n’est pas disponible.", "このビューは使用できません。", "此视图不可用。"],
["This command is unavailable.", "Cette commande n’est pas disponible.", "このコマンドは使用できません。", "此命令不可用。"],
["This feature cannot receive this tab.", "Cette fonctionnalité ne peut pas recevoir cet onglet.", "この機能はこのタブを受け取れません。", "此功能无法接收此标签页。"],
["Git", "Git", "Git", "Git"],
["Review changes, stage files, commit, and see the commit graph of the workspace repository.", "Examinez les modifications, indexez des fichiers, validez et consultez le graphe des commits du dépôt de l’espace de travail.", "ワークスペースのリポジトリで変更の確認、ファイルのステージ、コミット、コミットグラフの表示を行います。", "查看更改、暂存文件、提交,并查看工作区仓库的提交图。"],
["Source control", "Contrôle de code source", "ソース管理", "源代码管理"],
["Git source control", "Contrôle de code source Git", "Git ソース管理", "Git 源代码管理"],
["Git diff", "Diff Git", "Git の差分", "Git 差异"],
["Git graph", "Graphe Git", "Git グラフ", "Git 图"],
["Git history", "Historique Git", "Git の履歴", "Git 历史"],
["Show Git graph", "Afficher le graphe Git", "Git グラフを表示", "显示 Git 图"],
["Refresh source control", "Actualiser le contrôle de code source", "ソース管理を更新", "刷新源代码管理"],
["Pull from the upstream branch", "Récupérer depuis la branche amont", "上流ブランチからプル", "从上游分支拉取"],
["Push to the upstream branch", "Envoyer vers la branche amont", "上流ブランチにプッシュ", "推送到上游分支"],
["Pull in progress…", "Récupération en cours…", "プル中…", "正在拉取…"],
["Pull complete. The branch is up to date.", "Récupération terminée. La branche est à jour.", "プルが完了しました。ブランチは最新です。", "拉取完成。分支已是最新。"],
["Push in progress…", "Envoi en cours…", "プッシュ中…", "正在推送…"],
["Push complete.", "Envoi terminé.", "プッシュが完了しました。", "推送完成。"],
["Loading repository…", "Chargement du dépôt…", "リポジトリを読み込み中…", "正在加载仓库…"],
["Commit message", "Message de commit", "コミットメッセージ", "提交信息"],
["Commit staged", "Valider les modifications indexées", "ステージ済みをコミット", "提交已暂存的更改"],
["Only staged files enter the commit. Press {shortcut} to commit.", "Seuls les fichiers indexés entrent dans le commit. Appuyez sur {shortcut} pour valider.", "コミットに含まれるのはステージ済みのファイルだけです。{shortcut} でコミットします。", "只有已暂存的文件会进入提交。按 {shortcut} 提交。"],
["Commit created.", "Commit créé.", "コミットを作成しました。", "已创建提交。"],
["Changes ({count})", "Modifications ({count})", "変更 ({count})", "更改 ({count})"],
["Staged changes ({count})", "Modifications indexées ({count})", "ステージ済みの変更 ({count})", "已暂存的更改 ({count})"],
["Stage all", "Tout indexer", "すべてステージ", "全部暂存"],
["Unstage all", "Tout désindexer", "すべてステージ解除", "全部取消暂存"],
["Stage {path}", "Indexer {path}", "{path} をステージ", "暂存 {path}"],
["Unstage {path}", "Désindexer {path}", "{path} のステージを解除", "取消暂存 {path}"],
["{path} — {status}", "{path} — {status}", "{path} — {status}", "{path} — {status}"],
["{path} — {status}, from {original}", "{path} — {status}, depuis {original}", "{path} — {status}(元: {original})", "{path} — {status},来自 {original}"],
["Conflict", "Conflit", "競合", "冲突"],
["New", "Nouveau", "新規", "新文件"],
["Added", "Ajouté", "追加", "已添加"],
["Modified", "Modifié", "変更", "已修改"],
["Deleted", "Supprimé", "削除", "已删除"],
["Renamed", "Renommé", "名前変更", "已重命名"],
["Type changed", "Type modifié", "種類の変更", "类型已更改"],
["Git is not installed. Install Git, then restart RuneStone.", "Git n’est pas installé. Installez Git, puis redémarrez RuneStone.", "Git がインストールされていません。Git をインストールしてから RuneStone を再起動してください。", "未安装 Git。请安装 Git,然后重新启动 RuneStone。"],
["Open a Git repository root as your workspace. Create repositories with Git outside RuneStone.", "Ouvrez la racine d’un dépôt Git comme espace de travail. Créez les dépôts avec Git en dehors de RuneStone.", "Git リポジトリのルートをワークスペースとして開いてください。リポジトリは RuneStone の外で Git を使って作成します。", "请将 Git 仓库的根目录作为工作区打开。请在 RuneStone 之外使用 Git 创建仓库。"],
["Resolve the conflicts, then stage the files before you commit.", "Résolvez les conflits, puis indexez les fichiers avant de valider.", "競合を解決してから、コミットの前にファイルをステージしてください。", "请解决冲突,然后在提交前暂存文件。"],
["No changes. Your working tree is clean.", "Aucune modification. Votre arbre de travail est propre.", "変更はありません。作業ツリーはクリーンです。", "没有更改。工作树是干净的。"],
["Open file", "Ouvrir le fichier", "ファイルを開く", "打开文件"],
["{path} · Staged", "{path} · Indexé", "{path} · ステージ済み", "{path} · 已暂存"],
["{path} · Working tree", "{path} · Arbre de travail", "{path} · 作業ツリー", "{path} · 工作树"],
["Select a file in Source control to see its diff.", "Sélectionnez un fichier dans Contrôle de code source pour voir son diff.", "差分を表示するには、ソース管理でファイルを選択してください。", "在源代码管理中选择一个文件以查看其差异。"],
["Loading diff…", "Chargement du diff…", "差分を読み込み中…", "正在加载差异…"],
["No text changes.", "Aucune modification de texte.", "テキストの変更はありません。", "没有文本更改。"],
["Commit graph", "Graphe des commits", "コミットグラフ", "提交图"],
["Refresh commit graph", "Actualiser le graphe des commits", "コミットグラフを更新", "刷新提交图"],
["Latest 100 commits. Select a commit to see its files. Dashed lines continue beyond this history.", "Les 100 derniers commits. Sélectionnez un commit pour voir ses fichiers. Les lignes en pointillés continuent au-delà de cet historique.", "最新の 100 件のコミットです。コミットを選択するとファイルを表示します。破線はこの履歴の外に続きます。", "最近 100 个提交。选择一个提交以查看其文件。虚线表示延续到此历史之外。"],
["Loading history…", "Chargement de l’historique…", "履歴を読み込み中…", "正在加载历史…"],
["Commit graph with branches, authors, and dates", "Graphe des commits avec branches, auteurs et dates", "ブランチ、作成者、日付を含むコミットグラフ", "包含分支、作者和日期的提交图"],
["Commit details", "Détails du commit", "コミットの詳細", "提交详情"],
["Commits", "Commits", "コミット", "提交"],
["Select a commit.", "Sélectionnez un commit.", "コミットを選択してください。", "请选择一个提交。"],
["Loading commit…", "Chargement du commit…", "コミットを読み込み中…", "正在加载提交…"],
["Changes against the first parent.", "Modifications par rapport au premier parent.", "最初の親コミットとの差分です。", "与第一个父提交的差异。"],
["Changed files: {count}", "Fichiers modifiés : {count}", "変更されたファイル: {count}", "已更改的文件:{count}"],
["Changed files", "Fichiers modifiés", "変更されたファイル", "已更改的文件"],
["Select a file to see its diff.", "Sélectionnez un fichier pour voir son diff.", "差分を表示するファイルを選択してください。", "选择一个文件以查看其差异。"],
["This commit contains no file changes.", "Ce commit ne contient aucune modification de fichier.", "このコミットにはファイルの変更がありません。", "此提交不包含文件更改。"],
["Commit file diff", "Diff du fichier du commit", "コミットのファイル差分", "提交的文件差异"],
["No commit is selected.", "Aucun commit n’est sélectionné.", "コミットが選択されていません。", "未选择提交。"],
["Select Refresh to try again.", "Sélectionnez Actualiser pour réessayer.", "もう一度試すには[更新]を選択してください。", "选择“刷新”以重试。"],
["No commits yet. Create a commit to start the graph.", "Aucun commit pour l’instant. Créez un commit pour commencer le graphe.", "まだコミットがありません。コミットを作成するとグラフが始まります。", "还没有提交。创建一个提交以开始图表。"],
["Parents: {parents}", "Parents : {parents}", "親: {parents}", "父提交:{parents}"],
["Root commit", "Commit racine", "ルートコミット", "根提交"],
];
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
+4 -2
View File
@@ -1,7 +1,8 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { commandShortcut } from "./workbenchKeys";
import { pluginHost } from "$lib/plugins/registry";
import { featureSwitches } from "$lib/features/state";
import { gitApi } from "$lib/git/service";
import type { GitLineInfo } from "$lib/git/contracts";
import FindPanel from "$lib/editor/FindPanel.svelte";
import { readingSearch } from "$lib/editor/readingSearch";
@@ -49,7 +50,8 @@
let { buffer, tabs, chrome, reading, split, focusLine, onChange, onRenameTitle, onInsertImage, onView, onSplit, onCursor, onOpenLink, onOpenWorkspace, onNewFile, onNewNote, onQuickOpen, onOpenBrowser, browserOpening = false, hasWorkspace, tableActions, linkActions, active = true, onCloseSplit }: Props = $props();
let selectedLine = $state(1);
let lineInfo = $state<GitLineInfo | null>(null);
const git = $derived.by(() => { void $pluginHost; return pluginHost.get("git"); });
// The blame line needs no feature code: it calls the host Git service while the Git feature is on.
const git = $derived($featureSwitches.git ? gitApi : null);
$effect(() => { void buffer?.id; selectedLine = 1; });
$effect(() => {
void buffer?.id;
+27
View File
@@ -8,6 +8,9 @@
import PluginSettings from "$lib/plugins/PluginSettings.svelte";
import { installedPlugins, pluginTools } from "$lib/plugins/external";
import { pluginHost } from "$lib/plugins/registry";
import { FEATURES, type FeatureId } from "$lib/features/catalog";
import { featureSwitches, setFeature } from "$lib/features/state";
import { featureErrors } from "$lib/features/loader";
import { onMount, untrack, type Snippet } from "svelte";
import Icon from "$lib/ui/Icon.svelte";
import IconButton, { type IconName } from "$lib/ui/IconButton.svelte";
@@ -51,6 +54,7 @@
{ id: "about", label: $t("Help and about"), icon: "help", keywords: "help about version shortcuts keyboard guide" },
{ id: "general", label: $t("General"), icon: "settings", keywords: "auto-save autosave save interval seconds files language français 日本語 简体中文 tables table formulas calculate" },
{ id: "appearance", label: $t("Appearance"), icon: "sun", keywords: "theme colors light dark Claude Sakura Harvest Moon Crimson Pilot Silver Serpent" },
{ id: "features", label: $t("Features"), icon: "toggle", keywords: `features off switch memory ${FEATURES.map(feature => `${$t(feature.name)} ${feature.keywords}`).join(" ")}` },
{ id: "plugins", label: $t("Plug-ins"), icon: "puzzle", keywords: "plugins extensions community" },
]);
let section = $state<Section>(untrack(() => help ? "about" : "general"));
@@ -95,6 +99,12 @@
apply({ ...settings, autosaveSeconds: seconds });
}
function changeFeature(id: FeatureId, on: boolean) {
error = "";
setFeature(id, on).then(() => { message = $t("Changes saved."); })
.catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; });
}
function select(next: Section) { section = next; error = ""; message = ""; seconds = settings.autosaveSeconds; }
function trapFocus(event: KeyboardEvent) {
@@ -180,6 +190,23 @@
<p class="saved" role="status">{message}</p>
{:else if selected.id === "appearance"}
<AppearanceSettings />
{:else if selected.id === "features"}
<h2>{$t("Features")}</h2>
<p class="intro">{$t("Turn off the features that you do not use. A feature that is off does not load, and its controls do not show.")}</p>
<div class="card">
{#each FEATURES as feature (feature.id)}
<div class="setting-row">
<div>
<label for={`feature-${feature.id}`}>{$t(feature.name)}</label>
<p id={`feature-${feature.id}-description`}>{$t(feature.description)}</p>
{#if $featureErrors[feature.id]}<p class="error" role="alert">{$t("{name} could not load: {error}", { name: $t(feature.name), error: $featureErrors[feature.id] ?? "" })}</p>{/if}
</div>
<input id={`feature-${feature.id}`} class="rs-switch" type="checkbox" role="switch" aria-describedby={`feature-${feature.id}-description`} checked={$featureSwitches[feature.id]} onchange={event => changeFeature(feature.id, event.currentTarget.checked)} />
</div>
{/each}
</div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<p class="saved" role="status">{message}</p>
{:else if selected.id === "plugins"}
<PluginManager />
{:else if selected.id === "browser"}
+8 -2
View File
@@ -2,6 +2,7 @@
import { t } from "$lib/i18n";
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
import type PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { featureOfOwner } from "$lib/features/catalog";
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } from "$lib/plugins/external";
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
@@ -152,14 +153,19 @@
const reading = $derived(activeDocumentPane?.reading ?? false);
let quickOpen = $state(false);
let palette = $state(false);
/** The commands of the palette: the app commands that apply here, then the plugin commands. */
/** The name of a native feature, or of an installed plugin. */
function ownerName(owner: string) {
const feature = featureOfOwner(owner);
return feature ? $t(feature.name) : $installedPlugins.plugins.find(row => row.manifest.id === owner)?.manifest.name ?? owner;
}
/** The commands of the palette: the app commands that apply here, then the feature and plugin commands. */
function paletteCommands(): PaletteCommand[] {
const hidden = new Set<WorkbenchCommand>(["command-palette", ...(terminalEnabled ? [] : ["toggle-terminal" as const]), ...(workspace ? [] : ["quick-open" as const])]);
const app = (Object.keys(COMMAND_LABELS) as WorkbenchCommand[]).filter(command => !hidden.has(command)).map(command => ({
id: command, label: $t(COMMAND_LABELS[command]), shortcut: commandShortcut(command) || undefined, run: () => { runCommand(command); },
}));
const plugins = $pluginTools.filter(tool => tool.kind === "command" && tool.surface === "commands").map(tool => ({
id: `plugin:${tool.owner}:${tool.id}`, label: tool.title, detail: $installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner,
id: `plugin:${tool.owner}:${tool.id}`, label: tool.title, detail: ownerName(tool.owner),
run: () => { void runPluginCommand(tool.owner, tool.id).catch(reason => error = String(reason)); },
}));
return [...app, ...plugins];
+2 -1
View File
@@ -6,6 +6,7 @@
import ContextMenu from "$lib/layout/ContextMenu.svelte";
import type { MenuItem } from "$lib/layout/menuTypes";
import { installedPlugins, isBuiltInModule, pluginTools, pluginNavigation, openPluginView, runPluginCommand } from "./external";
import { featureOfOwner } from "$lib/features/catalog";
// `side` places the menu below the button (the header) or at its right (the left ribbon).
let { surface, compact = false, side = "bottom" }: { surface: "commands" | "open"; compact?: boolean; side?: "bottom" | "right" } = $props();
let anchor = $state<HTMLButtonElement>();
@@ -15,7 +16,7 @@
const label = $derived(surface === "open" ? $t("Plug-in views") : $t("Commands"));
function tooltip(node: HTMLElement) { return { destroy: attachTooltip(node, () => compact ? label : "") }; }
const tools = $derived($pluginTools.filter(tool => tool.surface === surface
&& !isBuiltInModule(tool.owner)
&& !isBuiltInModule(tool.owner) && !featureOfOwner(tool.owner)
&& !(surface === "open" && tool.kind === "view" && $pluginNavigation.some(item => item.owner === tool.owner && item.id === tool.id && item.placement === "sidebar"))));
const signature = $derived(JSON.stringify([tools, $installedPlugins.plugins.map(row => [row.manifest.id, row.manifest.name])]));
const items: MenuItem[] = $derived.by(() => { void signature; return untrack(() => tools.map(tool => ({
+7 -1
View File
@@ -1,12 +1,15 @@
<script lang="ts">
import { tick, untrack } from "svelte";
import { findPluginEditor, mountPluginView, type OpenPluginView } from "./external";
import { t } from "$lib/i18n";
import FindPanel from "$lib/editor/FindPanel.svelte";
import { readingSearch } from "$lib/editor/readingSearch";
import type { FindTarget } from "$lib/editor/findTarget";
let { view }: { view: OpenPluginView } = $props();
let host: HTMLDivElement | undefined = $state();
let error = $state("");
// Retry mounts the view again, for example after a feature module failed to load.
let attempt = $state(0);
let findTarget = $state.raw<FindTarget>();
let findPanel = $state<FindPanel>();
let returnFocus: HTMLElement | null = null;
@@ -36,6 +39,7 @@
$effect(() => {
const element = host;
void attempt;
if (!element) return;
error = "";
findTarget = undefined;
@@ -54,7 +58,7 @@
<div id={`plugin-editor-${view.key}`} class="plugin-editor-pane"
role="tabpanel" aria-label={view.title} tabindex="-1" onkeydowncapture={searchKey}>
{#if error}<p class="error" role="alert">{error}</p>{/if}
{#if error}<p class="error" role="alert">{error} <button class="retry" onclick={() => attempt++}>{$t("Retry")}</button></p>{/if}
{#if findTarget}<FindPanel bind:this={findPanel} target={findTarget} />{/if}
{#key `${view.owner}:${view.id}:${view.document?.path ?? ""}`}
<div class="plugin-editor-content" tabindex="-1" bind:this={host}></div>
@@ -65,4 +69,6 @@
.plugin-editor-pane { display: flex; flex: 1; min-height: 0; min-width: 0; flex-direction: column; overflow: hidden; }
.plugin-editor-content { flex: 1; min-height: 0; min-width: 0; overflow: auto; }
.error { color: var(--rs-error); padding: 12px; }
.retry { margin-left: 8px; min-height: 24px; padding: 2px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); }
.retry:hover { background: var(--rs-bg-active); }
</style>
+40 -9
View File
@@ -3,13 +3,17 @@ import { completionTransport } from "../completion/transport";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { workspaceList, workspaceRead, workspaceReadBytes, workspaceWrite } from "../workspace/api";
import { gitApi } from "../git/service";
import { ExternalSession, deadline } from "./externalSession";
import { filesTransport, ptyTransport } from "./nativeServices";
import { pluginAccess, type PluginTool } from "./access";
import { containsPane, splitPane, removePane, type SplitLayout } from "../workspace/splitLayout";
import type { PluginViewOpenOptions } from "./sdk";
import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView, PluginDocumentContext, PluginDocumentType } from "./sdk";
import { locale } from "../i18n";
import { FEATURES, type FeatureEntry } from "../features/catalog";
import { FeatureSession } from "../features/session";
import { featureSwitches, type FeatureSwitches } from "../features/state";
import type { FeatureContext } from "../features/types";
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
export const externalErrors = writable<Record<string, string>>({});
@@ -78,7 +82,7 @@ export const pluginEditorActive = writable(false);
export const pluginServiceError = writable("");
export const restartPlugins = writable<string[]>([]);
/** Old packages of features that RuneStone now includes. The host never loads their code. */
export const builtInPackages: readonly string[] = ["runestone.browser", "runestone.table-formulas", "runestone.theme-editor"];
export const builtInPackages: readonly string[] = ["runestone.browser", "runestone.table-formulas", "runestone.theme-editor", ...FEATURES.map(feature => feature.owner)];
export const browserModule = "runestone.browser";
/** Features of RuneStone that use the plugin API. They are not installed packages, and the plugin menus do not list their tools. */
export const builtInModules: readonly { id: string; name: string; browserWindow: boolean; load: () => Promise<PluginModule> }[] = [
@@ -86,7 +90,13 @@ export const builtInModules: readonly { id: string; name: string; browserWindow:
{ id: "runestone.theme-editor", name: "Theme editor", browserWindow: false, load: () => import("../theme/editorView") },
];
export const isBuiltInModule = (id: string) => builtInModules.some(module => module.id === id);
const sessions = new Map<string, { hash: string; session: ExternalSession }>();
/**
* The owner of a set of views and commands: an installed plugin, a built-in module, or a native feature.
* The hash is the package hash of a plugin, "builtin" for a built-in module, and "feature" for a native feature.
*/
type ViewSession = Pick<ExternalSession, "views" | "documentTypes" | "commands" | "controller" | "launch" | "run" | "mount" | "dropTab" | "stop">;
const sessions = new Map<string, { hash: string; session: ViewSession }>();
const packaged = (hash: string | undefined) => hash !== undefined && hash !== "builtin" && hash !== "feature";
const failures = new Map<string, string>();
const errors: Record<string, string> = {};
const restarted = new Set<string>();
@@ -210,10 +220,10 @@ async function stop(id: string) {
for (const view of get(pluginEditors)) if (view.owner === id) closePluginEditor(view.key);
pluginDocuments.set({});
pluginView.update(view => view?.owner === id ? null : view);
restarted.add(id); restartPlugins.set([...restarted]);
if (loaded.hash !== "feature") { restarted.add(id); restartPlugins.set([...restarted]); }
let error: string | undefined;
try { await loaded.session.stop(); } catch (reason) { error = String(reason); report(id, reason); }
if (loaded.hash !== "builtin") await release(id, error); publish();
if (packaged(loaded.hash)) await release(id, error); publish();
}
function show(owner: string, id: string, options?: PluginViewOpenOptions) {
const view = sessions.get(owner)?.session.views.get(id);
@@ -260,7 +270,6 @@ async function activate(row: InstalledPlugin, builtin?: PluginModule) {
let leased = false;
const session = new ExternalSession(id, {
completionTransport,
git: gitApi,
pty: ptyTransport,
files: filesTransport(id),
backgrounds: {
@@ -341,7 +350,7 @@ export function refreshPlugins(): Promise<void> {
if (!snapshot || version !== generation) return;
installedPlugins.set(snapshot); pluginServiceError.set("");
for (const id of sessions.keys()) {
if (sessions.get(id)?.hash === "builtin") continue;
if (!packaged(sessions.get(id)?.hash)) continue;
const row = snapshot.plugins.find(row => row.manifest.id === id);
if (!row?.enabled || row.hash !== sessions.get(id)?.hash) await stop(id);
}
@@ -371,7 +380,26 @@ export async function mountPluginView(owner: string, id: string, element: HTMLEl
if (!session) throw new Error("The plugin is disabled.");
return session.mount(id, element, document, surface);
}
/** A browser window starts only the built-in modules for browser windows, and no installed plugin. */
function featureContext(entry: FeatureEntry): FeatureContext {
return {
openView: id => show(entry.owner, id),
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
onWorkspaceChange: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
};
}
/** Start each native feature that is on, and stop each one that is off. The feature code loads later, at first need. */
function syncFeatures(switches: FeatureSwitches) {
queue = queue.then(async () => {
for (const entry of FEATURES) {
const loaded = sessions.get(entry.owner);
if (switches[entry.id] && !loaded) {
sessions.set(entry.owner, { hash: "feature", session: new FeatureSession(entry, featureContext(entry)) });
publish();
} else if (!switches[entry.id] && loaded?.hash === "feature") await stop(entry.owner);
}
}).catch(reason => pluginServiceError.set(String(reason)));
}
/** A browser window starts only the built-in modules for browser windows, no native feature, and no installed plugin. */
export function startExternalPlugins(options: { browserWindow?: boolean } = {}): () => void {
if (!isTauri() || started) return () => {};
started = true;
@@ -387,12 +415,15 @@ export function startExternalPlugins(options: { browserWindow?: boolean } = {}):
await activate({ manifest: { schemaVersion: 1, id: builtIn.id, name: builtIn.name, author: "RuneStone", description: `Built-in ${builtIn.name.toLowerCase()}`, version: "0.0.0", apiVersion: 1, entry: "builtin", access: "full-app" }, hash: "builtin", enabled: true, installedAt: null, path: "", error: null, removal: false }, module);
}).catch(reason => report(builtIn.id, reason));
}
const offFeatures = browserWindow ? undefined : featureSwitches.subscribe(syncFeatures);
// Feature titles follow the interface language.
const offLocale = locale.subscribe(() => publish());
void refreshPlugins();
// Scans run at start, on window focus, on Refresh, and on `plugins-changed`. There is no timed scan.
const focus = () => { void refreshPlugins(); };
window.addEventListener("focus", focus);
return () => {
disposed = true; started = false; generation++; off?.(); window.removeEventListener("focus", focus);
disposed = true; started = false; generation++; off?.(); offFeatures?.(); offLocale(); window.removeEventListener("focus", focus);
for (const id of [...sessions.keys()]) void stop(id).catch(reason => report(id, reason));
};
}
+1 -14
View File
@@ -9,7 +9,7 @@ import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, Plugi
/** The host services that a session gives to its plugin. The host binds them to the plugin ID. */
export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & {
openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles;
openFile?: PluginApi["openFile"]; backgrounds?: BackgroundFiles;
completionTransport?: NonNullable<PluginApi["completion"]>["transport"];
pty?: PtyTransport; files?: FilesTransport; serviceHub?: ServiceHub;
};
@@ -88,19 +88,6 @@ export class ExternalSession {
},
} } : {}),
ui: { showActionMenu: options => { this.check(); const menu = showActionMenu(options, this.controller.signal); return { close: () => menu.close() }; } },
...(this.services.git ? { git: {
status: () => { this.check(); return this.services.git!.status(); },
diff: (path: string, staged: boolean) => { this.check(); return this.services.git!.diff(path, staged); },
stage: (paths: string[]) => { this.check(); return this.services.git!.stage(paths); },
unstage: (paths: string[]) => { this.check(); return this.services.git!.unstage(paths); },
commit: (message: string) => { this.check(); return this.services.git!.commit(message); },
blame: (path: string, line: number) => { this.check(); return this.services.git!.blame(path, line); },
push: () => { this.check(); return this.services.git!.push(); },
pull: () => { this.check(); return this.services.git!.pull(); },
graph: () => { this.check(); return this.services.git!.graph(); },
commitDetails: (commit: string) => { this.check(); return this.services.git!.commitDetails!(commit); },
commitDiff: (commit: string, path: string) => { this.check(); return this.services.git!.commitDiff!(commit, path); },
} } : {}),
completion: {
version: 1,
registerProvider: provider => { this.check(); const off = completionHub.registerProvider({ ...provider, id: this.id + ":" + provider.id }); this.contributions.push(off); return off; },
+1 -1
View File
@@ -9,7 +9,7 @@ export class ContributionRegistry {
return this.entries.get(key)?.value as Contributions[K] | undefined;
}
register<K extends keyof Contributions>(owner: string, key: K, value: Contributions[K]): () => void {
if (key !== "terminal" && key !== "browser" && key !== "git") throw new Error("Unknown plugin contribution.");
if (key !== "terminal" && key !== "browser") throw new Error("Unknown plugin contribution.");
if (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`);
const entry = { owner, value };
this.entries.set(key, entry); this.emit();
+2 -1
View File
@@ -10,7 +10,7 @@
import { invoke, isTauri } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language'] as const;
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features'] as const;
export type SettingsSection = typeof SETTINGS_SECTIONS[number];
export type SettingsSections = Partial<Record<SettingsSection, unknown>>;
@@ -21,6 +21,7 @@ export const LEGACY_KEYS: Readonly<Record<SettingsSection, string>> = {
customThemes: 'runestone.custom-themes',
customThemesLegacy: 'runestone.custom-themes.legacy',
language: 'runestone.language',
features: 'runestone.features',
};
/** Make the first settings file from the old localStorage values. `read` returns the value of a key, or null. */
+6
View File
@@ -144,6 +144,12 @@
<path d="M5 12h14" />
{:else if icon === "download"}
<path d="M12 4v11" /><path d="M7 10l5 5 5-5" /><path d="M5 20h14" />
{:else if icon === "upload"}
<path d="M12 20V9" /><path d="M7 14l5-5 5 5" /><path d="M5 4h14" />
{:else if icon === "minus"}
<path d="M5 12h14" />
{:else if icon === "toggle"}
<rect x="3" y="7" width="18" height="10" rx="5" /><circle cx="16" cy="12" r="2.5" />
{/if}
</svg>
<style>
+4 -1
View File
@@ -54,7 +54,10 @@
| "close"
| "trash"
| "plus"
| "download";
| "download"
| "upload"
| "minus"
| "toggle";
type Props = {
icon: IconName;
+3
View File
@@ -4,11 +4,14 @@
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
import { initSettings } from "$lib/settings/store";
import { migrateLegacyPreferences } from "$lib/settings/migration";
import { migrateFeaturesOnStart } from "$lib/features/migration";
export const ssr = false;
// Each window loads the user preferences before its first render, so later reads need no wait.
export async function load() {
await initSettings(migrateLegacyPreferences);
// The first start after an update gives each new native feature the state of its old plugin package.
await migrateFeaturesOnStart();
return {};
}