Official
tabs
The tabbed detail pane beside the chat: files to edit and diffs (JavaScript UI plugin).
The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/tabs@0.2.5
Permissions in 0.2.5
Files
tabs.ts10.4 KB
// Tab identity, selection and content handling, independent of host calls.
// Legacy requests are parsed at the app-state boundary rather than cast.
import * as z from "zod";
export const openRequest = z.object({
kind: z.enum(["file", "diff", "terminal", "diagram"]),
workspaceId: z.string(),
path: z.string(),
nonce: z.number(),
title: z.string().optional(),
icon: z.string().optional(),
diff: z.string().optional(),
// A diff tab that follows the working tree (false) or the index (true).
staged: z.boolean().optional(),
// A diagram tab draws this source of a markdown fence of `language`.
source: z.string().optional(),
language: z.string().optional(),
// The chat it comes from: the tab then belongs to that chat's task.
chatId: z.string().optional(),
});
export const closeRequest = z.object({ kind: openRequest.shape.kind, path: z.string(), nonce: z.number() });
export type TabInput = Omit<z.infer<typeof openRequest>, "nonce">;
export interface Tab extends Omit<TabInput, "diff"> {
id: string;
preview: boolean;
}
export interface Content {
// A file's text as last read or saved.
text?: string;
// What the editor holds after an edit; unsaved while it differs from `text`.
draft?: string;
// Cut short for size: shown, never saved.
truncated?: boolean;
diff?: string;
error?: string;
// Raised at every read and save: an HTML preview then loads again.
revision?: number;
// A native file editor reports only its lifecycle and dirty bit; its text
// stays in the kernel's rope.
fileState?: FileState;
}
export interface FileState {
readonly state: "loading" | "ready" | "error";
readonly dirty: boolean;
readonly error?: string;
}
export interface TabsState {
tabs: Tab[];
active: string | null;
handled: number;
handledClose: number;
contents: Record<string, Content>;
// Whether a new Markdown or HTML tab opens in its preview: the choice last
// made with the Preview and Editor buttons, kept in plugin storage.
preview: boolean;
// Files whose tab waits a moment for their text before it draws.
waiting: Set<string>;
}
export const initialState = (): TabsState => ({
tabs: [],
active: null,
handled: 0,
handledClose: 0,
contents: {},
preview: true,
waiting: new Set(),
});
// The plugin storage key of `TabsState.preview`.
export const PREVIEW_KEY = "preview";
export const tabId = (request: TabInput): string => `${request.kind}:${request.workspaceId}:${request.path}`;
// The node id of a file tab's editor, which the keyboard is given to.
export const editorId = (tab: Tab): string => `file-${tab.id}`;
export const extension = (path: string): string => (path.split(".").pop() ?? "").toLowerCase();
// What a file tab offers beside its editor: Markdown drawn natively, HTML
// live in the web view.
export const previewKind = (path: string): "markdown" | "html" | null => {
const ext = extension(path);
return ext === "md" || ext === "markdown" ? "markdown" : ext === "html" || ext === "htm" ? "html" : null;
};
export const nextRevision = (content: Content | undefined): number => (content?.revision ?? 0) + 1;
export const nativeFileContent = (): Content => ({
revision: 1,
fileState: { state: "loading", dirty: false },
});
export const activeTab = (state: TabsState): Tab | undefined =>
state.tabs.find((tab) => tab.id === state.active) ?? state.tabs[0];
export const fileContent = (text: string): Content =>
text.length > 2_000_000 ? { text: `${text.slice(0, 2_000_000)}\n… file truncated`, truncated: true } : { text };
export const isDirty = (content: Content | undefined): boolean =>
content?.fileState?.dirty ?? (content?.draft !== undefined && content.draft !== content.text);
// What the editor shows: the unsaved text, which outlives the editor while
// its tab is behind another.
export const editorText = (content: Content): string => content.draft ?? content.text ?? "";
export const fileResponse = z.object({ text: z.string() }).nullable();
export const readContent = (result: z.infer<typeof fileResponse>): Content =>
result === null ? { error: "This file no longer exists." } : fileContent(result.text);
// What a failed read of an open file says: a file that went says so plainly.
export const readError = (message: string): string =>
/no such file|not found|os error 2\b/i.test(message) ? "This file no longer exists." : message;
// A diff tab reads its diff again as the repository changes: one Source
// Control opened (it says which side) or one brought back after a restart.
export const liveDiff = (tab: Tab): boolean => tab.kind === "diff" && !tab.chatId && tab.staged !== undefined;
export function openTab(state: TabsState, request: TabInput): Tab {
const id = tabId(request);
let tab = state.tabs.find((tab) => tab.id === id);
if (!tab) {
tab = {
id,
kind: request.kind,
workspaceId: request.workspaceId,
path: request.path,
title: request.title,
icon: request.icon,
source: request.source,
language: request.language,
...(request.staged !== undefined ? { staged: request.staged } : {}),
...(request.chatId ? { chatId: request.chatId } : {}),
preview: state.preview,
};
state.tabs.push(tab);
}
if (request.kind === "diff") state.contents[id] = { diff: request.diff ?? "" };
state.active = id;
return tab;
}
// What the detail view's `ctx.state` holds: it survives reloads of this
// plugin, and every save of the plugin's files reloads it.
export interface KeptTabs {
tabs?: TabsState;
}
// Keeps `state` in the view's `ctx.state`. On the first render after a
// reload, the strip kept there comes back into `state`: the tabs open then,
// with their unsaved changes, then those opened since, one of which stays
// the visible tab. Whether it came back.
export function keepStrip(state: TabsState, kept: KeptTabs): boolean {
const previous = kept.tabs;
kept.tabs = state;
if (!previous || previous === state) return false;
const opened = state.tabs;
state.tabs = [...previous.tabs.filter((tab) => !opened.some((other) => other.id === tab.id)), ...opened];
for (const [id, content] of Object.entries(previous.contents)) {
if (!state.contents[id] || isDirty(content)) state.contents[id] = content;
}
if (opened.length === 0) state.active = previous.active;
return true;
}
export function closeTab(state: TabsState, id: string): Tab | undefined {
const index = state.tabs.findIndex((tab) => tab.id === id);
state.tabs = state.tabs.filter((tab) => tab.id !== id);
delete state.contents[id];
if (state.active === id) state.active = state.tabs[Math.min(index, state.tabs.length - 1)]?.id ?? null;
return state.tabs.find((tab) => tab.id === state.active);
}
// A tab dropped on another lands beside it, on the side the kernel reports.
// A kernel without `reorder` reports `into`: the tab takes the other's place.
export function moveTab(state: TabsState, id: string, target: string, zone: string): void {
const from = state.tabs.findIndex((tab) => tab.id === id);
const to = state.tabs.findIndex((tab) => tab.id === target);
if (from < 0 || to < 0 || from === to) return;
const [tab] = state.tabs.splice(from, 1);
const at = state.tabs.findIndex((tab) => tab.id === target);
const after = zone === "after" || (zone !== "before" && from < to);
state.tabs.splice(after ? at + 1 : at, 0, tab!);
}
/** A tab made again from its key (`tabId`), as the app brings it back after
* a restart: a file, a diff (of the working tree, read again), a terminal,
* or a diagram (its source comes from storage, `diagramKey`). */
export function tabFromKey(state: TabsState, key: string): Tab | undefined {
const [kind, workspaceId, ...rest] = key.split(":");
const path = rest.join(":");
if (!workspaceId || !path || (kind !== "file" && kind !== "diff" && kind !== "terminal" && kind !== "diagram")) return undefined;
const tab: Tab = { id: key, kind, workspaceId, path, preview: state.preview, ...(kind === "diff" ? { staged: false } : {}) };
state.tabs.push(tab);
return tab;
}
/** The plugin storage key a diagram tab's source is kept under, so the tab draws it after a restart. */
export const diagramKey = (id: string): string => `diagram:${id}`;
export const storedDiagram = z.object({ source: z.string(), language: z.string().optional(), title: z.string().optional() });
/** The name of the file a file or diff tab's key names, whose file icon its tab shows. */
/** The workspace a file's, a diff's or a terminal's tab belongs to, from its key. */
export function workspaceOfKey(key: string): string | null {
const [kind, workspaceId] = key.split(":");
return (kind === "file" || kind === "diff" || kind === "terminal") && workspaceId ? workspaceId : null;
}
export function fileOfKey(key: string): string | null {
const [kind, , ...rest] = key.split(":");
if (kind !== "file" && kind !== "diff") return null;
return rest.join(":").split("/").pop() || null;
}
export function tabName(tab: Tab): string {
if (tab.kind === "terminal") return tab.title ?? "Terminal";
if (tab.kind === "diagram") return tab.title ?? "Diagram";
return tab.path.split("/").pop() ?? "";
}
export const LANGUAGES: Readonly<Record<string, string>> = {
rs: "rust",
js: "javascript",
mjs: "javascript",
cjs: "javascript",
jsx: "javascript",
ts: "typescript",
mts: "typescript",
cts: "typescript",
tsx: "tsx",
json: "json",
jsonc: "json",
md: "markdown",
markdown: "markdown",
py: "python",
sh: "bash",
bash: "bash",
zsh: "bash",
fish: "bash",
toml: "toml",
yml: "yaml",
yaml: "yaml",
go: "go",
html: "html",
htm: "html",
css: "css",
diff: "diff",
patch: "diff",
};
// What a reply to a selection in a tab puts in the prompt box: where it is,
// then what is selected. Code comes fenced with its lines; a Markdown
// preview's selection comes as Markdown, with no lines.
export interface CodeQuote {
readonly text: string;
readonly lines?: readonly [number, number];
readonly side?: "original" | "modified";
}
export function quoteOf(path: string, quote: CodeQuote): string {
if (!quote.lines) return `\`${path}\`:\n${quote.text}`;
const [first, last] = quote.lines;
const lines = first === last ? `line ${first}` : `lines ${first}–${last}`;
const before = quote.side === "original" ? ", before the change" : "";
return `\`${path}\` ${lines}${before}:\n${quote.text}`;
}
const finished = z.object({ event: z.literal("run_finished") });
export const runFinished = (kind: unknown): boolean => finished.safeParse(kind).success;
No comments yet.