Skip to content

The agent that grows with you

feat(desktop): the layout tree moves a tab block as one unit

Brooklyn Nicholsoncc8e97499cab
diff --git a/apps/desktop/src/components/pane-shell/tree/model.ts b/apps/desktop/src/components/pane-shell/tree/model.ts
index 7f61143babf..06810cb4c58 100644
--- a/apps/desktop/src/components/pane-shell/tree/model.ts
+++ b/apps/desktop/src/components/pane-shell/tree/model.ts
@@ -317,6 +317,66 @@ export function movePane(
return shapeSignature(next) === shapeSignature(root) ? root : next
}
+/**
+ * Move a SELECTION of panes together (multi-tab drag), preserving their strip
+ * order. The lead pane lands exactly like a single `movePane` (center joins at
+ * `before`, an edge opens the split); the rest stack in behind it. `activeId`
+ * (the pressed tab) fronts in the landing group. Same no-op guard as
+ * `movePane`: a drop that rebuilds the visible arrangement returns `root`.
+ */
+export function movePanes(
+ root: LayoutNode,
+ paneIds: readonly string[],
+ target: { groupId: string; pos: DropPosition; before?: null | string },
+ activeId: string = paneIds[0] ?? ''
+): LayoutNode {
+ if (paneIds.length <= 1) {
+ return paneIds.length === 1 ? movePane(root, paneIds[0], target) : root
+ }
+
+ let without: LayoutNode | null = root
+
+ for (const id of paneIds) {
+ without = without && removePane(without, id)
+ }
+
+ // The selection was the whole tree, or removal dissolved the target zone
+ // (the selection was its only occupancy) — nowhere left to land.
+ if (!without || !findGroup(without, target.groupId)) {
+ return root
+ }
+
+ // The lead insert decides geometry; the rest stack into the lead's group at
+ // the same slot (each lands before `before`, so the block keeps its order).
+ // Only the lead activates — `insertAtGroup(activate)` would otherwise front
+ // each follower in turn.
+ const lead = paneIds[0]
+ let next: LayoutNode | null = insertAtGroup(without, target.groupId, lead, target.pos, target.before)
+
+ for (let i = 1; next && i < paneIds.length; i++) {
+ const leadGroup = findGroupOfPane(next, lead)
+
+ if (!leadGroup) {
+ return root
+ }
+
+ const before = target.pos === 'center' ? (target.before ?? null) : null
+ next = insertAtGroup(next, leadGroup.id, paneIds[i], 'center', before, false)
+ }
+
+ if (!next) {
+ return root
+ }
+
+ const landed = findGroupOfPane(next, lead)
+
+ if (landed && landed.panes.includes(activeId)) {
+ next = setActivePane(next, landed.id, activeId)
+ }
+
+ return shapeSignature(next) === shapeSignature(root) ? root : next
+}
+
/** Group ids of every leaf under a node, in tree order. */
export function groupLeafIds(node: LayoutNode): string[] {
return node.type === 'group' ? [node.id] : node.children.flatMap(groupLeafIds)
@@ -347,26 +407,32 @@ function findCover(node: LayoutNode, set: Set<string>): LayoutNode | null {
}
/**
- * FancyZones span: merge the highlighted zones into ONE group holding
- * `paneId`, absorbing any panes that lived in those zones as tabs. Only works
- * when the highlighted set forms a rectangular subtree (it always does for a
- * combined zone range on a guillotine tree); returns null otherwise so the
- * caller can fall back to a single-zone drop.
+ * FancyZones span: merge the highlighted zones into ONE group holding the
+ * dragged pane block (one pane, or a multi-tab selection in strip order),
+ * absorbing any panes that lived in those zones as tabs. Only works when the
+ * highlighted set forms a rectangular subtree (it always does for a combined
+ * zone range on a guillotine tree); returns null otherwise so the caller can
+ * fall back to a single-zone drop.
*/
-export function mergeZonesWithPane(root: LayoutNode, groupIds: string[], paneId: string): LayoutNode | null {
+export function mergeZonesWithPane(
+ root: LayoutNode,
+ groupIds: string[],
+ paneId: string | readonly string[]
+): LayoutNode | null {
+ const paneIds = typeof paneId === 'string' ? [paneId] : [...paneId]
const set = new Set(groupIds)
if (set.size <= 1 || !findCover(root, set)) {
return null
}
- // Panes from the merged zones (tree order), minus the dragged one.
+ // Panes from the merged zones (tree order), minus the dragged block.
const panesInSet: string[] = []
const collect = (n: LayoutNode) => {
if (n.type === 'group') {
if (set.has(n.id)) {
- panesInSet.push(...n.panes.filter(p => p !== paneId))
+ panesInSet.push(...n.panes.filter(p => !paneIds.includes(p)))
}
} else {
n.children.forEach(collect)
@@ -375,16 +441,19 @@ export function mergeZonesWithPane(root: LayoutNode, groupIds: string[], paneId:
collect(root)
- // If the dragged pane lives OUTSIDE the merged set, pull it from its origin
+ // Any dragged pane living OUTSIDE the merged set is pulled from its origin
// first (leaving that origin an empty zone). Inside the set it's absorbed.
- const origin = findGroupOfPane(root, paneId)
let working = root
- if (origin && !set.has(origin.id)) {
- working = removePane(root, paneId) ?? root
+ for (const id of paneIds) {
+ const origin = findGroupOfPane(working, id)
+
+ if (origin && !set.has(origin.id)) {
+ working = removePane(working, id) ?? working
+ }
}
- const merged = group([paneId, ...panesInSet])
+ const merged = group([...paneIds, ...panesInSet])
const replace = (n: LayoutNode): LayoutNode => {
if (sameSet(groupLeafIds(n), set)) {
@@ -409,16 +478,23 @@ export function setActivePane(root: LayoutNode, groupId: string, paneId: string)
return mapGroups(root, g => (g.id === groupId && g.panes.includes(paneId) ? { ...g, active: paneId } : g))
}
-/** Reorder a pane within its group's tab stack (browser-tab drag semantics). */
-export function reorderPaneInGroup(root: LayoutNode, groupId: string, paneId: string, toIndex: number): LayoutNode {
+/** Reorder a block of panes within a group as one unit (browser-tab drag
+ * semantics; a single-tab drag is a one-id block): the block lands at
+ * `toIndex` among the remaining tabs, keeping its own order. */
+export function reorderPanesInGroup(
+ root: LayoutNode,
+ groupId: string,
+ paneIds: readonly string[],
+ toIndex: number
+): LayoutNode {
return mapGroups(root, g => {
- if (g.id !== groupId || !g.panes.includes(paneId)) {
+ if (g.id !== groupId || !paneIds.every(p => g.panes.includes(p))) {
return g
}
- const without = g.panes.filter(p => p !== paneId)
+ const without = g.panes.filter(p => !paneIds.includes(p))
const index = Math.max(0, Math.min(without.length, toIndex))
- const panes = [...without.slice(0, index), paneId, ...without.slice(index)]
+ const panes = [...without.slice(0, index), ...paneIds, ...without.slice(index)]
return { ...g, panes }
})
diff --git a/apps/desktop/src/components/pane-shell/tree/multi-tab-drag.test.ts b/apps/desktop/src/components/pane-shell/tree/multi-tab-drag.test.ts
new file mode 100644
index 00000000000..1766e53fc75
--- /dev/null
+++ b/apps/desktop/src/components/pane-shell/tree/multi-tab-drag.test.ts
@@ -0,0 +1,147 @@
+import { describe, expect, it } from 'vitest'
+
+import { findGroup, findGroupOfPane, group, mergeZonesWithPane, movePanes, reorderPanesInGroup, split } from './model'
+import { $tabSelection, clearTabSelection, selectionFor, selectTabRange, toggleTabSelected } from './tab-selection'
+
+describe('movePanes (multi-tab drag)', () => {
+ it('stacks the whole block into the target group at the divider slot, in strip order', () => {
+ const tree = split('row', [
+ group(['a', 'b', 'c'], { active: 'a', id: 'left' }),
+ group(['x', 'y'], { active: 'x', id: 'right' })
+ ])
+
+ const next = movePanes(tree, ['a', 'c'], { before: 'y', groupId: 'right', pos: 'center' }, 'c')
+ const right = findGroup(next, 'right')
+
+ expect(right).toMatchObject({ panes: ['x', 'a', 'c', 'y'], active: 'c' })
+ expect(findGroup(next, 'left')).toMatchObject({ panes: ['b'] })
+ })
+
+ it('an edge drop opens ONE split holding the block as tabs, pressed tab fronted', () => {
+ const tree = split('row', [
+ group(['a', 'b', 'c'], { active: 'a', id: 'left' }),
+ group(['x'], { active: 'x', id: 'right' })
+ ])
+
+ const next = movePanes(tree, ['b', 'c'], { groupId: 'right', pos: 'bottom' }, 'b')
+ const landed = findGroupOfPane(next, 'b')
+
+ expect(landed).toMatchObject({ panes: ['b', 'c'], active: 'b' })
+ // One new zone, not one per pane: b and c share a group.
+ expect(findGroupOfPane(next, 'c')).toBe(landed)
+ expect(findGroup(next, 'left')).toMatchObject({ panes: ['a'] })
+ })
+
+ it('dragging a whole zone into a sibling dissolves the source zone', () => {
+ const tree = split('row', [
+ group(['a', 'b'], { active: 'a', id: 'left' }),
+ group(['x'], { active: 'x', id: 'right' })
+ ])
+
+ const next = movePanes(tree, ['a', 'b'], { groupId: 'right', pos: 'center' }, 'a')
+
+ expect(next).toMatchObject({ type: 'group', panes: ['x', 'a', 'b'], active: 'a' })
+ })
+
+ it('is a no-op when removal dissolves the target zone itself', () => {
+ const tree = split('row', [
+ group(['a', 'b'], { active: 'a', id: 'left' }),
+ group(['x'], { active: 'x', id: 'right' })
+ ])
+
+ // Dropping right's only pane (as part of a block) "into right" — the
+ // target vanishes with the removal, so nothing moves.
+ expect(movePanes(tree, ['x', 'a'], { groupId: 'right', pos: 'center' }, 'x')).toBe(tree)
+ })
+
+ it('falls back to single-pane semantics for a one-id block', () => {
+ const tree = split('row', [
+ group(['a', 'b'], { active: 'a', id: 'left' }),
+ group(['x'], { active: 'x', id: 'right' })
+ ])
+
+ const next = movePanes(tree, ['b'], { groupId: 'right', pos: 'center' })
+
+ expect(findGroup(next, 'right')).toMatchObject({ panes: ['x', 'b'], active: 'b' })
+ })
+})
+
+describe('reorderPanesInGroup (block reorder)', () => {
+ it('moves a selection as one unit, preserving its internal order', () => {
+ const tree = group(['a', 'b', 'c', 'd'], { active: 'a', id: 'g' })
+
+ // [a, c] to the end: index 2 among the remaining [b, d].
+ expect(reorderPanesInGroup(tree, 'g', ['a', 'c'], 2)).toMatchObject({ panes: ['b', 'd', 'a', 'c'] })
+ })
+
+ it('leaves the group alone when any id is missing (stale selection)', () => {
+ const tree = group(['a', 'b'], { active: 'a', id: 'g' })
+
+ expect(reorderPanesInGroup(tree, 'g', ['a', 'ghost'], 0)).toBe(tree)
+ })
+})
+
+describe('mergeZonesWithPane with a multi-tab block', () => {
+ it('merges the span into one group led by the block in strip order', () => {
+ const tree = split('row', [
+ group(['a', 'b'], { active: 'a', id: 'left' }),
+ split('column', [group(['x'], { active: 'x', id: 'mid' }), group(['y'], { active: 'y', id: 'right' })])
+ ])
+
+ const next = mergeZonesWithPane(tree, ['mid', 'right'], ['a', 'b'])
+
+ expect(next).toMatchObject({ type: 'group', panes: ['a', 'b', 'x', 'y'] })
+ })
+
+ it('returns null for a non-rectangular span (caller falls back to a single-zone drop)', () => {
+ const tree = split('row', [
+ group(['a', 'b'], { active: 'a', id: 'left' }),
+ group(['x'], { active: 'x', id: 'mid' }),
+ group(['y'], { active: 'y', id: 'right' })
+ ])
+
+ expect(mergeZonesWithPane(tree, ['mid', 'right'], ['a', 'b'])).toBeNull()
+ })
+})
+
+describe('tab selection (Chrome grammar)', () => {
+ it('⌥-click seeds with the active tab, toggles, and dissolves at ≤1', () => {
+ clearTabSelection()
+ toggleTabSelected('g', 'c', 'a')
+
+ expect([...$tabSelection.get()!.ids].sort()).toEqual(['a', 'c'])
+
+ toggleTabSelected('g', 'c', 'a')
+
+ expect($tabSelection.get()).toBeNull()
+ })
+
+ it('shift-click ranges from the anchor and re-ranges on the next shift-click', () => {
+ clearTabSelection()
+
+ const order = ['a', 'b', 'c', 'd']
+ selectTabRange('g', order, 'c', 'a')
+
+ expect(selectionFor('g', order, 'b')).toEqual(['a', 'b', 'c'])
+
+ // Anchor holds at a (Chrome): re-ranging to d replaces, not extends.
+ selectTabRange('g', order, 'd', 'a')
+
+ expect(selectionFor('g', order, 'd')).toEqual(['a', 'b', 'c', 'd'])
+ })
+
+ it('selectionFor answers null for an unselected pressed tab and drops stale ids', () => {
+ clearTabSelection()
+ toggleTabSelected('g', 'b', 'a')
+ toggleTabSelected('g', 'c', 'a')
+
+ // Pressed tab outside the selection = single-tab drag.
+ expect(selectionFor('g', ['a', 'b', 'c', 'd'], 'd')).toBeNull()
+ // 'a' closed since: it silently falls out, strip order preserved.
+ expect(selectionFor('g', ['b', 'c', 'd'], 'b')).toEqual(['b', 'c'])
+ // Another zone never sees it.
+ expect(selectionFor('other', ['b', 'c'], 'b')).toBeNull()
+
+ clearTabSelection()
+ })
+})
diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/drag-session.ts b/apps/desktop/src/components/pane-shell/tree/renderer/drag-session.ts
index d37853f8e16..6e479c67952 100644
--- a/apps/desktop/src/components/pane-shell/tree/renderer/drag-session.ts
+++ b/apps/desktop/src/components/pane-shell/tree/renderer/drag-session.ts
@@ -35,7 +35,8 @@ import { ESCAPE_PRIORITY, pushEscapeLayer } from '@/lib/escape-layers'
import { reorderCommitHaptic, reorderStepHaptic } from '@/lib/reorder'
import type { DropPosition } from '../model'
-import { $dropHint, $treeDragging, type DropHint, mergeTreeZones, moveTreePane, reorderTreePane } from '../store'
+import { $dropHint, $treeDragging, type DropHint, mergeTreeZones, moveTreePanes, reorderTreePanes } from '../store'
+import { clearTabSelection } from '../tab-selection'
import { type EngineZone, HighlightedZones, primaryZone, type ZoneRect } from '../zones-engine'
const DRAG_THRESHOLD_PX = 4
@@ -96,10 +97,18 @@ const stripSlots = (strip: HTMLElement): StripSlot[] =>
})
/** Insertion slot from the pointer x against the OTHER tabs' midpoints:
- * stack BEFORE the returned pane id (`null` = append). */
-export function slotBefore(slots: StripSlot[], x: number, excludePaneId = ''): { before: null | string } {
+ * stack BEFORE the returned pane id (`null` = append). `exclude` is the
+ * dragged tab — or the whole selection on a multi-tab drag, so the block
+ * can't target a slot inside itself. */
+export function slotBefore(
+ slots: StripSlot[],
+ x: number,
+ exclude: readonly string[] | string = ''
+): { before: null | string } {
+ const excluded = typeof exclude === 'string' ? [exclude] : exclude
+
for (const slot of slots) {
- if (slot.id === excludePaneId) {
+ if (excluded.includes(slot.id)) {
continue
}
@@ -422,7 +431,11 @@ export function startPaneDrag(
onTap?: () => void,
reorder?: ReorderContext,
double?: DoubleTapContext,
- ghostLabel?: string
+ ghostLabel?: string,
+ /** Multi-tab selection riding this drag (strip order, includes `paneId`).
+ * The whole block moves/reorders together; `paneId` stays the pressed tab
+ * (it fronts at the destination). */
+ selection?: readonly string[]
) {
if (e.button !== 0) {
return
@@ -431,17 +444,28 @@ export function startPaneDrag(
e.preventDefault()
e.stopPropagation()
+ // The moving block: the selection when the pressed tab rides one, else just
+ // the pressed tab. Order is strip order (selectionFor guarantees it).
+ const moving: readonly string[] = selection && selection.length > 1 ? selection : [paneId]
+
const highlighted = new HighlightedZones()
let zones: EngineZone[] = []
let strips: StripSnapshot[] = []
let mode: 'reorder' | 'zone' | null = null
- let dimmed: HTMLElement | null = null
+ let dimmed: HTMLElement[] = []
const markSource = () => {
- // The dragged tab dims for the drag's life — the divider says where it
- // GOES, the dim says what MOVES. No live shuffle (placement-on-release).
- dimmed ??= reorder?.strip.querySelector<HTMLElement>(`[data-tree-tab="${CSS.escape(paneId)}"]`) ?? null
- dimmed?.style.setProperty('opacity', '0.45')
+ // Every dragged tab dims for the drag's life — the divider says where they
+ // GO, the dim says what MOVES. No live shuffle (placement-on-release).
+ if (dimmed.length === 0 && reorder) {
+ dimmed = moving
+ .map(id => reorder.strip.querySelector<HTMLElement>(`[data-tree-tab="${CSS.escape(id)}"]`))
+ .filter((el): el is HTMLElement => el !== null)
+ }
+
+ for (const el of dimmed) {
+ el.style.setProperty('opacity', '0.45')
+ }
}
const enterZoneMode = () => {
@@ -494,7 +518,7 @@ export function startPaneDrag(
groupId: reorder!.groupId,
groupIds: [reorder!.groupId],
pos: 'center',
- stack: slotBefore(reorderStrip().slots, x, paneId)
+ stack: slotBefore(reorderStrip().slots, x, moving)
}
}
@@ -525,7 +549,7 @@ export function startPaneDrag(
const strip =
groupIds.length === 1 && groupId ? strips.find(s => s.groupId === groupId && rectContains(s.rect, x, y)) : null
- const stack = strip ? slotBefore(strip.slots, x, paneId) : undefined
+ const stack = strip ? slotBefore(strip.slots, x, moving) : undefined
const pos: DropPosition = stack
? 'center'
@@ -537,17 +561,26 @@ export function startPaneDrag(
},
onCommit(hint) {
+ // A multi-tab selection is spent by a LANDED drop (reorder or zone) —
+ // a deny-area release keeps it, so a missed drop can just be retried.
+ const spendSelection = () => {
+ if (moving.length > 1) {
+ clearTabSelection()
+ }
+ }
+
if (mode === 'reorder' && reorder && hint?.stack !== undefined) {
- // Slot -> index among the OTHER tabs (reorderPaneInGroup inserts there).
+ // Slot -> index among the OTHER tabs (the block re-inserts there).
const others = [...reorder.strip.querySelectorAll<HTMLElement>('[data-tree-tab]')]
.map(el => el.dataset.treeTab)
- .filter((id): id is string => Boolean(id) && id !== paneId)
+ .filter((id): id is string => Boolean(id) && !moving.includes(id!))
const toIndex = hint.stack.before ? others.indexOf(hint.stack.before) : others.length
if (toIndex >= 0) {
- reorderTreePane(reorder.groupId, paneId, toIndex)
+ reorderTreePanes(reorder.groupId, moving, toIndex)
reorderCommitHaptic()
+ spendSelection()
}
}
@@ -559,18 +592,28 @@ export function startPaneDrag(
const targets = hint?.groupIds ?? []
if (targets.length > 1) {
- // Shift-span: merge the highlighted zones, dropping the pane across them.
- mergeTreeZones([...targets], paneId, hint?.groupId ?? null)
+ // Shift-span: merge the highlighted zones, dropping the block across them.
+ mergeTreeZones([...targets], moving, hint?.groupId ?? null)
+ spendSelection()
} else if (hint?.groupId) {
// strip = stack at the divider slot; center = join the stack;
- // an edge = split the zone and land there.
- moveTreePane(paneId, { groupId: hint.groupId, pos: hint.pos ?? 'center', before: hint.stack?.before })
+ // an edge = split the zone and land there. The whole selection
+ // rides — the pressed tab fronts at the destination.
+ moveTreePanes(
+ moving,
+ { groupId: hint.groupId, pos: hint.pos ?? 'center', before: hint.stack?.before },
+ paneId
+ )
+ spendSelection()
}
}
},
onEnd() {
- dimmed?.style.removeProperty('opacity')
+ for (const el of dimmed) {
+ el.style.removeProperty('opacity')
+ }
+
highlighted.reset()
}
})
diff --git a/apps/desktop/src/components/pane-shell/tree/store.ts b/apps/desktop/src/components/pane-shell/tree/store.ts
index 8399eb36ef5..5601c666f47 100644
--- a/apps/desktop/src/components/pane-shell/tree/store.ts
+++ b/apps/desktop/src/components/pane-shell/tree/store.ts
@@ -28,9 +28,10 @@ import {
mergeZonesWithPane as mergeZonesWithPaneOp,
mirrorTreeHorizontal,
movePane as movePaneOp,
+ movePanes as movePanesOp,
normalize,
removePane,
- reorderPaneInGroup as reorderPaneInGroupOp,
+ reorderPanesInGroup as reorderPanesInGroupOp,
setActivePane as setActivePaneOp,
setGroupHeaderHidden as setGroupHeaderHiddenOp,
setGroupMinimized,
@@ -1243,26 +1244,62 @@ export function applyTree(tree: LayoutNode, presetId: string) {
}
}
+/**
+ * Move a multi-tab SELECTION in one commit (drag any selected tab): the lead
+ * pane takes the drop geometry, the rest stack in behind it in strip order,
+ * and `activeId` (the pressed tab) fronts in the landing group.
+ */
+export function moveTreePanes(
+ paneIds: readonly string[],
+ target: { groupId: string; pos: DropPosition; before?: null | string },
+ activeId?: string
+) {
+ const tree = $layoutTree.get()
+
+ if (!tree) {
+ return
+ }
+
+ const next = movePanesOp(tree, paneIds, target, activeId)
+
+ if (next !== tree) {
+ commit(next)
+ markActivePreset('custom')
+
+ for (const paneId of paneIds) {
+ markPaneUserPlaced(paneId)
+ }
+ }
+}
+
/**
* Shift-drag span: merge the highlighted zones into one holding `paneId`. Falls
* back to a single-zone move at `fallbackGroupId` when the set can't merge
* (non-rectangular selection).
*/
-export function mergeTreeZones(groupIds: string[], paneId: string, fallbackGroupId: string | null) {
+export function mergeTreeZones(
+ groupIds: string[],
+ paneId: string | readonly string[],
+ fallbackGroupId: null | string
+) {
const tree = $layoutTree.get()
if (!tree) {
return
}
+ const paneIds = typeof paneId === 'string' ? [paneId] : paneId
const merged = mergeZonesWithPaneOp(tree, groupIds, paneId)
if (merged) {
commit(merged)
markActivePreset('custom')
- markPaneUserPlaced(paneId)
+
+ for (const id of paneIds) {
+ markPaneUserPlaced(id)
+ }
} else if (fallbackGroupId) {
- moveTreePane(paneId, { groupId: fallbackGroupId, pos: 'center' })
+ moveTreePanes(paneIds, { groupId: fallbackGroupId, pos: 'center' })
}
}
@@ -1274,11 +1311,13 @@ export function activateTreePane(groupId: string, paneId: string) {
}
}
-export function reorderTreePane(groupId: string, paneId: string, toIndex: number) {
+/** Reorder a tab block (multi-tab selection, or a single tab) within its
+ * group's strip — the block keeps its own order. */
+export function reorderTreePanes(groupId: string, paneIds: readonly string[], toIndex: number) {
const tree = $layoutTree.get()
if (tree) {
- commit(reorderPaneInGroupOp(tree, groupId, paneId, toIndex))
+ commit(reorderPanesInGroupOp(tree, groupId, paneIds, toIndex))
markActivePreset('custom')
}
}
diff --git a/apps/desktop/src/components/pane-shell/tree/tab-selection.ts b/apps/desktop/src/components/pane-shell/tree/tab-selection.ts
new file mode 100644
index 00000000000..9653468ddab
--- /dev/null
+++ b/apps/desktop/src/components/pane-shell/tree/tab-selection.ts
@@ -0,0 +1,99 @@
+/**
+ * Multi-tab selection on a zone's tab strip — Chrome's tab-selection grammar:
+ *
+ * - ⌥-click (Ctrl-click off-Mac) → toggle the tab in/out of the selection;
+ * - Shift-click → select the range from the anchor
+ * (the last explicitly clicked tab, else
+ * the active one) to the clicked tab;
+ * - plain click → collapse back to a single tab.
+ *
+ * ⌘-click stays CLOSE (middle-click.ts) and ⌃-click stays the macOS context
+ * menu, so the toggle chord is ⌥ on Mac / Ctrl elsewhere. One selection at a
+ * time, scoped to one zone — dragging any selected tab carries the whole set
+ * (drag-session resolves it), and ids are validated against the strip's
+ * current tabs at use time, so closed/moved panes fall out on their own.
+ */
+
+import { atom } from 'nanostores'
+
+export interface TabSelection {
+ groupId: string
+ ids: ReadonlySet<string>
+ /** Range anchor: the last explicitly clicked tab (Chrome semantics). */
+ anchor: string
+}
+
+export const $tabSelection = atom<null | TabSelection>(null)
+
+const isMac = typeof navigator !== 'undefined' && /Mac|iP(hone|ad|od)/.test(navigator.platform)
+
+/** The toggle-select chord: ⌥-click on Mac (⌘ closes, ⌃ is the context menu),
+ * Ctrl-click elsewhere — ⌥ is accepted everywhere for one muscle memory. */
+export const isToggleSelectClick = (event: { altKey: boolean; button: number; ctrlKey: boolean; metaKey: boolean }) =>
+ event.button === 0 && !event.metaKey && (event.altKey || (!isMac && event.ctrlKey))
+
+export function clearTabSelection() {
+ if ($tabSelection.get()) {
+ $tabSelection.set(null)
+ }
+}
+
+/** ⌥/Ctrl-click: toggle `paneId`. A fresh selection seeds with the active tab
+ * (it is implicitly selected, as in Chrome); collapsing to ≤1 dissolves the
+ * selection entirely — a single "selected" tab is just a tab. */
+export function toggleTabSelected(groupId: string, paneId: string, activeId: string) {
+ const current = $tabSelection.get()
+ const ids = new Set(current?.groupId === groupId ? current.ids : [activeId])
+
+ if (ids.has(paneId)) {
+ ids.delete(paneId)
+ } else {
+ ids.add(paneId)
+ }
+
+ if (ids.size <= 1) {
+ $tabSelection.set(null)
+
+ return
+ }
+
+ $tabSelection.set({ anchor: paneId, groupId, ids })
+}
+
+/** Shift-click: select the contiguous range anchor→`paneId` in strip order,
+ * replacing the previous range (the anchor holds, Chrome-style). */
+export function selectTabRange(groupId: string, orderedPanes: readonly string[], paneId: string, activeId: string) {
+ const current = $tabSelection.get()
+ const anchor = current?.groupId === groupId && orderedPanes.includes(current.anchor) ? current.anchor : activeId
+ const a = orderedPanes.indexOf(anchor)
+ const b = orderedPanes.indexOf(paneId)
+
+ if (a === -1 || b === -1) {
+ return
+ }
+
+ const ids = new Set(orderedPanes.slice(Math.min(a, b), Math.max(a, b) + 1))
+
+ if (ids.size <= 1) {
+ $tabSelection.set(null)
+
+ return
+ }
+
+ $tabSelection.set({ anchor, groupId, ids })
+}
+
+/** The selection as an ordered slice of `orderedPanes` — but only when the
+ * pressed tab rides it (dragging an unselected tab is a single-tab drag).
+ * Stale ids (closed panes) drop out here. */
+export function selectionFor(groupId: string, orderedPanes: readonly string[], paneId: string): null | string[] {
+ const current = $tabSelection.get()
+
+ if (current?.groupId !== groupId || !current.ids.has(paneId)) {
+ return null
+ }
+
+ const ids = orderedPanes.filter(id => current.ids.has(id))
+
+ return ids.length > 1 ? ids : null
+}