feat: refactor sidebar to nested draggable lists with long-press gesture arbitration

This commit is contained in:
Mohamed Boudra
2026-03-04 10:27:01 +07:00
parent bf1cded8a1
commit 3c066f5dd9
14 changed files with 830 additions and 327 deletions
@@ -1,6 +1,7 @@
import { RefreshControl } from "react-native";
import { useCallback, useState } from "react";
import DraggableFlatList, {
NestableDraggableFlatList,
type RenderItemParams,
} from "react-native-draggable-flatlist";
import { useUnistyles } from "react-native-unistyles";
@@ -32,6 +33,7 @@ export function DraggableList<T>({
simultaneousGestureRef,
waitFor,
onDragBegin: onDragBeginProp,
nestable = false,
}: DraggableListProps<T>) {
const { theme } = useUnistyles();
const [isDragging, setIsDragging] = useState(false);
@@ -75,9 +77,13 @@ export function DraggableList<T>({
const showRefreshControl = Boolean(onRefresh) && (!isDragging || Boolean(refreshing));
const resolvedContainerStyle =
containerStyle ?? (scrollEnabled ? { flex: 1 } : undefined);
const ListComponent: typeof DraggableFlatList = (nestable
? (NestableDraggableFlatList as any)
: DraggableFlatList) as any;
const shouldShowRefreshControl = showRefreshControl && !nestable;
return (
<DraggableFlatList
<ListComponent
testID={testID}
data={data}
keyExtractor={keyExtractor}
@@ -99,7 +105,7 @@ export function DraggableList<T>({
// @ts-expect-error - waitFor is supported by RNGH FlatList but not typed in DraggableFlatList
waitFor={waitFor}
refreshControl={
showRefreshControl ? (
shouldShowRefreshControl ? (
<RefreshControl
refreshing={refreshing ?? false}
onRefresh={onRefresh}
@@ -52,4 +52,9 @@ export interface DraggableListProps<T> {
waitFor?: MutableRefObject<GestureType | undefined> | MutableRefObject<GestureType | undefined>[];
/** Called when a drag gesture begins (before items are reordered) */
onDragBegin?: () => void;
/**
* Native-only: use the nestable draggable-flatlist variant for nested drag
* lists coordinated by a shared NestableScrollContainer.
*/
nestable?: boolean;
}
@@ -136,6 +136,7 @@ export function DraggableList<T>({
useDragHandle = false,
// simultaneousGestureRef is native-only, ignored on web
onDragBegin,
nestable: _nestable = false,
}: DraggableListProps<T>) {
const [activeId, setActiveId] = useState<string | null>(null);
const [items, setItems] = useState(data);
File diff suppressed because it is too large Load Diff
+4 -2
View File
@@ -18,7 +18,7 @@ import {
resolveNewAgentWorkingDir,
} from "@/utils/new-agent-routing";
import {
buildHostAgentDetailRoute,
buildHostWorkspaceAgentTabRoute,
buildHostSettingsRoute,
parseHostAgentRouteFromPathname,
parseServerIdFromPathname,
@@ -230,7 +230,9 @@ export function useCommandCenter() {
// Don't restore focus back to the prior element after we navigate.
clearCommandCenterFocusRestoreElement();
setOpen(false);
navigate(buildHostAgentDetailRoute(agent.serverId, agent.id) as any);
navigate(
buildHostWorkspaceAgentTabRoute(agent.serverId, agent.cwd, agent.id) as any
);
},
[pathname, requestMessageInputAction, setOpen]
);
@@ -48,7 +48,7 @@ import type {
AgentSessionConfig,
} from '@server/server/agent/agent-sdk-types'
import { AGENT_PROVIDER_DEFINITIONS } from '@server/server/agent/provider-manifest'
import { buildHostAgentDetailRoute } from '@/utils/host-routes'
import { buildHostWorkspaceAgentTabRoute } from '@/utils/host-routes'
import { useTauriDragHandlers } from '@/utils/tauri-window'
import { useKeyboardShiftStyle } from '@/hooks/use-keyboard-shift-style'
import { normalizeAgentSnapshot } from '@/utils/agent-snapshots'
@@ -1032,7 +1032,14 @@ function DraftAgentScreenContent({
next.set(agentId, normalizeAgentSnapshot(result, selectedServerId))
return next
})
router.replace(buildHostAgentDetailRoute(selectedServerId, agentId) as any)
const createdWorkingDir =
typeof result.cwd === 'string' ? result.cwd.trim() : ''
const configuredWorkingDir = config.cwd.trim()
const workspaceId =
createdWorkingDir.length > 0 ? createdWorkingDir : configuredWorkingDir
router.replace(
buildHostWorkspaceAgentTabRoute(selectedServerId, workspaceId, agentId) as any
)
return
}
@@ -177,7 +177,7 @@ export function WorkspaceDraftAgentTab({
pendingPermissions: [],
persistence: null,
runtimeInfo: { provider: selectedProvider, sessionId: null, model, modeId },
title: "New agent",
title: "Agent",
cwd: workspaceId,
model,
thinkingOptionId,
@@ -16,7 +16,6 @@ import {
FileText,
Folder,
GitBranch,
MoreVertical,
PanelRight,
Plus,
Pencil,
@@ -31,12 +30,6 @@ import { ScreenHeader } from "@/components/headers/screen-header";
import { Combobox } from "@/components/ui/combobox";
import { ClaudeIcon } from "@/components/icons/claude-icon";
import { CodexIcon } from "@/components/icons/codex-icon";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
Tooltip,
TooltipContent,
@@ -60,7 +53,6 @@ import {
type WorkspaceTab,
} from "@/stores/workspace-tabs-store";
import {
buildHostAgentDetailRoute,
buildHostWorkspaceRoute,
buildHostWorkspaceTabRoute,
decodeWorkspaceIdFromPathSegment,
@@ -88,7 +80,6 @@ import {
} from "@/screens/workspace/workspace-header-source";
const TERMINALS_QUERY_STALE_TIME = 5_000;
const DROPDOWN_WIDTH = 220;
const NEW_TAB_AGENT_OPTION_ID = "__new_tab_agent__";
const NEW_TAB_TERMINAL_OPTION_ID = "__new_tab_terminal__";
const EMPTY_OPEN_FILE_PATHS: string[] = [];
@@ -166,6 +157,20 @@ function formatProviderLabel(provider: Agent["provider"]): string {
return provider.charAt(0).toUpperCase() + provider.slice(1);
}
function resolveWorkspaceAgentTabLabel(title: string | null | undefined): string {
if (typeof title !== "string") {
return "Agent";
}
const normalized = title.trim();
if (!normalized) {
return "Agent";
}
if (normalized.toLowerCase() === "new agent") {
return "Agent";
}
return normalized;
}
function resolveTabAvailability(input: {
tab: WorkspaceTabTarget;
agentsHydrated: boolean;
@@ -755,7 +760,7 @@ function WorkspaceScreenContent({
tabId: tab.tabId,
kind: "draft",
draftId: target.draftId,
label: "New agent",
label: "Draft",
subtitle: "Draft",
});
continue;
@@ -769,7 +774,7 @@ function WorkspaceScreenContent({
kind: "agent",
agentId: target.agentId,
provider,
label: agent?.title?.trim() || "Agent",
label: resolveWorkspaceAgentTabLabel(agent?.title),
subtitle: `${formatProviderLabel(provider)} agent`,
});
continue;
@@ -868,13 +873,6 @@ function WorkspaceScreenContent({
[tabs]
);
const activeAgent = useMemo(() => {
if (activeTab?.target.kind !== "agent") {
return null;
}
return sessionAgents?.get(activeTab.target.agentId) ?? null;
}, [activeTab, sessionAgents]);
const activeTabLabel = useMemo(() => {
const active = tabs.find((tab) => tab.key === activeTabKey);
return active?.label ?? "Select tab";
@@ -1210,15 +1208,6 @@ function WorkspaceScreenContent({
]
);
const handleOpenAgentChatView = useCallback(() => {
if (!activeAgent) {
return;
}
router.push(
buildHostAgentDetailRoute(normalizedServerId, activeAgent.id) as any
);
}, [activeAgent, normalizedServerId, router]);
const renderContent = () => {
if (
shouldRenderMissingWorkspaceDescriptor({
@@ -1385,32 +1374,6 @@ function WorkspaceScreenContent({
)}
</HeaderToggleButton>
{activeAgent ? (
<DropdownMenu>
<DropdownMenuTrigger
testID="workspace-agent-overflow-menu"
style={styles.menuButton}
>
<MoreVertical
size={isMobile ? theme.iconSize.lg : theme.iconSize.md}
color={theme.colors.foregroundMuted}
/>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
width={DROPDOWN_WIDTH}
testID="workspace-agent-overflow-content"
>
<DropdownMenuItem
testID="workspace-agent-overflow-open-chat"
description="Open this agent with the full chat header"
onSelect={handleOpenAgentChatView}
>
Open chat view
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : null}
</View>
}
/>
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import {
decideLongPressMove,
shouldOpenContextMenuOnPressOut,
} from "./sidebar-gesture-arbitration";
describe("decideLongPressMove", () => {
it("keeps long press pending for small movement before long-press arm", () => {
expect(
decideLongPressMove({
longPressArmed: false,
didStartDrag: false,
startPoint: { x: 0, y: 0 },
currentPoint: { x: 3, y: 2 },
})
).toBe("none");
});
it("cancels long press when movement exceeds cancel slop before arm", () => {
expect(
decideLongPressMove({
longPressArmed: false,
didStartDrag: false,
startPoint: { x: 0, y: 0 },
currentPoint: { x: 12, y: 0 },
})
).toBe("cancel_long_press");
});
it("starts drag when movement exceeds drag slop after long-press arm", () => {
expect(
decideLongPressMove({
longPressArmed: true,
didStartDrag: false,
startPoint: { x: 0, y: 0 },
currentPoint: { x: 0, y: 9 },
})
).toBe("start_drag");
});
it("does nothing when drag already started", () => {
expect(
decideLongPressMove({
longPressArmed: true,
didStartDrag: true,
startPoint: { x: 0, y: 0 },
currentPoint: { x: 20, y: 20 },
})
).toBe("none");
});
});
describe("shouldOpenContextMenuOnPressOut", () => {
it("opens menu only when long-press is armed and drag did not start", () => {
expect(
shouldOpenContextMenuOnPressOut({
longPressArmed: true,
didStartDrag: false,
})
).toBe(true);
expect(
shouldOpenContextMenuOnPressOut({
longPressArmed: false,
didStartDrag: false,
})
).toBe(false);
expect(
shouldOpenContextMenuOnPressOut({
longPressArmed: true,
didStartDrag: true,
})
).toBe(false);
});
});
@@ -0,0 +1,37 @@
export type LongPressMoveDecision = "none" | "cancel_long_press" | "start_drag";
export function decideLongPressMove(input: {
longPressArmed: boolean;
didStartDrag: boolean;
startPoint: { x: number; y: number } | null;
currentPoint: { x: number; y: number };
cancelSlopPx?: number;
dragSlopPx?: number;
}): LongPressMoveDecision {
const cancelSlopPx = input.cancelSlopPx ?? 10;
const dragSlopPx = input.dragSlopPx ?? 8;
if (!input.startPoint) {
return "none";
}
if (input.didStartDrag) {
return "none";
}
const dx = input.currentPoint.x - input.startPoint.x;
const dy = input.currentPoint.y - input.startPoint.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (!input.longPressArmed) {
return distance > cancelSlopPx ? "cancel_long_press" : "none";
}
return distance > dragSlopPx ? "start_drag" : "none";
}
export function shouldOpenContextMenuOnPressOut(input: {
longPressArmed: boolean;
didStartDrag: boolean;
}): boolean {
return input.longPressArmed && !input.didStartDrag;
}
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import { hasVisibleOrderChanged, mergeWithRemainder } from "./sidebar-reorder";
describe("hasVisibleOrderChanged", () => {
it("returns false when visible order is unchanged", () => {
expect(
hasVisibleOrderChanged({
currentOrder: ["a", "b", "c", "d"],
reorderedVisibleKeys: ["a", "b", "c"],
})
).toBe(false);
});
it("returns true when visible items are reordered", () => {
expect(
hasVisibleOrderChanged({
currentOrder: ["a", "b", "c", "d"],
reorderedVisibleKeys: ["b", "a", "c"],
})
).toBe(true);
});
it("returns true when a visible key is missing from current order", () => {
expect(
hasVisibleOrderChanged({
currentOrder: ["a", "b"],
reorderedVisibleKeys: ["a", "c"],
})
).toBe(true);
});
});
describe("mergeWithRemainder", () => {
it("appends non-visible stored keys after reordered visible keys", () => {
expect(
mergeWithRemainder({
currentOrder: ["a", "x", "b", "y"],
reorderedVisibleKeys: ["b", "a"],
})
).toEqual(["b", "a", "x", "y"]);
});
it("keeps unknown current keys when no visible keys are reordered", () => {
expect(
mergeWithRemainder({
currentOrder: ["stale", "hidden"],
reorderedVisibleKeys: [],
})
).toEqual(["stale", "hidden"]);
});
});
+21
View File
@@ -0,0 +1,21 @@
export function mergeWithRemainder(input: {
currentOrder: string[]
reorderedVisibleKeys: string[]
}): string[] {
const reorderedSet = new Set(input.reorderedVisibleKeys)
const remainder = input.currentOrder.filter((key) => !reorderedSet.has(key))
return [...input.reorderedVisibleKeys, ...remainder]
}
export function hasVisibleOrderChanged(input: {
currentOrder: string[]
reorderedVisibleKeys: string[]
}): boolean {
const visibleSet = new Set(input.reorderedVisibleKeys)
const currentVisible = input.currentOrder.filter((key) => visibleSet.has(key))
if (currentVisible.length !== input.reorderedVisibleKeys.length) {
return true
}
return input.reorderedVisibleKeys.some((key, index) => currentVisible[index] !== key)
}
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { SidebarProjectEntry, SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import { buildSidebarWorkspaceViewModel } from "./sidebar-shortcuts";
import { buildSidebarShortcutModel } from "./sidebar-shortcuts";
function workspace(serverId: string, cwd: string): SidebarWorkspaceEntry {
return {
@@ -27,20 +27,18 @@ function project(projectKey: string, workspaces: SidebarWorkspaceEntry[]): Sideb
};
}
describe("buildSidebarWorkspaceViewModel", () => {
it("builds visible rows and shortcut targets in visual order", () => {
describe("buildSidebarShortcutModel", () => {
it("builds shortcut targets in visual order and excludes collapsed projects", () => {
const projects = [
project("p1", [workspace("s1", "/repo/main"), workspace("s1", "/repo/feat-a")]),
project("p2", [workspace("s1", "/repo2/main")]),
];
const model = buildSidebarWorkspaceViewModel({
const model = buildSidebarShortcutModel({
projects,
collapsedProjectKeys: new Set<string>(["p2"]),
getProjectDisplayName: (entry) => entry.projectName,
});
expect(model.rows.map((row) => row.kind)).toEqual(["project", "workspace", "workspace", "project"]);
expect(model.shortcutTargets).toEqual([
{ serverId: "s1", workspaceId: "/repo/main" },
{ serverId: "s1", workspaceId: "/repo/feat-a" },
@@ -54,10 +52,9 @@ describe("buildSidebarWorkspaceViewModel", () => {
const workspaces = Array.from({ length: 20 }, (_, index) => workspace("s", `/repo/w${index + 1}`));
const projects = [project("p", workspaces)];
const model = buildSidebarWorkspaceViewModel({
const model = buildSidebarShortcutModel({
projects,
collapsedProjectKeys: new Set<string>(),
getProjectDisplayName: (entry) => entry.projectName,
});
expect(model.shortcutTargets).toHaveLength(9);
+4 -37
View File
@@ -8,46 +8,21 @@ export interface SidebarShortcutWorkspaceTarget {
workspaceId: string
}
export type SidebarWorkspaceTreeRow =
| {
kind: 'project'
rowKey: string
project: SidebarProjectEntry
displayName: string
}
| {
kind: 'workspace'
rowKey: string
projectKey: string
workspace: SidebarWorkspaceEntry
shortcutNumber: number | null
}
export interface SidebarWorkspaceViewModel {
rows: SidebarWorkspaceTreeRow[]
export interface SidebarShortcutModel {
shortcutTargets: SidebarShortcutWorkspaceTarget[]
shortcutIndexByWorkspaceKey: Map<string, number>
}
export function buildSidebarWorkspaceViewModel(input: {
export function buildSidebarShortcutModel(input: {
projects: SidebarProjectEntry[]
collapsedProjectKeys: ReadonlySet<string>
getProjectDisplayName: (project: SidebarProjectEntry) => string
shortcutLimit?: number
}): SidebarWorkspaceViewModel {
}): SidebarShortcutModel {
const maxShortcuts = Math.max(0, Math.floor(input.shortcutLimit ?? 9))
const rows: SidebarWorkspaceTreeRow[] = []
const shortcutTargets: SidebarShortcutWorkspaceTarget[] = []
const shortcutIndexByWorkspaceKey = new Map<string, number>()
for (const project of input.projects) {
rows.push({
kind: 'project',
rowKey: `project:${project.projectKey}`,
project,
displayName: input.getProjectDisplayName(project),
})
if (input.collapsedProjectKeys.has(project.projectKey)) {
continue
}
@@ -62,16 +37,8 @@ export function buildSidebarWorkspaceViewModel(input: {
})
shortcutIndexByWorkspaceKey.set(workspace.workspaceKey, shortcutNumber)
}
rows.push({
kind: 'workspace',
rowKey: `workspace:${project.projectKey}:${workspace.workspaceKey}`,
projectKey: project.projectKey,
workspace,
shortcutNumber,
})
}
}
return { rows, shortcutTargets, shortcutIndexByWorkspaceKey }
return { shortcutTargets, shortcutIndexByWorkspaceKey }
}