refactor: simplify tab layout to use equal widths with ideal clamping

This commit is contained in:
Mohamed Boudra
2026-03-18 16:59:03 +07:00
parent b5212a69c9
commit 3bdc90a661
7 changed files with 68 additions and 61 deletions
+8 -11
View File
@@ -7,7 +7,7 @@ import {
View, View,
Platform, Platform,
} from "react-native"; } from "react-native";
import { memo, useEffect, useMemo, useRef, type ReactNode } from "react"; import { memo, useEffect, useRef, type ReactNode } from "react";
import { Plus, Settings } from "lucide-react-native"; import { Plus, Settings } from "lucide-react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles"; import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { useCommandCenter } from "@/hooks/use-command-center"; import { useCommandCenter } from "@/hooks/use-command-center";
@@ -69,6 +69,9 @@ export function CommandCenter() {
const resultsRef = useRef<ScrollView>(null); const resultsRef = useRef<ScrollView>(null);
useEffect(() => { useEffect(() => {
if (!open) {
return;
}
const row = rowRefs.current.get(activeIndex); const row = rowRefs.current.get(activeIndex);
if (!row || typeof document === "undefined") { if (!row || typeof document === "undefined") {
return; return;
@@ -99,18 +102,12 @@ export function CommandCenter() {
if (rowBottom > visibleBottom) { if (rowBottom > visibleBottom) {
scrollNode.scrollTop = rowBottom - scrollNode.clientHeight; scrollNode.scrollTop = rowBottom - scrollNode.clientHeight;
} }
}, [activeIndex]); }, [activeIndex, open]);
if (Platform.OS !== "web") return null; if (Platform.OS !== "web" || !open) return null;
const actionItems = useMemo( const actionItems = items.filter((item) => item.kind === "action");
() => items.filter((item) => item.kind === "action"), const agentItems = items.filter((item) => item.kind === "agent");
[items]
);
const agentItems = useMemo(
() => items.filter((item) => item.kind === "agent"),
[items]
);
return ( return (
<Modal <Modal
@@ -680,6 +680,9 @@ function SplitPaneView({
return ( return (
<View <View
style={styles.pane} style={styles.pane}
onFocus={() => {
onFocusPane(pane.id);
}}
onPointerDownCapture={() => { onPointerDownCapture={() => {
onFocusPane(pane.id); onFocusPane(pane.id);
}} }}
@@ -769,7 +772,9 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surface0, backgroundColor: theme.colors.surface0,
overflow: "hidden", overflow: "hidden",
}, },
paneTabs: {}, paneTabs: {
minWidth: 0,
},
paneContent: { paneContent: {
position: "relative", position: "relative",
flex: 1, flex: 1,
+20 -4
View File
@@ -20,6 +20,10 @@ import {
import type { ShortcutKey } from "@/utils/format-shortcut"; import type { ShortcutKey } from "@/utils/format-shortcut";
import { focusWithRetries } from "@/utils/web-focus"; import { focusWithRetries } from "@/utils/web-focus";
const EMPTY_AGENTS: AggregatedAgent[] = [];
const EMPTY_ACTION_ITEMS: CommandCenterActionItem[] = [];
const EMPTY_COMMAND_CENTER_ITEMS: CommandCenterItem[] = [];
function isMatch(agent: AggregatedAgent, query: string): boolean { function isMatch(agent: AggregatedAgent, query: string): boolean {
if (!query) return true; if (!query) return true;
const q = query.toLowerCase(); const q = query.toLowerCase();
@@ -118,6 +122,9 @@ export function useCommandCenter() {
const [activeIndex, setActiveIndex] = useState(0); const [activeIndex, setActiveIndex] = useState(0);
const activeServerId = useMemo(() => { const activeServerId = useMemo(() => {
if (!open) {
return null;
}
const serverIdFromPath = parseServerIdFromPathname(pathname); const serverIdFromPath = parseServerIdFromPathname(pathname);
if (serverIdFromPath) { if (serverIdFromPath) {
const routeMatch = daemons.find((entry) => entry.serverId === serverIdFromPath); const routeMatch = daemons.find((entry) => entry.serverId === serverIdFromPath);
@@ -126,17 +133,20 @@ export function useCommandCenter() {
} }
} }
return daemons[0]?.serverId ?? null; return daemons[0]?.serverId ?? null;
}, [daemons, pathname]); }, [daemons, open, pathname]);
const { agents } = useAllAgentsList({ const { agents } = useAllAgentsList({
serverId: activeServerId, serverId: activeServerId,
}); });
const agentResults = useMemo(() => { const agentResults = useMemo(() => {
if (!open || agents.length === 0) {
return EMPTY_AGENTS;
}
const filtered = agents.filter((agent) => isMatch(agent, query)); const filtered = agents.filter((agent) => isMatch(agent, query));
filtered.sort(sortAgents); filtered.sort(sortAgents);
return filtered; return filtered;
}, [agents, query]); }, [agents, open, query]);
const newAgentRoute = useMemo<Href>(() => { const newAgentRoute = useMemo<Href>(() => {
const serverIdFromPath = activeServerId; const serverIdFromPath = activeServerId;
@@ -149,6 +159,9 @@ export function useCommandCenter() {
}, [activeServerId]); }, [activeServerId]);
const actionItems = useMemo(() => { const actionItems = useMemo(() => {
if (!open) {
return EMPTY_ACTION_ITEMS;
}
return COMMAND_CENTER_ACTIONS.filter((action) => return COMMAND_CENTER_ACTIONS.filter((action) =>
matchesActionQuery(query, action) matchesActionQuery(query, action)
).map<CommandCenterActionItem>((action) => ({ ).map<CommandCenterActionItem>((action) => ({
@@ -159,9 +172,12 @@ export function useCommandCenter() {
route: action.buildRoute({ newAgentRoute, settingsRoute }), route: action.buildRoute({ newAgentRoute, settingsRoute }),
shortcutKeys: action.shortcutKeys, shortcutKeys: action.shortcutKeys,
})); }));
}, [newAgentRoute, query, settingsRoute]); }, [newAgentRoute, open, query, settingsRoute]);
const items = useMemo(() => { const items = useMemo(() => {
if (!open) {
return EMPTY_COMMAND_CENTER_ITEMS;
}
const next: CommandCenterItem[] = []; const next: CommandCenterItem[] = [];
for (const action of actionItems) { for (const action of actionItems) {
next.push({ next.push({
@@ -176,7 +192,7 @@ export function useCommandCenter() {
}); });
} }
return next; return next;
}, [actionItems, agentResults]); }, [actionItems, agentResults, open]);
const handleClose = useCallback(() => { const handleClose = useCallback(() => {
setOpen(false); setOpen(false);
@@ -513,6 +513,7 @@ function ResolvedDesktopTabChip({
const styles = StyleSheet.create((theme) => ({ const styles = StyleSheet.create((theme) => ({
tabsContainer: { tabsContainer: {
minWidth: 0,
borderBottomWidth: 1, borderBottomWidth: 1,
borderBottomColor: theme.colors.border, borderBottomColor: theme.colors.border,
backgroundColor: theme.colors.surface0, backgroundColor: theme.colors.surface0,
@@ -523,8 +524,7 @@ const styles = StyleSheet.create((theme) => ({
minWidth: 0, minWidth: 0,
}, },
tabsScrollFitContent: { tabsScrollFitContent: {
flexGrow: 0, flex: 1,
flexShrink: 1,
}, },
tabsScrollOverflow: { tabsScrollOverflow: {
flex: 1, flex: 1,
@@ -2008,12 +2008,12 @@ function WorkspaceScreenContent({
onSelectNewTabOption={handleSelectNewTabOption} onSelectNewTabOption={handleSelectNewTabOption}
newTabAgentOptionId={NEW_TAB_AGENT_OPTION_ID} newTabAgentOptionId={NEW_TAB_AGENT_OPTION_ID}
buildPaneContentModel={({ paneId, tab }) => buildPaneContentModel={({ paneId, tab }) =>
buildPaneContentModel({ buildPaneContentModel({
tab, tab,
paneId, paneId,
focusPaneBeforeOpen: true, focusPaneBeforeOpen: true,
}) })
} }
onFocusPane={(paneId) => { onFocusPane={(paneId) => {
focusWorkspacePane(persistenceKey, paneId); focusWorkspacePane(persistenceKey, paneId);
}} }}
@@ -14,7 +14,7 @@ const metrics = {
}; };
describe("computeWorkspaceTabLayout", () => { describe("computeWorkspaceTabLayout", () => {
it("keeps fit-content tab widths when there is extra horizontal space", () => { it("caps equal-width tabs at the ideal width when there is extra horizontal space", () => {
const result = computeWorkspaceTabLayout({ const result = computeWorkspaceTabLayout({
viewportWidth: 1200, viewportWidth: 1200,
tabLabelLengths: [8, 10, 7], tabLabelLengths: [8, 10, 7],
@@ -25,10 +25,10 @@ describe("computeWorkspaceTabLayout", () => {
expect(result.requiresHorizontalScrollFallback).toBe(false); expect(result.requiresHorizontalScrollFallback).toBe(false);
expect(result.items).toHaveLength(3); expect(result.items).toHaveLength(3);
expect(result.items.every((item) => item.showLabel)).toBe(true); expect(result.items.every((item) => item.showLabel)).toBe(true);
expect(result.items.map((item) => item.width)).toEqual([126, 140, 119]); expect(result.items.map((item) => item.width)).toEqual([200, 200, 200]);
}); });
it("shrinks tab widths proportionally before hiding labels", () => { it("shrinks equal-width tabs proportionally to fit the pane", () => {
const result = computeWorkspaceTabLayout({ const result = computeWorkspaceTabLayout({
viewportWidth: 520, viewportWidth: 520,
tabLabelLengths: [24, 12, 8], tabLabelLengths: [24, 12, 8],
@@ -37,10 +37,27 @@ describe("computeWorkspaceTabLayout", () => {
expect(result.closeButtonPolicy).toBe("all"); expect(result.closeButtonPolicy).toBe("all");
expect(result.requiresHorizontalScrollFallback).toBe(false); expect(result.requiresHorizontalScrollFallback).toBe(false);
expect(result.items.map((item) => item.width)).toEqual([151, 121, 103]); expect(result.items.map((item) => item.width)).toEqual([125, 125, 125]);
expect(result.items.every((item) => item.showLabel)).toBe(true); expect(result.items.every((item) => item.showLabel)).toBe(true);
}); });
it("uses the split width for evenly sized tabs when space is available", () => {
const result = computeWorkspaceTabLayout({
viewportWidth: 743,
tabLabelLengths: [8, 8, 8, 8],
metrics: {
...metrics,
actionsReservedWidth: 44,
rowPaddingHorizontal: 0,
tabGap: 0,
},
});
expect(result.closeButtonPolicy).toBe("all");
expect(result.requiresHorizontalScrollFallback).toBe(false);
expect(result.items.map((item) => item.width)).toEqual([175, 175, 175, 175]);
});
it("collapses to icon-only before allowing horizontal scroll fallback", () => { it("collapses to icon-only before allowing horizontal scroll fallback", () => {
const result = computeWorkspaceTabLayout({ const result = computeWorkspaceTabLayout({
viewportWidth: 388, viewportWidth: 388,
@@ -38,14 +38,6 @@ function clamp(value: number, min: number, max: number): number {
return value; return value;
} }
function sum(values: number[]): number {
let total = 0;
for (const value of values) {
total += value;
}
return total;
}
export function computeWorkspaceTabLayout( export function computeWorkspaceTabLayout(
input: WorkspaceTabLayoutInput input: WorkspaceTabLayoutInput
): WorkspaceTabLayoutResult { ): WorkspaceTabLayoutResult {
@@ -67,33 +59,13 @@ export function computeWorkspaceTabLayout(
const availableTabsWidth = Math.max(0, availableWidth - rowOverhead); const availableTabsWidth = Math.max(0, availableWidth - rowOverhead);
const iconOnlyTabWidth = const iconOnlyTabWidth =
input.metrics.tabIconWidth + input.metrics.tabHorizontalPadding * 2 + input.metrics.closeButtonWidth; input.metrics.tabIconWidth + input.metrics.tabHorizontalPadding * 2 + input.metrics.closeButtonWidth;
const labelSafetyPadding = 10;
const estimateLabelWidth = (labelLength: number) => labelLength * input.metrics.estimatedCharWidth;
const desiredTabWidths = input.tabLabelLengths.map((rawLength) => {
const labelLength = Math.max(rawLength, 1);
const estimatedWidth = iconOnlyTabWidth + estimateLabelWidth(labelLength) + labelSafetyPadding;
return clamp(estimatedWidth, iconOnlyTabWidth, input.metrics.maxTabWidth);
});
const desiredTotalTabsWidth = sum(desiredTabWidths);
const iconOnlyTotalTabsWidth = iconOnlyTabWidth * tabCount; const iconOnlyTotalTabsWidth = iconOnlyTabWidth * tabCount;
const requiresHorizontalScrollFallback = availableTabsWidth < iconOnlyTotalTabsWidth; const requiresHorizontalScrollFallback = availableTabsWidth < iconOnlyTotalTabsWidth;
const resolvedWidths = new Array(tabCount).fill(
let resolvedWidths: number[]; requiresHorizontalScrollFallback
if (desiredTotalTabsWidth <= availableTabsWidth) { ? iconOnlyTabWidth
// Fit-content baseline: do not stretch tabs when there is spare space. : clamp(availableTabsWidth / tabCount, iconOnlyTabWidth, input.metrics.maxTabWidth)
resolvedWidths = desiredTabWidths; );
} else if (availableTabsWidth <= iconOnlyTotalTabsWidth) {
resolvedWidths = new Array(tabCount).fill(iconOnlyTabWidth);
} else {
const desiredExpandableWidth = desiredTotalTabsWidth - iconOnlyTotalTabsWidth;
const availableExpandableWidth = availableTabsWidth - iconOnlyTotalTabsWidth;
const proportionalRatio =
desiredExpandableWidth > 0 ? availableExpandableWidth / desiredExpandableWidth : 0;
resolvedWidths = desiredTabWidths.map(
(desiredWidth) => iconOnlyTabWidth + (desiredWidth - iconOnlyTabWidth) * proportionalRatio
);
}
const roundedWidths = resolvedWidths.map((width) => const roundedWidths = resolvedWidths.map((width) =>
Math.round(clamp(width, iconOnlyTabWidth, input.metrics.maxTabWidth)) Math.round(clamp(width, iconOnlyTabWidth, input.metrics.maxTabWidth))