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:
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<script lang="ts">
|
||||
import { diffLineKind } from "./model";
|
||||
let { text, error = false, label }: { text: string; error?: boolean; label: string } = $props();
|
||||
const lines = $derived(text.split("\n"));
|
||||
</script>
|
||||
|
||||
<!-- One block element for each line, so that the add and remove fills cover the full width.
|
||||
The diff takes focus, so that a keyboard user can scroll it. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
|
||||
<pre class="diff" class:error tabindex="0" aria-label={label}>{#each lines as line, index (index)}<span class="line {diffLineKind(line)}">{line || " "}</span>{/each}</pre>
|
||||
|
||||
<style>
|
||||
.diff { flex: 1; min-height: 0; margin: 0; padding: 8px; overflow: auto; font: 12px/1.6 var(--rs-font-mono); font-weight: var(--rs-code-font-weight); tab-size: 4; background: var(--rs-image-editor-bg, var(--rs-bg)); border-radius: var(--rs-control-radius); }
|
||||
.diff:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.line { display: block; min-width: max-content; min-height: 1.6em; }
|
||||
.add { background: color-mix(in srgb, var(--rs-ok) 18%, transparent); }
|
||||
.remove { background: color-mix(in srgb, var(--rs-error) 18%, transparent); }
|
||||
.range { color: var(--rs-accent); }
|
||||
.error { color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -0,0 +1,39 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import DiffText from "./DiffText.svelte";
|
||||
import type { GitState } from "./state.svelte";
|
||||
|
||||
let { git, openFile }: { git: GitState; openFile: (path: string) => Promise<void> } = $props();
|
||||
let error = $state("");
|
||||
|
||||
const title = $derived(git.selected
|
||||
? git.selected.staged ? $t("{path} · Staged", { path: git.selected.path }) : $t("{path} · Working tree", { path: git.selected.path })
|
||||
: $t("Git diff"));
|
||||
|
||||
async function open() {
|
||||
if (!git.selected) return;
|
||||
error = "";
|
||||
try { await openFile(git.selected.path); }
|
||||
catch (reason) { error = String(reason); }
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="git-diff">
|
||||
<div class="header">
|
||||
<strong>{title}</strong>
|
||||
<button class="text-button" type="button" disabled={!git.selected} onclick={open}>{$t("Open file")}</button>
|
||||
</div>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<DiffText text={git.selected?.text ?? $t("Select a file in Source control to see its diff.")} error={!!git.selected?.error} label={$t("Git diff")} />
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.git-diff { display: flex; flex-direction: column; gap: 10px; height: 100%; padding: 12px; box-sizing: border-box; overflow: hidden; font-size: 13px; }
|
||||
.header { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
strong { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
||||
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
|
||||
.text-button:hover:not(:disabled) { background: var(--rs-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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,62 @@
|
||||
// The Git feature. `loader.ts` imports this module at first need: the Source control pane, a Git tab, or the graph command.
|
||||
// It uses the host Git service directly. `src-tauri/src/git.rs` runs the `git` program for the workspace of the window.
|
||||
import { mount, unmount } from "svelte";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { gitApi } from "../../git/service.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||
import { GitState } from "./state.svelte.ts";
|
||||
import SourceControl from "./SourceControl.svelte";
|
||||
import GitDiff from "./GitDiff.svelte";
|
||||
import GitGraph from "./GitGraph.svelte";
|
||||
|
||||
export function start(context: FeatureContext): FeatureInstance {
|
||||
const state = new GitState();
|
||||
|
||||
async function loadDiff(path: string, staged: boolean) {
|
||||
const sequence = ++state.sequence;
|
||||
state.selected = { path, staged, text: tr("Loading diff…"), error: false };
|
||||
try {
|
||||
const text = await gitApi.diff(path, staged);
|
||||
if (state.disposed || sequence !== state.sequence) return;
|
||||
state.selected = { path, staged, text: text || tr("No text changes."), error: false };
|
||||
} catch (reason) {
|
||||
if (state.disposed || sequence !== state.sequence) return;
|
||||
state.selected = { path, staged, text: String(reason), error: true };
|
||||
}
|
||||
}
|
||||
|
||||
const views: Record<string, (target: HTMLElement) => Record<string, unknown>> = {
|
||||
"source-control": target => mount(SourceControl, { target, props: {
|
||||
git: state,
|
||||
showDiff: (path: string, staged: boolean) => { context.openView("diff"); void loadDiff(path, staged); },
|
||||
showGraph: () => context.openView("graph"),
|
||||
onWorkspaceChange: context.onWorkspaceChange,
|
||||
} }),
|
||||
diff: target => mount(GitDiff, { target, props: { git: state, openFile: context.openFile } }),
|
||||
graph: target => mount(GitGraph, { target, props: { git: state } }),
|
||||
};
|
||||
|
||||
return {
|
||||
mount(view, element) {
|
||||
const create = views[view];
|
||||
if (!create) throw new Error(tr("This view is unavailable."));
|
||||
const component = create(element);
|
||||
return () => unmount(component);
|
||||
},
|
||||
saveTabState(view) {
|
||||
if (view === "diff") return state.selected ? { path: state.selected.path, staged: state.selected.staged } : null;
|
||||
if (view === "graph") return { selectedId: state.history.selectedId, file: state.history.file };
|
||||
return undefined;
|
||||
},
|
||||
async restoreTabState(view, value) {
|
||||
const saved = value && typeof value === "object" ? value as Record<string, unknown> : null;
|
||||
if (!saved) return;
|
||||
if (view === "diff" && typeof saved.path === "string" && typeof saved.staged === "boolean") await loadDiff(saved.path, saved.staged);
|
||||
if (view === "graph") {
|
||||
state.history.selectedId = typeof saved.selectedId === "string" ? saved.selectedId : null;
|
||||
state.history.file = typeof saved.file === "string" ? saved.file : null;
|
||||
}
|
||||
},
|
||||
dispose() { state.disposed = true; state.sequence++; },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Pure Git helpers of the Git feature: change groups, labels, and the lanes of the commit graph.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { GitChange, GitGraph, GitGraphCommit } from "../../git/contracts.ts";
|
||||
|
||||
export function isConflict(change: GitChange): boolean {
|
||||
return change.index === "U" || change.worktree === "U" || ["AA", "DD"].includes(change.index + change.worktree);
|
||||
}
|
||||
|
||||
/** Staged changes and working tree changes. A conflict shows only with the working tree changes. */
|
||||
export function groups(changes: GitChange[]): { staged: GitChange[]; working: GitChange[] } {
|
||||
return {
|
||||
staged: changes.filter(change => !isConflict(change) && ![" ", "?", "!"].includes(change.index)),
|
||||
working: changes.filter(change => isConflict(change) || ![" ", "!"].includes(change.worktree)),
|
||||
};
|
||||
}
|
||||
|
||||
/** The paths to stage or unstage. A rename needs both its old and its new path. */
|
||||
export function pathsFor(changes: GitChange[]): string[] {
|
||||
return [...new Set(changes.flatMap(change => change.originalPath ? [change.originalPath, change.path] : [change.path]))];
|
||||
}
|
||||
|
||||
export function changeLabel(change: GitChange, staged: boolean): string {
|
||||
if (isConflict(change)) return tr("Conflict");
|
||||
const code = staged ? change.index : change.worktree;
|
||||
switch (code) {
|
||||
case "?": return tr("New");
|
||||
case "A": return tr("Added");
|
||||
case "M": return tr("Modified");
|
||||
case "D": return tr("Deleted");
|
||||
case "R": return tr("Renamed");
|
||||
case "C": return tr("Copied");
|
||||
case "T": return tr("Type changed");
|
||||
default: return code;
|
||||
}
|
||||
}
|
||||
|
||||
export type DiffLineKind = "add" | "remove" | "range" | "context";
|
||||
|
||||
export function diffLineKind(line: string): DiffLineKind {
|
||||
if (line.startsWith("+") && !line.startsWith("+++")) return "add";
|
||||
if (line.startsWith("-") && !line.startsWith("---")) return "remove";
|
||||
return line.startsWith("@@") ? "range" : "context";
|
||||
}
|
||||
|
||||
export interface GraphNode extends GitGraphCommit { row: number; lane: number; color: number }
|
||||
export interface GraphEdge { from: string; to: string; row: number; lane: number; parentLane: number; color: number; outside: boolean; endRow: number }
|
||||
|
||||
/** Lanes and colors for the commit graph. The six colors repeat, and lanes that are in use do not share a color. */
|
||||
export function graphLayout(history: GitGraph | null | undefined): { nodes: GraphNode[]; edges: GraphEdge[]; lanes: number } {
|
||||
const commits = history?.commits ?? [];
|
||||
const lanes: (string | null)[] = [];
|
||||
const nodes: GraphNode[] = [];
|
||||
const edges: Omit<GraphEdge, "endRow">[] = [];
|
||||
const colors = new Map<string, number>();
|
||||
let nextColor = 0;
|
||||
const ids = new Set(commits.map(commit => commit.id));
|
||||
const reserve = (id: string, preferredColor?: number) => {
|
||||
let lane = lanes.indexOf(id);
|
||||
if (lane < 0) {
|
||||
lane = lanes.indexOf(null);
|
||||
if (lane < 0) lane = lanes.length;
|
||||
lanes[lane] = id;
|
||||
if (preferredColor === undefined) {
|
||||
const activeColors = new Set(lanes.filter(value => value !== id && value !== null).map(value => colors.get(value!)));
|
||||
preferredColor = nextColor++;
|
||||
for (let offset = 0; offset < 6 && activeColors.has(preferredColor % 6); offset++) preferredColor = nextColor++;
|
||||
}
|
||||
colors.set(id, preferredColor % 6);
|
||||
}
|
||||
return lane;
|
||||
};
|
||||
let width = 1;
|
||||
for (const [row, commit] of commits.entries()) {
|
||||
const lane = reserve(commit.id);
|
||||
const color = colors.get(commit.id)!;
|
||||
nodes.push({ ...commit, row, lane, color });
|
||||
lanes[lane] = null;
|
||||
for (const [index, parent] of commit.parents.entries()) {
|
||||
const parentLane = reserve(parent, index === 0 ? color : undefined);
|
||||
edges.push({ from: commit.id, to: parent, row, lane, parentLane, color: index === 0 ? color : colors.get(parent)!, outside: !ids.has(parent) });
|
||||
}
|
||||
width = Math.max(width, lanes.length, lane + 1);
|
||||
}
|
||||
const rows = new Map(nodes.map(node => [node.id, node.row]));
|
||||
return { nodes, edges: edges.map(edge => ({ ...edge, endRow: rows.get(edge.to) ?? nodes.length })), lanes: width };
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// The shared state of one Git feature instance. The Source control pane, the diff tab, and the graph tab read it.
|
||||
|
||||
export interface DiffSelection {
|
||||
path: string;
|
||||
staged: boolean;
|
||||
text: string;
|
||||
error: boolean;
|
||||
}
|
||||
|
||||
export class GitState {
|
||||
/** The file of the diff tab. */
|
||||
selected = $state<DiffSelection | null>(null);
|
||||
/** The commit and the file of the graph tab. Tab transfers carry them. */
|
||||
history = $state<{ selectedId: string | null; file: string | null }>({ selectedId: null, file: null });
|
||||
/** Grows after each commit, push, or pull, so that the graph reads the history again. */
|
||||
historyVersion = $state(0);
|
||||
/** The diff request that may write `selected`. */
|
||||
sequence = 0;
|
||||
disposed = false;
|
||||
}
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// The feature switches: the `features` section of the settings file, for example `{ "git": true }`.
|
||||
// A missing key means that the migration from the old plugin package has not run for that feature yet.
|
||||
import { readable } from "svelte/store";
|
||||
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
|
||||
import { FEATURES, type FeatureId } from "./catalog.ts";
|
||||
|
||||
export type FeatureSwitches = Record<FeatureId, boolean>;
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
/** The stored switches of the known features. Other keys are ignored. */
|
||||
export function storedSwitches(value: unknown): Partial<FeatureSwitches> {
|
||||
const stored = record(value);
|
||||
const result: Partial<FeatureSwitches> = {};
|
||||
for (const { id } of FEATURES) if (typeof stored[id] === "boolean") result[id] = stored[id];
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The switches with the default of each feature that has no stored value. */
|
||||
export function switchesFrom(value: unknown): FeatureSwitches {
|
||||
const stored = storedSwitches(value);
|
||||
return Object.fromEntries(FEATURES.map(entry => [entry.id, stored[entry.id] ?? entry.defaultOn])) as FeatureSwitches;
|
||||
}
|
||||
|
||||
export function readSwitches(): FeatureSwitches {
|
||||
return switchesFrom(readSection("features"));
|
||||
}
|
||||
|
||||
/** The switches in this window. Changes from other windows arrive through `settings-changed`. */
|
||||
export const featureSwitches = readable<FeatureSwitches>(readSwitches(), set => {
|
||||
// The settings can load after this module, so read them again for the first subscriber.
|
||||
set(readSwitches());
|
||||
return onSettingsChange("features", () => set(readSwitches()));
|
||||
});
|
||||
|
||||
/** Turn one feature on or off. Keys of unknown features stay, so a newer version keeps its values. */
|
||||
export function setFeature(id: FeatureId, on: boolean): Promise<void> {
|
||||
return writeSection("features", { ...record(readSection("features")), [id]: on });
|
||||
}
|
||||
@@ -0,0 +1,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;
|
||||
}
|
||||
Reference in New Issue
Block a user