diff --git a/src/renderer/src/components/tab-bar/TabBar.tsx b/src/renderer/src/components/tab-bar/TabBar.tsx
index 51f3fe4c283..6b9a2098c00 100644
--- a/src/renderer/src/components/tab-bar/TabBar.tsx
+++ b/src/renderer/src/components/tab-bar/TabBar.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback } from 'react'
+import React, { useCallback, useMemo } from 'react'
import { useTabStripOverflowNavigation } from './strip/tab-strip-overflow-navigation'
import { useTabStripDragScrollHandlers } from './strip/tab-strip-drag-scroll'
import type { TabBarProps } from './tab-bar-props'
@@ -94,13 +94,28 @@ function TabBarInner(props: TabBarProps): React.JSX.Element {
groupId: runtime.resolvedGroupId,
groupActiveTabId: props.groupActiveTabId ?? null
})
+ const clientHostedBrowserRows = props.clientHostedBrowserRows
+ const slotIds = useMemo(
+ () => [
+ ...itemProjection.sortableIds,
+ ...(clientHostedBrowserRows ?? []).map((row) => row.browserPageId)
+ ],
+ [clientHostedBrowserRows, itemProjection.sortableIds]
+ )
+ // Why memoized: the key spans every tab, and a windowed strip re-renders as it scrolls.
+ const stripLayoutKey = useMemo(
+ () =>
+ [
+ itemProjection.tabStripLayoutKey,
+ ...(clientHostedBrowserRows ?? []).map((row) => row.browserPageId)
+ ].join('|'),
+ [clientHostedBrowserRows, itemProjection.tabStripLayoutKey]
+ )
const tabStripNavigation = useTabStripOverflowNavigation({
activeVisibleTabId: itemProjection.activeVisibleTabId,
activeDockSlotId: activeClientHostedBrowserRowId ?? itemProjection.activeVisibleTabId,
- layoutKey: [
- itemProjection.tabStripLayoutKey,
- ...(props.clientHostedBrowserRows ?? []).map((row) => row.browserPageId)
- ].join('|'),
+ layoutKey: stripLayoutKey,
+ slotIds,
worktreeId
})
const attachFileDropOwner = useEditorGroupFileDropOwner({ worktreeId, groupId })
diff --git a/src/renderer/src/components/tab-bar/model/tab-bar-item-surface.tsx b/src/renderer/src/components/tab-bar/model/tab-bar-item-surface.tsx
index 7d88c2bdb7d..1b38b224f02 100644
--- a/src/renderer/src/components/tab-bar/model/tab-bar-item-surface.tsx
+++ b/src/renderer/src/components/tab-bar/model/tab-bar-item-surface.tsx
@@ -11,6 +11,7 @@ import type { TabBarProps } from '../tab-bar-props'
import type { TabBarRuntimeModel } from './use-tab-bar-runtime-model'
import type { TabBarItemActions } from './use-tab-bar-item-actions'
import TabBarItemRow from './TabBarItemRow'
+import { TAB_STRIP_WINDOW_SLOT_PX, type TabStripSegment } from '../strip/tab-strip-window'
export type TabBarItemSurfaceProps = Pick<
TabBarProps,
@@ -43,9 +44,12 @@ export function renderTabBarItems({
actions,
dropIndicatorByVisibleId,
includeTopTabBorder,
- activeClientHostedBrowserRowId
+ activeClientHostedBrowserRowId,
+ segments
}: {
items: TabBarItem[]
+ /** Mounted runs of `items`; gaps render as fixed-width spacers. */
+ segments: readonly TabStripSegment[]
props: TabBarItemSurfaceProps
runtime: TabBarItemSurfaceRuntime
actions: TabBarItemActions
@@ -97,7 +101,7 @@ export function renderTabBarItems({
return (activeTabType === 'editor' || activeTabType === 'simulator') && activeFileId === item.id
}
- return items.map((item, index) => {
+ function renderRow(item: TabBarItem, index: number): React.ReactNode {
let canToggleViewMode = false
let isChatView = false
let viewModeTabId: string | undefined
@@ -147,5 +151,27 @@ export function renderTabBarItems({
}
/>
)
- })
+ }
+
+ const rows: React.ReactNode[] = []
+ for (const segment of segments) {
+ if (segment.kind === 'gap') {
+ rows.push(
+
+ )
+ continue
+ }
+ for (let index = segment.start; index < segment.end; index++) {
+ rows.push(renderRow(items[index], index))
+ }
+ }
+ return rows
}
diff --git a/src/renderer/src/components/tab-bar/model/use-tab-bar-item-projection.ts b/src/renderer/src/components/tab-bar/model/use-tab-bar-item-projection.ts
index a0225f5ed7b..f66aa0b85a2 100644
--- a/src/renderer/src/components/tab-bar/model/use-tab-bar-item-projection.ts
+++ b/src/renderer/src/components/tab-bar/model/use-tab-bar-item-projection.ts
@@ -18,6 +18,8 @@ export type TabBarItemProjection = {
sortableIds: string[]
dropIndicatorByVisibleId: Map
activeVisibleTabId: string | null
+ /** The active item's unified tab id; resolved here so strip re-renders don't search every tab. */
+ activeUnifiedTabId: string | null
tabStripLayoutKey: string
}
@@ -121,8 +123,13 @@ export function useTabBarItemProjection({
const orderedIds = useMemo(() => orderedItems.map((item) => item.id), [orderedItems])
// Why: dnd-kit re-renders every tab when this array's identity changes, and the items rebuild on any tab write.
const [sortableIds, setSortableIds] = useState(orderedIds)
- if (!sameStringArray(sortableIds, orderedIds)) {
- setSortableIds(orderedIds)
+ // Compare once per rebuilt id list: a windowed strip re-renders on scroll without any tab change.
+ const [comparedIds, setComparedIds] = useState(orderedIds)
+ if (comparedIds !== orderedIds) {
+ setComparedIds(orderedIds)
+ if (!sameStringArray(sortableIds, orderedIds)) {
+ setSortableIds(orderedIds)
+ }
}
const activeIndicator =
hoveredTabInsertion?.groupId === resolvedGroupId ? hoveredTabInsertion : null
@@ -148,6 +155,10 @@ export function useTabBarItemProjection({
orderedItems
]
)
+ const activeUnifiedTabId = useMemo(
+ () => orderedItems.find((item) => item.id === activeVisibleTabId)?.unifiedTabId ?? null,
+ [activeVisibleTabId, orderedItems]
+ )
const chatNames = useStructuredChatTabNames()
const tabStripLayoutKey = useMemo(
() =>
@@ -166,6 +177,7 @@ export function useTabBarItemProjection({
sortableIds,
dropIndicatorByVisibleId,
activeVisibleTabId,
+ activeUnifiedTabId,
tabStripLayoutKey
}
}
diff --git a/src/renderer/src/components/tab-bar/strip/WindowedTabStrip.tsx b/src/renderer/src/components/tab-bar/strip/WindowedTabStrip.tsx
new file mode 100644
index 00000000000..e1929d5823a
--- /dev/null
+++ b/src/renderer/src/components/tab-bar/strip/WindowedTabStrip.tsx
@@ -0,0 +1,71 @@
+import React, { useMemo, useState, type RefObject } from 'react'
+import { SortableContext } from '@dnd-kit/sortable'
+import { sameStringArray } from '@/runtime/web-session-tabs-sync/snapshots/state-equality-core'
+import { useActiveDragVisibleTabId } from '../../tab-group/drag/tab-drag-context'
+import {
+ buildTabStripSegments,
+ useTabStripWindowState,
+ type TabStripSegment
+} from './tab-strip-window'
+
+/** Owns the strip's window state, so scrolling re-renders the strip alone, not the tab bar around it. */
+export function WindowedTabStrip({
+ stripRef,
+ subscribeToStripResize,
+ sortableIds,
+ activeVisibleTabId,
+ renderStrip
+}: {
+ stripRef: RefObject
+ subscribeToStripResize: (listener: () => void) => () => void
+ sortableIds: string[]
+ activeVisibleTabId: string | null
+ /** Renders the scroller (which must attach `stripRef`) with these mounted runs of the tabs. */
+ renderStrip: (segments: readonly TabStripSegment[]) => React.ReactNode
+}): React.JSX.Element {
+ const count = sortableIds.length
+ const { range, focusedSlotId } = useTabStripWindowState(stripRef, count, subscribeToStripResize)
+ const activeDragVisibleTabId = useActiveDragVisibleTabId()
+ const windowed = range !== null
+ // Why keyed on sortableIds: they change only when tabs open, close or move, not on every tab write.
+ const indexBySortableId = useMemo(
+ () => (windowed ? new Map(sortableIds.map((id, index) => [id, index])) : null),
+ [sortableIds, windowed]
+ )
+ const tabStripWindow = useMemo(() => {
+ if (range === null || indexBySortableId === null) {
+ return { segments: buildTabStripSegments(count, null, []), sortableIds }
+ }
+ // Keep the active, dragged and focused tabs mounted wherever they sit in the order.
+ const keptIndices = [activeVisibleTabId, activeDragVisibleTabId, focusedSlotId].flatMap(
+ (id) => {
+ const index = id === null ? undefined : indexBySortableId.get(id)
+ return index === undefined ? [] : [index]
+ }
+ )
+ const segments = buildTabStripSegments(count, range, keptIndices)
+ const mountedIds = segments.flatMap((segment) =>
+ segment.kind === 'tabs' ? sortableIds.slice(segment.start, segment.end) : []
+ )
+ return { segments, sortableIds: mountedIds }
+ }, [
+ activeDragVisibleTabId,
+ activeVisibleTabId,
+ count,
+ focusedSlotId,
+ indexBySortableId,
+ range,
+ sortableIds
+ ])
+ // Why: dnd-kit re-renders every mounted tab when this array's identity changes, and tab writes rebuild it.
+ const [mountedSortableIds, setMountedSortableIds] = useState(tabStripWindow.sortableIds)
+ if (!sameStringArray(mountedSortableIds, tabStripWindow.sortableIds)) {
+ setMountedSortableIds(tabStripWindow.sortableIds)
+ }
+ // Why the scroller renders inside: its ref must attach before the window state's layout effect reads it.
+ return (
+
+ {renderStrip(tabStripWindow.segments)}
+
+ )
+}
diff --git a/src/renderer/src/components/tab-bar/strip/tab-bar-surface.tsx b/src/renderer/src/components/tab-bar/strip/tab-bar-surface.tsx
index 7809facf94e..b314ac11081 100644
--- a/src/renderer/src/components/tab-bar/strip/tab-bar-surface.tsx
+++ b/src/renderer/src/components/tab-bar/strip/tab-bar-surface.tsx
@@ -1,5 +1,4 @@
import React from 'react'
-import { SortableContext } from '@dnd-kit/sortable'
import { ChevronLeft, ChevronRight, Plus } from 'lucide-react'
import { translate } from '@/i18n/i18n'
import type { Translate } from '@/i18n/use-translate'
@@ -24,6 +23,8 @@ import type { TabBarCreateMenuController } from '../create-menu/tab-bar-create-m
import type { TabBarItemProjection } from '../model/use-tab-bar-item-projection'
import type { TabBarItemActions } from '../model/use-tab-bar-item-actions'
import { renderTabBarItems } from '../model/tab-bar-item-surface'
+import { WindowedTabStrip } from './WindowedTabStrip'
+import type { TabStripSegment } from './tab-strip-window'
import { TabBarStaticCreateMenu } from '../create-menu/tab-bar-static-create-menu'
import { NewTabMenuContent } from '../menu-fit/NewTabMenuContent'
import ClientHostedBrowserTabRows from '../browser-tabs/ClientHostedBrowserTabRows'
@@ -101,7 +102,7 @@ export function renderTabBarSurface(
queueFocusAfterNewTabMenuClose,
showStaticCreateMenuItems
} = createMenu
- const { orderedItems, sortableIds, dropIndicatorByVisibleId } = itemProjection
+ const { orderedItems, dropIndicatorByVisibleId, sortableIds, activeVisibleTabId } = itemProjection
const clientHostedBrowserRows = props.clientHostedBrowserRows ?? EMPTY_CLIENT_HOSTED_ROWS
const {
tabStripRef,
@@ -112,15 +113,17 @@ export function renderTabBarSurface(
} = tabStripNavigation
const singleTab = orderedItems.length + clientHostedBrowserRows.length === 1
const includeTopTabBorder = tabStripChrome !== 'floating-panel'
- const renderedItems = renderTabBarItems({
- items: orderedItems,
- props,
- runtime,
- actions: itemActions,
- dropIndicatorByVisibleId,
- includeTopTabBorder,
- activeClientHostedBrowserRowId
- })
+ const renderItems = (segments: readonly TabStripSegment[]): React.ReactNode[] =>
+ renderTabBarItems({
+ items: orderedItems,
+ props,
+ runtime,
+ actions: itemActions,
+ dropIndicatorByVisibleId,
+ includeTopTabBorder,
+ activeClientHostedBrowserRowId,
+ segments
+ })
const hasTabs = orderedItems.length + clientHostedBrowserRows.length > 0
return (
@@ -151,51 +154,57 @@ export function renderTabBarSurface(
) : null}
{/* Keep drag siblings anchored; only the insertion bar moves. */}
-
- {/* Why: no-drag lets tab interactions work inside the titlebar's drag region (outer container stays window-draggable). */}
-
+
(
+ // Why no-drag: tab interactions must work inside the titlebar's drag region (outer container stays window-draggable).
-
- {renderedItems}
- {clientHostedBrowserRows.length > 0 ? (
-
- ) : null}
-
+
+
+ {renderItems(segments)}
+ {clientHostedBrowserRows.length > 0 ? (
+
+ ) : null}
+
+
+
-
-
-
+ )}
+ />
{tabStripOverflowState.hasOverflow ? (
@@ -258,10 +267,7 @@ export function renderTabBarSurface(
worktreeId={worktreeId}
groupId={resolvedGroupId}
excludedTabId={
- activeClientHostedBrowserRowId === null
- ? (orderedItems.find((item) => item.id === itemProjection.activeVisibleTabId)
- ?.unifiedTabId ?? null)
- : null
+ activeClientHostedBrowserRowId === null ? itemProjection.activeUnifiedTabId : null
}
menuOpen={newTabMenuOpen}
menuOptions={createMenuOptions}
diff --git a/src/renderer/src/components/tab-bar/strip/tab-strip-overflow-navigation.ts b/src/renderer/src/components/tab-bar/strip/tab-strip-overflow-navigation.ts
index 666afcdc2ae..2ba130b82fb 100644
--- a/src/renderer/src/components/tab-bar/strip/tab-strip-overflow-navigation.ts
+++ b/src/renderer/src/components/tab-bar/strip/tab-strip-overflow-navigation.ts
@@ -25,6 +25,13 @@ import {
} from './tab-strip-slot-geometry'
import { motionSafeScrollBehavior } from '@/hooks/theme/usePrefersReducedMotion'
import { useTabDragActive } from '../../tab-group/drag/tab-drag-context'
+import {
+ notifyTabStripListeners,
+ revealFirstUnmountedTabStripSlot,
+ useNotifyTabStripScrollAfterCommit,
+ useTabStripCommitStartScroll,
+ useTabStripListenerSubscribe
+} from './tab-strip-window'
const TAB_STRIP_SCROLL_FRACTION = 0.75
const TAB_STRIP_MIN_SCROLL_STEP_PX = 120
@@ -53,12 +60,15 @@ export function useTabStripOverflowNavigation({
activeVisibleTabId,
activeDockSlotId,
layoutKey,
+ slotIds,
worktreeId
}: {
activeVisibleTabId: string | null
/** The slot drawn active; a client-hosted row can take it without `activeVisibleTabId` changing. */
activeDockSlotId: string | null
layoutKey: string
+ /** Every slot in strip order, mounted or not: a windowed strip's DOM holds only part of it. */
+ slotIds: readonly string[]
worktreeId: string
}): {
tabStripRef: RefObject
@@ -69,11 +79,15 @@ export function useTabStripOverflowNavigation({
} {
const isTabDragActive = useTabDragActive()
const tabStripRef = useRef(null)
+ // Why first: this hook's effects below are the ones that scroll the strip.
+ const commitStartScrollRef = useTabStripCommitStartScroll(tabStripRef)
const stripResizeListenersRef = useRef void>>(new Set())
+ const subscribeToStripResize = useTabStripListenerSubscribe(stripResizeListenersRef)
const prevStripRef = useRef<{ worktreeId: string; tabIds: ReadonlySet } | null>(null)
const stickToEndRef = useRef(false)
const tabClosedThisCommitRef = useRef(false)
const activeTabIdRef = useRef(null)
+ const slotIdsRef = useRef(slotIds)
const hoverDeferredRevealIdsRef = useRef>(new Set())
const scrollAnchorRef = useRef<{
activeTabId: string | null
@@ -150,9 +164,7 @@ export function useTabStripOverflowNavigation({
el.scrollLeft = Math.max(0, el.scrollWidth - el.clientWidth)
}
recordScrollAnchor()
- for (const listener of stripResizeListenersRef.current) {
- listener()
- }
+ notifyTabStripListeners(stripResizeListenersRef)
}
const disconnectResizeObservers = bindTabStripContentResizeObservers(el, handleStripResize)
@@ -179,13 +191,16 @@ export function useTabStripOverflowNavigation({
}
const knownIds = new Set([...readTabStripSlotIds(el)].filter((id) => !deferred.has(id)))
const offscreenOpened = findOffscreenOpenedTabStripSlot(el, knownIds)
- if (!offscreenOpened) {
+ if (offscreenOpened) {
+ revealTabStripSlot(el, offscreenOpened)
+ } else if (!revealFirstUnmountedTabStripSlot(el, slotIdsRef.current, deferred)) {
return
}
- revealTabStripSlot(el, offscreenOpened)
stickToEndRef.current = isTabStripScrolledToEnd(el)
updateTabStripOverflowState()
recordScrollAnchor()
+ // Why: this scroll happens outside a commit, so the commit-end notify can't see it.
+ notifyTabStripListeners(stripResizeListenersRef)
}
el.addEventListener('pointerleave', onPointerLeave)
return () => el.removeEventListener('pointerleave', onPointerLeave)
@@ -195,6 +210,9 @@ export function useTabStripOverflowNavigation({
useLayoutEffect(() => {
activeTabIdRef.current = activeVisibleTabId
}, [activeVisibleTabId])
+ useLayoutEffect(() => {
+ slotIdsRef.current = slotIds
+ }, [slotIds])
useLayoutEffect(() => {
const strip = tabStripRef.current
@@ -203,7 +221,8 @@ export function useTabStripOverflowNavigation({
return
}
const prev = prevStripRef.current
- const tabIds = readTabStripSlotIds(strip)
+ // Why logical ids: scrolling a windowed strip mounts and unmounts slots without opening or closing tabs.
+ const tabIds: ReadonlySet = new Set(slotIdsRef.current)
prevStripRef.current = { worktreeId, tabIds }
if (!prev || prev.worktreeId !== worktreeId) {
hoverDeferredRevealIdsRef.current = new Set()
@@ -243,6 +262,9 @@ export function useTabStripOverflowNavigation({
const offscreenOpened = findOffscreenOpenedTabStripSlot(strip, prev.tabIds)
if (offscreenOpened) {
revealTabStripSlot(strip, offscreenOpened)
+ } else {
+ const opened = [...tabIds].filter((id) => !prev.tabIds.has(id))
+ revealFirstUnmountedTabStripSlot(strip, slotIdsRef.current, opened)
}
}
stickToEndRef.current = isTabStripScrolledToEnd(strip)
@@ -298,14 +320,8 @@ export function useTabStripOverflowNavigation({
useLayoutEffect(() => {
tabClosedThisCommitRef.current = false
})
-
- // Why share these observers: each one watches every tab, so a second set doubles that work.
- const subscribeToStripResize = useCallback((listener: () => void): (() => void) => {
- stripResizeListenersRef.current.add(listener)
- return () => {
- stripResizeListenersRef.current.delete(listener)
- }
- }, [])
+ // Why last: it must follow every effect above that scrolls the strip.
+ useNotifyTabStripScrollAfterCommit(tabStripRef, stripResizeListenersRef, commitStartScrollRef)
return {
tabStripRef,
diff --git a/src/renderer/src/components/tab-bar/strip/tab-strip-scroll-anchor.ts b/src/renderer/src/components/tab-bar/strip/tab-strip-scroll-anchor.ts
index 44f8fa11411..f7009047563 100644
--- a/src/renderer/src/components/tab-bar/strip/tab-strip-scroll-anchor.ts
+++ b/src/renderer/src/components/tab-bar/strip/tab-strip-scroll-anchor.ts
@@ -57,5 +57,11 @@ export function restoreTabStripScrollAnchor(
}
export function isLastTabStripTab(strip: HTMLElement, tabId: string | null): boolean {
- return tabId !== null && tabElements(strip).at(-1)?.dataset.tabId === tabId
+ const last = tabElements(strip).at(-1)
+ if (tabId === null || last?.dataset.tabId !== tabId) {
+ return false
+ }
+ // A windowed strip ends in a spacer for unmounted tabs; the last mounted tab isn't last then.
+ const lastGap = Array.from(strip.querySelectorAll(':scope > [data-tab-strip-gap]')).at(-1)
+ return !lastGap || !(last.compareDocumentPosition(lastGap) & Node.DOCUMENT_POSITION_FOLLOWING)
}
diff --git a/src/renderer/src/components/tab-bar/strip/tab-strip-slot-geometry.ts b/src/renderer/src/components/tab-bar/strip/tab-strip-slot-geometry.ts
index 2717849fc5c..42e4c4961d7 100644
--- a/src/renderer/src/components/tab-bar/strip/tab-strip-slot-geometry.ts
+++ b/src/renderer/src/components/tab-bar/strip/tab-strip-slot-geometry.ts
@@ -44,7 +44,8 @@ function getSlotNaturalSpan(strip: HTMLElement, slot: HTMLElement): [number, num
return [rect.left, rect.right]
}
let prev = slot.previousElementSibling
- while (prev && !prev.matches(SLOT_SELECTOR)) {
+ // A windowed strip's spacer stands in for the unmounted tabs before it.
+ while (prev && !prev.matches(`${SLOT_SELECTOR}, [data-tab-strip-gap]`)) {
prev = prev.previousElementSibling
}
const left = prev
diff --git a/src/renderer/src/components/tab-bar/strip/tab-strip-window.test.ts b/src/renderer/src/components/tab-bar/strip/tab-strip-window.test.ts
new file mode 100644
index 00000000000..3a016f55a37
--- /dev/null
+++ b/src/renderer/src/components/tab-bar/strip/tab-strip-window.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest'
+import { buildTabStripSegments, computeTabStripRange } from './tab-strip-window'
+
+describe('tab strip window', () => {
+ it('renders every tab below the windowing threshold', () => {
+ expect(computeTabStripRange(99, 5000, 800)).toBeNull()
+ expect(buildTabStripSegments(3, null, [])).toEqual([{ kind: 'tabs', start: 0, end: 3 }])
+ })
+
+ it('mounts the viewport plus a viewport each side, snapped to blocks', () => {
+ // 800px shows 6 tabs of 144px; scrolled to tab 100.
+ expect(computeTabStripRange(10_000, 14_400, 800)).toEqual({ start: 80, end: 112 })
+ expect(computeTabStripRange(10_000, 0, 800)).toEqual({ start: 0, end: 16 })
+ expect(computeTabStripRange(120, 16_000, 800)).toEqual({ start: 96, end: 120 })
+ })
+
+ it('keeps tabs outside the range mounted in place, with spacers around them', () => {
+ expect(buildTabStripSegments(1000, { start: 80, end: 112 }, [5, 112, 999, 90])).toEqual([
+ { kind: 'gap', start: 0, end: 5 },
+ { kind: 'tabs', start: 5, end: 6 },
+ { kind: 'gap', start: 6, end: 80 },
+ { kind: 'tabs', start: 80, end: 113 },
+ { kind: 'gap', start: 113, end: 999 },
+ { kind: 'tabs', start: 999, end: 1000 }
+ ])
+ })
+
+ it('clamps a range left over from before tabs closed', () => {
+ expect(buildTabStripSegments(119, { start: 96, end: 120 }, [])).toEqual([
+ { kind: 'gap', start: 0, end: 96 },
+ { kind: 'tabs', start: 96, end: 119 }
+ ])
+ expect(buildTabStripSegments(1, { start: 4992, end: 5024 }, [0])).toEqual([
+ { kind: 'tabs', start: 0, end: 1 }
+ ])
+ })
+})
diff --git a/src/renderer/src/components/tab-bar/strip/tab-strip-window.ts b/src/renderer/src/components/tab-bar/strip/tab-strip-window.ts
new file mode 100644
index 00000000000..450269504c7
--- /dev/null
+++ b/src/renderer/src/components/tab-bar/strip/tab-strip-window.ts
@@ -0,0 +1,232 @@
+import { useCallback, useLayoutEffect, useRef, useState, type RefObject } from 'react'
+import { findTabStripSlot } from './tab-strip-slot-geometry'
+
+/** Overflowing tabs sit at their 144px minimum (tab-width-rules.ts), so unmounted runs need no measuring. */
+export const TAB_STRIP_WINDOW_SLOT_PX = 144
+/** Below this every tab renders; at this count the minimum widths alone overflow any pane. */
+export const TAB_STRIP_WINDOW_MIN_TABS = 100
+// Snap range edges so scrolling re-renders once per block of tabs, not per frame.
+const WINDOW_BLOCK = 16
+
+export type TabStripRange = { start: number; end: number }
+
+export type TabStripSegment =
+ | { kind: 'tabs'; start: number; end: number }
+ | { kind: 'gap'; start: number; end: number }
+
+/** Tabs to mount: the viewport plus one viewport each side; null renders every tab. */
+export function computeTabStripRange(
+ count: number,
+ scrollLeft: number,
+ viewportWidth: number
+): TabStripRange | null {
+ if (count < TAB_STRIP_WINDOW_MIN_TABS) {
+ return null
+ }
+ const perView = Math.max(1, Math.ceil(viewportWidth / TAB_STRIP_WINDOW_SLOT_PX))
+ const first = Math.floor(Math.max(0, scrollLeft) / TAB_STRIP_WINDOW_SLOT_PX)
+ const start = Math.max(0, Math.floor((first - perView) / WINDOW_BLOCK) * WINDOW_BLOCK)
+ const end = Math.min(count, Math.ceil((first + 2 * perView) / WINDOW_BLOCK) * WINDOW_BLOCK)
+ return { start, end: Math.max(end, Math.min(count, start + WINDOW_BLOCK)) }
+}
+
+/** Mounted runs and the gaps between them; `keptIndices` stay mounted at their own place in the order. */
+export function buildTabStripSegments(
+ count: number,
+ range: TabStripRange | null,
+ keptIndices: readonly number[]
+): TabStripSegment[] {
+ // Why clamp: the range follows scroll in a layout effect, so the render that closes tabs still holds the old one.
+ if (range === null || count < TAB_STRIP_WINDOW_MIN_TABS) {
+ return count > 0 ? [{ kind: 'tabs', start: 0, end: count }] : []
+ }
+ const end = Math.min(range.end, count)
+ const runs: [number, number][] = [[Math.min(range.start, end), end]]
+ for (const index of keptIndices) {
+ if (index >= 0 && index < count) {
+ runs.push([index, index + 1])
+ }
+ }
+ runs.sort((a, b) => a[0] - b[0])
+ const segments: TabStripSegment[] = []
+ let cursor = 0
+ for (const [start, end] of runs) {
+ if (end <= cursor) {
+ continue
+ }
+ const from = Math.max(start, cursor)
+ if (from > cursor) {
+ segments.push({ kind: 'gap', start: cursor, end: from })
+ }
+ const last = segments.at(-1)
+ if (last?.kind === 'tabs' && last.end === from) {
+ last.end = end
+ } else {
+ segments.push({ kind: 'tabs', start: from, end })
+ }
+ cursor = end
+ }
+ if (cursor < count) {
+ segments.push({ kind: 'gap', start: cursor, end: count })
+ }
+ return segments
+}
+
+function sameRange(a: TabStripRange | null, b: TabStripRange | null): boolean {
+ return a === b || (a !== null && b !== null && a.start === b.start && a.end === b.end)
+}
+
+function slotIdOf(strip: HTMLElement, target: EventTarget | null): string | null {
+ const slot =
+ target instanceof Element ? target.closest('[data-tab-strip-slot]') : null
+ return slot && strip.contains(slot) ? (slot.dataset.tabStripSlot ?? null) : null
+}
+
+export type TabStripWindowState = {
+ range: TabStripRange | null
+ /** The slot holding focus (rename input, keyboard focus), kept mounted so scrolling never drops it. */
+ focusedSlotId: string | null
+}
+
+const UNWINDOWED: TabStripWindowState = { range: null, focusedSlotId: null }
+
+/** Follow the strip's scroll, size and focus; re-renders only when the range moves a block or focus changes slot. */
+export function useTabStripWindowState(
+ stripRef: RefObject,
+ count: number,
+ subscribeToStripResize: (listener: () => void) => () => void
+): TabStripWindowState {
+ const [state, setState] = useState(() => {
+ const range = computeTabStripRange(count, 0, 0)
+ return range ? { range, focusedSlotId: null } : UNWINDOWED
+ })
+ useLayoutEffect(() => {
+ const el = stripRef.current
+ if (!el || count < TAB_STRIP_WINDOW_MIN_TABS) {
+ setState(UNWINDOWED)
+ return
+ }
+ const update = (focusTarget: EventTarget | null = document.activeElement): void => {
+ const range = computeTabStripRange(count, el.scrollLeft, el.clientWidth)
+ // Why read focus with the range: the first windowed render must already keep a focused tab (a rename) mounted.
+ const focusedSlotId = slotIdOf(el, focusTarget)
+ setState((previous) =>
+ sameRange(previous.range, range) && previous.focusedSlotId === focusedSlotId
+ ? previous
+ : { range, focusedSlotId }
+ )
+ }
+ update()
+ let frame = 0
+ const onScroll = (): void => {
+ if (frame === 0) {
+ frame = requestAnimationFrame(() => {
+ frame = 0
+ update()
+ })
+ }
+ }
+ const onFocusIn = (event: FocusEvent): void => update(event.target)
+ const onFocusOut = (event: FocusEvent): void => update(event.relatedTarget)
+ const onResize = (): void => update()
+ el.addEventListener('scroll', onScroll, { passive: true })
+ el.addEventListener('focusin', onFocusIn)
+ el.addEventListener('focusout', onFocusOut)
+ const unsubscribe = subscribeToStripResize(onResize)
+ return () => {
+ el.removeEventListener('scroll', onScroll)
+ el.removeEventListener('focusin', onFocusIn)
+ el.removeEventListener('focusout', onFocusOut)
+ unsubscribe()
+ cancelAnimationFrame(frame)
+ }
+ }, [count, stripRef, subscribeToStripResize])
+ return state
+}
+
+export function notifyTabStripListeners(listenersRef: RefObject void>>): void {
+ for (const listener of listenersRef.current) {
+ listener()
+ }
+}
+
+/** Call before the strip owner's scrolling effects: the strip's offset before this commit's own scrolls. */
+export function useTabStripCommitStartScroll(
+ stripRef: RefObject
+): RefObject {
+ const startRef = useRef(null)
+ useLayoutEffect(() => {
+ startRef.current = stripRef.current?.scrollLeft ?? null
+ })
+ return startRef
+}
+
+/** Subscribe to the strip's shared resize observers: each one watches every tab, so a second set doubles that work. */
+export function useTabStripListenerSubscribe(
+ listenersRef: RefObject void>>
+): (listener: () => void) => () => void {
+ return useCallback(
+ (listener: () => void): (() => void) => {
+ listenersRef.current.add(listener)
+ return () => {
+ listenersRef.current.delete(listener)
+ }
+ },
+ [listenersRef]
+ )
+}
+
+/** Call last: re-notify strip listeners when this commit's effects scrolled the strip, since child listeners ran first. */
+export function useNotifyTabStripScrollAfterCommit(
+ stripRef: RefObject,
+ listenersRef: RefObject void>>,
+ startRef: RefObject
+): void {
+ useLayoutEffect(() => {
+ const strip = stripRef.current
+ const start = startRef.current
+ if (strip && start !== null && strip.scrollLeft !== start) {
+ notifyTabStripListeners(listenersRef)
+ }
+ })
+}
+
+/** Scroll-space left of an unmounted tab, measured from its spacer so wider mounted tabs (a rename) count. */
+function unmountedSlotLeft(strip: HTMLElement, index: number): number {
+ for (const gap of strip.querySelectorAll(':scope > [data-tab-strip-gap]')) {
+ const start = Number(gap.dataset.tabStripGapStart)
+ if (index >= start && index < Number(gap.dataset.tabStripGapEnd)) {
+ const gapLeft =
+ gap.getBoundingClientRect().left - strip.getBoundingClientRect().left + strip.scrollLeft
+ return gapLeft + (index - start) * TAB_STRIP_WINDOW_SLOT_PX
+ }
+ }
+ return index * TAB_STRIP_WINDOW_SLOT_PX
+}
+
+/** Scroll the first opened tab a windowed strip hasn't mounted into view by its index; false when none. */
+export function revealFirstUnmountedTabStripSlot(
+ strip: HTMLElement,
+ slotIds: readonly string[],
+ openedIds: Iterable
+): boolean {
+ if (slotIds.length < TAB_STRIP_WINDOW_MIN_TABS) {
+ return false
+ }
+ // One pass over the order: opened ids can include tabs that already closed again.
+ const opened = new Set(openedIds)
+ for (let index = 0; index < slotIds.length && opened.size > 0; index++) {
+ if (!opened.delete(slotIds[index]) || findTabStripSlot(strip, slotIds[index])) {
+ continue
+ }
+ const left = unmountedSlotLeft(strip, index)
+ const right = left + TAB_STRIP_WINDOW_SLOT_PX
+ if (left < strip.scrollLeft) {
+ strip.scrollLeft = left
+ } else if (right > strip.scrollLeft + strip.clientWidth) {
+ strip.scrollLeft = right - strip.clientWidth
+ }
+ return true
+ }
+ return false
+}
diff --git a/src/renderer/src/components/tab-group/WorkspaceTabDragLayer.tsx b/src/renderer/src/components/tab-group/WorkspaceTabDragLayer.tsx
index b6a5cfdbcc3..4f989fa3bb1 100644
--- a/src/renderer/src/components/tab-group/WorkspaceTabDragLayer.tsx
+++ b/src/renderer/src/components/tab-group/WorkspaceTabDragLayer.tsx
@@ -28,6 +28,7 @@ export function WorkspaceTabDragLayer({
+ /** The dragged tab's visible id; a windowed strip keeps it mounted so the drag survives scrolling. */
+ activeDragVisibleTabId: string | null
}
const defaultRef: RefObject = { current: false }
const TabDragContext = createContext({
isTabDragActive: false,
- isTabDragActiveRef: defaultRef
+ isTabDragActiveRef: defaultRef,
+ activeDragVisibleTabId: null
})
export function TabDragProvider({
isTabDragActive,
isTabDragActiveRef,
+ activeDragVisibleTabId,
children
}: {
isTabDragActive: boolean
isTabDragActiveRef: RefObject
+ activeDragVisibleTabId: string | null
children: React.ReactNode
}): React.JSX.Element {
const value = useMemo(
- () => ({ isTabDragActive, isTabDragActiveRef }),
- [isTabDragActive, isTabDragActiveRef]
+ () => ({ isTabDragActive, isTabDragActiveRef, activeDragVisibleTabId }),
+ [isTabDragActive, isTabDragActiveRef, activeDragVisibleTabId]
)
return {children}
}
@@ -31,3 +36,7 @@ export function TabDragProvider({
export function useTabDragActive(): boolean {
return useContext(TabDragContext).isTabDragActive
}
+
+export function useActiveDragVisibleTabId(): string | null {
+ return useContext(TabDragContext).activeDragVisibleTabId
+}