mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
perf(tab-bar): render only the visible part of a long tab strip (#43703)
* perf(tab-bar): render only the visible part of a long tab strip A strip with thousands of tabs mounted a full tab subtree for every one, about 0.14 MB each. Past 100 tabs the strip now mounts the viewport plus a viewport on each side, the active, dragged and focused tabs, and fixed-width spacers for the rest, so its cost no longer grows with the tab count. * fix(tab-bar): clamp the strip window to the current tab count and reveal unmounted new tabs The range follows scroll after commit, so the render that closed tabs could read past the end of the list. A tab opened beyond the mounted range is now scrolled into view by its index, and focus tracking runs only in windowed strips. * perf(tab-bar): find kept tabs by index instead of scanning the strip on every window move Also keep a tab focused before the strip started windowing mounted. * perf(tab-bar): find unmounted opened tabs in one pass over the strip order Deferred reveal ids can include tabs that already closed; looking each one up separately scanned the whole strip per id. * fix(tab-bar): read the focused tab with the first windowed range A rename in progress when the strip reached 100 tabs could unmount on the first windowed render, before focus tracking started. * fix(tab-bar): reveal unmounted tabs from their spacer and compare tab ids once per list Revealing by index assumed every earlier tab was 144px, which missed past a wider mounted tab such as one being renamed. A windowed strip re-renders on scroll, so the tab id comparison now runs once per rebuilt list, not per render. * perf(tab-bar): resolve the active tab's unified id once per tab change, not per strip render A windowed strip re-renders as it scrolls, and the agent picker's excluded-tab lookup searched every tab on each render. * perf(tab-bar): memoize the strip layout key, which spans every tab * perf(tab-bar): keep the strip's window state in its own component, so scrolling re-renders only the strip * fix(tab-bar): update the strip window before paint when the tab bar scrolls the strip * fix(tab-bar): notify the strip window after every tab bar commit * perf(tab-bar): notify the strip window only when a tab bar commit scrolled the strip * fix(tab-bar): notify the strip window when the mount commit scrolled the strip * fix(tab-bar): compare the strip offset with its value before the commit's own scrolls * fix(tab-bar): keep strip listener refs compiler-safe and notify after the pointer-leave reveal
This commit is contained in:
@@ -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 })
|
||||
|
||||
@@ -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(
|
||||
<div
|
||||
key={`tab-strip-gap-${segment.start}`}
|
||||
aria-hidden
|
||||
data-tab-strip-gap=""
|
||||
data-tab-strip-gap-start={segment.start}
|
||||
data-tab-strip-gap-end={segment.end}
|
||||
className="flex-none"
|
||||
style={{ width: (segment.end - segment.start) * TAB_STRIP_WINDOW_SLOT_PX }}
|
||||
/>
|
||||
)
|
||||
continue
|
||||
}
|
||||
for (let index = segment.start; index < segment.end; index++) {
|
||||
rows.push(renderRow(items[index], index))
|
||||
}
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ export type TabBarItemProjection = {
|
||||
sortableIds: string[]
|
||||
dropIndicatorByVisibleId: Map<string, DropIndicator>
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<HTMLDivElement | null>
|
||||
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 (
|
||||
<SortableContext items={mountedSortableIds}>
|
||||
{renderStrip(tabStripWindow.segments)}
|
||||
</SortableContext>
|
||||
)
|
||||
}
|
||||
@@ -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(
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{/* Keep drag siblings anchored; only the insertion bar moves. */}
|
||||
<SortableContext items={sortableIds}>
|
||||
{/* Why: no-drag lets tab interactions work inside the titlebar's drag region (outer container stays window-draggable). */}
|
||||
<div
|
||||
data-single-tab={singleTab ? '' : undefined}
|
||||
// Why: tabs are the only drag source, so a narrow pane clips the "+" before the last tab sliver.
|
||||
className={`group/tab-strip relative flex min-h-0 w-max max-w-full shrink ${
|
||||
hasTabs ? 'min-w-10' : 'min-w-0'
|
||||
}`}
|
||||
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
|
||||
>
|
||||
<WindowedTabStrip
|
||||
stripRef={tabStripRef}
|
||||
subscribeToStripResize={subscribeToStripResize}
|
||||
sortableIds={sortableIds}
|
||||
activeVisibleTabId={activeVisibleTabId}
|
||||
renderStrip={(segments) => (
|
||||
// Why no-drag: tab interactions must work inside the titlebar's drag region (outer container stays window-draggable).
|
||||
<div
|
||||
ref={tabStripRef}
|
||||
// Tab drags clip drop targets to this box (tab-drag-collision.ts).
|
||||
data-tab-strip-scroller=""
|
||||
data-active-tab-docked={activeTabDockSide ?? undefined}
|
||||
// Why: only `border-r` here — a strip-level `border-l` would render a heavier L-corner than the first tab's own `border-l`.
|
||||
className={[
|
||||
'terminal-tab-strip flex h-full min-w-0 max-w-full flex-1 items-stretch overflow-x-auto overflow-y-hidden',
|
||||
'border-r border-border/70',
|
||||
getTabStripScrollMaskClassName(tabStripOverflowState, activeTabDockSide)
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
data-single-tab={singleTab ? '' : undefined}
|
||||
// Why: tabs are the only drag source, so a narrow pane clips the "+" before the last tab sliver.
|
||||
className={`group/tab-strip relative flex min-h-0 w-max max-w-full shrink ${
|
||||
hasTabs ? 'min-w-10' : 'min-w-0'
|
||||
}`}
|
||||
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
|
||||
>
|
||||
<TabStripTooltipProvider>
|
||||
{renderedItems}
|
||||
{clientHostedBrowserRows.length > 0 ? (
|
||||
<ClientHostedBrowserTabRows
|
||||
rows={clientHostedBrowserRows}
|
||||
worktreeId={worktreeId}
|
||||
groupId={resolvedGroupId}
|
||||
groupActiveTabId={props.groupActiveTabId ?? null}
|
||||
includeTopTabBorder={includeTopTabBorder}
|
||||
/>
|
||||
) : null}
|
||||
</TabStripTooltipProvider>
|
||||
<div
|
||||
ref={tabStripRef}
|
||||
// Tab drags clip drop targets to this box (tab-drag-collision.ts).
|
||||
data-tab-strip-scroller=""
|
||||
data-active-tab-docked={activeTabDockSide ?? undefined}
|
||||
// Why: only `border-r` here — a strip-level `border-l` would render a heavier L-corner than the first tab's own `border-l`.
|
||||
className={[
|
||||
'terminal-tab-strip flex h-full min-w-0 max-w-full flex-1 items-stretch overflow-x-auto overflow-y-hidden',
|
||||
'border-r border-border/70',
|
||||
getTabStripScrollMaskClassName(tabStripOverflowState, activeTabDockSide)
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
>
|
||||
<TabStripTooltipProvider>
|
||||
{renderItems(segments)}
|
||||
{clientHostedBrowserRows.length > 0 ? (
|
||||
<ClientHostedBrowserTabRows
|
||||
rows={clientHostedBrowserRows}
|
||||
worktreeId={worktreeId}
|
||||
groupId={resolvedGroupId}
|
||||
groupActiveTabId={props.groupActiveTabId ?? null}
|
||||
includeTopTabBorder={includeTopTabBorder}
|
||||
/>
|
||||
) : null}
|
||||
</TabStripTooltipProvider>
|
||||
</div>
|
||||
<TabStripScrollIndicator
|
||||
hasOverflow={tabStripOverflowState.hasOverflow}
|
||||
scrollContainerRef={tabStripRef}
|
||||
subscribeToStripResize={subscribeToStripResize}
|
||||
disabled={tabStripDragScroll.isTabDragActive}
|
||||
/>
|
||||
</div>
|
||||
<TabStripScrollIndicator
|
||||
hasOverflow={tabStripOverflowState.hasOverflow}
|
||||
scrollContainerRef={tabStripRef}
|
||||
subscribeToStripResize={subscribeToStripResize}
|
||||
disabled={tabStripDragScroll.isTabDragActive}
|
||||
/>
|
||||
</div>
|
||||
</SortableContext>
|
||||
)}
|
||||
/>
|
||||
{tabStripOverflowState.hasOverflow ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
@@ -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}
|
||||
|
||||
@@ -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<HTMLDivElement | null>
|
||||
@@ -69,11 +79,15 @@ export function useTabStripOverflowNavigation({
|
||||
} {
|
||||
const isTabDragActive = useTabDragActive()
|
||||
const tabStripRef = useRef<HTMLDivElement>(null)
|
||||
// Why first: this hook's effects below are the ones that scroll the strip.
|
||||
const commitStartScrollRef = useTabStripCommitStartScroll(tabStripRef)
|
||||
const stripResizeListenersRef = useRef<Set<() => void>>(new Set())
|
||||
const subscribeToStripResize = useTabStripListenerSubscribe(stripResizeListenersRef)
|
||||
const prevStripRef = useRef<{ worktreeId: string; tabIds: ReadonlySet<string> } | null>(null)
|
||||
const stickToEndRef = useRef(false)
|
||||
const tabClosedThisCommitRef = useRef(false)
|
||||
const activeTabIdRef = useRef<string | null>(null)
|
||||
const slotIdsRef = useRef<readonly string[]>(slotIds)
|
||||
const hoverDeferredRevealIdsRef = useRef<Set<string>>(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<string> = 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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 }
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -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<HTMLElement>('[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<HTMLElement | null>,
|
||||
count: number,
|
||||
subscribeToStripResize: (listener: () => void) => () => void
|
||||
): TabStripWindowState {
|
||||
const [state, setState] = useState<TabStripWindowState>(() => {
|
||||
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<Set<() => 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<HTMLElement | null>
|
||||
): RefObject<number | null> {
|
||||
const startRef = useRef<number | null>(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<Set<() => 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<HTMLElement | null>,
|
||||
listenersRef: RefObject<Set<() => void>>,
|
||||
startRef: RefObject<number | null>
|
||||
): 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<HTMLElement>(':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<string>
|
||||
): 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
|
||||
}
|
||||
@@ -28,6 +28,7 @@ export function WorkspaceTabDragLayer({
|
||||
<TabDragProvider
|
||||
isTabDragActive={dragSplit.activeDrag !== null}
|
||||
isTabDragActiveRef={dragSplit.isTabDragActiveRef}
|
||||
activeDragVisibleTabId={dragSplit.activeDrag?.visibleTabId ?? null}
|
||||
>
|
||||
<DndContext
|
||||
sensors={dragSplit.sensors}
|
||||
|
||||
@@ -3,27 +3,32 @@ import { createContext, useContext, useMemo, type RefObject } from 'react'
|
||||
type TabDragContextValue = {
|
||||
isTabDragActive: boolean
|
||||
isTabDragActiveRef: RefObject<boolean>
|
||||
/** The dragged tab's visible id; a windowed strip keeps it mounted so the drag survives scrolling. */
|
||||
activeDragVisibleTabId: string | null
|
||||
}
|
||||
|
||||
const defaultRef: RefObject<boolean> = { current: false }
|
||||
|
||||
const TabDragContext = createContext<TabDragContextValue>({
|
||||
isTabDragActive: false,
|
||||
isTabDragActiveRef: defaultRef
|
||||
isTabDragActiveRef: defaultRef,
|
||||
activeDragVisibleTabId: null
|
||||
})
|
||||
|
||||
export function TabDragProvider({
|
||||
isTabDragActive,
|
||||
isTabDragActiveRef,
|
||||
activeDragVisibleTabId,
|
||||
children
|
||||
}: {
|
||||
isTabDragActive: boolean
|
||||
isTabDragActiveRef: RefObject<boolean>
|
||||
activeDragVisibleTabId: string | null
|
||||
children: React.ReactNode
|
||||
}): React.JSX.Element {
|
||||
const value = useMemo(
|
||||
() => ({ isTabDragActive, isTabDragActiveRef }),
|
||||
[isTabDragActive, isTabDragActiveRef]
|
||||
() => ({ isTabDragActive, isTabDragActiveRef, activeDragVisibleTabId }),
|
||||
[isTabDragActive, isTabDragActiveRef, activeDragVisibleTabId]
|
||||
)
|
||||
return <TabDragContext.Provider value={value}>{children}</TabDragContext.Provider>
|
||||
}
|
||||
@@ -31,3 +36,7 @@ export function TabDragProvider({
|
||||
export function useTabDragActive(): boolean {
|
||||
return useContext(TabDragContext).isTabDragActive
|
||||
}
|
||||
|
||||
export function useActiveDragVisibleTabId(): string | null {
|
||||
return useContext(TabDragContext).activeDragVisibleTabId
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user