Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(desktop): rework the tab strip for many-tab use (#17809)

Inneib7751030a798
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 549e2d38a4a..04c1c319174 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -326,6 +326,40 @@ is what selects the Render component) and the tool message (`updateMessagePlugin
(NOT `lobe-claude-code`) and PascalCase `apiName` (`TodoWrite`). All of this is
in-memory only — a reload clears it; delete the temp topic at teardown.
+### Desktop theme follows the system appearance, not `settings.general.themeMode`
+
+**Situation:** capturing dark-mode evidence for a desktop UI change.
+
+**Doesn't work:** `window.__LOBE_STORES.user().updateGeneralConfig({ themeMode: 'dark' })`.
+The setting persists (reading it back returns `dark`, and it survives a restart),
+but `document.documentElement.dataset.theme` stays `light` and every token keeps its
+light value. Restarting the instance does not apply it either. Treating the stored
+setting as proof of the rendered theme yields evidence captured in the wrong theme.
+
+**Works:** assert `document.documentElement.dataset.theme` — never the stored
+setting — before capturing any theme-dependent evidence. The renderer tracks the OS
+appearance, so switching it means changing the user's macOS system setting, which is
+outside the harness's remit: mark the dark case untested and say why, rather than
+flipping a device-level preference. Note the setting write is not free — it syncs to
+the account and affects other surfaces; restore it (`auto`) at teardown if you set it.
+
+### A node reference captured before a re-render is silently dead — re-query per assertion
+
+**Situation:** asserting several tab-strip interactions (close, pin, switch) in one
+`agent-browser eval` payload, reusing the element list collected at the top.
+
+**Doesn't work:** collecting `roots` once and then acting on `roots[0]`, `roots[1]`, …
+in sequence. Each action that mutates the tab list re-renders the strip, so every
+reference collected earlier now points at a detached node. Dispatching to a detached
+node throws nothing and changes nothing — React never sees it — so the assertion reads
+as "this interaction does not work". In this catalogue's first occurrence it produced a
+confident "middle-click does not close a pinned tab" that was purely an artefact of the
+stale reference, and it survived review because the number looked plausible.
+
+**Works:** one assertion per `eval`, re-querying the strip each time. When several must
+share a payload, re-query between actions and assert `el.isConnected` before dispatch.
+The same applies to any probe whose own action re-renders the tree it is measuring.
+
### `eval` declarations persist in the page global scope
**Situation:** running several `agent-browser eval` payloads against one renderer.
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index 74cba3b7825..7aa05426519 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -120,7 +120,10 @@
"tab.closeOtherTabs": "Close Other Tabs",
"tab.closeRightTabs": "Close Tabs to the Right",
"tab.newTab": "New Tab",
+ "tab.overflow": "{{count}} more tabs",
+ "tab.pin": "Pin Tab",
"tab.running": "Agent is running",
+ "tab.unpin": "Unpin Tab",
"tab.unread": "New message",
"updater.checkingUpdate": "Checking for updates",
"updater.checkingUpdateDesc": "Retrieving version information...",
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index 83485dc901f..78c44570cda 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -120,7 +120,10 @@
"tab.closeOtherTabs": "关闭其他标签页",
"tab.closeRightTabs": "关闭右侧标签页",
"tab.newTab": "新建标签页",
+ "tab.overflow": "另有 {{count}} 个标签页",
+ "tab.pin": "固定标签页",
"tab.running": "智能体运行中",
+ "tab.unpin": "取消固定",
"tab.unread": "新消息",
"updater.checkingUpdate": "检查新版本",
"updater.checkingUpdateDesc": "正在获取版本信息…",
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index 53e38b5100a..60c221a5a4b 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -46,7 +46,10 @@ export default {
'tab.closeOtherTabs': 'Close Other Tabs',
'tab.closeRightTabs': 'Close Tabs to the Right',
'tab.newTab': 'New Tab',
+ 'tab.overflow': '{{count}} more tabs',
+ 'tab.pin': 'Pin Tab',
'tab.running': 'Agent is running',
+ 'tab.unpin': 'Unpin Tab',
'tab.unread': 'New message',
'proxy.auth': 'Authentication Required',
'proxy.authDesc': 'If the proxy server requires a username and password',
diff --git a/src/features/Electron/titlebar/TabBar/TabItem.tsx b/src/features/Electron/titlebar/TabBar/TabItem.tsx
index 84d7970bf51..4b0045bbfdc 100644
--- a/src/features/Electron/titlebar/TabBar/TabItem.tsx
+++ b/src/features/Electron/titlebar/TabBar/TabItem.tsx
@@ -6,13 +6,15 @@ import {
ActionIcon,
Avatar,
ContextMenuTrigger,
- Flexbox,
type GenericItemType,
Icon,
+ Tooltip,
} from '@lobehub/ui';
import { cx } from 'antd-style';
import { X } from 'lucide-react';
-import { memo, useCallback } from 'react';
+import { useMotionValue, useSpring } from 'motion/react';
+import * as m from 'motion/react-m';
+import { memo, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { electronStylish } from '@/styles/electron';
@@ -22,6 +24,27 @@ import { useTabRunning } from './hooks/useTabRunning';
import { useTabUnread } from './hooks/useTabUnread';
import { useStyles } from './styles';
import { buildTabContextMenuItems } from './tabContextMenu';
+import { type TabTier } from './tabLayout';
+
+// Width is driven by a spring rather than a CSS transition: tab widths are a layout
+// response — several tabs resize at once whenever one is activated, added or closed —
+// and a spring both settles more naturally and is interruptible, so rapid switching
+// redirects the motion instead of restarting a fixed 180ms ramp.
+//
+// Only `width` is animated here. dnd-kit owns `transform`/`transition` on the same
+// element (and inline style beats any class-level declaration), so background-color
+// keeps its own CSS transition composed alongside dnd-kit's below.
+// restDelta of half a pixel: without it the spring keeps ticking rAF long after the
+// motion is visually over (measured still 0.1px short at 425ms), which costs a frame
+// callback per tab for nothing.
+const WIDTH_SPRING = {
+ damping: 26,
+ mass: 0.4,
+ restDelta: 0.5,
+ restSpeed: 2,
+ stiffness: 380,
+} as const;
+const BACKGROUND_MOTION = 'background-color 0.15s var(--ant-motion-ease-in-out)';
interface TabItemProps {
index: number;
@@ -32,7 +55,11 @@ interface TabItemProps {
onCloseLeft: (id: string) => void;
onCloseOthers: (id: string) => void;
onCloseRight: (id: string) => void;
+ onTogglePin: (id: string) => void;
+ pinnedCount: number;
+ tier: TabTier;
totalCount: number;
+ width: number;
}
const TabItem = memo<TabItemProps>(
@@ -40,12 +67,16 @@ const TabItem = memo<TabItemProps>(
item,
isActive,
index,
+ pinnedCount,
+ tier,
totalCount,
+ width,
onActivate,
onClose,
onCloseOthers,
onCloseLeft,
onCloseRight,
+ onTogglePin,
}) => {
const styles = useStyles;
const { t } = useTranslation('electron');
@@ -54,11 +85,28 @@ const TabItem = memo<TabItemProps>(
const isRunning = useTabRunning(tab);
const isUnread = useTabUnread(tab);
const showUnreadDot = !isRunning && isUnread;
+ const pinned = !!tab.pinned;
+ const iconOnly = tier === 'icon';
+ // The close button needs 22px of its own, and below the compact tier the tab cannot
+ // spare them: the title would be cut to a couple of glyphs to make room for a button
+ // that is usually not even shown. Narrower tabs close by middle-click or the context
+ // menu instead. At icon width there is the further problem that the icon is the only
+ // identity signal left, so overlaying it would also change what a click does.
+ const closable = !pinned && totalCount > 1 && (tier === 'full' || tier === 'compact');
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id,
});
+ // A newly opened tab springs out from zero rather than popping in at full width; the
+ // motion value starts collapsed and is set to the real width on mount.
+ const targetWidth = useMotionValue(0);
+ const springWidth = useSpring(targetWidth, WIDTH_SPRING);
+
+ useEffect(() => {
+ targetWidth.set(width);
+ }, [width, targetWidth]);
+
const handleClick = useCallback(() => {
if (!isActive) {
onActivate(id, tab.url);
@@ -73,6 +121,15 @@ const TabItem = memo<TabItemProps>(
[onClose, id],
);
+ const handleAuxClick = useCallback(
+ (e: React.MouseEvent) => {
+ if (e.button !== 1 || totalCount === 1) return;
+ e.preventDefault();
+ onClose(id);
+ },
+ [onClose, id, totalCount],
+ );
+
const contextMenuItems = useCallback(
(): GenericItemType[] =>
buildTabContextMenuItems({
@@ -82,63 +139,94 @@ const TabItem = memo<TabItemProps>(
onCloseLeft,
onCloseOthers,
onCloseRight,
+ onTogglePin,
+ pinned,
+ pinnedCount,
t,
totalCount,
}),
- [t, id, index, totalCount, onClose, onCloseOthers, onCloseLeft, onCloseRight],
+ [
+ t,
+ id,
+ index,
+ totalCount,
+ pinned,
+ pinnedCount,
+ onClose,
+ onCloseOthers,
+ onCloseLeft,
+ onCloseRight,
+ onTogglePin,
+ ],
+ );
+
+ const indicator = (
+ <span className={styles.avatarWrapper}>
+ {meta.avatar ? (
+ <Avatar
+ emojiScaleWithBackground
+ avatar={meta.avatar}
+ background={meta.backgroundColor}
+ shape="square"
+ size={16}
+ />
+ ) : (
+ meta.icon && <Icon className={styles.tabIcon} icon={meta.icon} size="small" />
+ )}
+ {isRunning && <span aria-label={t('tab.running')} className={styles.runningDot} />}
+ {showUnreadDot && <span aria-label={t('tab.unread')} className={styles.unreadDot} />}
+ </span>
+ );
+
+ const face = (
+ <m.div
+ data-active={isActive ? 'true' : undefined}
+ data-tier={tier}
+ ref={setNodeRef}
+ className={cx(
+ electronStylish.nodrag,
+ styles.tab,
+ isActive && styles.tabActive,
+ isDragging && styles.tabDragging,
+ )}
+ style={{
+ gap: iconOnly ? 0 : 6,
+ justifyContent: iconOnly ? 'center' : undefined,
+ transform: CSS.Translate.toString(transform),
+ transition: transition ? `${transition}, ${BACKGROUND_MOTION}` : BACKGROUND_MOTION,
+ width: springWidth,
+ zIndex: isDragging ? 1 : undefined,
+ }}
+ onAuxClick={handleAuxClick}
+ onClick={handleClick}
+ {...attributes}
+ {...listeners}
+ >
+ {indicator}
+ {!iconOnly && (
+ <span data-tab-title className={styles.tabTitle}>
+ {meta.title}
+ </span>
+ )}
+ {closable && (
+ <ActionIcon
+ data-tab-close
+ className={styles.closeIcon}
+ icon={X}
+ size="small"
+ onClick={handleClose}
+ />
+ )}
+ </m.div>
);
+ // The Tooltip wraps unconditionally and opts out via an empty title. Swapping between
+ // a wrapped and a bare node would remount the tab on every tier change — which is
+ // exactly when the width animates, so the new node would mount at its final width and
+ // the transition would never run.
return (
<ContextMenuTrigger items={contextMenuItems}>
- <Flexbox
- horizontal
- align="center"
- data-active={isActive ? 'true' : undefined}
- gap={6}
- ref={setNodeRef}
- className={cx(
- electronStylish.nodrag,
- styles.tab,
- isActive && styles.tabActive,
- isDragging && styles.tabDragging,
- )}
- style={{
- transform: CSS.Translate.toString(transform),
- transition,
- zIndex: isDragging ? 1 : undefined,
- }}
- onClick={handleClick}
- {...attributes}
- {...listeners}
- >
- {meta.avatar ? (
- <span className={styles.avatarWrapper}>
- <Avatar
- emojiScaleWithBackground
- avatar={meta.avatar}
- background={meta.backgroundColor}
- shape="square"
- size={16}
- />
- {isRunning && <span aria-label={t('tab.running')} className={styles.runningDot} />}
- {showUnreadDot && <span aria-label={t('tab.unread')} className={styles.unreadDot} />}
- </span>
- ) : (
- meta.icon && (
- <span className={styles.avatarWrapper}>
- <Icon className={styles.tabIcon} icon={meta.icon} size="small" />
- {isRunning && <span aria-label={t('tab.running')} className={styles.runningDot} />}
- {showUnreadDot && (
- <span aria-label={t('tab.unread')} className={styles.unreadDot} />
- )}
- </span>
- )
- )}
- <span className={styles.tabTitle}>{meta.title}</span>
- {totalCount > 1 && (
- <ActionIcon className={styles.closeIcon} icon={X} size="small" onClick={handleClose} />
- )}
- </Flexbox>
+ <Tooltip title={tier === 'full' ? '' : meta.title}>{face}</Tooltip>
</ContextMenuTrigger>
);
},
diff --git a/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap b/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap
index d7fd1f71570..e4006e75230 100644
--- a/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap
+++ b/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap
@@ -4,11 +4,19 @@ exports[`tab context menu ownership > goes native on macOS desktop (plain string
[
{
"id": "0",
+ "label": "tab.pin",
+ "type": "normal",
+ },
+ {
+ "type": "separator",
+ },
+ {
+ "id": "2",
"label": "tab.closeCurrentTab",
"type": "normal",
},
{
- "id": "1",
+ "id": "3",
"label": "tab.closeOtherTabs",
"type": "normal",
},
@@ -16,12 +24,12 @@ exports[`tab context menu ownership > goes native on macOS desktop (plain string
"type": "separator",
},
{
- "id": "3",
+ "id": "5",
"label": "tab.closeLeftTabs",
"type": "normal",
},
{
- "id": "4",
+ "id": "6",
"label": "tab.closeRightTabs",
"type": "normal",
},
diff --git a/src/features/Electron/titlebar/TabBar/hooks/useStripWidth.ts b/src/features/Electron/titlebar/TabBar/hooks/useStripWidth.ts
new file mode 100644
index 00000000000..9ddb7e87424
--- /dev/null
+++ b/src/features/Electron/titlebar/TabBar/hooks/useStripWidth.ts
@@ -0,0 +1,35 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+
+type StripRef = (node: HTMLDivElement | null) => void;
+
+/**
+ * Content-box width of the strip, plus the ref to attach to it. `contentRect` already
+ * excludes the leading inset that clears the content card's top corner, so callers can
+ * budget against it directly.
+ *
+ * A callback ref rather than `useRef`: TabBar returns null until its tabs load, so a
+ * `[ref]`-keyed effect would run once against an unmounted strip, never observe
+ * anything, and leave every tab pinned to its minimum width.
+ */
+export const useStripWidth = (): [number, StripRef] => {
+ const [width, setWidth] = useState(0);
+ const [node, setNode] = useState<HTMLDivElement | null>(null);
+
+ useEffect(() => {
+ if (!node) return;
+
+ setWidth(node.clientWidth);
+ if (typeof ResizeObserver === 'undefined') return;
+
+ const observer = new ResizeObserver(([entry]) => {
+ if (entry) setWidth(entry.contentRect.width);
+ });
+ observer.observe(node);
+
+ return () => observer.disconnect();
+ }, [node]);
+
+ return [width, setNode];
+};
diff --git a/src/features/Electron/titlebar/TabBar/index.tsx b/src/features/Electron/titlebar/TabBar/index.tsx
index 784b27f4bcf..65880a7c8a9 100644
--- a/src/features/Electron/titlebar/TabBar/index.tsx
+++ b/src/features/Electron/titlebar/TabBar/index.tsx
@@ -12,10 +12,11 @@ import {
} from '@dnd-kit/core';
import { horizontalListSortingStrategy, SortableContext } from '@dnd-kit/sortable';
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
-import { ActionIcon, ScrollArea } from '@lobehub/ui';
+import { ActionIcon, Flexbox } from '@lobehub/ui';
+import { type DropdownItem, DropdownMenu } from '@lobehub/ui/base-ui';
import { cx } from 'antd-style';
-import { Plus } from 'lucide-react';
-import { useCallback, useEffect, useMemo, useRef } from 'react';
+import { ChevronDown, Plus } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
@@ -27,14 +28,21 @@ import { useElectronStore } from '@/store/electron';
import { electronStylish } from '@/styles/electron';
import { useResolvedTabs } from './hooks/useResolvedTabs';
+import { useStripWidth } from './hooks/useStripWidth';
import { resolveTabScope } from './scope';
import { useStyles } from './styles';
import TabItem from './TabItem';
-
-const TAB_WIDTH = 180;
-const TAB_GAP = 0;
+import {
+ allocateTabWidths,
+ OVERFLOW_CONTROL_WIDTH,
+ PINNED_TAB_WIDTH,
+ resolveTabTier,
+ TAB_GAP,
+} from './tabLayout';
const NEW_TAB_URL = '/';
+const NEW_TAB_BUTTON_WIDTH = 26 + TAB_GAP;
+const PINNED_DIVIDER_WIDTH = 13;
// Tabs only reorder along the horizontal axis, so lock the drag transform to X.
const restrictToHorizontalAxis: Modifier = ({ transform }) => ({ ...transform, y: 0 });
@@ -45,8 +53,7 @@ const TabBar = () => {
useRegisterDesktopTabHotkeys();
const { t } = useTranslation('electron');
const { allowed: canCreate, reason } = usePermission('create_content');
- const viewportRef = useRef<HTMLDivElement>(null);
- const scrolledActiveTabIdRef = useRef<string | null>(null);
+ const [stripWidth, stripRef] = useStripWidth();
const { tabs, activeTabId } = useResolvedTabs();
const activateTab = useElectronStore((s) => s.activateTab);
const addNewTab = useElectronStore((s) => s.addNewTab);
@@ -55,6 +62,8 @@ const TabBar = () => {
const closeLeftTabs = useElectronStore((s) => s.closeLeftTabs);
const closeRightTabs = useElectronStore((s) => s.closeRightTabs);
const reorderTabs = useElectronStore((s) => s.reorderTabs);
+ const pinTab = useElectronStore((s) => s.pinTab);
+ const unpinTab = useElectronStore((s) => s.unpinTab);
const sensors = useSensors(
// Require a small drag distance so a plain click still activates the tab.
@@ -63,6 +72,21 @@ const TabBar = () => {
);
const tabIds = useMemo(() => tabs.map((tab) => tab.tab.id), [tabs]);
+ const pinnedTabs = useMemo(() => tabs.filter((tab) => tab.tab.pinned), [tabs]);
+ const flowTabs = useMemo(() => tabs.filter((tab) => !tab.tab.pinned), [tabs]);
+
+ const layout = useMemo(() => {
+ const pinnedWidth = pinnedTabs.length
+ ? pinnedTabs.length * (PINNED_TAB_WIDTH + TAB_GAP) + PINNED_DIVIDER_WIDTH
+ : 0;
+
+ return allocateTabWidths({
+ activeIndex: flowTabs.findIndex((tab) => tab.tab.id === activeTabId),
+ count: flowTabs.length,
+ usableWidth: Math.max(0, stripWidth - pinnedWidth - NEW_TAB_BUTTON_WIDTH),
+ });
+ }, [flowTabs, pinnedTabs.length, activeTabId, stripWidth]);
+
const newTabUrl = useMemo(() => {
const scope = resolveTabScope(location.pathname + location.search);
const activeSlug = scope.type === 'workspace' ? scope.slug : null;
@@ -119,30 +143,16 @@ const TabBar = () => {
[closeRightTabs],
);
- useEffect(() => {
- const viewport = viewportRef.current;
- if (!viewport || !activeTabId) return;
-
- const activeIndex = tabs.findIndex((tab) => tab.tab.id === activeTabId);
- if (activeIndex < 0) return;
-
- // Only scroll into view when the active tab itself changes. Reordering
- // background tabs keeps the same active tab, so skip it — otherwise every
- // drop would yank the viewport back to the active tab and lose the user's
- // scroll position.
- if (scrolledActiveTabIdRef.current === activeTabId) return;
- scrolledActiveTabIdRef.current = activeTabId;
-
- const tabLeft = activeIndex * (TAB_WIDTH + TAB_GAP);
- const tabRight = tabLeft + TAB_WIDTH;
- const { scrollLeft, clientWidth } = viewport;
+ const handleTogglePin = useCallback(
+ (id: string) => {
+ const target = tabs.find((tab) => tab.tab.id === id);
+ if (!target) return;
- if (tabLeft < scrollLeft) {
- viewport.scrollLeft = tabLeft;
- } else if (tabRight > scrollLeft + clientWidth) {
- viewport.scrollLeft = tabRight - clientWidth;
- }
- }, [activeTabId, tabs]);
+ if (target.tab.pinned) unpinTab(id);
+ else pinTab(id);
+ },
+ [tabs, pinTab, unpinTab],
+ );
useWatchBroadcast('closeCurrentTabOrWindow', () => {
if (tabs.length > 1 && activeTabId) {
@@ -163,16 +173,42 @@ const TabBar = () => {
handleNewTab();
});
+ const overflowItems = useCallback((): DropdownItem[] => {
+ const visible = new Set(layout.visibleIndices);
+
+ return flowTabs
+ .map((tab, index) => ({ index, tab }))
+ .filter(({ index }) => !visible.has(index))
+ .map(({ tab }) => ({
+ key: tab.tab.id,
+ label: tab.meta.title,
+ onClick: () => handleActivate(tab.tab.id),
+ }));
+ }, [flowTabs, layout.visibleIndices, handleActivate]);
+
if (tabs.length === 0) return null;
+ const renderTab = (tab: (typeof tabs)[number], width: number) => (
+ <TabItem
+ index={tabIds.indexOf(tab.tab.id)}
+ isActive={tab.tab.id === activeTabId}
+ item={tab}
+ key={tab.tab.id}
+ pinnedCount={pinnedTabs.length}
+ tier={resolveTabTier(width)}
+ totalCount={tabs.length}
+ width={width}
+ onActivate={handleActivate}
+ onClose={handleClose}
+ onCloseLeft={handleCloseLeft}
+ onCloseOthers={handleCloseOthers}
+ onCloseRight={handleCloseRight}
+ onTogglePin={handleTogglePin}
+ />
+ );
+
return (
- <ScrollArea
- className={styles.container}
- viewportProps={{ ref: viewportRef }}
- contentProps={{
- style: { alignItems: 'center', flexDirection: 'row', gap: TAB_GAP },
- }}
- >
+ <Flexbox horizontal align={'center'} className={styles.container} gap={TAB_GAP} ref={stripRef}>
<DndContext
collisionDetection={closestCenter}
modifiers={[restrictToHorizontalAxis]}
@@ -180,20 +216,11 @@ const TabBar = () => {
onDragEnd={handleDragEnd}
>
<SortableContext items={tabIds} strategy={horizontalListSortingStrategy}>
- {tabs.map((tab, index) => (
- <TabItem
- index={index}
- isActive={tab.tab.id === activeTabId}
- item={tab}
- key={tab.tab.id}
- totalCount={tabs.length}
- onActivate={handleActivate}
- onClose={handleClose}
- onCloseLeft={handleCloseLeft}
- onCloseOthers={handleCloseOthers}
- onCloseRight={handleCloseRight}
- />
- ))}
+ {pinnedTabs.map((tab) => renderTab(tab, PINNED_TAB_WIDTH))}
+ {pinnedTabs.length > 0 && <span className={styles.pinnedDivider} />}
+ {layout.visibleIndices.map((tabIndex, position) =>
+ renderTab(flowTabs[tabIndex], layout.widths[position]),
+ )}
</SortableContext>
</DndContext>
<ActionIcon
@@ -204,7 +231,22 @@ const TabBar = () => {
title={canCreate ? t('tab.newTab') : reason}
onClick={canCreate ? handleNewTab : undefined}
/>
- </ScrollArea>
+ {layout.hiddenCount > 0 && (
+ <DropdownMenu items={overflowItems} placement={'bottomRight'}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={cx(electronStylish.nodrag, styles.overflowButton)}
+ gap={2}
+ style={{ width: OVERFLOW_CONTROL_WIDTH }}
+ title={t('tab.overflow', { count: layout.hiddenCount })}
+ >
+ <ChevronDown size={12} />
+ {layout.hiddenCount}
+ </Flexbox>
+ </DropdownMenu>
+ )}
+ </Flexbox>
);
};
diff --git a/src/features/Electron/titlebar/TabBar/styles.ts b/src/features/Electron/titlebar/TabBar/styles.ts
index 286640278ee..9fc6728600f 100644
--- a/src/features/Electron/titlebar/TabBar/styles.ts
+++ b/src/features/Electron/titlebar/TabBar/styles.ts
@@ -1,5 +1,7 @@
import { createStaticStyles } from 'antd-style';
+const TAB_HEIGHT = 26;
+
export const useStyles = createStaticStyles(({ css, cssVar }) => ({
avatarWrapper: css`
position: relative;
@@ -7,9 +9,17 @@ export const useStyles = createStaticStyles(({ css, cssVar }) => ({
line-height: 0;
`,
closeIcon: css`
+ position: absolute;
+ inset-inline-end: 4px;
+
flex-shrink: 0;
+
color: ${cssVar.colorTextTertiary};
+ opacity: 0;
+
+ transition: opacity 0.15s ${cssVar.motionEaseInOut};
+
&:hover {
color: ${cssVar.colorText};
}
@@ -42,8 +52,6 @@ export const useStyles = createStaticStyles(({ css, cssVar }) => ({
container: css`
flex: 1;
min-width: 0;
- border-radius: 0;
- background: transparent;
`,
tab: css`
cursor: default;
@@ -51,45 +59,65 @@ export const useStyles = createStaticStyles(({ css, cssVar }) => ({
position: relative;
- overflow: hidden;
+ display: flex;
flex-shrink: 0;
+ align-items: center;
- width: 180px;
- padding-block: 2px;
- padding-inline: 10px 2px;
- border-radius: ${cssVar.borderRadiusSM};
+ height: ${TAB_HEIGHT}px;
+ padding-inline: 8px 6px;
+ border-radius: ${cssVar.borderRadius};
font-size: 12px;
background-color: transparent;
- transition: background-color 0.15s ${cssVar.motionEaseInOut};
+ /* No transition here: dnd-kit writes its own into the inline style, which would win
+ over anything declared in this class. TabItem composes both. */
&:hover {
- background-color: ${cssVar.colorFillTertiary};
+ background-color: ${cssVar.colorFillQuaternary};
+ }
+
+ /* Persistent on a full tab, hover-only on a compact one. Narrower tiers carry no
+ close button at all — see TabItem. */
+ &[data-tier='full'] [data-tab-close],
+ &:hover [data-tab-close] {
+ opacity: 1;
}
- & + &::before {
- content: '';
+ /* Reserve the button's footprint whether or not it is currently visible, so the
+ title's ellipsis lands before it. Fading the title out under the button instead
+ leaves half-opaque glyphs inside the gradient, which reads as an overlap. Keeping
+ the reservation constant also stops the text reflowing on hover. */
+ &[data-tier='full'] [data-tab-title],
+ &[data-tier='compact'] [data-tab-title] {
+ padding-inline-end: 22px;
+ }
+ `,
+ pinnedDivider: css`
+ align-self: center;
+
+ width: 1px;
+ height: 18px;
+ margin-inline: 6px;
- position: absolute;
- inset-block-start: 50%;
- inset-inline-start: 0;
- transform: translateY(-50%);
+ background-color: ${cssVar.colorBorder};
+ `,
+ overflowButton: css`
+ cursor: default;
- width: 1px;
- height: 16px;
+ flex-shrink: 0;
+ justify-content: center;
- background-color: ${cssVar.colorBorderSecondary};
+ height: 22px;
+ border-radius: ${cssVar.borderRadiusSM};
- transition: opacity 0.15s ${cssVar.motionEaseInOut};
- }
+ font-size: 11px;
+ color: ${cssVar.colorTextSecondary};
- &:hover::before,
- &[data-active='true']::before,
- &:hover + &::before,
- &[data-active='true'] + &::before {
- opacity: 0;
+ &:hover {
+ color: ${cssVar.colorText};
+ background-color: ${cssVar.colorFillTertiary};
}
`,
tabDragging: css`
@@ -97,14 +125,13 @@ export const useStyles = createStaticStyles(({ css, cssVar }) => ({
z-index: 1;
background-color: ${cssVar.colorBgElevated};
box-shadow: ${cssVar.boxShadowSecondary};
-
- &::before,
- & + &::before {
- opacity: 0;
- }
`,
+ // The active tab floats above the titlebar rather than merging into the content card.
+ // An attached (Chrome-style) treatment was built and tried on the real desktop app and
+ // rejected: the seam it produced read worse than the separation it replaced.
tabActive: css`
background-color: ${cssVar.colorBgElevated};
+ box-shadow: ${cssVar.boxShadowTertiary};
&:hover {
background-color: ${cssVar.colorBgElevated};
@@ -127,6 +154,8 @@ export const useStyles = createStaticStyles(({ css, cssVar }) => ({
overflow: hidden;
flex: 1;
+ min-width: 0;
+
font-size: 12px;
color: ${cssVar.colorText};
text-overflow: ellipsis;
diff --git a/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts b/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts
index 18167387b06..d3684559ce6 100644
--- a/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts
+++ b/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts
@@ -5,7 +5,7 @@ import { toNativeTemplate } from '@/libs/contextMenu/toNativeTemplate';
import { buildTabContextMenuItems } from './tabContextMenu';
-const build = (index: number, totalCount: number) =>
+const build = (index: number, totalCount: number, pinned = false, pinnedCount = 0) =>
buildTabContextMenuItems({
id: 'tab-1',
index,
@@ -13,10 +13,18 @@ const build = (index: number, totalCount: number) =>
onCloseLeft: vi.fn(),
onCloseOthers: vi.fn(),
onCloseRight: vi.fn(),
+ onTogglePin: vi.fn(),
+ pinned,
+ pinnedCount,
t: (key) => key,
totalCount,
});
+const isDisabled = (items: ReturnType<typeof build>, key: string) => {
+ const entry = items.find((item) => !!item && 'key' in item && item.key === key);
+ return entry && 'disabled' in entry ? !!entry.disabled : false;
+};
+
describe('tab context menu ownership', () => {
it('goes native on macOS desktop (plain string labels, no web-only capabilities)', () => {
const items = build(1, 3);
@@ -29,3 +37,50 @@ describe('tab context menu ownership', () => {
expect(canGoNative(build(0, 1))).toBe(true);
});
});
+
+describe('pin entry', () => {
+ it('offers pinning for an unpinned tab and unpinning for a pinned one', () => {
+ const labelOf = (pinned: boolean) => {
+ const entry = build(1, 3, pinned).find(
+ (item) => !!item && 'key' in item && item.key === 'togglePin',
+ );
+ return entry && 'label' in entry ? entry.label : undefined;
+ };
+
+ expect(labelOf(false)).toBe('tab.pin');
+ expect(labelOf(true)).toBe('tab.unpin');
+ });
+
+ it('stays available when closing is not — a lone tab can still be pinned', () => {
+ const items = build(0, 1);
+ const pin = items.find((item) => !!item && 'key' in item && item.key === 'togglePin');
+
+ expect(pin && 'disabled' in pin ? pin.disabled : undefined).toBeFalsy();
+ });
+});
+
+describe('bulk close entries reflect what pinning spares', () => {
+ it('disables closing others when every other tab is pinned', () => {
+ expect(isDisabled(build(2, 3, false, 2), 'closeOtherTabs')).toBe(true);
+ });
+
+ it('keeps closing others available while an unpinned neighbour remains', () => {
+ expect(isDisabled(build(2, 4, false, 2), 'closeOtherTabs')).toBe(false);
+ });
+
+ it('disables closing left when only pinned tabs lie to the left', () => {
+ expect(isDisabled(build(1, 3, false, 1), 'closeLeftTabs')).toBe(true);
+ });
+
+ it('keeps closing left available once an unpinned tab lies to the left', () => {
+ expect(isDisabled(build(2, 3, false, 1), 'closeLeftTabs')).toBe(false);
+ });
+
+ it('disables closing right when only pinned tabs lie to the right', () => {
+ expect(isDisabled(build(0, 2, true, 2), 'closeRightTabs')).toBe(true);
+ });
+
+ it('keeps closing right available for a pinned tab with unpinned tabs after the run', () => {
+ expect(isDisabled(build(0, 3, true, 2), 'closeRightTabs')).toBe(false);
+ });
+});
diff --git a/src/features/Electron/titlebar/TabBar/tabContextMenu.ts b/src/features/Electron/titlebar/TabBar/tabContextMenu.ts
index cb4a847ba6f..e9b4a069ec2 100644
--- a/src/features/Electron/titlebar/TabBar/tabContextMenu.ts
+++ b/src/features/Electron/titlebar/TabBar/tabContextMenu.ts
@@ -1,7 +1,12 @@
import type { GenericItemType } from '@lobehub/ui';
type TabContextMenuLabelKey =
- 'tab.closeCurrentTab' | 'tab.closeLeftTabs' | 'tab.closeOtherTabs' | 'tab.closeRightTabs';
+ | 'tab.closeCurrentTab'
+ | 'tab.closeLeftTabs'
+ | 'tab.closeOtherTabs'
+ | 'tab.closeRightTabs'
+ | 'tab.pin'
+ | 'tab.unpin';
interface TabContextMenuParams {
id: string;
@@ -10,10 +15,16 @@ interface TabContextMenuParams {
onCloseLeft: (id: string) => void;
onCloseOthers: (id: string) => void;
onCloseRight: (id: string) => void;
+ onTogglePin: (id: string) => void;
+ pinned: boolean;
+ pinnedCount: number;
t: (key: TabContextMenuLabelKey) => string;
totalCount: number;
}
+// The bulk closes spare pinned tabs, so each entry is offered only when it would still
+// reach something. Pinned tabs occupy indices 0..pinnedCount-1, which is what lets the
+// reachable counts fall out of the target's index alone.
export const buildTabContextMenuItems = ({
id,
index,
@@ -21,32 +32,47 @@ export const buildTabContextMenuItems = ({
onCloseLeft,
onCloseOthers,
onCloseRight,
+ onTogglePin,
+ pinned,
+ pinnedCount,
t,
totalCount,
-}: TabContextMenuParams): GenericItemType[] => [
- {
- disabled: totalCount === 1,
- key: 'closeCurrentTab',
- label: t('tab.closeCurrentTab'),
- onClick: () => onClose(id),
- },
- {
- disabled: totalCount === 1,
- key: 'closeOtherTabs',
- label: t('tab.closeOtherTabs'),
- onClick: () => onCloseOthers(id),
- },
- { type: 'divider' },
- {
- disabled: index === 0,
- key: 'closeLeftTabs',
- label: t('tab.closeLeftTabs'),
- onClick: () => onCloseLeft(id),
- },
- {
- disabled: index === totalCount - 1,
- key: 'closeRightTabs',
- label: t('tab.closeRightTabs'),
- onClick: () => onCloseRight(id),
- },
-];
+}: TabContextMenuParams): GenericItemType[] => {
+ const closableLeft = Math.max(0, index - pinnedCount);
+ const closableRight = Math.max(0, totalCount - Math.max(index + 1, pinnedCount));
+ const closableOthers = totalCount - pinnedCount - (pinned ? 0 : 1);
+
+ return [
+ {
+ key: 'togglePin',
+ label: pinned ? t('tab.unpin') : t('tab.pin'),
+ onClick: () => onTogglePin(id),
+ },
+ { type: 'divider' },
+ {
+ disabled: totalCount === 1,
+ key: 'closeCurrentTab',
+ label: t('tab.closeCurrentTab'),
+ onClick: () => onClose(id),
+ },
+ {
+ disabled: closableOthers <= 0,
+ key: 'closeOtherTabs',
+ label: t('tab.closeOtherTabs'),
+ onClick: () => onCloseOthers(id),
+ },
+ { type: 'divider' },
+ {
+ disabled: closableLeft === 0,
+ key: 'closeLeftTabs',
+ label: t('tab.closeLeftTabs'),
+ onClick: () => onCloseLeft(id),
+ },
+ {
+ disabled: closableRight === 0,
+ key: 'closeRightTabs',
+ label: t('tab.closeRightTabs'),
+ onClick: () => onCloseRight(id),
+ },
+ ];
+};
diff --git a/src/features/Electron/titlebar/TabBar/tabLayout.test.ts b/src/features/Electron/titlebar/TabBar/tabLayout.test.ts
new file mode 100644
index 00000000000..0718cad94c4
--- /dev/null
+++ b/src/features/Electron/titlebar/TabBar/tabLayout.test.ts
@@ -0,0 +1,185 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ ACTIVE_TAB_MIN_WIDTH,
+ allocateTabWidths,
+ MAX_TAB_WIDTH,
+ MIN_TAB_WIDTH,
+ OVERFLOW_CONTROL_WIDTH,
+ resolveTabTier,
+ TAB_GAP,
+} from './tabLayout';
+
+const totalWidth = (widths: number[]) =>
+ widths.reduce((sum, width) => sum + width, 0) + widths.length * TAB_GAP;
+
+describe('resolveTabTier', () => {
+ it.each([
+ [200, 'full'],
+ [130, 'full'],
+ [129, 'compact'],
+ [96, 'compact'],
+ [95, 'narrow'],
+ [58, 'narrow'],
+ [57, 'icon'],
+ [MIN_TAB_WIDTH, 'icon'],
+ ])('maps %ipx to %s', (width, tier) => {
+ expect(resolveTabTier(width)).toBe(tier);
+ });
+});
+
+describe('allocateTabWidths', () => {
+ it('returns nothing for an empty strip', () => {
+ expect(allocateTabWidths({ activeIndex: -1, count: 0, usableWidth: 800 })).toEqual({
+ hiddenCount: 0,
+ visibleIndices: [],
+ widths: [],
+ });
+ });
+
+ it('caps a lone tab at the maximum width', () => {
+ const { widths, hiddenCount } = allocateTabWidths({
+ activeIndex: 0,
+ count: 1,
+ usableWidth: 900,
+ });
+
+ expect(widths).toEqual([MAX_TAB_WIDTH]);
+ expect(hiddenCount).toBe(0);
+ });
+
+ it('splits evenly while every tab still clears the active floor', () => {
+ const { widths, hiddenCount } = allocateTabWidths({
+ activeIndex: 1,
+ count: 3,
+ usableWidth: 900,
+ });
+
+ expect(widths).toEqual([MAX_TAB_WIDTH, MAX_TAB_WIDTH, MAX_TAB_WIDTH]);
+ expect(hiddenCount).toBe(0);
+ });
+
+ it('holds the active tab at its floor once the even split drops below it', () => {
+ const { widths, visibleIndices, hiddenCount } = allocateTabWidths({
+ activeIndex: 2,
+ count: 8,
+ usableWidth: 800,
+ });
+
+ expect(hiddenCount).toBe(0);
+ expect(visibleIndices).toEqual([0, 1, 2, 3, 4, 5, 6, 7]);
+ expect(widths[2]).toBe(ACTIVE_TAB_MIN_WIDTH);
+ expect(widths.filter((_, index) => index !== 2)).toSatisfy((rest: number[]) =>
+ rest.every((width) => width < ACTIVE_TAB_MIN_WIDTH && width >= MIN_TAB_WIDTH),
+ );
+ expect(totalWidth(widths)).toBeLessThanOrEqual(800);
+ });
+
+ it('never shrinks a tab below the minimum, pushing the remainder into overflow', () => {
+ const { widths, hiddenCount } = allocateTabWidths({
+ activeIndex: 0,
+ count: 30,
+ usableWidth: 600,
+ });
+
+ expect(hiddenCount).toBeGreaterThan(0);
+ expect(Math.min(...widths)).toBeGreaterThanOrEqual(MIN_TAB_WIDTH);
+ expect(totalWidth(widths)).toBeLessThanOrEqual(600 - OVERFLOW_CONTROL_WIDTH);
+ });
+
+ it('keeps the active tab on screen when it sits past the overflow cut', () => {
+ const { visibleIndices, widths } = allocateTabWidths({
+ activeIndex: 25,
+ count: 30,
+ usableWidth: 600,
+ });
+
+ expect(visibleIndices).toContain(25);
+ expect(visibleIndices.at(-1)).toBe(25);
+ expect(widths.at(-1)).toBe(ACTIVE_TAB_MIN_WIDTH);
+ });
+
+ it('reserves room for the overflow control itself', () => {
+ const usableWidth = 500;
+ const { widths, hiddenCount } = allocateTabWidths({
+ activeIndex: 0,
+ count: 20,
+ usableWidth,
+ });
+
+ expect(hiddenCount).toBeGreaterThan(0);
+ expect(totalWidth(widths) + OVERFLOW_CONTROL_WIDTH).toBeLessThanOrEqual(usableWidth);
+ });
+
+ it('still renders one tab when the strip is narrower than a single tab', () => {
+ const { widths, visibleIndices, hiddenCount } = allocateTabWidths({
+ activeIndex: 3,
+ count: 6,
+ usableWidth: 20,
+ });
+
+ expect(widths).toHaveLength(1);
+ expect(visibleIndices).toEqual([3]);
+ expect(hiddenCount).toBe(5);
+ });
+
+ it('falls back to an even split when no tab is active', () => {
+ const { widths } = allocateTabWidths({ activeIndex: -1, count: 6, usableWidth: 600 });
+
+ expect(widths.every((width) => Math.abs(width - widths[0]) <= 1)).toBe(true);
+ });
+
+ // An active pinned tab leaves the flow list with no active index. Callers index straight
+ // into the flow list with what comes back, so a lone flow tab must still resolve to a real
+ // index — including before the strip is measured, when usableWidth is still 0.
+ it('shows the lone flow tab when the active tab is pinned out of the list', () => {
+ expect(allocateTabWidths({ activeIndex: -1, count: 1, usableWidth: 0 })).toEqual({
+ hiddenCount: 0,
+ visibleIndices: [0],
+ widths: [MIN_TAB_WIDTH],
+ });
+ });
+
+ it('never emits an index outside the flow list', () => {
+ const offenders: string[] = [];
+
+ for (const count of [1, 2, 3, 8, 30])
+ for (const usableWidth of [0, 20, 29, 42, 76, 120, 600, 900])
+ for (const activeIndex of [-1, 0, count - 1]) {
+ const { visibleIndices, widths } = allocateTabWidths({ activeIndex, count, usableWidth });
+ const invalid = visibleIndices.some((index) => index < 0 || index >= count);
+
+ if (invalid || visibleIndices.length !== widths.length)
+ offenders.push(
+ `count=${count} width=${usableWidth} active=${activeIndex} → [${visibleIndices}]`,
+ );
+ }
+
+ expect(offenders).toEqual([]);
+ });
+
+ // The trailing "+" button sits right after the last tab, so any width the split leaves
+ // unspent moves it. Flooring alone leaves a different remainder per tab count, which
+ // makes the button drift sideways on every added tab even when the strip is full.
+ it('spends the whole budget once compressed, so the trailing control cannot drift', () => {
+ const usableWidth = 900;
+ const totals = Array.from({ length: 12 }, (_, index) => {
+ const count = index + 8;
+ const { widths, hiddenCount } = allocateTabWidths({ activeIndex: 0, count, usableWidth });
+ return { hiddenCount, total: totalWidth(widths) };
+ });
+
+ for (const { total, hiddenCount } of totals) {
+ const budget = hiddenCount > 0 ? usableWidth - OVERFLOW_CONTROL_WIDTH : usableWidth;
+ expect(total).toBe(budget);
+ }
+ expect(new Set(totals.map((t) => t.total)).size).toBeLessThanOrEqual(2);
+ });
+
+ it('leaves the strip short of the budget only while tabs still fit at their maximum', () => {
+ const { widths } = allocateTabWidths({ activeIndex: 0, count: 2, usableWidth: 900 });
+
+ expect(widths).toEqual([MAX_TAB_WIDTH, MAX_TAB_WIDTH]);
+ expect(totalWidth(widths)).toBeLessThan(900);
+ });
+});
diff --git a/src/features/Electron/titlebar/TabBar/tabLayout.ts b/src/features/Electron/titlebar/TabBar/tabLayout.ts
new file mode 100644
index 00000000000..c954263b814
--- /dev/null
+++ b/src/features/Electron/titlebar/TabBar/tabLayout.ts
@@ -0,0 +1,127 @@
+export const MAX_TAB_WIDTH = 200;
+export const MIN_TAB_WIDTH = 40;
+export const ACTIVE_TAB_MIN_WIDTH = 150;
+export const PINNED_TAB_WIDTH = 34;
+export const TAB_GAP = 2;
+export const OVERFLOW_CONTROL_WIDTH = 34;
+
+export type TabTier = 'compact' | 'full' | 'icon' | 'narrow';
+
+export interface TabLayoutInput {
+ activeIndex: number;
+ count: number;
+ usableWidth: number;
+}
+
+export interface TabLayoutResult {
+ hiddenCount: number;
+ /** Indices into the original tab list, in render order. */
+ visibleIndices: number[];
+ /** Width for each entry of `visibleIndices`. */
+ widths: number[];
+}
+
+export const resolveTabTier = (width: number): TabTier => {
+ if (width >= 130) return 'full';
+ if (width >= 96) return 'compact';
+ if (width >= 58) return 'narrow';
+ return 'icon';
+};
+
+const clampWidth = (width: number): number =>
+ Math.max(MIN_TAB_WIDTH, Math.min(MAX_TAB_WIDTH, Math.floor(width)));
+
+interface Attempt {
+ indices: number[];
+ total: number;
+ widths: number[];
+}
+
+const attemptLayout = (
+ visibleCount: number,
+ budget: number,
+ count: number,
+ activeIndex: number,
+): Attempt => {
+ const indices = Array.from({ length: visibleCount }, (_, index) => index);
+
+ // The active tab must stay on screen; when it falls past the cut, it takes the last
+ // visible slot instead of disappearing into the overflow list.
+ if (activeIndex >= visibleCount && activeIndex < count) indices[visibleCount - 1] = activeIndex;
+
+ const activePosition = indices.indexOf(activeIndex);
+ const gaps = visibleCount * TAB_GAP;
+ const even = clampWidth((budget - gaps) / visibleCount);
+
+ const activeHeldAtFloor = visibleCount > 1 && activePosition >= 0 && even < ACTIVE_TAB_MIN_WIDTH;
+
+ const widths = activeHeldAtFloor
+ ? indices.map((_, position) =>
+ position === activePosition
+ ? ACTIVE_TAB_MIN_WIDTH
+ : clampWidth((budget - ACTIVE_TAB_MIN_WIDTH - gaps) / (visibleCount - 1)),
+ )
+ : indices.map(() => even);
+
+ const sum = () => widths.reduce((acc, width) => acc + width, 0) + gaps;
+
+ // Hand the flooring remainder back out, one pixel at a time. Without this the strip
+ // stops a few pixels short of its budget and by a different amount for each tab count,
+ // so the trailing "+" button drifts sideways every time a tab is added — even once the
+ // strip is visually full and nothing should move any more.
+ if (sum() <= budget) {
+ let remainder = budget - sum();
+ while (remainder > 0) {
+ const before = remainder;
+ for (let index = 0; index < widths.length && remainder > 0; index += 1) {
+ // The active tab's floor is a fixed, predictable number — it does not absorb
+ // leftover pixels; the tabs sharing the remaining space do.
+ if (widths[index] >= MAX_TAB_WIDTH || (activeHeldAtFloor && index === activePosition))
+ continue;
+ widths[index] += 1;
+ remainder -= 1;
+ }
+ if (remainder === before) break;
+ }
+ }
+
+ return { indices, total: sum(), widths };
+};
+
+/**
+ * Splits the strip among tabs: everyone shrinks toward MIN_TAB_WIDTH, except the active
+ * tab which holds ACTIVE_TAB_MIN_WIDTH outside the split so the current page keeps a
+ * readable title at any density. Tabs that no longer fit are reported as hiddenCount for
+ * the overflow control, whose own width is reserved before the split.
+ */
+export const allocateTabWidths = ({
+ activeIndex,
+ count,
+ usableWidth,
+}: TabLayoutInput): TabLayoutResult => {
+ if (count <= 0) return { hiddenCount: 0, visibleIndices: [], widths: [] };
+
+ const full = attemptLayout(count, usableWidth, count, activeIndex);
+ if (full.total <= usableWidth) {
+ return { hiddenCount: 0, visibleIndices: full.indices, widths: full.widths };
+ }
+
+ const budget = Math.max(MIN_TAB_WIDTH + TAB_GAP, usableWidth - OVERFLOW_CONTROL_WIDTH);
+ // Overflow implies at least one hidden tab, hence the `count - 1` ceiling — but a single tab
+ // is shown at any width, so the floor of 1 wins over it.
+ const start = Math.max(1, Math.min(count - 1, Math.floor(budget / (MIN_TAB_WIDTH + TAB_GAP))));
+
+ for (let visibleCount = start; visibleCount > 1; visibleCount -= 1) {
+ const attempt = attemptLayout(visibleCount, budget, count, activeIndex);
+ if (attempt.total <= budget) {
+ return {
+ hiddenCount: count - visibleCount,
+ visibleIndices: attempt.indices,
+ widths: attempt.widths,
+ };
+ }
+ }
+
+ const last = attemptLayout(1, budget, count, activeIndex);
+ return { hiddenCount: count - 1, visibleIndices: last.indices, widths: last.widths };
+};
diff --git a/src/features/Electron/titlebar/TabBar/types.ts b/src/features/Electron/titlebar/TabBar/types.ts
index b2cdd3f41ad..586ae846e83 100644
--- a/src/features/Electron/titlebar/TabBar/types.ts
+++ b/src/features/Electron/titlebar/TabBar/types.ts
@@ -4,6 +4,8 @@ export interface TabItem {
cached?: DynamicRouteMeta;
id: string;
lastVisited: number;
+ /** Pinned tabs occupy a fixed-width run at the head of the list. */
+ pinned?: boolean;
url: string;
visitCount?: number;
}
diff --git a/src/features/Electron/titlebar/TitleBar.tsx b/src/features/Electron/titlebar/TitleBar.tsx
index f1b4fb9f271..1945afc0062 100644
--- a/src/features/Electron/titlebar/TitleBar.tsx
+++ b/src/features/Electron/titlebar/TitleBar.tsx
@@ -1,6 +1,7 @@
import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';
import { Flexbox } from '@lobehub/ui';
import { Divider } from 'antd';
+import { createStaticStyles, cx } from 'antd-style';
import { memo } from 'react';
import { electronStylish } from '@/styles/electron';
@@ -17,6 +18,20 @@ import WinControl from './WinControl';
const platform = getPlatform();
+// A translucent tint rather than a solid color: the desktop body is deliberately
+// semi-transparent for vibrancy, and an opaque titlebar would kill it. The tint only
+// needs to push the bar a step away from the opaque content card so the attached
+// active tab reads as part of the card.
+const styles = createStaticStyles(({ css }) => ({
+ bar: css`
+ background-color: rgb(0 0 0 / 4%);
+
+ html[data-theme='dark'] & {
+ background-color: rgb(0 0 0 / 20%);
+ }
+ `,
+}));
+
const TitleBar = memo(() => {
useWatchThemeUpdate();
@@ -26,7 +41,7 @@ const TitleBar = memo(() => {
<Flexbox
horizontal
align={'center'}
- className={electronStylish.draggable}
+ className={cx(electronStylish.draggable, styles.bar)}
height={TITLE_BAR_HEIGHT}
justify={'space-between'}
style={{ minHeight: TITLE_BAR_HEIGHT, padding }}
diff --git a/src/store/electron/actions/__tests__/tabPages.test.ts b/src/store/electron/actions/__tests__/tabPages.test.ts
index bbe37249e61..0ff34976503 100644
--- a/src/store/electron/actions/__tests__/tabPages.test.ts
+++ b/src/store/electron/actions/__tests__/tabPages.test.ts
@@ -432,4 +432,202 @@ describe('tabPages actions', () => {
});
});
});
+
+ describe('pinning keeps array order equal to render order', () => {
+ const urls = (tabs: TabItem[]) => tabs.map((tab) => tab.url);
+
+ const seed = () => {
+ const { result } = renderHook(() => useElectronStore());
+ const tabs = [buildTab('/a'), buildTab('/b'), buildTab('/c')];
+
+ act(() => {
+ useElectronStore.setState({ activeTabId: '/a', tabs });
+ });
+
+ return result;
+ };
+
+ it('moves a pinned tab to the head so Mod+1 still means the leftmost tab', () => {
+ const result = seed();
+
+ act(() => {
+ result.current.pinTab('/c');
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/c', '/a', '/b']);
+ expect(result.current.tabs[0].pinned).toBe(true);
+ });
+
+ it('appends to the pinned run rather than jumping ahead of earlier pins', () => {
+ const result = seed();
+
+ act(() => {
+ result.current.pinTab('/c');
+ });
+ act(() => {
+ result.current.pinTab('/b');
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/c', '/b', '/a']);
+ });
+
+ it('returns an unpinned tab to the first slot after the pinned run', () => {
+ const result = seed();
+
+ act(() => {
+ result.current.pinTab('/c');
+ });
+ act(() => {
+ result.current.pinTab('/b');
+ });
+ act(() => {
+ result.current.unpinTab('/c');
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/b', '/c', '/a']);
+ expect(result.current.tabs[1].pinned).toBe(false);
+ });
+
+ it('ignores a repeated pin', () => {
+ const result = seed();
+
+ act(() => {
+ result.current.pinTab('/b');
+ });
+ act(() => {
+ result.current.pinTab('/b');
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/b', '/a', '/c']);
+ });
+
+ it('refuses a drag that would interleave pinned and unpinned tabs', () => {
+ const result = seed();
+
+ act(() => {
+ result.current.pinTab('/c');
+ });
+ act(() => {
+ result.current.reorderTabs(2, 0);
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/c', '/a', '/b']);
+ });
+
+ it('still reorders within the unpinned run', () => {
+ const result = seed();
+
+ act(() => {
+ result.current.pinTab('/c');
+ });
+ act(() => {
+ result.current.reorderTabs(2, 1);
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/c', '/b', '/a']);
+ });
+
+ it('survives a storage round-trip written before the field existed', () => {
+ const legacy = [{ id: '/a', lastVisited: 1, url: '/a' }] as TabItem[];
+ saveTabPages(PERSONAL_TAB_SCOPE, legacy, '/a');
+
+ const restored = getTabPages(PERSONAL_TAB_SCOPE);
+
+ expect(restored.tabs).toHaveLength(1);
+ expect(restored.tabs[0].pinned).toBeUndefined();
+ });
+ });
+
+ describe('bulk closes spare the pinned run', () => {
+ const urls = (tabs: TabItem[]) => tabs.map((tab) => tab.url);
+
+ const seed = (pins: string[], activeTabId = '/c') => {
+ const { result } = renderHook(() => useElectronStore());
+
+ act(() => {
+ useElectronStore.setState({
+ activeTabId,
+ tabs: [buildTab('/a'), buildTab('/b'), buildTab('/c'), buildTab('/d')],
+ });
+ });
+ for (const url of pins) {
+ act(() => {
+ result.current.pinTab(url);
+ });
+ }
+
+ return result;
+ };
+
+ it('keeps pinned tabs when closing the others', () => {
+ const result = seed(['/a', '/b']);
+
+ act(() => {
+ result.current.closeOtherTabs('/c');
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/a', '/b', '/c']);
+ });
+
+ it('keeps pinned tabs when closing to the left', () => {
+ const result = seed(['/a']);
+
+ act(() => {
+ result.current.closeLeftTabs('/c');
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/a', '/c', '/d']);
+ });
+
+ it('keeps the rest of the pinned run when closing to the right of a pinned tab', () => {
+ const result = seed(['/a', '/b']);
+
+ act(() => {
+ result.current.closeRightTabs('/a');
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/a', '/b']);
+ });
+
+ it('still closes a pinned tab that was targeted on its own', () => {
+ const result = seed(['/a']);
+
+ act(() => {
+ result.current.removeTab('/a');
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/b', '/c', '/d']);
+ });
+
+ it('does nothing when every tab the bulk close would reach is pinned', () => {
+ const result = seed(['/a', '/b']);
+ const before = result.current.tabs;
+
+ act(() => {
+ result.current.closeLeftTabs('/c');
+ });
+
+ expect(result.current.tabs).toBe(before);
+ });
+
+ it('leaves focus on a pinned tab that survived the close', () => {
+ const result = seed(['/a'], '/a');
+
+ act(() => {
+ result.current.closeOtherTabs('/c');
+ });
+
+ expect(result.current.activeTabId).toBe('/a');
+ });
+
+ it('moves focus to the target when the active tab was closed', () => {
+ const result = seed(['/a'], '/d');
+
+ act(() => {
+ result.current.closeOtherTabs('/c');
+ });
+
+ expect(result.current.activeTabId).toBe('/c');
+ });
+ });
});
diff --git a/src/store/electron/actions/tabPages.ts b/src/store/electron/actions/tabPages.ts
index d5d1f163dee..d1121cd0046 100644
--- a/src/store/electron/actions/tabPages.ts
+++ b/src/store/electron/actions/tabPages.ts
@@ -123,50 +123,35 @@ export class TabPagesActionImpl {
};
closeLeftTabs = (id: string): void => {
- const { tabs, activeTabId } = this.#get();
+ const { tabs } = this.#get();
const index = tabs.findIndex((t) => t.id === id);
if (index <= 0) return;
- const newTabs = tabs.slice(index);
- const newActiveId = newTabs.some((t) => t.id === activeTabId) ? activeTabId : id;
-
- this.#set(
- { activeTabId: newActiveId, tabs: this.#touch(newTabs, newActiveId) },
- false,
- 'closeLeftTabs',
- );
- this.#persist();
+ this.#closeExcept((_, i) => i >= index, id, 'closeLeftTabs');
};
closeOtherTabs = (id: string): void => {
const { tabs } = this.#get();
- const target = tabs.find((t) => t.id === id);
- if (!target) return;
+ if (!tabs.some((t) => t.id === id)) return;
- this.#set({ activeTabId: id, tabs: this.#touch([target], id) }, false, 'closeOtherTabs');
- this.#persist();
+ this.#closeExcept((tab) => tab.id === id, id, 'closeOtherTabs');
};
closeRightTabs = (id: string): void => {
- const { tabs, activeTabId } = this.#get();
+ const { tabs } = this.#get();
const index = tabs.findIndex((t) => t.id === id);
if (index < 0 || index >= tabs.length - 1) return;
- const newTabs = tabs.slice(0, index + 1);
- const newActiveId = newTabs.some((t) => t.id === activeTabId) ? activeTabId : id;
-
- this.#set(
- { activeTabId: newActiveId, tabs: this.#touch(newTabs, newActiveId) },
- false,
- 'closeRightTabs',
- );
- this.#persist();
+ this.#closeExcept((_, i) => i <= index, id, 'closeRightTabs');
};
reorderTabs = (fromIndex: number, toIndex: number): void => {
const { tabs } = this.#get();
if (fromIndex < 0 || fromIndex >= tabs.length) return;
if (toIndex < 0 || toIndex >= tabs.length) return;
+ // Pinned tabs form a run at the head of the list; a drag across that boundary would
+ // interleave the two groups and desync array order from render order.
+ if (!!tabs[fromIndex].pinned !== !!tabs[toIndex].pinned) return;
const newTabs = [...tabs];
const [moved] = newTabs.splice(fromIndex, 1);
@@ -176,6 +161,14 @@ export class TabPagesActionImpl {
this.#persist();
};
+ pinTab = (id: string): void => {
+ this.#setPinned(id, true);
+ };
+
+ unpinTab = (id: string): void => {
+ this.#setPinned(id, false);
+ };
+
updateTab = (id: string, url: string): string => {
const { tabs } = this.#get();
const index = tabs.findIndex((t) => t.id === id);
@@ -247,6 +240,45 @@ export class TabPagesActionImpl {
this.#persist();
};
+ // Pinning is a retention promise, so a bulk close only ever narrows the unpinned run —
+ // a pinned tab leaves solely through removeTab, where the user named that one tab.
+ // Focus therefore stays put unless the close actually took the active tab.
+ #closeExcept = (
+ keep: (tab: TabItem, index: number) => boolean,
+ targetId: string,
+ action: string,
+ ): void => {
+ const { tabs, activeTabId } = this.#get();
+ const newTabs = tabs.filter((tab, index) => tab.pinned || keep(tab, index));
+ if (newTabs.length === tabs.length) return;
+
+ const newActiveId = newTabs.some((t) => t.id === activeTabId) ? activeTabId : targetId;
+
+ this.#set({ activeTabId: newActiveId, tabs: this.#touch(newTabs, newActiveId) }, false, action);
+ this.#persist();
+ };
+
+ // Pinning moves the tab to the end of the pinned run, unpinning to the first slot
+ // after it. Array order must equal render order, or Mod+1–9, Ctrl+Tab cycling and drag
+ // reorder would each describe a different sequence.
+ #setPinned = (id: string, pinned: boolean): void => {
+ const { tabs } = this.#get();
+ const index = tabs.findIndex((t) => t.id === id);
+ if (index < 0 || !!tabs[index].pinned === pinned) return;
+
+ const target: TabItem = { ...tabs[index], pinned };
+ const rest = tabs.filter((_, i) => i !== index);
+ const firstUnpinned = rest.findIndex((t) => !t.pinned);
+ const position = firstUnpinned < 0 ? rest.length : firstUnpinned;
+
+ this.#set(
+ { tabs: [...rest.slice(0, position), target, ...rest.slice(position)] },
+ false,
+ pinned ? 'pinTab' : 'unpinTab',
+ );
+ this.#persist();
+ };
+
// Every path that makes a tab active must refresh its `lastVisited`: TabHost
// ranks keep-alive routers by that timestamp, so a tab activated without a
// navigation would stay at its stale recency and get its router disposed (and