chore: v2.8.23 — workspace groups, inner repos in Changes (opt-in), sub-agent tokens counted
Workspace groups: named, foldable, ordered sidebar sections kept per account (agenthub.workspace.groups); a workspace joins one from its menu, a drop on the header, a drag under a row, or Alt+Up/Down past a group's edge; headers drag to reorder; a folded header shows its most urgent state; New workspace in this group; fold/unfold all. Inner repos: GET /api/lanes/:id/repos + ?repo= on git/fs routes; the Changes panel shows a parent folder's repos only when Settings -> Git -> Changes panel turns it on (agenthub.changes.innerRepos, off by default). Cost: the hook writer adds a session's sub-agent transcripts to its tokens and hours (server/lib/subagent-usage.js) — a sub-agent on the session's own model was never counted live (~8% of a week here); an imported session is re-raised on every pass, so a claude -p run first seen with an empty transcript no longer stays at $0 (~10%). A one-time raise-only catch-up (user_version 5) re-reads ~/.claude/projects. Also: omp install script may redirect to its exact install.redirect URL (#85, repo-links test exempts it), native paste in the terminal.
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* @file workspaceGroups.test.ts
|
||||
* @description Tests for the sidebar's workspace groups store: create, rename,
|
||||
* move (by step or onto another group) and delete (which only ungroups), fold all, assignment, pruning of removed
|
||||
* workspaces, a damaged stored value, and the arrangement the sidebar draws —
|
||||
* groups in order, each keeping the drag order, ungrouped last.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import {
|
||||
WORKSPACE_GROUPS_KEY,
|
||||
arrangeByGroup,
|
||||
assignGroup,
|
||||
createGroup,
|
||||
deleteGroup,
|
||||
groupOf,
|
||||
moveGroup,
|
||||
moveGroupBefore,
|
||||
pruneWorkspaceGroups,
|
||||
readWorkspaceGroups,
|
||||
renameGroup,
|
||||
setAllFolded,
|
||||
setGroupFolded,
|
||||
} from "../workspaceGroups";
|
||||
|
||||
const lanes = (...ids: number[]) => ids.map((id) => ({ id }));
|
||||
|
||||
describe("workspaceGroups", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
it("starts empty and survives a damaged value", () => {
|
||||
expect(readWorkspaceGroups()).toEqual({ groups: [], of: {} });
|
||||
localStorage.setItem(WORKSPACE_GROUPS_KEY, "{nope");
|
||||
expect(readWorkspaceGroups()).toEqual({ groups: [], of: {} });
|
||||
});
|
||||
|
||||
it("creates a group holding workspaces, renames, folds and deletes it", () => {
|
||||
const id = createGroup(" Frontend ", [1, 2]);
|
||||
let v = readWorkspaceGroups();
|
||||
expect(v.groups).toEqual([{ id, name: "Frontend" }]);
|
||||
expect(groupOf(v, 1)?.id).toBe(id);
|
||||
renameGroup(id, " ");
|
||||
expect(readWorkspaceGroups().groups[0]!.name).toBe("Frontend");
|
||||
renameGroup(id, "Web");
|
||||
setGroupFolded(id, true);
|
||||
v = readWorkspaceGroups();
|
||||
expect(v.groups[0]).toMatchObject({ name: "Web", folded: true });
|
||||
deleteGroup(id);
|
||||
v = readWorkspaceGroups();
|
||||
expect(v.groups).toEqual([]);
|
||||
expect(v.of).toEqual({});
|
||||
});
|
||||
|
||||
it("moves a workspace between groups and out of them", () => {
|
||||
const a = createGroup("A");
|
||||
const b = createGroup("B");
|
||||
assignGroup(5, a);
|
||||
assignGroup(5, b);
|
||||
expect(readWorkspaceGroups().of["5"]).toBe(b);
|
||||
assignGroup(5, "missing");
|
||||
expect(readWorkspaceGroups().of["5"]).toBeUndefined();
|
||||
assignGroup(5, a);
|
||||
assignGroup(5, null);
|
||||
expect(readWorkspaceGroups().of["5"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reorders groups, clamped at both ends", () => {
|
||||
const a = createGroup("A");
|
||||
const b = createGroup("B");
|
||||
moveGroup(a, 1);
|
||||
expect(readWorkspaceGroups().groups.map((g) => g.id)).toEqual([b, a]);
|
||||
moveGroup(a, 5);
|
||||
expect(readWorkspaceGroups().groups.map((g) => g.id)).toEqual([b, a]);
|
||||
});
|
||||
|
||||
it("forgets removed workspaces and ignores ids naming no group", () => {
|
||||
const a = createGroup("A", [1, 2, 3]);
|
||||
pruneWorkspaceGroups([1, 3]);
|
||||
expect(readWorkspaceGroups().of).toEqual({ 1: a, 3: a });
|
||||
localStorage.setItem(
|
||||
WORKSPACE_GROUPS_KEY,
|
||||
JSON.stringify({ groups: [{ id: a, name: "A" }], of: { 1: a, 2: "gone" } })
|
||||
);
|
||||
expect(readWorkspaceGroups().of).toEqual({ 1: a });
|
||||
});
|
||||
|
||||
it("arranges groups in order, keeping the drag order, ungrouped last", () => {
|
||||
const a = createGroup("A", [4, 2]);
|
||||
const b = createGroup("B", [3]);
|
||||
moveGroup(b, -1);
|
||||
const v = readWorkspaceGroups();
|
||||
expect(arrangeByGroup(lanes(1, 2, 3, 4, 5), v).map((l) => l.id)).toEqual([3, 2, 4, 1, 5]);
|
||||
expect(groupOf(v, 2)?.id).toBe(a);
|
||||
});
|
||||
|
||||
it("moves a group before another, or last, and folds every group at once", () => {
|
||||
const a = createGroup("A");
|
||||
const b = createGroup("B");
|
||||
const c = createGroup("C");
|
||||
const ids = () => readWorkspaceGroups().groups.map((g) => g.id);
|
||||
moveGroupBefore(c, a);
|
||||
expect(ids()).toEqual([c, a, b]);
|
||||
moveGroupBefore(c, null);
|
||||
expect(ids()).toEqual([a, b, c]);
|
||||
moveGroupBefore(a, a);
|
||||
moveGroupBefore("nope", b);
|
||||
expect(ids()).toEqual([a, b, c]);
|
||||
setAllFolded(true);
|
||||
expect(readWorkspaceGroups().groups.every((g) => g.folded)).toBe(true);
|
||||
setAllFolded(false);
|
||||
expect(readWorkspaceGroups().groups.some((g) => g.folded)).toBe(false);
|
||||
});
|
||||
});
|
||||
+22
-7
@@ -895,11 +895,17 @@ async function send<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
/**
|
||||
* What a workspace git call works on: the workspace (its id) or, with
|
||||
* `session`, that session's own worktree (`claude --worktree`), or, with
|
||||
* `source`, one of the workspace's extra folders — the server resolves the
|
||||
* tree from the session or `lane_sources` row (`?session=` / `?source=`),
|
||||
* never from a path.
|
||||
* `source`, one of the workspace's extra folders, or with `repo`, a repo
|
||||
* inside the workspace folder — the server resolves the tree from the session
|
||||
* or `lane_sources` row (`?session=` / `?source=`), or accepts `?repo=` only
|
||||
* when its own walk of the folder found that repo; never from a path.
|
||||
*/
|
||||
export type GitTarget = number | { lane: number; session?: string; source?: number };
|
||||
export type GitTarget = number | { lane: number; session?: string; source?: number; repo?: string };
|
||||
|
||||
/** Which extra repo a Changes section reads: an extra folder's `lane_sources`
|
||||
* id (number), or a repo inside the workspace folder, by its path relative
|
||||
* to it (string, from `GET /lanes/:id/repos`). */
|
||||
export type GitSource = number | string;
|
||||
|
||||
/** `/lanes/<id>/git<sub>` plus `q` and the target's `session=` / `source=`. */
|
||||
function gitUrl(target: GitTarget, sub: string, q?: URLSearchParams): string {
|
||||
@@ -907,6 +913,7 @@ function gitUrl(target: GitTarget, sub: string, q?: URLSearchParams): string {
|
||||
const lane = typeof target === "number" ? target : target.lane;
|
||||
if (typeof target !== "number" && target.session) params.set("session", target.session);
|
||||
if (typeof target !== "number" && target.source) params.set("source", String(target.source));
|
||||
if (typeof target !== "number" && target.repo) params.set("repo", target.repo);
|
||||
const qs = params.toString();
|
||||
return `/lanes/${lane}/git${sub}${qs ? `?${qs}` : ""}`;
|
||||
}
|
||||
@@ -1005,13 +1012,14 @@ export interface FsTrashItem {
|
||||
/** How a taken name is settled: ask (409 EEXISTS with `names`), skip, keep both, replace. */
|
||||
export type FsConflict = "fail" | "skip" | "keep" | "replace";
|
||||
|
||||
/** The target for `laneId`: an extra folder's repo, else `session`'s worktree, else the workspace. */
|
||||
/** The target for `laneId`: an extra folder's or an inner repo, else `session`'s worktree, else the workspace. */
|
||||
export function gitTarget(
|
||||
laneId: number,
|
||||
session?: string | null,
|
||||
source?: number | null
|
||||
source?: GitSource | null
|
||||
): GitTarget {
|
||||
if (source) return { lane: laneId, source };
|
||||
if (typeof source === "string" && source) return { lane: laneId, repo: source };
|
||||
if (typeof source === "number" && source) return { lane: laneId, source };
|
||||
return session ? { lane: laneId, session } : laneId;
|
||||
}
|
||||
|
||||
@@ -4174,6 +4182,13 @@ export const api = {
|
||||
/** GET /api/lanes/:id/sources — the workspace's instructions, extra
|
||||
* folders and context files, and whether its tool can take them. */
|
||||
sources: (id: number) => request<LaneSourcesView>(`/lanes/${id}/sources`),
|
||||
/** GET /api/lanes/:id/repos — the git repos inside the workspace folder
|
||||
* (a parent folder of several repos), each a Changes section read with
|
||||
* `?repo=<path>`; `root` = the folder itself is in a repo. */
|
||||
repos: (id: number, refresh = false) =>
|
||||
request<{ root: boolean; items: { path: string; name: string }[]; truncated: boolean }>(
|
||||
`/lanes/${id}/repos${refresh ? "?refresh=1" : ""}`
|
||||
),
|
||||
/** PUT /api/lanes/:id/instructions — appended to every new pane's system prompt. */
|
||||
setInstructions: (id: number, instructions: string | null) =>
|
||||
request<LaneSourcesView>(`/lanes/${id}/instructions`, {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* @file innerReposPref — whether the Changes panel lists the git repositories
|
||||
* INSIDE a workspace folder (a parent folder of several repos, one section
|
||||
* each via `GET /api/lanes/:id/repos`) or only the folder's own git. Off by
|
||||
* default ("own"): the panel neither walks the folder nor shows them until
|
||||
* the account turns it on in Settings → Git → Changes panel. One account
|
||||
* preference, `agenthub.changes.innerRepos` (`lib/userPrefs.ts`,
|
||||
* `server/routes/me.js`), read through `useSyncExternalStore` and re-read
|
||||
* when the account's preferences load (`PREFS_EVENT`) or another tab writes.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { PREFS_EVENT } from "./workspaceGroups";
|
||||
|
||||
export const INNER_REPOS_KEY = "agenthub.changes.innerRepos";
|
||||
export type InnerReposMode = "all" | "own";
|
||||
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
export function readInnerReposMode(): InnerReposMode {
|
||||
try {
|
||||
return localStorage.getItem(INNER_REPOS_KEY) === "all" ? "all" : "own";
|
||||
} catch {
|
||||
return "own";
|
||||
}
|
||||
}
|
||||
|
||||
export function writeInnerReposMode(mode: InnerReposMode): void {
|
||||
try {
|
||||
// The default is stored as no value, so an account that never chose keeps following it.
|
||||
if (mode === "all") localStorage.setItem(INNER_REPOS_KEY, "all");
|
||||
else localStorage.removeItem(INNER_REPOS_KEY);
|
||||
} catch {
|
||||
/* disabled storage: nothing to remember */
|
||||
}
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
|
||||
function subscribe(l: () => void) {
|
||||
listeners.add(l);
|
||||
const onStorage = (e: StorageEvent) => {
|
||||
if (e.key === INNER_REPOS_KEY || e.key === null) l();
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
window.addEventListener(PREFS_EVENT, l);
|
||||
return () => {
|
||||
listeners.delete(l);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
window.removeEventListener(PREFS_EVENT, l);
|
||||
};
|
||||
}
|
||||
|
||||
export function useInnerReposMode(): InnerReposMode {
|
||||
return useSyncExternalStore(subscribe, readInnerReposMode);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* @file nativePaste — Settings → Appearance → "Paste images natively": a
|
||||
* per-browser preference in `localStorage` (`agenthub.terminal.nativePaste`,
|
||||
* deliberately NOT synced to the account — it is about this browser's
|
||||
* machine). On (the default), a `claude` pane in a local-mode dashboard opened
|
||||
* from this machine's own browser gets an image paste as `^V`, so `claude`
|
||||
* reads the desktop clipboard itself like a native terminal — nothing is
|
||||
* uploaded or copied. Off, the image is uploaded like a remote browser's. An
|
||||
* SSH tunnel's browser also reaches the dashboard by loopback, and its `^V`
|
||||
* would read the SERVER's clipboard — that is what turning it off is for.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
export const NATIVE_PASTE_KEY = "agenthub.terminal.nativePaste";
|
||||
|
||||
/** True unless this browser turned native image paste off. */
|
||||
export function readNativePaste(): boolean {
|
||||
try {
|
||||
return window.localStorage.getItem(NATIVE_PASTE_KEY) !== "off";
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeNativePaste(on: boolean) {
|
||||
try {
|
||||
if (on) window.localStorage.removeItem(NATIVE_PASTE_KEY);
|
||||
else window.localStorage.setItem(NATIVE_PASTE_KEY, "off");
|
||||
} catch {
|
||||
/* storage blocked — the default */
|
||||
}
|
||||
}
|
||||
@@ -375,6 +375,12 @@ export const SETTINGS_INDEX: {
|
||||
},
|
||||
{ section: "git", titleKey: "worktrees.claude", to: "#worktrees" },
|
||||
{ section: "git", titleKey: "worktrees.agenthub", to: "#worktrees" },
|
||||
{
|
||||
section: "git",
|
||||
titleKey: "changesPanel.innerRepos",
|
||||
keywords: ["repositories", "nested", "monorepo", "changes"],
|
||||
to: "#changes-panel",
|
||||
},
|
||||
];
|
||||
|
||||
function tier(hay: string | undefined, q: string, exact: number): number {
|
||||
|
||||
@@ -20,6 +20,7 @@ import { api } from "./api";
|
||||
import i18n from "../i18n";
|
||||
import { applyStoredTheme } from "../hooks/useTheme";
|
||||
import { FONT_SIZE_EVENT, applyUiFontSize } from "./fontSize";
|
||||
import { PREFS_EVENT } from "./workspaceGroups";
|
||||
|
||||
/** The localStorage keys an account's preferences are made of (server/routes/me.js). */
|
||||
export const PREF_KEYS = [
|
||||
@@ -44,6 +45,8 @@ export const PREF_KEYS = [
|
||||
"agenthub.tour",
|
||||
"agenthub.workspace.allTabs",
|
||||
"agenthub.markdown.view",
|
||||
"agenthub.workspace.groups",
|
||||
"agenthub.changes.innerRepos",
|
||||
] as const;
|
||||
const SYNCED = new Set<string>(PREF_KEYS);
|
||||
const PUSH_DELAY_MS = 400;
|
||||
@@ -116,6 +119,8 @@ function reapply(prefs: Record<string, string>) {
|
||||
window.dispatchEvent(new Event("sagi:prefs"));
|
||||
applyUiFontSize();
|
||||
window.dispatchEvent(new Event(FONT_SIZE_EVENT));
|
||||
// Every other store that reads these keys (the sidebar's workspace groups).
|
||||
window.dispatchEvent(new Event(PREFS_EVENT));
|
||||
const lng = prefs.i18nextLng;
|
||||
if (lng && lng !== i18n.language) void i18n.changeLanguage(lng);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* @file workspaceGroups — the sidebar's user-made workspace groups ("Frontend",
|
||||
* "Client A", …): their names, order and fold state, and which group each
|
||||
* workspace sits in. One JSON value under `agenthub.workspace.groups`, one of
|
||||
* the account preference keys (`lib/userPrefs.ts`, `server/routes/me.js`), so
|
||||
* the groups are kept per ACCOUNT on the server and follow it to any browser,
|
||||
* machine or port, and through updates. Like the drag order, it is a viewer's
|
||||
* arrangement, not a workspace fact: nothing about a lane changes, the CLI and
|
||||
* `GET /api/lanes` know nothing of it, and deleting a group only ungroups its
|
||||
* workspaces. A `useSyncExternalStore` reader cached on the raw string, so
|
||||
* every reader agrees; it re-reads when the account's preferences are loaded
|
||||
* (`PREFS_EVENT`) and when another tab writes.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
|
||||
export const WORKSPACE_GROUPS_KEY = "agenthub.workspace.groups";
|
||||
/** Fired by `userPrefs.hydrate` once an account's values are in localStorage. */
|
||||
export const PREFS_EVENT = "agenthub:prefs";
|
||||
|
||||
export interface WorkspaceGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
/** Folded shut in the sidebar. */
|
||||
folded?: boolean;
|
||||
}
|
||||
|
||||
export interface WorkspaceGroups {
|
||||
/** In display order. */
|
||||
groups: WorkspaceGroup[];
|
||||
/** Lane id → group id. A lane absent here, or naming no group, is ungrouped. */
|
||||
of: Record<string, string>;
|
||||
}
|
||||
|
||||
const EMPTY: WorkspaceGroups = { groups: [], of: {} };
|
||||
export const MAX_GROUP_NAME = 60;
|
||||
const listeners = new Set<() => void>();
|
||||
let cache: { raw: string | null; value: WorkspaceGroups } = { raw: null, value: EMPTY };
|
||||
|
||||
function readRaw(): string | null {
|
||||
try {
|
||||
return localStorage.getItem(WORKSPACE_GROUPS_KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parse(raw: string | null): WorkspaceGroups {
|
||||
if (!raw) return EMPTY;
|
||||
try {
|
||||
const v = JSON.parse(raw) as Partial<WorkspaceGroups>;
|
||||
const groups = (Array.isArray(v.groups) ? v.groups : []).filter(
|
||||
(g): g is WorkspaceGroup =>
|
||||
!!g && typeof g.id === "string" && !!g.id && typeof g.name === "string"
|
||||
);
|
||||
const ids = new Set(groups.map((g) => g.id));
|
||||
const of: Record<string, string> = {};
|
||||
if (v.of && typeof v.of === "object") {
|
||||
for (const [lane, gid] of Object.entries(v.of)) {
|
||||
if (typeof gid === "string" && ids.has(gid)) of[lane] = gid;
|
||||
}
|
||||
}
|
||||
return { groups, of };
|
||||
} catch {
|
||||
return EMPTY;
|
||||
}
|
||||
}
|
||||
|
||||
export function readWorkspaceGroups(): WorkspaceGroups {
|
||||
const raw = readRaw();
|
||||
if (raw === cache.raw) return cache.value;
|
||||
cache = { raw, value: parse(raw) };
|
||||
return cache.value;
|
||||
}
|
||||
|
||||
function write(next: WorkspaceGroups): void {
|
||||
try {
|
||||
localStorage.setItem(WORKSPACE_GROUPS_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
/* disabled storage: the groups live until the page closes */
|
||||
cache = { raw: JSON.stringify(next), value: next };
|
||||
}
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
|
||||
/** Change the groups through `fn` (given the current value, never mutated). */
|
||||
export function updateWorkspaceGroups(fn: (cur: WorkspaceGroups) => WorkspaceGroups): void {
|
||||
write(fn(readWorkspaceGroups()));
|
||||
}
|
||||
|
||||
const cleanName = (name: string) => name.trim().slice(0, MAX_GROUP_NAME);
|
||||
|
||||
/** A new group at the end, holding `laneIds` (moved out of their old group). Returns its id. */
|
||||
export function createGroup(name: string, laneIds: number[] = []): string {
|
||||
const id = `g${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
updateWorkspaceGroups((cur) => {
|
||||
const of = { ...cur.of };
|
||||
for (const lane of laneIds) of[lane] = id;
|
||||
return { groups: [...cur.groups, { id, name: cleanName(name) }], of };
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Rename; a blank name keeps the old one. */
|
||||
export function renameGroup(id: string, name: string): void {
|
||||
const clean = cleanName(name);
|
||||
if (!clean) return;
|
||||
updateWorkspaceGroups((cur) => ({
|
||||
...cur,
|
||||
groups: cur.groups.map((g) => (g.id === id ? { ...g, name: clean } : g)),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Delete the group; its workspaces become ungrouped (nothing else changes). */
|
||||
export function deleteGroup(id: string): void {
|
||||
updateWorkspaceGroups((cur) => ({
|
||||
groups: cur.groups.filter((g) => g.id !== id),
|
||||
of: Object.fromEntries(Object.entries(cur.of).filter(([, gid]) => gid !== id)),
|
||||
}));
|
||||
}
|
||||
|
||||
export function setGroupFolded(id: string, folded: boolean): void {
|
||||
updateWorkspaceGroups((cur) => ({
|
||||
...cur,
|
||||
groups: cur.groups.map((g) => (g.id === id ? { ...g, folded } : g)),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Move the group `by` places (−1 up, +1 down), clamped. */
|
||||
export function moveGroup(id: string, by: number): void {
|
||||
updateWorkspaceGroups((cur) => {
|
||||
const from = cur.groups.findIndex((g) => g.id === id);
|
||||
const to = Math.max(0, Math.min(cur.groups.length - 1, from + by));
|
||||
if (from < 0 || from === to) return cur;
|
||||
const groups = [...cur.groups];
|
||||
groups.splice(to, 0, ...groups.splice(from, 1));
|
||||
return { ...cur, groups };
|
||||
});
|
||||
}
|
||||
|
||||
/** Move the group to just before `beforeId` (a drag onto that header), or to the end (null). */
|
||||
export function moveGroupBefore(id: string, beforeId: string | null): void {
|
||||
updateWorkspaceGroups((cur) => {
|
||||
const moving = cur.groups.find((g) => g.id === id);
|
||||
if (!moving || id === beforeId) return cur;
|
||||
const rest = cur.groups.filter((g) => g.id !== id);
|
||||
const at = beforeId === null ? -1 : rest.findIndex((g) => g.id === beforeId);
|
||||
const groups = at < 0 ? [...rest, moving] : [...rest.slice(0, at), moving, ...rest.slice(at)];
|
||||
if (groups.every((g, i) => g === cur.groups[i])) return cur;
|
||||
return { ...cur, groups };
|
||||
});
|
||||
}
|
||||
|
||||
/** Fold (or unfold) every group at once. */
|
||||
export function setAllFolded(folded: boolean): void {
|
||||
updateWorkspaceGroups((cur) => ({
|
||||
...cur,
|
||||
groups: cur.groups.map((g) => (!!g.folded === folded ? g : { ...g, folded })),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Put a workspace in a group, or (null) take it out of every group. */
|
||||
export function assignGroup(laneId: number, groupId: string | null): void {
|
||||
updateWorkspaceGroups((cur) => {
|
||||
const of = { ...cur.of };
|
||||
if (groupId && cur.groups.some((g) => g.id === groupId)) of[laneId] = groupId;
|
||||
else delete of[laneId];
|
||||
return { ...cur, of };
|
||||
});
|
||||
}
|
||||
|
||||
/** Forget the lanes that no longer exist, so the stored value stays small. */
|
||||
export function pruneWorkspaceGroups(laneIds: number[]): void {
|
||||
const cur = readWorkspaceGroups();
|
||||
const live = new Set(laneIds.map(String));
|
||||
const stale = Object.keys(cur.of).filter((k) => !live.has(k));
|
||||
if (!stale.length) return;
|
||||
write({ ...cur, of: Object.fromEntries(Object.entries(cur.of).filter(([k]) => live.has(k))) });
|
||||
}
|
||||
|
||||
/**
|
||||
* `lanes` (already in the stored drag order) arranged by group: each group's
|
||||
* workspaces in group order, keeping their relative order, then the
|
||||
* ungrouped ones. Stable, never mutates.
|
||||
*/
|
||||
export function arrangeByGroup<T extends { id: number }>(lanes: T[], value: WorkspaceGroups): T[] {
|
||||
const rank = new Map(value.groups.map((g, i) => [g.id, i]));
|
||||
const at = (l: T) => {
|
||||
const gid = value.of[l.id];
|
||||
return gid !== undefined && rank.has(gid) ? rank.get(gid)! : value.groups.length;
|
||||
};
|
||||
return lanes
|
||||
.map((l, i) => ({ l, i }))
|
||||
.sort((a, b) => at(a.l) - at(b.l) || a.i - b.i)
|
||||
.map((x) => x.l);
|
||||
}
|
||||
|
||||
/** The group a workspace is in, or null. */
|
||||
export function groupOf(value: WorkspaceGroups, laneId: number): WorkspaceGroup | null {
|
||||
const gid = value.of[laneId];
|
||||
return (gid && value.groups.find((g) => g.id === gid)) || null;
|
||||
}
|
||||
|
||||
function subscribe(l: () => void) {
|
||||
listeners.add(l);
|
||||
const onStorage = (e: StorageEvent) => {
|
||||
if (e.key === WORKSPACE_GROUPS_KEY || e.key === null) l();
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
window.addEventListener(PREFS_EVENT, l);
|
||||
return () => {
|
||||
listeners.delete(l);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
window.removeEventListener(PREFS_EVENT, l);
|
||||
};
|
||||
}
|
||||
|
||||
export function useWorkspaceGroups(): WorkspaceGroups {
|
||||
return useSyncExternalStore(subscribe, readWorkspaceGroups);
|
||||
}
|
||||
Reference in New Issue
Block a user