mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-22 08:03:40 +00:00
* Add terminals to workspace + New Workspace from QuickSwitcher
Two entry points share a single multi-select picker that lets the
user add Local Terminal + any combination of hosts into a workspace:
1. Focus-mode sidebar "+" button appends the selected targets to the
active workspace as new panes.
2. QuickSwitcher "New Workspace" button (small inline action next to
the Jump To hint) spins up a brand-new workspace tab populated
with the selected targets.
## Changes
### domain/workspace.ts
- pruneWorkspaceNode now rebalances surviving siblings to EQUAL
sizes after removal, instead of re-normalising the prior skew.
Matches the "auto-redistribute on close" expectation.
- New appendPaneToWorkspaceRoot(root, sessionId, direction='vertical'):
if root already splits in the requested direction, pushes the new
pane onto its children and resets sizes to equal; otherwise wraps
root + new pane in a new 0.5/0.5 split. Flattens long chains of
appends instead of producing degenerate nested trees.
### application/state/useSessionState.ts
- appendHostToWorkspace(workspaceId, host, direction?) — atomic
"build a session for this host and append it to the root", keeps
activeTab on the workspace and focuses the new pane.
- appendLocalTerminalToWorkspace(workspaceId, options?, direction?)
— mirror of the above for local shells.
- createWorkspaceFromTargets(targets, name?) — accepts a mixed list
of {kind:'local',...} / {kind:'host',host} and creates a new
workspace with one pane per target. Defaults viewMode to 'focus'
so the QuickSwitcher flow lands in the sidebar layout.
- All three exported from the hook.
### components/workspace/AddToWorkspaceDialog.tsx (new)
QuickSwitcher-styled multi-select picker:
- Fixed top-center overlay, same chrome as QuickSwitcher (border,
shadow, rounded-xl, borderless search input, bg-primary/15 cursor).
- Two sections: Local Shells (currently just Local Terminal) and
Hosts. Hover follows keyboard cursor.
- Toggle rows with click or Space / Enter; ⌘/Ctrl+Enter submits;
Esc closes. Right-side Check marks visible items.
- Thin footer bar with Cancel + "Add N" button.
### App.tsx
- Root-mounted single instance of AddToWorkspaceDialog with a
discriminated-union state:
{ mode: 'append'; workspaceId } | { mode: 'create' } | null.
- onAdd dispatches based on mode — append loops through the picker
targets calling the two append helpers; create calls
createWorkspaceFromTargets once.
- TerminalLayer's focus "+" now sends an onRequestAddToWorkspace
(workspaceId) up to App instead of owning its own dialog.
- QuickSwitcher's onCreateWorkspace callback repurposed to open the
dialog in create mode (replaces the older CreateWorkspaceDialog
route for this specific flow).
### components/TerminalLayer.tsx
- Dropped the inline AddToWorkspaceDialog + addHostPanelOpen state;
replaced the two append callbacks with a single
onRequestAddToWorkspace prop wired to the "+" button.
- Focus-sidebar header: replaced the "Terminals · N" counter with an
immersive borderless search input (bg-transparent, shadow-none,
termFg color) for filtering the terminal list; "+" and Columns2
buttons moved to the right.
- Session list filtered client-side by the search term across
hostLabel / hostname / username.
### components/QuickSwitcher.tsx
- Re-introduced onCreateWorkspace prop (was removed as unused).
- "New Workspace" inline button (Plus icon + label) sits on the
right of the Jump To hint row: border, rounded, hover bg. Click
fires onCreateWorkspace then closes QS.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Add configurable New Workspace shortcut
Mirrors QuickSwitcher's "+ New Workspace" button via a keyboard
binding so the dialog can open in one keystroke without passing
through QS.
- domain/models.ts: new DEFAULT_KEY_BINDINGS entry id=new-workspace,
action=newWorkspace, default ⌘+Shift+J (Mac) / Ctrl+Shift+J (PC).
Audited the defaults — only quick-switch uses J (⌘+J), so the
shifted combo is free. The binding sits in the 'app' category so
it shows up in Settings → Shortcuts and can be rebound by the user.
- application/state/useGlobalHotkeys.ts: wire newWorkspace into the
HotkeyActions interface, getAppLevelActions() allowlist, and the
global keydown switch so the scheme-driven handler dispatches it.
- App.tsx: handle case 'newWorkspace' inside executeHotkeyAction by
calling setAddToWorkspaceDialog({ mode: 'create' }) — same entry
as QuickSwitcher's button, just without having to open QS first.
- application/i18n/locales/zh-CN.ts: add '新建工作区' translation for
settings.shortcuts.binding.new-workspace. English falls back to
the KeyBinding.label field ("New Workspace"), so no en.ts change.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Address codex P1: don't check setState flag after the updater returns
Codex flagged that appendHostToWorkspace / appendLocalTerminalToWorkspace
were racy: both flipped an `inserted` flag inside setWorkspaces'
updater and then read it synchronously to decide whether to commit
the matching session via setSessions. React does NOT guarantee
updaters run synchronously (concurrent rendering, StrictMode
double-invoke, etc.), so the flag could still be false at the read
site even though the workspace exists. In that case setSessions was
skipped while the queued workspace update could still insert a new
pane referencing newSessionId — leaving a pane with no backing
session in state.
Fix: add a workspacesRef kept in sync with the workspaces state on
every render, and perform the existence check synchronously *before*
queuing any setState. Once we've confirmed the workspace exists on
the latest committed state, both setWorkspaces and setSessions are
called unconditionally, so they can never diverge.
The ref approach also correctly handles the multi-target append
loop path — React batches the updaters and applies them in sequence,
so sibling pane/session writes land in matching order.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Address codex P1+P2: narrow prune rebalance; append in root direction
### P1 — pruneWorkspaceNode over-rebalanced ancestor splits
The equal-sizes rebalance was unconditional during the recursive
walk, so closing a pane deep in one branch also rewrote unrelated
ancestor ratios (e.g., a root 0.8/0.2 vertical split got normalised
to 0.5/0.5 when a grand-child horizontal pane closed).
Now each split level tracks whether it actually lost a DIRECT
child. Only splits where a direct child disappeared get their
siblings reset to equal sizes. Ancestors whose direct children all
survived keep their original ratios (defensively re-normalised in
case a descendant subtree collapsed shape).
### P2 — Append path ignored the root's current direction
onAdd in App.tsx called the two append helpers without a direction,
so both defaulted to 'vertical'. appendPaneToWorkspaceRoot only
flattens into the root split when the directions match; if the
workspace root was horizontal (e.g., user split top/bottom earlier),
each append wrapped the entire existing tree into one side of a new
vertical split — existing panes crammed into one branch, new pane
hoarding half the space.
Read the current root direction out of the target workspace and
pass it down so new panes become peers of the existing root
siblings regardless of horizontal vs vertical.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Address codex P2: allow serial hosts in create-workspace picker
The picker used to filter out every host with protocol='serial'
regardless of mode. That was correct for append mode (the
appendHostToWorkspace helper has no serial path and early-returns)
but a regression for create mode — the old createWorkspaceWithHosts
flow passed serial hosts through and createWorkspaceFromTargets
still builds a SerialConfig-backed session for them, so there was
no reason to block them in the "+ New Workspace" entry.
Move the filter from the dialog up to App.tsx:
- AddToWorkspaceDialog drops the serial filter; selectableHosts is
simply the hosts prop.
- App.tsx passes `hosts.filter(h => h.protocol !== 'serial')` when
mode is 'append', and the full list when mode is 'create'.
Result: users can once again build a workspace from serial hosts
via QuickSwitcher's "+ New Workspace" button or the ⌘/Ctrl+Shift+J
hotkey, while append-to-existing keeps its earlier safe behaviour.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Address codex P2: don't commit session when append target disappears
Follow-up to the earlier ref-based guard. The ref check eliminates
the common "workspace already gone" case but still leaves a small
race: if closeWorkspace runs between the ref read and setWorkspaces'
updater firing, prev.map returns the unchanged workspaces but
setSessions / setActiveTabId still execute — leaving an orphan
session whose workspaceId points at a deleted workspace and jumping
activeTabId to a closed tab.
Nest setSessions + setActiveTabId inside the setWorkspaces updater
so the writes are gated on the same authoritative match used for
the tree update. The setSessions updater also de-dupes by newSessionId
so React 18 StrictMode's dev-time double-invoke of the outer updater
doesn't append the same row twice. Same pattern applied to
appendLocalTerminalToWorkspace.
The existing closeSession already uses the nested-setState shape, so
this matches the codebase convention.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
445 lines
14 KiB
TypeScript
445 lines
14 KiB
TypeScript
import { Workspace,WorkspaceNode,WorkspaceViewMode } from './models';
|
|
|
|
export type SplitDirection = 'horizontal' | 'vertical';
|
|
type SplitPosition = 'left' | 'right' | 'top' | 'bottom';
|
|
|
|
export type SplitHint = {
|
|
direction: SplitDirection;
|
|
position: SplitPosition;
|
|
targetSessionId?: string;
|
|
};
|
|
|
|
export const pruneWorkspaceNode = (node: WorkspaceNode, targetSessionId: string): WorkspaceNode | null => {
|
|
if (node.type === 'pane') {
|
|
return node.sessionId === targetSessionId ? null : node;
|
|
}
|
|
|
|
const nextChildren: WorkspaceNode[] = [];
|
|
const nextSizes: number[] = [];
|
|
const sizeList = node.sizes && node.sizes.length === node.children.length
|
|
? node.sizes
|
|
: node.children.map(() => 1 / node.children.length);
|
|
let removedDirectChild = false;
|
|
|
|
node.children.forEach((child, idx) => {
|
|
const pruned = pruneWorkspaceNode(child, targetSessionId);
|
|
if (pruned) {
|
|
nextChildren.push(pruned);
|
|
nextSizes.push(sizeList[idx] ?? 1 / node.children.length);
|
|
} else {
|
|
removedDirectChild = true;
|
|
}
|
|
});
|
|
|
|
if (nextChildren.length === 0) return null;
|
|
if (nextChildren.length === 1) return nextChildren[0];
|
|
|
|
// Only rebalance siblings to equal sizes when this level actually
|
|
// lost one of its direct children. If the prune happened deeper in
|
|
// one branch, this split's direct children are unchanged and their
|
|
// original ratios must be preserved (otherwise e.g. a root 0.8/0.2
|
|
// split gets rewritten to 0.5/0.5 when a grand-child pane closes).
|
|
if (removedDirectChild) {
|
|
const equalSize = 1 / nextChildren.length;
|
|
return { ...node, children: nextChildren, sizes: nextChildren.map(() => equalSize) };
|
|
}
|
|
|
|
// Preserve existing ratios; normalise defensively in case sibling
|
|
// subtrees changed shape (e.g. a split collapsed to a single pane).
|
|
const total = nextSizes.reduce((acc, n) => acc + n, 0) || 1;
|
|
const normalized = nextSizes.map(n => n / total);
|
|
return { ...node, children: nextChildren, sizes: normalized };
|
|
};
|
|
|
|
/**
|
|
* Append a new pane containing `sessionId` to the end of the workspace
|
|
* root's split. If the root already splits in the requested direction,
|
|
* the new pane becomes its last sibling and all sibling sizes are reset
|
|
* to equal. Otherwise the root is wrapped in a new split (same behaviour
|
|
* as the existing `insertPaneIntoWorkspace(root, id, { targetSessionId:
|
|
* undefined })` path) with two equal children.
|
|
*/
|
|
export const appendPaneToWorkspaceRoot = (
|
|
root: WorkspaceNode,
|
|
sessionId: string,
|
|
direction: SplitDirection = 'vertical',
|
|
): WorkspaceNode => {
|
|
const newPane: WorkspaceNode = { id: crypto.randomUUID(), type: 'pane', sessionId };
|
|
|
|
if (root.type === 'split' && root.direction === direction) {
|
|
const nextChildren = [...root.children, newPane];
|
|
const equalSize = 1 / nextChildren.length;
|
|
return {
|
|
...root,
|
|
children: nextChildren,
|
|
sizes: nextChildren.map(() => equalSize),
|
|
};
|
|
}
|
|
|
|
return {
|
|
id: crypto.randomUUID(),
|
|
type: 'split',
|
|
direction,
|
|
children: [root, newPane],
|
|
sizes: [0.5, 0.5],
|
|
};
|
|
};
|
|
|
|
const createSplitFromPane = (
|
|
existingPane: WorkspaceNode,
|
|
newPane: WorkspaceNode,
|
|
hint: SplitHint
|
|
): WorkspaceNode => {
|
|
const children = (hint.position === 'left' || hint.position === 'top') ? [newPane, existingPane] : [existingPane, newPane];
|
|
return {
|
|
id: crypto.randomUUID(),
|
|
type: 'split',
|
|
direction: hint.direction,
|
|
children,
|
|
sizes: [1, 1],
|
|
};
|
|
};
|
|
|
|
export const insertPaneIntoWorkspace = (
|
|
root: WorkspaceNode,
|
|
sessionId: string,
|
|
hint: SplitHint
|
|
): WorkspaceNode => {
|
|
const pane: WorkspaceNode = { id: crypto.randomUUID(), type: 'pane', sessionId };
|
|
|
|
if (!hint.targetSessionId) {
|
|
const children = (hint.position === 'left' || hint.position === 'top') ? [pane, root] : [root, pane];
|
|
return {
|
|
id: crypto.randomUUID(),
|
|
type: 'split',
|
|
direction: hint.direction,
|
|
children,
|
|
sizes: [1, 1],
|
|
};
|
|
}
|
|
|
|
const insertPane = (node: WorkspaceNode): WorkspaceNode => {
|
|
if (node.type === 'pane' && node.sessionId === hint.targetSessionId) {
|
|
return createSplitFromPane(node, pane, hint);
|
|
}
|
|
if (node.type === 'split') {
|
|
return { ...node, children: node.children.map(child => insertPane(child)) };
|
|
}
|
|
return node;
|
|
};
|
|
|
|
return insertPane(root);
|
|
};
|
|
|
|
export const createWorkspaceFromSessions = (
|
|
baseSessionId: string,
|
|
joiningSessionId: string,
|
|
hint: SplitHint
|
|
): Workspace => {
|
|
const basePane: WorkspaceNode = { id: crypto.randomUUID(), type: 'pane', sessionId: baseSessionId };
|
|
const newPane: WorkspaceNode = { id: crypto.randomUUID(), type: 'pane', sessionId: joiningSessionId };
|
|
const children = (hint.position === 'left' || hint.position === 'top') ? [newPane, basePane] : [basePane, newPane];
|
|
|
|
return {
|
|
id: `ws-${crypto.randomUUID()}`,
|
|
title: 'Workspace',
|
|
focusedSessionId: baseSessionId, // Initialize with the base session focused
|
|
root: {
|
|
id: crypto.randomUUID(),
|
|
type: 'split',
|
|
direction: hint.direction,
|
|
children,
|
|
sizes: [1, 1],
|
|
},
|
|
};
|
|
};
|
|
|
|
export const updateWorkspaceSplitSizes = (
|
|
root: WorkspaceNode,
|
|
splitId: string,
|
|
sizes: number[]
|
|
): WorkspaceNode => {
|
|
const patch = (node: WorkspaceNode): WorkspaceNode => {
|
|
if (node.type === 'split') {
|
|
if (node.id === splitId) {
|
|
return { ...node, sizes };
|
|
}
|
|
return { ...node, children: node.children.map(child => patch(child)) };
|
|
}
|
|
return node;
|
|
};
|
|
return patch(root);
|
|
};
|
|
|
|
/**
|
|
* Create a workspace from multiple session IDs.
|
|
* Used for snippet runner - creates a workspace with all sessions in a horizontal split.
|
|
*/
|
|
export const createWorkspaceFromSessionIds = (
|
|
sessionIds: string[],
|
|
options: {
|
|
title: string;
|
|
viewMode?: WorkspaceViewMode;
|
|
snippetId?: string;
|
|
}
|
|
): Workspace => {
|
|
if (sessionIds.length === 0) {
|
|
throw new Error('Cannot create workspace with no sessions');
|
|
}
|
|
|
|
if (sessionIds.length === 1) {
|
|
// Single pane workspace
|
|
return {
|
|
id: `ws-${crypto.randomUUID()}`,
|
|
title: options.title,
|
|
viewMode: options.viewMode,
|
|
snippetId: options.snippetId,
|
|
focusedSessionId: sessionIds[0],
|
|
root: {
|
|
id: crypto.randomUUID(),
|
|
type: 'pane',
|
|
sessionId: sessionIds[0],
|
|
},
|
|
};
|
|
}
|
|
|
|
// Multiple sessions - create a horizontal split
|
|
const children: WorkspaceNode[] = sessionIds.map(sessionId => ({
|
|
id: crypto.randomUUID(),
|
|
type: 'pane' as const,
|
|
sessionId,
|
|
}));
|
|
|
|
return {
|
|
id: `ws-${crypto.randomUUID()}`,
|
|
title: options.title,
|
|
viewMode: options.viewMode,
|
|
snippetId: options.snippetId,
|
|
focusedSessionId: sessionIds[0],
|
|
root: {
|
|
id: crypto.randomUUID(),
|
|
type: 'split',
|
|
direction: 'vertical', // Side by side
|
|
children,
|
|
sizes: children.map(() => 1),
|
|
},
|
|
};
|
|
};
|
|
|
|
/**
|
|
* Collect all session IDs from a workspace node tree.
|
|
*/
|
|
export const collectSessionIds = (node: WorkspaceNode): string[] => {
|
|
if (node.type === 'pane') {
|
|
return [node.sessionId];
|
|
}
|
|
return node.children.flatMap(child => collectSessionIds(child));
|
|
};
|
|
|
|
/**
|
|
* Find a pane node by session ID in the workspace tree.
|
|
*/
|
|
const _findPaneBySessionId = (node: WorkspaceNode, sessionId: string): WorkspaceNode | null => {
|
|
if (node.type === 'pane') {
|
|
return node.sessionId === sessionId ? node : null;
|
|
}
|
|
for (const child of node.children) {
|
|
const found = _findPaneBySessionId(child, sessionId);
|
|
if (found) return found;
|
|
}
|
|
return null;
|
|
};
|
|
|
|
/**
|
|
* Get the path to a session in the workspace tree.
|
|
* Returns an array of indices representing the path from root to the pane.
|
|
*/
|
|
const _getPathToSession = (node: WorkspaceNode, sessionId: string, path: number[] = []): number[] | null => {
|
|
if (node.type === 'pane') {
|
|
return node.sessionId === sessionId ? path : null;
|
|
}
|
|
for (let i = 0; i < node.children.length; i++) {
|
|
const result = _getPathToSession(node.children[i], sessionId, [...path, i]);
|
|
if (result) return result;
|
|
}
|
|
return null;
|
|
};
|
|
|
|
/**
|
|
* Get all panes with their positions for navigation.
|
|
*/
|
|
interface PanePosition {
|
|
sessionId: string;
|
|
path: number[];
|
|
// Calculated bounds (normalized 0-1)
|
|
x: number;
|
|
y: number;
|
|
width: number;
|
|
height: number;
|
|
}
|
|
|
|
const collectPanePositions = (
|
|
node: WorkspaceNode,
|
|
path: number[] = [],
|
|
bounds: { x: number; y: number; width: number; height: number } = { x: 0, y: 0, width: 1, height: 1 }
|
|
): PanePosition[] => {
|
|
if (node.type === 'pane') {
|
|
return [{
|
|
sessionId: node.sessionId,
|
|
path,
|
|
...bounds,
|
|
}];
|
|
}
|
|
|
|
const positions: PanePosition[] = [];
|
|
const sizes = node.sizes || node.children.map(() => 1 / node.children.length);
|
|
const totalSize = sizes.reduce((a, b) => a + b, 0) || 1;
|
|
|
|
let offset = 0;
|
|
for (let i = 0; i < node.children.length; i++) {
|
|
const sizeRatio = (sizes[i] || 1 / node.children.length) / totalSize;
|
|
|
|
let childBounds: { x: number; y: number; width: number; height: number };
|
|
if (node.direction === 'horizontal') {
|
|
// Top/bottom split
|
|
childBounds = {
|
|
x: bounds.x,
|
|
y: bounds.y + bounds.height * offset,
|
|
width: bounds.width,
|
|
height: bounds.height * sizeRatio,
|
|
};
|
|
} else {
|
|
// Left/right split
|
|
childBounds = {
|
|
x: bounds.x + bounds.width * offset,
|
|
y: bounds.y,
|
|
width: bounds.width * sizeRatio,
|
|
height: bounds.height,
|
|
};
|
|
}
|
|
|
|
positions.push(...collectPanePositions(node.children[i], [...path, i], childBounds));
|
|
offset += sizeRatio;
|
|
}
|
|
|
|
return positions;
|
|
};
|
|
|
|
export type FocusDirection = 'up' | 'down' | 'left' | 'right';
|
|
|
|
/**
|
|
* Find the next session to focus when moving in a direction.
|
|
* Returns the session ID to focus, or null if no valid target.
|
|
*/
|
|
export const getNextFocusSessionId = (
|
|
root: WorkspaceNode,
|
|
currentSessionId: string,
|
|
direction: FocusDirection
|
|
): string | null => {
|
|
const positions = collectPanePositions(root);
|
|
|
|
const current = positions.find(p => p.sessionId === currentSessionId);
|
|
if (!current) {
|
|
return null;
|
|
}
|
|
|
|
// Filter candidates based on direction
|
|
let candidates: PanePosition[] = [];
|
|
const otherPanes = positions.filter(p => p.sessionId !== currentSessionId);
|
|
|
|
switch (direction) {
|
|
case 'left':
|
|
// Find panes to the left
|
|
candidates = otherPanes.filter(p =>
|
|
p.x + p.width <= current.x + 0.001 // Allow small epsilon for floating point
|
|
);
|
|
// Wraparound: if no pane to the left, find the rightmost pane
|
|
if (candidates.length === 0 && otherPanes.length > 0) {
|
|
const maxX = Math.max(...otherPanes.map(p => p.x));
|
|
candidates = otherPanes.filter(p => p.x >= maxX - 0.001);
|
|
}
|
|
break;
|
|
case 'right':
|
|
// Find panes to the right
|
|
candidates = otherPanes.filter(p =>
|
|
p.x >= current.x + current.width - 0.001
|
|
);
|
|
// Wraparound: if no pane to the right, find the leftmost pane
|
|
if (candidates.length === 0 && otherPanes.length > 0) {
|
|
const minX = Math.min(...otherPanes.map(p => p.x));
|
|
candidates = otherPanes.filter(p => p.x <= minX + 0.001);
|
|
}
|
|
break;
|
|
case 'up':
|
|
// Find panes above
|
|
candidates = otherPanes.filter(p =>
|
|
p.y + p.height <= current.y + 0.001
|
|
);
|
|
// Wraparound: if no pane above, find the bottommost pane
|
|
if (candidates.length === 0 && otherPanes.length > 0) {
|
|
const maxY = Math.max(...otherPanes.map(p => p.y));
|
|
candidates = otherPanes.filter(p => p.y >= maxY - 0.001);
|
|
}
|
|
break;
|
|
case 'down':
|
|
// Find panes below
|
|
candidates = otherPanes.filter(p =>
|
|
p.y >= current.y + current.height - 0.001
|
|
);
|
|
// Wraparound: if no pane below, find the topmost pane
|
|
if (candidates.length === 0 && otherPanes.length > 0) {
|
|
const minY = Math.min(...otherPanes.map(p => p.y));
|
|
candidates = otherPanes.filter(p => p.y <= minY + 0.001);
|
|
}
|
|
break;
|
|
}
|
|
|
|
if (candidates.length === 0) return null;
|
|
|
|
// Calculate center point of current pane for scoring
|
|
const currentCenterX = current.x + current.width / 2;
|
|
const currentCenterY = current.y + current.height / 2;
|
|
|
|
// Find the closest candidate
|
|
// For left/right, prefer candidates that overlap vertically
|
|
// For up/down, prefer candidates that overlap horizontally
|
|
let best: PanePosition | null = null;
|
|
let bestScore = Infinity;
|
|
|
|
for (const candidate of candidates) {
|
|
const candidateCenterX = candidate.x + candidate.width / 2;
|
|
const candidateCenterY = candidate.y + candidate.height / 2;
|
|
|
|
let score: number;
|
|
|
|
if (direction === 'left' || direction === 'right') {
|
|
// Check vertical overlap
|
|
const overlapTop = Math.max(current.y, candidate.y);
|
|
const overlapBottom = Math.min(current.y + current.height, candidate.y + candidate.height);
|
|
const hasOverlap = overlapBottom > overlapTop;
|
|
|
|
// Distance is horizontal distance, but penalize if no overlap
|
|
const distance = Math.abs(candidateCenterX - currentCenterX);
|
|
const verticalPenalty = hasOverlap ? 0 : Math.abs(candidateCenterY - currentCenterY) * 2;
|
|
score = distance + verticalPenalty;
|
|
} else {
|
|
// Check horizontal overlap
|
|
const overlapLeft = Math.max(current.x, candidate.x);
|
|
const overlapRight = Math.min(current.x + current.width, candidate.x + candidate.width);
|
|
const hasOverlap = overlapRight > overlapLeft;
|
|
|
|
// Distance is vertical distance, but penalize if no overlap
|
|
const distance = Math.abs(candidateCenterY - currentCenterY);
|
|
const horizontalPenalty = hasOverlap ? 0 : Math.abs(candidateCenterX - currentCenterX) * 2;
|
|
score = distance + horizontalPenalty;
|
|
}
|
|
|
|
if (score < bestScore) {
|
|
bestScore = score;
|
|
best = candidate;
|
|
}
|
|
}
|
|
|
|
return best?.sessionId || null;
|
|
};
|