Open History to see the last commit
1import { msg } from "gt-i18n";
2
3const SIDEBAR_ROW_LINES = ["top", "middle", "bottom", "hidden"] as const;
4export type SidebarRowLine = (typeof SIDEBAR_ROW_LINES)[number];
5
6// Ids are stored in client settings, so never rename one.
7export const SIDEBAR_ROW_ITEMS = [
8 { id: "title", label: msg("Thread title") },
9 { id: "projectIcon", label: msg("Project icon") },
10 { id: "projectName", label: msg("Project name") },
11 { id: "environment", label: msg("Environment") },
12 { id: "branch", label: msg("Branch and worktree") },
13 { id: "terminals", label: msg("Running terminals") },
14 { id: "pullRequest", label: msg("Pull request") },
15 { id: "issues", label: msg("Linked issues") },
16 // Stored as "agents" from before it was named; it is the provider running the thread.
17 {
18 id: "agents",
19 label: msg("Provider", { $context: "the AI provider running a thread, shown as its logo" }),
20 },
21 { id: "subagents", label: msg("Running subagents") },
22 // A thread's status, such as Working or Done, shows in the time's place.
23 {
24 id: "time",
25 label: msg("Time and status", {
26 $context: "how long ago a thread was active, or its status such as Working",
27 }),
28 },
29 { id: "spacer", label: msg("Spacer", { $context: "flexible empty space in a layout" }) },
30] as const;
31
32export type SidebarRowItemId = (typeof SIDEBAR_ROW_ITEMS)[number]["id"];
33export type SidebarRowItemForm = "wide" | "compact" | "truncate" | "wrap";
34
35/**
36 * Items with more than one look; the first form is the default. Environment and branch show as
37 * icon and name ("wide") or icon only ("compact"); the title stays on one line ("truncate") or
38 * wraps onto a second ("wrap").
39 */
40const SIDEBAR_ROW_ITEM_FORMS: Partial<Record<SidebarRowItemId, ReadonlyArray<SidebarRowItemForm>>> =
41 {
42 environment: ["wide", "compact"],
43 branch: ["wide", "compact"],
44 title: ["truncate", "wrap"],
45 };
46
47/** The forms an item can take, in their default-first order; empty for items with one look. */
48export function sidebarRowItemForms(id: SidebarRowItemId): ReadonlyArray<SidebarRowItemForm> {
49 return SIDEBAR_ROW_ITEM_FORMS[id] ?? [];
50}
51
52export interface SidebarRowToken {
53 readonly id: SidebarRowItemId;
54 readonly form: SidebarRowItemForm | null;
55 /** Unique within a layout, so several spacers can be told apart while dragging. */
56 readonly key: string;
57}
58
59/** Lines that may collapse when a thread has nothing for them; the top line always shows. */
60export type SidebarRowCollapsibleLine = "middle" | "bottom";
61
62export type SidebarRowLayout = Readonly<Record<SidebarRowLine, ReadonlyArray<SidebarRowToken>>> & {
63 /** Lines kept even when empty, so every card has the same height. */
64 readonly keepLines: ReadonlyArray<SidebarRowCollapsibleLine>;
65};
66
67type MutableLayout = Record<SidebarRowLine, SidebarRowToken[]> & {
68 keepLines: ReadonlyArray<SidebarRowCollapsibleLine>;
69};
70
71export type StoredSidebarRowLayout = Readonly<Record<string, ReadonlyArray<string>>>;
72type DefaultStoredLayout = Readonly<Record<SidebarRowLine, ReadonlyArray<string>>> & {
73 readonly keep?: ReadonlyArray<SidebarRowCollapsibleLine>;
74};
75
76// Stored as "id" or "id:form". Spacers may repeat; every other item appears once.
77// The card as it looked before rows could be arranged, so nobody's sidebar changes until they edit
78// it. Running subagents is new; it only shows while a thread runs some.
79const DEFAULT_STORED_LAYOUT: DefaultStoredLayout = {
80 top: ["projectIcon", "projectName", "spacer", "time"],
81 middle: ["title"],
82 bottom: [
83 "environment:wide",
84 "spacer",
85 "terminals",
86 "subagents",
87 "pullRequest",
88 "issues",
89 "agents",
90 ],
91 hidden: ["branch:wide"],
92};
93
94const ITEM_IDS = new Set<string>(SIDEBAR_ROW_ITEMS.map((item) => item.id));
95
96function parseToken(stored: string): Omit<SidebarRowToken, "key"> | null {
97 const [id, form] = stored.split(":");
98 if (id === undefined || !ITEM_IDS.has(id)) return null;
99 const forms = SIDEBAR_ROW_ITEM_FORMS[id as SidebarRowItemId];
100 return {
101 id: id as SidebarRowItemId,
102 form: forms ? (forms.find((candidate) => candidate === form) ?? forms[0] ?? null) : null,
103 };
104}
105
106/** Mobile's thread list keeps its two-line look until someone edits the layout. */
107export const MOBILE_DEFAULT_STORED_LAYOUT: DefaultStoredLayout = {
108 top: ["projectIcon", "title:wrap", "time"],
109 middle: [],
110 bottom: ["environment:wide", "spacer", "pullRequest", "agents"],
111 hidden: ["projectName", "branch:wide", "terminals", "subagents", "issues"],
112 keep: ["middle", "bottom"],
113};
114
115export function resolveSidebarRowLayout(
116 stored: StoredSidebarRowLayout,
117 defaults: DefaultStoredLayout = DEFAULT_STORED_LAYOUT,
118): SidebarRowLayout {
119 const placed = new Set<string>();
120 let spacers = 0;
121 const layout: MutableLayout = {
122 top: [],
123 middle: [],
124 bottom: [],
125 hidden: [],
126 keepLines: [],
127 };
128 const place = (line: SidebarRowLine, token: Omit<SidebarRowToken, "key">) => {
129 if (token.id === "spacer") {
130 if (line !== "hidden") layout[line].push({ ...token, key: `spacer-${spacers++}` });
131 return;
132 }
133 if (placed.has(token.id)) return;
134 placed.add(token.id);
135 // Every row needs its title, so a hidden title goes back to the middle line.
136 layout[token.id === "title" && line === "hidden" ? "middle" : line].push({
137 ...token,
138 key: token.id,
139 });
140 };
141 const hasStored = SIDEBAR_ROW_LINES.some((line) => (stored[line]?.length ?? 0) > 0);
142 // Stored under "keep" next to the lines.
143 const keep = hasStored ? stored.keep : defaults.keep;
144 // Height is all-or-nothing: an older layout that kept one line keeps both.
145 layout.keepLines = keep?.some((line) => line === "middle" || line === "bottom")
146 ? ["middle", "bottom"]
147 : [];
148 for (const line of SIDEBAR_ROW_LINES) {
149 for (const value of (hasStored ? stored[line] : defaults[line]) ?? []) {
150 const token = parseToken(value);
151 if (token) place(line, token);
152 }
153 }
154 // Items a saved layout never mentions, such as ones added later, take their default line.
155 for (const line of SIDEBAR_ROW_LINES) {
156 for (const value of defaults[line]) {
157 const token = parseToken(value);
158 if (token && token.id !== "spacer") place(line, token);
159 }
160 }
161 return layout;
162}
163
164export const DEFAULT_SIDEBAR_ROW_LAYOUT = resolveSidebarRowLayout({});
165
166function storedLines(layout: SidebarRowLayout): Record<SidebarRowLine | "keep", string[]> {
167 return {
168 ...(Object.fromEntries(
169 SIDEBAR_ROW_LINES.map((line) => [
170 line,
171 layout[line].map((token) => (token.form ? `${token.id}:${token.form}` : token.id)),
172 ]),
173 ) as Record<SidebarRowLine, string[]>),
174 keep: [...layout.keepLines],
175 };
176}
177
178export function isDefaultSidebarRowLayout(
179 layout: SidebarRowLayout,
180 defaults: DefaultStoredLayout = DEFAULT_STORED_LAYOUT,
181) {
182 // Compared resolved, so a default written without its form ("title") equals "title:truncate".
183 const stored = storedLines(layout);
184 const expected = storedLines(resolveSidebarRowLayout({}, defaults));
185 return (
186 stored.keep.join() === expected.keep.join() &&
187 SIDEBAR_ROW_LINES.every((line) => stored[line].join() === expected[line].join())
188 );
189}
190
191/** A layout equal to the default saves as `{}`, so later default changes still reach it. */
192export function storedSidebarRowLayout(
193 layout: SidebarRowLayout,
194 defaults: DefaultStoredLayout = DEFAULT_STORED_LAYOUT,
195): StoredSidebarRowLayout {
196 return isDefaultSidebarRowLayout(layout, defaults) ? {} : storedLines(layout);
197}
198
199export function findSidebarRowToken(layout: SidebarRowLayout, key: string) {
200 for (const line of SIDEBAR_ROW_LINES) {
201 const index = layout[line].findIndex((token) => token.key === key);
202 const token = layout[line][index];
203 if (token) return { line, index, token };
204 }
205 return null;
206}
207
208function mapLines(
209 layout: SidebarRowLayout,
210 map: (tokens: ReadonlyArray<SidebarRowToken>) => SidebarRowToken[],
211): MutableLayout {
212 return {
213 ...(Object.fromEntries(SIDEBAR_ROW_LINES.map((line) => [line, map(layout[line])])) as Record<
214 SidebarRowLine,
215 SidebarRowToken[]
216 >),
217 keepLines: layout.keepLines,
218 };
219}
220
221function withoutToken(layout: SidebarRowLayout, key: string) {
222 return mapLines(layout, (tokens) => tokens.filter((token) => token.key !== key));
223}
224
225/**
226 * Moves a token to `index` of `line`; an index past the end appends. A spacer moved to hidden is
227 * removed, and the title cannot be hidden.
228 */
229export function moveSidebarRowToken(
230 layout: SidebarRowLayout,
231 key: string,
232 line: SidebarRowLine,
233 index: number,
234): SidebarRowLayout {
235 const found = findSidebarRowToken(layout, key);
236 if (!found || (found.token.id === "title" && line === "hidden")) return layout;
237 const next = withoutToken(layout, key);
238 if (found.token.id === "spacer" && line === "hidden") return next;
239 next[line].splice(Math.max(0, Math.min(index, next[line].length)), 0, found.token);
240 return next;
241}
242
243export function setSidebarRowTokenForm(
244 layout: SidebarRowLayout,
245 key: string,
246 form: SidebarRowItemForm,
247): SidebarRowLayout {
248 return mapLines(layout, (tokens) =>
249 tokens.map((token) =>
250 token.key === key && sidebarRowItemForms(token.id).includes(form)
251 ? { ...token, form }
252 : token,
253 ),
254 );
255}
256
257export function setSidebarRowLineKept(
258 layout: SidebarRowLayout,
259 line: SidebarRowCollapsibleLine,
260 kept: boolean,
261): SidebarRowLayout {
262 const others = layout.keepLines.filter((candidate) => candidate !== line);
263 return { ...layout, keepLines: kept ? [...others, line] : others };
264}
265
266export function insertSidebarRowSpacer(
267 layout: SidebarRowLayout,
268 line: Exclude<SidebarRowLine, "hidden">,
269 index: number,
270): { layout: SidebarRowLayout; key: string } {
271 const used = new Set(SIDEBAR_ROW_LINES.flatMap((name) => layout[name].map((t) => t.key)));
272 let n = 0;
273 while (used.has(`spacer-${n}`)) n++;
274 const key = `spacer-${n}`;
275 const next = withoutToken(layout, key);
276 next[line].splice(Math.max(0, Math.min(index, next[line].length)), 0, {
277 id: "spacer",
278 form: null,
279 key,
280 });
281 return { layout: next, key };
282}
283
284/** Hides an item without saving, as mobile does for terminals, which its list does not track. */
285export function withoutSidebarRowItem(
286 layout: SidebarRowLayout,
287 id: SidebarRowItemId,
288): SidebarRowLayout {
289 return moveSidebarRowToken(layout, id, "hidden", Number.POSITIVE_INFINITY);
290}
291
292export type SidebarRowVisibleLine = Exclude<SidebarRowLine, "hidden">;
293
294/**
295 * What each line of a thread row holds, or null when it folds away. A line with nothing but
296 * agents and spacers folds, and its agents join the title's line. A kept line holds its place
297 * unless it has no items at all, which would only add an empty row to every card. A spacer counts:
298 * a line holding only a spacer is a blank line someone asked for.
299 */
300export function resolveSidebarRowLines(input: {
301 readonly lines: Readonly<Record<SidebarRowVisibleLine, ReadonlyArray<SidebarRowToken>>>;
302 readonly titleLine: SidebarRowVisibleLine;
303 readonly keepLines: ReadonlyArray<SidebarRowCollapsibleLine>;
304 /** False when this thread has nothing to show for the item, such as no pull request. */
305 readonly hasContent: (token: SidebarRowToken) => boolean;
306}): Record<SidebarRowVisibleLine, ReadonlyArray<SidebarRowToken> | null> {
307 const folds = (line: SidebarRowVisibleLine) => {
308 const tokens = input.lines[line];
309 const kept = line !== "top" && input.keepLines.includes(line) && tokens.length > 0;
310 return (
311 line !== "top" &&
312 line !== input.titleLine &&
313 !kept &&
314 !tokens.some(
315 (token) => token.id !== "agents" && token.id !== "spacer" && input.hasContent(token),
316 )
317 );
318 };
319 const folded = (["middle", "bottom"] as const).filter(folds);
320 const foldedAgents = folded.flatMap((line) =>
321 input.lines[line].filter((token) => token.id === "agents"),
322 );
323 const resolve = (line: SidebarRowVisibleLine) =>
324 folded.includes(line as SidebarRowCollapsibleLine)
325 ? null
326 : line === input.titleLine
327 ? [...input.lines[line], ...foldedAgents]
328 : input.lines[line];
329 return { top: resolve("top"), middle: resolve("middle"), bottom: resolve("bottom") };
330}