feat(web): add tree view for changes panel (#1026)

This commit is contained in:
Carlos Florêncio
2026-05-23 21:19:30 +01:00
committed by GitHub
parent 586efd1c6b
commit 2c15cf83a9
23 changed files with 716 additions and 45 deletions
@@ -67,6 +67,7 @@ func (c *Controller) UpdateUserSettings(ctx context.Context, req dto.UpdateUserS
TerminalLinkBehavior: req.TerminalLinkBehavior,
TerminalFontFamily: req.TerminalFontFamily,
TerminalFontSize: req.TerminalFontSize,
ChangesPanelLayout: req.ChangesPanelLayout,
})
if err != nil {
return dto.UserSettingsResponse{}, err
+3
View File
@@ -38,6 +38,7 @@ type UserSettingsDTO struct {
TerminalLinkBehavior string `json:"terminal_link_behavior"`
TerminalFontFamily string `json:"terminal_font_family"`
TerminalFontSize int `json:"terminal_font_size"`
ChangesPanelLayout string `json:"changes_panel_layout"`
UpdatedAt string `json:"updated_at"`
}
@@ -80,6 +81,7 @@ type UpdateUserSettingsRequest struct {
TerminalLinkBehavior *string `json:"terminal_link_behavior,omitempty"`
TerminalFontFamily *string `json:"terminal_font_family,omitempty"`
TerminalFontSize *int `json:"terminal_font_size,omitempty"`
ChangesPanelLayout *string `json:"changes_panel_layout,omitempty"`
}
func FromUser(user *models.User) UserDTO {
@@ -117,6 +119,7 @@ func FromUserSettings(settings *models.UserSettings) UserSettingsDTO {
TerminalLinkBehavior: settings.TerminalLinkBehavior,
TerminalFontFamily: settings.TerminalFontFamily,
TerminalFontSize: settings.TerminalFontSize,
ChangesPanelLayout: settings.ChangesPanelLayout,
UpdatedAt: settings.UpdatedAt.Format(time.RFC3339),
}
}
@@ -37,6 +37,7 @@ type UserSettings struct {
TerminalLinkBehavior string `json:"terminal_link_behavior"` // "new_tab" | "browser_panel"
TerminalFontFamily string `json:"terminal_font_family"`
TerminalFontSize int `json:"terminal_font_size"`
ChangesPanelLayout string `json:"changes_panel_layout"` // "flat" | "tree"
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
@@ -52,6 +52,7 @@ type UpdateUserSettingsRequest struct {
TerminalLinkBehavior *string
TerminalFontFamily *string
TerminalFontSize *int
ChangesPanelLayout *string
}
func NewService(repo store.Repository, eventBus bus.EventBus, log *logger.Logger) *Service {
@@ -174,6 +175,9 @@ func applyBasicSettings(settings *models.UserSettings, req *UpdateUserSettingsRe
if err := applyTerminalLinkBehavior(settings, req.TerminalLinkBehavior); err != nil {
return err
}
if err := applyChangesPanelLayout(settings, req.ChangesPanelLayout); err != nil {
return err
}
if req.TerminalFontFamily != nil {
settings.TerminalFontFamily = strings.TrimSpace(*req.TerminalFontFamily)
}
@@ -199,6 +203,18 @@ func applyTerminalLinkBehavior(settings *models.UserSettings, value *string) err
return nil
}
func applyChangesPanelLayout(settings *models.UserSettings, value *string) error {
if value == nil {
return nil
}
v := strings.TrimSpace(*value)
if v != "flat" && v != "tree" {
return errors.New("changes_panel_layout must be 'flat' or 'tree'")
}
settings.ChangesPanelLayout = v
return nil
}
// applyChatSubmitKey validates and applies the chat_submit_key setting.
func (s *Service) applyChatSubmitKey(settings *models.UserSettings, req *UpdateUserSettingsRequest) error {
if req.ChatSubmitKey == nil {
@@ -310,6 +326,7 @@ func (s *Service) publishUserSettingsEvent(ctx context.Context, settings *models
"terminal_link_behavior": settings.TerminalLinkBehavior,
"terminal_font_family": settings.TerminalFontFamily,
"terminal_font_size": settings.TerminalFontSize,
"changes_panel_layout": settings.ChangesPanelLayout,
"updated_at": settings.UpdatedAt.Format(time.RFC3339),
}
if err := s.eventBus.Publish(ctx, events.UserSettingsUpdated, bus.NewEvent(events.UserSettingsUpdated, "user-service", data)); err != nil {
@@ -134,6 +134,60 @@ func TestApplyBasicSettings_TerminalFontFamily(t *testing.T) {
})
}
func TestApplyChangesPanelLayout(t *testing.T) {
t.Run("nil leaves settings unchanged", func(t *testing.T) {
settings := &models.UserSettings{ChangesPanelLayout: "tree"}
req := &UpdateUserSettingsRequest{}
if err := applyBasicSettings(settings, req); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if settings.ChangesPanelLayout != "tree" {
t.Fatalf("expected ChangesPanelLayout=tree, got %s", settings.ChangesPanelLayout)
}
})
t.Run("sets tree when provided", func(t *testing.T) {
settings := &models.UserSettings{}
req := &UpdateUserSettingsRequest{ChangesPanelLayout: ptr("tree")}
if err := applyBasicSettings(settings, req); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if settings.ChangesPanelLayout != "tree" {
t.Fatalf("expected ChangesPanelLayout=tree, got %s", settings.ChangesPanelLayout)
}
})
t.Run("sets flat when provided", func(t *testing.T) {
settings := &models.UserSettings{ChangesPanelLayout: "tree"}
req := &UpdateUserSettingsRequest{ChangesPanelLayout: ptr("flat")}
if err := applyBasicSettings(settings, req); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if settings.ChangesPanelLayout != "flat" {
t.Fatalf("expected ChangesPanelLayout=flat, got %s", settings.ChangesPanelLayout)
}
})
t.Run("rejects invalid value", func(t *testing.T) {
settings := &models.UserSettings{}
req := &UpdateUserSettingsRequest{ChangesPanelLayout: ptr("grid")}
if err := applyBasicSettings(settings, req); err == nil {
t.Fatal("expected error for invalid layout, got nil")
}
})
t.Run("trims whitespace before validation", func(t *testing.T) {
settings := &models.UserSettings{}
req := &UpdateUserSettingsRequest{ChangesPanelLayout: ptr(" tree ")}
if err := applyBasicSettings(settings, req); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if settings.ChangesPanelLayout != "tree" {
t.Fatalf("expected ChangesPanelLayout=tree, got %q", settings.ChangesPanelLayout)
}
})
}
func TestApplyBasicSettings_TerminalFontSize(t *testing.T) {
t.Run("nil leaves settings unchanged", func(t *testing.T) {
settings := &models.UserSettings{TerminalFontSize: 14}
@@ -161,6 +161,7 @@ func (r *sqliteRepository) UpsertUserSettings(ctx context.Context, settings *mod
"terminal_link_behavior": settings.TerminalLinkBehavior,
"terminal_font_family": settings.TerminalFontFamily,
"terminal_font_size": settings.TerminalFontSize,
"changes_panel_layout": settings.ChangesPanelLayout,
})
if err != nil {
return err
@@ -205,6 +206,7 @@ func scanUserSettings(scanner interface{ Scan(dest ...any) error }, userID strin
settings.ChatSubmitKey = "cmd_enter"
settings.KeyboardShortcuts = map[string]interface{}{}
settings.TerminalLinkBehavior = "new_tab"
settings.ChangesPanelLayout = "flat"
settings.SidebarViews = []models.SidebarView{}
return settings, nil
}
@@ -232,6 +234,7 @@ func scanUserSettings(scanner interface{ Scan(dest ...any) error }, userID strin
TerminalLinkBehavior string `json:"terminal_link_behavior"`
TerminalFontFamily string `json:"terminal_font_family"`
TerminalFontSize int `json:"terminal_font_size"`
ChangesPanelLayout string `json:"changes_panel_layout"`
}
if err := json.Unmarshal([]byte(settingsRaw), &payload); err != nil {
return nil, err
@@ -291,5 +294,10 @@ func scanUserSettings(scanner interface{ Scan(dest ...any) error }, userID strin
}
settings.TerminalFontFamily = payload.TerminalFontFamily
settings.TerminalFontSize = payload.TerminalFontSize
if payload.ChangesPanelLayout == "tree" {
settings.ChangesPanelLayout = "tree"
} else {
settings.ChangesPanelLayout = "flat"
}
return settings, nil
}
@@ -244,6 +244,7 @@ function buildUserSettingsFromResponse(
terminalLinkBehavior: parseTerminalLinkBehavior(s.terminal_link_behavior),
terminalFontFamily: s.terminal_font_family || null,
terminalFontSize: s.terminal_font_size || null,
changesPanelLayout: s.changes_panel_layout === "tree" ? ("tree" as const) : ("flat" as const),
...mapEditorSettingsFields(s),
};
}
@@ -8,6 +8,7 @@ import {
IconServer,
IconKeyboard,
IconTerminal2,
IconGitBranch,
} from "@tabler/icons-react";
import { Badge } from "@kandev/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@kandev/ui/card";
@@ -116,6 +117,65 @@ function ChatSubmitKeyCard() {
);
}
function ChangesPanelLayoutCard() {
const userSettings = useAppStore((state) => state.userSettings);
const setUserSettings = useAppStore((state) => state.setUserSettings);
const storeApi = useAppStoreApi();
const [isSaving, setIsSaving] = useState(false);
const handleChange = async (value: "flat" | "tree") => {
if (isSaving) return;
setIsSaving(true);
const current = storeApi.getState().userSettings;
const previous = current.changesPanelLayout;
try {
setUserSettings({ ...current, changesPanelLayout: value });
await updateUserSettings({
workspace_id: current.workspaceId || "",
repository_ids: current.repositoryIds || [],
changes_panel_layout: value,
});
} catch {
setUserSettings({ ...storeApi.getState().userSettings, changesPanelLayout: previous });
} finally {
setIsSaving(false);
}
};
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Changes Panel Layout</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
<Label htmlFor="changes-panel-layout">File list view</Label>
<Select
value={userSettings.changesPanelLayout}
onValueChange={(v) => handleChange(v as "flat" | "tree")}
disabled={isSaving}
>
<SelectTrigger
id="changes-panel-layout"
data-testid="changes-panel-layout-select"
className="cursor-pointer"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="flat">Flat list</SelectItem>
<SelectItem value="tree">Tree</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Display changed files as a flat list with full paths, or as a folder tree.
</p>
</div>
</CardContent>
</Card>
);
}
function TerminalLinksCard() {
const userSettings = useAppStore((state) => state.userSettings);
const setUserSettings = useAppStore((state) => state.setUserSettings);
@@ -450,6 +510,16 @@ export function GeneralSettings() {
<Separator />
<SettingsSection
icon={<IconGitBranch className="h-5 w-5" />}
title="Changes Panel"
description="Customize how changed files are displayed"
>
<ChangesPanelLayoutCard />
</SettingsSection>
<Separator />
<SettingsSection
icon={<IconCommand className="h-5 w-5" />}
title="Keyboard Shortcuts"
@@ -13,8 +13,9 @@ import { Button } from "@kandev/ui/button";
import { cn } from "@/lib/utils";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { LineStat } from "@/components/diff-stat";
import type { FileInfo } from "@/lib/state/store";
import { FileIcon } from "@/components/ui/file-icon";
import { FileStatusIcon } from "./file-status-icon";
import type { ChangedFile } from "./changes-panel-helpers";
import type { OpenDiffOptions } from "./changes-diff-target";
const splitPath = (path: string) => {
@@ -26,17 +27,6 @@ const splitPath = (path: string) => {
};
};
type ChangedFile = {
path: string;
status: FileInfo["status"];
staged: boolean;
plus: number | undefined;
minus: number | undefined;
oldPath: string | undefined;
/** Multi-repo: name of the repo this file lives in. Empty for single-repo. */
repositoryName?: string;
};
type FileRowProps = {
file: ChangedFile;
isPending: boolean;
@@ -52,6 +42,15 @@ type FileRowProps = {
onUnstage: (path: string, repo?: string) => void;
onDiscard: (path: string, repo?: string) => void;
onEditFile: (path: string) => void;
/**
* Tree mode: skip the folder prefix, swap the left-side stage button for a
* filetype icon, and surface the stage action only on row hover (VS Code-
* style). The Unstaged / Staged section split keeps the staged state
* visually obvious even without the always-on left chip.
*/
treeMode?: boolean;
/** Tree mode: left padding in pixels driven by depth. */
indentPx?: number;
};
export function FileRow({
@@ -65,8 +64,11 @@ export function FileRow({
onUnstage,
onDiscard,
onEditFile,
treeMode,
indentPx,
}: FileRowProps) {
const { folder, file: name } = splitPath(file.path);
const showFolder = !treeMode && folder;
const handleClick = (e: React.MouseEvent) => {
if (e.button === 2) return;
@@ -94,18 +96,25 @@ export function FileRow({
)}
onClick={handleClick}
>
<div className="flex items-center gap-2 min-w-0">
<StageButton
isPending={isPending}
staged={file.staged}
path={file.path}
repo={file.repositoryName}
onStage={onStage}
onUnstage={onUnstage}
/>
<div
className="flex items-center gap-2 min-w-0"
style={indentPx ? { paddingLeft: indentPx } : undefined}
>
{treeMode ? (
<FileIcon fileName={name} className="size-4 shrink-0" />
) : (
<StageButton
isPending={isPending}
staged={file.staged}
path={file.path}
repo={file.repositoryName}
onStage={onStage}
onUnstage={onUnstage}
/>
)}
<button type="button" className="min-w-0 text-left cursor-pointer" title={file.path}>
<p className="flex text-foreground text-xs min-w-0">
{folder && (
{showFolder && (
<span className="text-foreground/60 truncate min-w-0 [flex-shrink:9999]">
{folder}/
</span>
@@ -120,6 +129,18 @@ export function FileRow({
repo={file.repositoryName}
onDiscard={onDiscard}
onEditFile={onEditFile}
stageButton={
treeMode ? (
<StageButton
isPending={isPending}
staged={file.staged}
path={file.path}
repo={file.repositoryName}
onStage={onStage}
onUnstage={onUnstage}
/>
) : null
}
/>
<LineStat added={file.plus} removed={file.minus} />
<FileStatusIcon status={file.status} />
@@ -186,11 +207,14 @@ function FileRowActions({
repo,
onDiscard,
onEditFile,
stageButton,
}: {
path: string;
repo?: string;
onDiscard: (path: string, repo?: string) => void;
onEditFile: (path: string) => void;
/** Tree mode: stage/unstage control rendered alongside the other hover actions. */
stageButton?: React.ReactNode;
}) {
return (
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100">
@@ -224,6 +248,7 @@ function FileRowActions({
</TooltipTrigger>
<TooltipContent>Edit</TooltipContent>
</Tooltip>
{stageButton}
</div>
);
}
@@ -11,16 +11,7 @@ import { Button } from "@kandev/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { CommitRow, type CommitItem } from "./commit-row";
import { groupByRepositoryName } from "@/lib/group-by-repo";
type ChangedFile = {
path: string;
status: import("@/lib/state/store").FileInfo["status"];
staged: boolean;
plus: number | undefined;
minus: number | undefined;
oldPath: string | undefined;
repositoryName?: string;
};
import type { ChangedFile } from "./changes-panel-helpers";
export type RepoGroup = ReturnType<typeof groupByRepositoryName<ChangedFile>>[number];
@@ -25,6 +25,12 @@ vi.mock("@/hooks/use-multi-select", () => ({
}),
}));
vi.mock("@/components/state-provider", () => ({
useAppStore: (
selector: (state: { userSettings: { changesPanelLayout: "flat" | "tree" } }) => unknown,
) => selector({ userSettings: { changesPanelLayout: "flat" } }),
}));
import { FileListSection, CommitsSection } from "./changes-panel-timeline";
const REPO_HEADER_TID = "changes-repo-header";
@@ -7,7 +7,10 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { cn } from "@/lib/utils";
import type { FileInfo } from "@/lib/state/store";
import { useDockviewStore } from "@/lib/state/dockview-store";
import { useAppStore } from "@/components/state-provider";
import { FileRow, BulkActionBar } from "./changes-panel-file-row";
import { ChangesTree, RepoTreeGroup } from "./changes-panel-tree";
import type { ChangedFile } from "./changes-panel-helpers";
import { type CommitItem } from "./commit-row";
import { groupByRepositoryName, isSingleRepoGroup } from "@/lib/group-by-repo";
import {
@@ -21,17 +24,6 @@ import type { OpenDiffOptions } from "./changes-diff-target";
// --- Timeline visual components ---
type ChangedFile = {
path: string;
status: FileInfo["status"];
staged: boolean;
plus: number | undefined;
minus: number | undefined;
oldPath: string | undefined;
/** Repository this file belongs to in multi-repo workspaces; empty for single-repo. */
repositoryName?: string;
};
// Per-repo grouping is shared with the Review dialog — see @/lib/group-by-repo.
// --- Timeline section dot colors ---
@@ -274,11 +266,12 @@ type FileListBodyProps = {
};
function FileListBody(props: FileListBodyProps) {
const { variant, files, pendingStageFiles, multiSelect } = props;
const { files, pendingStageFiles, multiSelect } = props;
// Multi-repo nuance: activeFilePath carries the path but not repo; same path
// in two repos will light up both rows. Matches existing routing limit noted
// in FileRowProps comments.
const activeFilePath = useDockviewStore((s) => s.activeFilePath);
const layout = useAppStore((s) => s.userSettings.changesPanelLayout);
const groups = useMemo(() => groupByRepositoryName(files, (f) => f.repositoryName), [files]);
// Per-repo collapsed state: keyed by repositoryName. Default expanded;
// setting an entry to true collapses that group. Persists across re-renders
@@ -313,6 +306,92 @@ function FileListBody(props: FileListBodyProps) {
// / Commit / Unstage all) move up to the section header — see FileListSection.
const isSingleRepo = isSingleRepoGroup(groups);
if (layout === "tree") {
return (
<TreeFileListBody
{...props}
groups={groups}
isSingleRepo={isSingleRepo}
collapsedRepos={collapsedRepos}
toggleRepo={toggleRepo}
/>
);
}
return (
<FlatFileListBody
{...props}
groups={groups}
isSingleRepo={isSingleRepo}
collapsedRepos={collapsedRepos}
toggleRepo={toggleRepo}
renderRow={renderRow}
/>
);
}
type FileListBranchProps = FileListBodyProps & {
groups: ReturnType<typeof groupByRepositoryName<ChangedFile>>;
isSingleRepo: boolean;
collapsedRepos: Set<string>;
toggleRepo: (name: string) => void;
};
function TreeFileListBody(props: FileListBranchProps) {
const {
variant,
groups,
isSingleRepo,
collapsedRepos,
toggleRepo,
pendingStageFiles,
multiSelect,
} = props;
return (
<div tabIndex={-1} onKeyDown={props.onKeyDown}>
{isSingleRepo ? (
<ChangesTree
files={groups[0].items}
pendingStageFiles={pendingStageFiles}
onOpenDiff={props.onOpenDiff}
onEditFile={props.onEditFile}
onStage={props.onStage}
onUnstage={props.onUnstage}
onDiscard={props.onDiscard}
variant={variant}
multiSelect={multiSelect}
/>
) : (
groups.map((group) => (
<RepoTreeGroup
key={group.repositoryName || "__no_repo__"}
variant={variant}
repositoryName={group.repositoryName}
displayName={props.repoDisplayName?.(group.repositoryName)}
files={group.items}
pendingStageFiles={pendingStageFiles}
collapsed={collapsedRepos.has(group.repositoryName)}
onToggle={() => toggleRepo(group.repositoryName)}
onOpenDiff={props.onOpenDiff}
onEditFile={props.onEditFile}
onStage={props.onStage}
onUnstage={props.onUnstage}
onDiscard={props.onDiscard}
primaryLabel={props.primaryLabel}
secondaryLabel={props.secondaryLabel}
onRepoAction={props.onRepoAction}
onRepoSecondaryAction={props.onRepoSecondaryAction}
multiSelect={multiSelect}
/>
))
)}
</div>
);
}
function FlatFileListBody(
props: FileListBranchProps & { renderRow: (file: ChangedFile) => React.ReactNode },
) {
const { variant, groups, isSingleRepo, collapsedRepos, toggleRepo, renderRow } = props;
return (
<div>
<ul
@@ -0,0 +1,107 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import { render, screen, cleanup, fireEvent } from "@testing-library/react";
import type { ComponentProps } from "react";
vi.mock("./changes-panel-file-row", () => ({
FileRow: ({ file, indentPx }: { file: { path: string }; indentPx?: number }) => (
<li data-testid="file-row" data-indent={indentPx ?? 0}>
{file.path}
</li>
),
}));
vi.mock("@/lib/state/dockview-store", () => ({
useDockviewStore: () => null,
}));
import { ChangesTree } from "./changes-panel-tree";
afterEach(cleanup);
type Props = ComponentProps<typeof ChangesTree>;
const stubMultiSelect: Props["multiSelect"] = {
selectedPaths: new Set<string>(),
isSelected: () => false,
handleClick: vi.fn(() => false),
clearSelection: vi.fn(),
selectAll: vi.fn(),
setSelectedPaths: vi.fn(),
};
const baseProps: Omit<Props, "files" | "variant"> = {
pendingStageFiles: new Set(),
onOpenDiff: vi.fn(),
onEditFile: vi.fn(),
onStage: vi.fn(),
onUnstage: vi.fn(),
onDiscard: vi.fn(),
multiSelect: stubMultiSelect,
};
function file(path: string): Props["files"][number] {
return {
path,
status: "modified",
staged: false,
plus: 1,
minus: 0,
oldPath: undefined,
};
}
const APPS_WEB_DIR = "tree-dir-apps-web";
const FOO_TS = "apps/web/foo.ts";
const BAR_TS = "apps/web/bar.ts";
describe("ChangesTree", () => {
it("renders folders as dir rows and files as file rows", () => {
render(
<ChangesTree
{...baseProps}
variant="unstaged"
files={[file(FOO_TS), file(BAR_TS), file("README.md")]}
/>,
);
// Two file rows under apps/web plus README at root.
expect(screen.getAllByTestId("file-row")).toHaveLength(3);
// A directory row exists for "apps/web" (chain-collapsed).
const dir = screen.getByTestId(APPS_WEB_DIR);
expect(dir.textContent).toContain("apps/web");
});
it("collapses a single-child dir chain into one row", () => {
render(<ChangesTree {...baseProps} variant="unstaged" files={[file("a/b/c/file.ts")]} />);
// The chain a/b/c renders as a single dir row keyed by the deepest path.
const dir = screen.getByTestId("tree-dir-a-b-c");
expect(dir.textContent).toContain("a/b/c");
});
it("hides children when a folder is collapsed", () => {
render(<ChangesTree {...baseProps} variant="unstaged" files={[file(FOO_TS), file(BAR_TS)]} />);
expect(screen.getAllByTestId("file-row")).toHaveLength(2);
fireEvent.click(screen.getByTestId(APPS_WEB_DIR));
expect(screen.queryAllByTestId("file-row")).toHaveLength(0);
});
it("uses the parent multiSelect (not an internal one) so bulk actions stay wired", () => {
// Regression: tree mode used to instantiate its own useMultiSelect, which
// left the section-level BulkActionBar blind to tree selections. Verify
// the prop is consulted by checking that isSelected/handleClick come from
// the supplied object.
const isSelected = vi.fn(() => true);
const handleClick = vi.fn(() => false);
render(
<ChangesTree
{...baseProps}
multiSelect={{ ...stubMultiSelect, isSelected, handleClick }}
variant="unstaged"
files={[file(FOO_TS)]}
/>,
);
// Our FileRow mock surfaces isSelected via a data attribute when wired.
// Even without the attribute, the spy proves the parent's hook ran for
// this file's path during render.
expect(isSelected).toHaveBeenCalledWith(FOO_TS);
});
});
@@ -0,0 +1,277 @@
"use client";
import { useEffect, useMemo, useRef } from "react";
import { IconChevronDown, IconChevronRight } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { useTree, type VisibleRow } from "@/hooks/use-tree";
import { useDockviewStore } from "@/lib/state/dockview-store";
import type { useMultiSelect } from "@/hooks/use-multi-select";
import { FileRow } from "./changes-panel-file-row";
import type { ChangedFile } from "./changes-panel-helpers";
import type { OpenDiffOptions } from "./changes-diff-target";
type TreeNode = {
name: string;
path: string;
isDir: boolean;
children?: TreeNode[];
file?: ChangedFile;
};
/**
* Build a hierarchical tree from a flat list of changed files. Single-child
* directory chains stay separate nodes — useTree's `chainCollapse` merges them
* into one row at render time.
*/
function buildChangesTree(files: ChangedFile[]): TreeNode[] {
const root: TreeNode = { name: "", path: "", isDir: true, children: [] };
for (const file of files) {
const parts = file.path.split("/");
let current = root;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const isLast = i === parts.length - 1;
const partPath = parts.slice(0, i + 1).join("/");
if (isLast) {
current.children!.push({ name: part, path: file.path, isDir: false, file });
} else {
let child = current.children!.find((c) => c.isDir && c.name === part);
if (!child) {
child = { name: part, path: partPath, isDir: true, children: [] };
current.children!.push(child);
}
current = child;
}
}
}
return sortNodes(root.children ?? []);
}
function sortNodes(nodes: TreeNode[]): TreeNode[] {
return nodes
.sort((a, b) => {
if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
return a.name.localeCompare(b.name);
})
.map((n) => (n.isDir && n.children ? { ...n, children: sortNodes(n.children) } : n));
}
const GET_PATH = (n: TreeNode) => n.path;
const GET_CHILDREN = (n: TreeNode) => n.children;
const IS_DIR = (n: TreeNode) => n.isDir;
function collectDirPaths(nodes: TreeNode[]): string[] {
const out: string[] = [];
const walk = (list: TreeNode[]) => {
for (const n of list) {
if (n.isDir) {
out.push(n.path);
if (n.children) walk(n.children);
}
}
};
walk(nodes);
return out;
}
type ChangesTreeProps = {
files: ChangedFile[];
pendingStageFiles: Set<string>;
onOpenDiff: (path: string, options?: OpenDiffOptions) => void;
onEditFile: (path: string) => void;
onStage: (path: string, repo?: string) => void;
onUnstage: (path: string, repo?: string) => void;
onDiscard: (path: string, repo?: string) => void;
variant: "unstaged" | "staged";
/** Shared with the parent FileListSection so the BulkActionBar reflects
* selections made in tree mode. */
multiSelect: ReturnType<typeof useMultiSelect>;
};
export function ChangesTree({
files,
pendingStageFiles,
onOpenDiff,
onEditFile,
onStage,
onUnstage,
onDiscard,
variant,
multiSelect,
}: ChangesTreeProps) {
const tree = useMemo(() => buildChangesTree(files), [files]);
const { visibleRows, toggle, setExpanded } = useTree<TreeNode>({
nodes: tree,
getPath: GET_PATH,
getChildren: GET_CHILDREN,
isDir: IS_DIR,
defaultExpanded: "all",
chainCollapse: true,
});
// Auto-expand directories the user hasn't seen yet (e.g. new dirs that
// appear mid-task as the agent edits more files). Existing dirs keep
// whatever collapsed/expanded state the user set; only first-time dirs
// are forced open.
const seenDirPathsRef = useRef<Set<string>>(new Set(collectDirPaths(tree)));
useEffect(() => {
const current = collectDirPaths(tree);
const newDirs = current.filter((p) => !seenDirPathsRef.current.has(p));
if (newDirs.length === 0) return;
setExpanded((prev) => {
const next = new Set(prev);
for (const p of newDirs) next.add(p);
return next;
});
for (const p of newDirs) seenDirPathsRef.current.add(p);
}, [tree, setExpanded]);
const activeFilePath = useDockviewStore((s) => s.activeFilePath);
return (
<ul data-testid={`${variant}-file-tree`} className="space-y-0.5">
{visibleRows.map((row) =>
row.isDir ? (
<TreeDirRow key={row.path} row={row} onToggle={() => toggle(row.path)} />
) : (
<FileRow
key={`${row.node.file?.repositoryName ?? ""}:${row.path}`}
file={row.node.file!}
isPending={pendingStageFiles.has(`${row.node.file?.repositoryName ?? ""}::${row.path}`)}
isSelected={multiSelect.isSelected(row.path)}
isActive={row.path === activeFilePath}
onSelect={multiSelect.handleClick}
onOpenDiff={onOpenDiff}
onStage={onStage}
onUnstage={onUnstage}
onDiscard={onDiscard}
onEditFile={onEditFile}
treeMode
indentPx={row.depth * 12}
/>
),
)}
</ul>
);
}
type RepoTreeGroupProps = {
variant: "unstaged" | "staged";
repositoryName: string;
displayName?: string;
files: ChangedFile[];
pendingStageFiles: Set<string>;
collapsed: boolean;
onToggle: () => void;
onOpenDiff: (path: string, options?: OpenDiffOptions) => void;
onEditFile: (path: string) => void;
onStage: (path: string, repo?: string) => void;
onUnstage: (path: string, repo?: string) => void;
onDiscard: (path: string, repo?: string) => void;
primaryLabel: string;
secondaryLabel?: string;
onRepoAction?: (repo: string) => void;
onRepoSecondaryAction?: (repo: string) => void;
multiSelect: ReturnType<typeof useMultiSelect>;
};
export function RepoTreeGroup(props: RepoTreeGroupProps) {
const {
variant,
repositoryName,
displayName,
files,
pendingStageFiles,
collapsed,
onToggle,
primaryLabel,
secondaryLabel,
onRepoAction,
onRepoSecondaryAction,
} = props;
const label = displayName || repositoryName || "Repository";
const stop = (e: React.MouseEvent) => e.stopPropagation();
return (
<div data-testid="changes-repo-group" data-repository-name={repositoryName || ""}>
<div className="flex items-center justify-between gap-2 px-1 py-0.5">
<button
type="button"
className="flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground/80 uppercase tracking-wide cursor-pointer hover:text-foreground/80 min-w-0"
data-testid="changes-repo-header"
aria-expanded={!collapsed}
onClick={onToggle}
>
{collapsed ? (
<IconChevronRight className="h-3 w-3 text-muted-foreground/50 shrink-0" />
) : (
<IconChevronDown className="h-3 w-3 text-muted-foreground/50 shrink-0" />
)}
<span className="truncate">{label}</span>
<span className="text-muted-foreground/50 normal-case tracking-normal">
{files.length}
</span>
</button>
{(onRepoAction || onRepoSecondaryAction) && (
<div className="flex items-center gap-1" onClick={stop}>
{onRepoAction && (
<Button
size="sm"
variant="ghost"
className="h-5 text-[10px] px-1.5 cursor-pointer"
data-testid="repo-group-action"
onClick={() => onRepoAction(repositoryName)}
>
{primaryLabel}
</Button>
)}
{onRepoSecondaryAction && secondaryLabel && (
<Button
size="sm"
variant="ghost"
className="h-5 text-[10px] px-1.5 cursor-pointer text-muted-foreground"
data-testid="repo-group-secondary-action"
onClick={() => onRepoSecondaryAction(repositoryName)}
>
{secondaryLabel}
</Button>
)}
</div>
)}
</div>
{!collapsed && (
<ChangesTree
files={files}
pendingStageFiles={pendingStageFiles}
onOpenDiff={props.onOpenDiff}
onEditFile={props.onEditFile}
onStage={props.onStage}
onUnstage={props.onUnstage}
onDiscard={props.onDiscard}
variant={variant}
multiSelect={props.multiSelect}
/>
)}
</div>
);
}
function TreeDirRow({ row, onToggle }: { row: VisibleRow<TreeNode>; onToggle: () => void }) {
return (
<li>
<button
type="button"
className="flex items-center w-full gap-1 px-1 py-0.5 -mx-1 rounded-md hover:bg-muted/60 cursor-pointer text-xs text-foreground/70"
style={{ paddingLeft: row.depth * 12 + 4 }}
onClick={onToggle}
data-testid={`tree-dir-${row.path.replace(/[/\\]/g, "-")}`}
>
{row.isExpanded ? (
<IconChevronDown className="h-3 w-3 shrink-0 text-muted-foreground" />
) : (
<IconChevronRight className="h-3 w-3 shrink-0 text-muted-foreground" />
)}
<span className="truncate">{row.displayName}</span>
</button>
</li>
);
}
@@ -51,6 +51,7 @@ function carryForwardSettings(current: DisplaySettings) {
sidebarViews: current.sidebarViews ?? [],
defaultUtilityAgentId: current.defaultUtilityAgentId ?? null,
keyboardShortcuts: current.keyboardShortcuts ?? {},
changesPanelLayout: current.changesPanelLayout ?? "flat",
...carryForwardTerminalSettings(current),
};
}
+1
View File
@@ -51,6 +51,7 @@ export async function updateUserSettings(
terminal_link_behavior?: "new_tab" | "browser_panel";
terminal_font_family?: string;
terminal_font_size?: number;
changes_panel_layout?: "flat" | "tree";
},
options?: ApiRequestOptions,
) {
+19 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { buildCoreFields, mapUserSettingsResponse } from "./user-settings";
import { buildCoreFields, mapUserSettingsResponse, parseChangesPanelLayout } from "./user-settings";
describe("buildCoreFields", () => {
it("maps terminal_font_family to terminalFontFamily", () => {
@@ -84,4 +84,22 @@ describe("mapUserSettingsResponse", () => {
const result = mapUserSettingsResponse(null);
expect(result.terminalFontFamily).toBeNull();
});
it("defaults changesPanelLayout to flat when response is null", () => {
const result = mapUserSettingsResponse(null);
expect(result.changesPanelLayout).toBe("flat");
});
});
describe("parseChangesPanelLayout", () => {
it('returns "tree" for "tree"', () => {
expect(parseChangesPanelLayout("tree")).toBe("tree");
});
it('returns "flat" for "flat", undefined, or unknown values', () => {
expect(parseChangesPanelLayout("flat")).toBe("flat");
expect(parseChangesPanelLayout(undefined)).toBe("flat");
expect(parseChangesPanelLayout("grid")).toBe("flat");
expect(parseChangesPanelLayout("")).toBe("flat");
});
});
+6
View File
@@ -8,11 +8,16 @@ export function parseTerminalLinkBehavior(value: string | undefined): "new_tab"
return value === "browser_panel" ? "browser_panel" : "new_tab";
}
export function parseChangesPanelLayout(value: string | undefined): "flat" | "tree" {
return value === "tree" ? "tree" : "flat";
}
function buildTerminalFields(s: UserSettingsData) {
return {
terminalLinkBehavior: parseTerminalLinkBehavior(s.terminal_link_behavior),
terminalFontFamily: s.terminal_font_family || null,
terminalFontSize: s.terminal_font_size || null,
changesPanelLayout: parseChangesPanelLayout(s.changes_panel_layout),
};
}
@@ -85,6 +90,7 @@ export function mapUserSettingsResponse(response: UserSettingsResponse | null) {
terminalLinkBehavior: "new_tab" as const,
terminalFontFamily: null,
terminalFontSize: null,
changesPanelLayout: "flat" as const,
...buildLspFields(undefined),
loaded: false,
};
@@ -43,6 +43,7 @@ export const defaultSettingsState: SettingsSliceState = {
keyboardShortcuts: {},
terminalFontFamily: null,
terminalFontSize: null,
changesPanelLayout: "flat",
loaded: false,
},
};
@@ -155,6 +155,7 @@ export type UserSettingsState = {
terminalLinkBehavior: "new_tab" | "browser_panel";
terminalFontFamily: string | null;
terminalFontSize: number | null;
changesPanelLayout: "flat" | "tree";
loaded: boolean;
};
+1
View File
@@ -381,6 +381,7 @@ export type UserSettingsUpdatedPayload = {
default_utility_agent_id?: string;
keyboard_shortcuts?: Record<string, { key: string; modifiers?: Record<string, boolean> }>;
terminal_link_behavior?: string;
changes_panel_layout?: "flat" | "tree";
updated_at?: string;
};
+1
View File
@@ -430,6 +430,7 @@ export type UserSettings = {
terminal_link_behavior?: string;
terminal_font_family?: string;
terminal_font_size?: number;
changes_panel_layout?: "flat" | "tree";
updated_at: string;
};
+1
View File
@@ -30,6 +30,7 @@ export function registerUsersHandlers(store: StoreApi<AppState>): WsHandlers {
message.payload.terminal_link_behavior === "browser_panel"
? "browser_panel"
: "new_tab",
changesPanelLayout: message.payload.changes_panel_layout === "tree" ? "tree" : "flat",
loaded: true,
},
}));