feat(tabs): edit groups in the vertical rail

The grouped vertical rail can now be edited from the browser: groups are
created, renamed, reordered and deleted, and tabs are moved between them, by
menu, keyboard or pointer drag. Every edit is saved through the existing
PUT /api/tab-layout; there are no server changes.

Saving (tab-layout-browser.js, pure):
- Edits are named operations (createGroup, renameGroup, deleteGroup,
  reorderGroup, moveRef) applied to the rail at once, mirroring the server
  model: a moved session takes the sessions that still follow it, and a
  hand-moved child is marked placement 'manual'. normalizeLayout now keeps
  placement and updatedAt, since whole layouts are written back.
- createEditCoordinator keeps ONE PUT {baseVersion, layout} in flight. Edits
  made in the same turn share a write; edits made while one is in flight go
  out on the version it returns. A 409 replays the operations onto the
  layout the server returned and retries (bounded); an operation that no
  longer applies is dropped and reported. A 400 re-reads first; any other
  failure reports and re-reads.
- dropOperation maps a finished drag to one operation, or null for a drop
  that changes nothing.

Wiring (app.js, tab-rail-resize.js):
- The session row menu gains Move up/down, Move to <group>, Move to
  Ungrouped and Move to new group in the vertical rail. Before the first
  group exists it offers only "Move to new group", which is how a flat rail
  becomes grouped; the header strip's menu is unchanged.
- A group header opens its menu with Shift+F10 / ContextMenu, right-click or
  a hover glyph (a non-focusable aria-hidden span, so the treeitem still
  holds no interactive child): Rename, New group, Move group up/down,
  Delete. F2 renames inline. A web tab row's Shift+F10 opens its settings
  plus the same moves.
- The menu closes on Escape (consumed before the global Escape handler, focus
  back to its row or header), a pointer outside, Tab, focus leaving it, a
  resize, a second open and any full re-render.
- Inline group rename shares the session rename's ownership handle, so only
  the current editor releases the render guard. Enter or blur commits,
  Escape cancels, IME composition keys are left to the IME, and the label
  becomes a flex slot so the editor gets the full width while typing.
- Pointer drag (mouse and pen) in the grouped rail only: rows before/after a
  row or into a group, a header drag reorders groups. Escape cancels; the
  click that ends a drag neither selects nor toggles. The flat rail and the
  header strip keep their HTML5 drag untouched.
- A tab:layoutChanged read is deferred while a write is in flight and run
  once it settles; a read otherwise rebases unsaved edits. On pagehide,
  unconfirmed edits go out in a keepalive PUT and into sessionStorage, and
  replay after reload (a no-op when the keepalive landed).
- New strings have zh-CN entries; group names reach the DOM only as text.

Unchanged: the flat rail's markup when no group exists, the tree semantics
and single roving tab stop, sessionOrder and Alt+N.

Tests: test/tab-layout-editing.test.ts (operations, coordinator, drop
mapping, menus, rename, dismissal, SSE deferral, reload recovery, flat-rail
identity) and test/tab-layout-editing.browser.test.ts (real pointer drags,
editor paint, menu Escape), listed in BROWSER_TEST_GLOBS.
This commit is contained in:
Aamer Akhter
2026-10-04 20:10:32 -04:00
parent ffaa5ee80c
commit 97cb5b5799
12 changed files with 2239 additions and 20 deletions
+603 -9
View File
@@ -866,6 +866,8 @@ class CodemanApp {
// Flush the durable queue synchronously when the page is hidden/closed —
// debounced persistence may have a pending write we mustn't lose on reload.
window.addEventListener('pagehide', () => this._persistReliableNow());
// Tab group edits not yet confirmed by the server survive a reload.
window.addEventListener('pagehide', () => this._persistPendingTabLayoutEdits());
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') this._persistReliableNow();
// A background tab's timers are throttled, so the 5s watchdog may not
@@ -1267,6 +1269,16 @@ class CodemanApp {
// Escape - close panels and modals (different logic: no preventDefault, no return)
if (e.key === 'Escape') {
// An open group menu (or a grouped-rail drag) owns this Escape: close
// just that, not every panel behind it.
if (this._tabGroupMenu && this._tabGroupMenuKeydown) {
this._tabGroupMenuKeydown(e);
return;
}
if (this._tabLayoutDrag?.active && this._tabLayoutDragKeydown) {
this._tabLayoutDragKeydown(e);
return;
}
this.closeAllPanels();
this.closeHelp();
if (this.attachmentHistoryDrawerOpen) this.closeAttachmentHistory();
@@ -5695,6 +5707,8 @@ class CodemanApp {
_fullRenderSessionTabs() {
this.closeTabRailActionMenu?.();
if (this._inlineRenameActive) return;
// The group menu's trigger is about to be replaced.
this.closeTabGroupMenu();
const container = this.$('sessionTabs');
// Sidebar rows are always tall (name + folder) and never wrap. Re-assert it
@@ -5724,9 +5738,11 @@ class CodemanApp {
// The rebuild below destroys the focused row. In the grouped tree, put focus
// back on the same item (by identity) so a background render or a keyboard
// collapse does not drop a keyboard user to <body>.
const focusWasInside = container.contains(document.activeElement);
// An edit made from a menu (focus now on <body>) asks to land back in the rail.
const focusWasInside = container.contains(document.activeElement) || this._tabRefocusAfterEdit === true;
const focusIdentity = this._tabFocusIdentity || (focusWasInside ? this._tabTreeIdentity(document.activeElement) : null);
this._tabFocusIdentity = null;
this._tabRefocusAfterEdit = false;
// Build tabs HTML using array for better string concatenation performance.
// Iterate in sessionOrder to respect the user's custom tab arrangement, on
@@ -5887,6 +5903,9 @@ class CodemanApp {
// Set up drag-and-drop handlers for tab reordering
this.setupTabDragHandlers();
// The grouped rail drags with its own pointer model (rows across groups,
// group reorder); bound once, inert unless the rail is grouped.
this._bindTabLayoutPointerDrag(container);
// Set up keyboard navigation for tabs
this.setupTabKeyboardNavigation(container);
@@ -6211,18 +6230,22 @@ class CodemanApp {
if (groupId) toggle();
else this._activateTabRow(current);
break;
case 'F2':
if (!groupId || !this.startTabGroupRename(groupId)) return;
break;
case 'F10':
case 'ContextMenu':
case 'ContextMenu': {
if (e.key === 'F10' && !e.shiftKey) return;
if (current.dataset.id) {
this.openTabRailActionMenu?.(
{ preventDefault() {}, stopPropagation() {}, currentTarget: current },
current.dataset.id
);
const synthetic = { preventDefault() {}, stopPropagation() {}, currentTarget: current };
if (groupId) {
this.openTabGroupMenu(synthetic, groupId);
} else if (current.dataset.id) {
this.openTabRailActionMenu?.(synthetic, current.dataset.id);
} else if (current.dataset.webviewId) {
this.showWebviewModal?.(current.dataset.webviewId);
this.openTabWebviewMenu(synthetic, current.dataset.webviewId);
} else return;
break;
}
default:
return;
}
@@ -6356,6 +6379,12 @@ class CodemanApp {
// owner-scoped server-side, so this is a saved request, not a guard.)
if (me?.multiUser && typeof data?.owner === 'string' && data.owner !== me.username) return;
if (Number.isSafeInteger(data?.version) && this.tabLayout && data.version <= this.tabLayout.version) return;
// Our own write is in flight: its response is the newer truth, and a read
// racing it could repaint the pre-edit layout. Re-read once it settles.
if (this._tabLayoutEditor?.hasPending()) {
this._tabLayoutReloadPending = true;
return;
}
this._loadTabLayout();
}
@@ -6372,6 +6401,19 @@ class CodemanApp {
// An overtaken response is already dropped by the coordinator; this guards a
// reordering between the coordinator and an SSE-triggered reload.
if (next && this.tabLayout && next.version < this.tabLayout.version) return;
const editor = this._tabLayoutEditor;
if (editor) {
if (next && editor.isWriting()) {
// The write's own response decides; read again after it.
this._tabLayoutReloadPending = true;
return;
}
// Unsaved edits are rebased onto the read (adoptExternal repaints); with
// none, the editor is simply rebuilt from the new layout on next use.
if (next && editor.hasPending() && editor.adoptExternal(next)) return;
editor.dispose();
this._tabLayoutEditor = null;
}
this.tabLayout = next;
const storage = this._getTabCollapseStorage();
const collapsed = storage && next
@@ -6384,6 +6426,11 @@ class CodemanApp {
// rail (always so on the flat rail, which is every owner without groups).
// Rebuild only when what the rail would draw actually changed.
if (this._isTabGroupStructureStale()) this._fullRenderSessionTabs();
// Edits left unsaved by the previous page (see _persistPendingTabLayoutEdits).
if (next && !this._tabLayoutRestoreChecked) {
this._tabLayoutRestoreChecked = true;
this._restorePendingTabLayoutEdits();
}
}
/** localStorage, or null once it has failed (collapse then stays all-expanded). */
@@ -6446,6 +6493,551 @@ class CodemanApp {
return this.collapsedTabGroupIds.has(groupId) === shouldCollapse;
}
// ═══════════════════════════════════════════════════════════════
// Owner tab layout: editing groups from the vertical rail
// ═══════════════════════════════════════════════════════════════
//
// Every edit is a named operation (tab-layout-browser.js) applied to the rail
// at once and saved by ONE serialized PUT /api/tab-layout at a time, with the
// version the server last returned. A 409 is rebased onto the server's layout
// and retried; a failure re-reads. Editing is a vertical-rail feature: the
// header strip, the sidebar and phones never offer it.
_tabLayoutEditable() {
return !!(this.tabLayout && window.CodemanTabLayout && this._tabOrientation() === 'vertical');
}
/** child session id -> parent session id, so a moved session takes the sessions that follow it. */
_tabLayoutParents() {
const parents = {};
for (const session of this.sessions.values()) {
if (session?.parentSessionId && session.parentSessionId !== session.id) parents[session.id] = session.parentSessionId;
}
return parents;
}
async _putTabLayout({ baseVersion, layout }) {
const body = { baseVersion, layout: { ...layout, updatedAt: layout.updatedAt || new Date().toISOString() } };
const response = await this._api('/api/tab-layout', { method: 'PUT', body });
if (!response) return { ok: false, status: 0, layout: null };
let data = null;
try {
data = await response.json();
} catch {}
return { ok: response.ok, status: response.status, layout: data?.data?.layout || null };
}
_ensureTabLayoutEditor() {
if (this._tabLayoutEditor || !this.tabLayout) return this._tabLayoutEditor || null;
this._tabLayoutEditor = window.CodemanTabLayout.createEditCoordinator({
initialLayout: this.tabLayout,
put: (request) => this._putTabLayout(request),
fetchLayout: async () => {
const data = await this._apiJson('/api/tab-layout');
if (!data?.layout) throw new Error('Tab layout unavailable');
return data.layout;
},
applyLayout: (layout) => this._adoptEditedTabLayout(layout),
reportError: (message) => this.showToast?.(message, 'error'),
onFailure: () => {
// The rail may still show an edit the server refused: read the truth.
this._tabLayoutReloadPending = true;
},
onSettled: () => {
if (!this._tabLayoutReloadPending) return;
this._tabLayoutReloadPending = false;
this._loadTabLayout();
},
});
return this._tabLayoutEditor;
}
/** The editor's view of the layout (optimistic or confirmed) becomes the rail. */
_adoptEditedTabLayout(layout) {
this.tabLayout = layout;
const storage = this._getTabCollapseStorage();
if (storage) {
// Forget collapse state for groups that no longer exist.
const collapsed = window.CodemanTabLayout.loadCollapsedGroupIds(storage, layout.groups.map((group) => group.id));
if (collapsed.ok) this.collapsedTabGroupIds = new Set(collapsed.ids);
}
this._fullRenderSessionTabs();
}
/**
* Apply one edit. `focusIdentity` names the tree item that should hold focus
* afterwards (the moved row, the renamed group), so a keyboard user who acted
* from a menu lands back in the rail rather than on <body>.
*/
editTabLayout(operation, focusIdentity) {
if (!this._tabLayoutEditable()) return false;
const active = document.activeElement;
const rail = this.$('sessionTabs');
if (focusIdentity && (!active || active === document.body || rail?.contains(active))) {
this._tabFocusIdentity = focusIdentity;
this._tabRefocusAfterEdit = true;
}
try {
this._ensureTabLayoutEditor().enqueue(operation);
return true;
} catch (error) {
this._tabRefocusAfterEdit = false;
this.showToast?.(error?.message || 'Could not save tab groups.', 'error');
return false;
}
}
_newTabGroupId() {
return globalThis.crypto?.randomUUID?.() || `group-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
/** New group (optionally holding `ref`), then straight into renaming it. */
createTabGroup({ ref = null, index } = {}) {
if (!this._tabLayoutEditable()) return false;
const id = this._newTabGroupId();
const name = window.CodemanI18n?.t?.('New group') || 'New group';
if (!this.editTabLayout({ type: 'createGroup', id, name, ...(Number.isInteger(index) ? { index } : {}) }, `group:${id}`)) {
return false;
}
if (ref) this.editTabLayout({ type: 'moveRef', ref, groupId: id, index: 0, parents: this._tabLayoutParents() });
this.startTabGroupRename(id);
return true;
}
deleteTabGroup(groupId) {
const groups = this.tabLayout?.groups || [];
const index = groups.findIndex((group) => group.id === groupId);
if (index < 0) return false;
if (!window.confirm(`Delete group "${groups[index].name}"? Its tabs move to Ungrouped.`)) return false;
const neighbour = groups[index + 1] || groups[index - 1];
return this.editTabLayout({ type: 'deleteGroup', groupId }, neighbour ? `group:${neighbour.id}` : null);
}
moveTabGroup(groupId, delta) {
const groups = this.tabLayout?.groups || [];
const from = groups.findIndex((group) => group.id === groupId);
const to = from + delta;
if (from < 0 || to < 0 || to >= groups.length) return false;
return this.editTabLayout({ type: 'reorderGroup', groupId, index: to }, `group:${groupId}`);
}
/** Where a ref is stored: { groupId (null = Ungrouped), refs, index } or null. */
_tabRefLocation(ref) {
const same = (candidate) => candidate.kind === ref.kind && candidate.id === ref.id;
for (const group of this.tabLayout?.groups || []) {
const index = group.refs.findIndex(same);
if (index >= 0) return { groupId: group.id, refs: group.refs, index };
}
const index = this.tabLayout?.ungrouped?.findIndex(same) ?? -1;
return index >= 0 ? { groupId: null, refs: this.tabLayout.ungrouped, index } : null;
}
moveTabRef(ref, groupId, anchor = null, placement = 'before') {
const parents = this._tabLayoutParents();
let destination;
try {
destination = window.CodemanTabLayout.moveDestination(this.tabLayout, ref, groupId, anchor, placement, parents);
} catch {
return false;
}
return this.editTabLayout({ type: 'moveRef', ref, ...destination, parents }, `${ref.kind}:${ref.id}`);
}
/**
* Group placement actions for a row's action menu: reorder within its
* container, move to another group, out to Ungrouped, or into a new group.
* Empty outside the vertical rail, so the header strip's menu is unchanged.
*/
_tabRefMoveActions(ref) {
if (!this._tabLayoutEditable()) return [];
const location = this._tabRefLocation(ref);
if (!location) return [];
const actions = [];
const grouped = this.tabLayout.groups.length > 0;
// Up/down follow the STORED order, which is what the rail paints unless a
// sort is on (then the sort decides and there is nothing to reorder).
if (grouped && !this.isTabRailSorted()) {
// The sessions that follow this one move with it, so "down" means past
// the first row that is not part of that block.
const moving = new Set(window.CodemanTabLayout.movingRefKeys(this.tabLayout, ref, this._tabLayoutParents()));
const previous = location.refs[location.index - 1];
const next = location.refs.slice(location.index + 1).find((candidate) => !moving.has(`${candidate.kind}:${candidate.id}`));
if (previous) actions.push({ label: 'Move up', run: () => this.moveTabRef(ref, location.groupId, previous, 'before') });
if (next) actions.push({ label: 'Move down', run: () => this.moveTabRef(ref, location.groupId, next, 'after') });
}
for (const group of this.tabLayout.groups) {
if (group.id === location.groupId) continue;
actions.push({ label: `Move to ${group.name}`, run: () => this.moveTabRef(ref, group.id) });
}
if (location.groupId !== null) actions.push({ label: 'Move to Ungrouped', run: () => this.moveTabRef(ref, null) });
actions.push({ label: 'Move to new group', run: () => this.createTabGroup({ ref }) });
return actions;
}
// ─── Group and web-tab menus (right-click, the header's ⋯, Shift+F10) ──
/**
* Close the open group / web-tab menu. Every dismissal path lands here:
* Escape, a pointer outside it, focus leaving it, Tab, a viewport resize, an
* action, and any full re-render of the rail (which would orphan its trigger).
*/
closeTabGroupMenu({ restoreFocus = false } = {}) {
const menu = this._tabGroupMenu;
if (!menu) return;
const trigger = this._tabGroupMenuTrigger;
const identity = this._tabGroupMenuKey;
this._tabGroupMenu = null;
this._tabGroupMenuTrigger = null;
this._tabGroupMenuKey = null;
document.removeEventListener('pointerdown', this._tabGroupMenuOutside, true);
document.removeEventListener('keydown', this._tabGroupMenuKeydown, true);
window.removeEventListener('resize', this._tabGroupMenuResize);
this._tabGroupMenuOutside = this._tabGroupMenuKeydown = this._tabGroupMenuResize = null;
menu.remove();
if (!restoreFocus) return;
// The trigger may have been re-rendered while the menu was open; find the
// live tree item by identity.
const rail = this.$('sessionTabs');
const item =
(trigger?.isConnected && trigger.closest('[role="treeitem"]')) ||
[...(rail?.querySelectorAll('[role="treeitem"]') || [])].find((el) => this._tabTreeIdentity(el) === identity);
item?.focus();
}
openTabGroupMenu(event, groupId) {
const groups = this.tabLayout?.groups || [];
const index = groups.findIndex((group) => group.id === groupId);
if (index < 0) return false;
return this._openTabLayoutMenu(event, `group:${groupId}`, 'Group actions', [
{ label: 'Rename group', run: () => this.startTabGroupRename(groupId) },
{ label: 'New group', run: () => this.createTabGroup({ index: index + 1 }) },
...(index > 0 ? [{ label: 'Move group up', run: () => this.moveTabGroup(groupId, -1) }] : []),
...(index < groups.length - 1 ? [{ label: 'Move group down', run: () => this.moveTabGroup(groupId, 1) }] : []),
{ label: 'Delete group', className: 'danger', run: () => this.deleteTabGroup(groupId) },
]);
}
/** Keyboard actions for a web-tab row in the vertical rail: its settings plus group moves. */
openTabWebviewMenu(event, webviewId) {
const moves = this._tabRefMoveActions({ kind: 'webview', id: webviewId });
if (!moves.length) {
this.showWebviewModal?.(webviewId);
return false;
}
return this._openTabLayoutMenu(event, `webview:${webviewId}`, 'Web tab actions', [
{ label: 'Web tab settings', run: () => this.showWebviewModal?.(webviewId) },
...moves,
]);
}
_openTabLayoutMenu(event, identity, ariaLabel, actions) {
event?.preventDefault?.();
event?.stopPropagation?.();
const trigger = event?.currentTarget || null;
// Opening the same menu again closes it (a toggle, like the row menu).
if (this._tabGroupMenu && this._tabGroupMenuKey === identity) {
this.closeTabGroupMenu();
return false;
}
this.closeTabGroupMenu();
this.closeTabRailActionMenu?.();
if (!this._tabLayoutEditable()) return false;
const menu = document.createElement('div');
menu.className = 'tab-rail-action-menu tab-layout-group-action-menu';
menu.setAttribute('role', 'menu');
menu.setAttribute('aria-label', ariaLabel);
for (const action of actions) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('role', 'menuitem');
button.textContent = action.label;
if (action.className) button.className = action.className;
button.addEventListener('click', () => {
this.closeTabGroupMenu();
action.run();
});
menu.appendChild(button);
}
document.body.appendChild(menu);
const anchor = (trigger?.getBoundingClientRect ? trigger : null) || this.$('sessionTabs');
const rect = anchor?.getBoundingClientRect?.() || { left: 8, bottom: 8, right: 8 };
const menuRect = menu.getBoundingClientRect();
const left = event?.clientX && event.type === 'contextmenu' ? event.clientX : rect.left;
menu.style.left = `${Math.max(8, Math.min(left, window.innerWidth - menuRect.width - 8))}px`;
menu.style.top = `${Math.max(8, Math.min(rect.bottom + 4, window.innerHeight - menuRect.height - 8))}px`;
this._tabGroupMenu = menu;
this._tabGroupMenuTrigger = trigger;
this._tabGroupMenuKey = identity;
this._tabGroupMenuOutside = (pointerEvent) => {
if (menu.contains(pointerEvent.target) || (trigger && trigger.contains?.(pointerEvent.target))) return;
this.closeTabGroupMenu();
};
// Capture on document, so Escape closes THIS menu and nothing else (the
// global Escape handler defers to it, see the keydown listener in init).
this._tabGroupMenuKeydown = (keyEvent) => {
if (keyEvent.key !== 'Escape') return;
keyEvent.preventDefault();
keyEvent.stopImmediatePropagation();
this.closeTabGroupMenu({ restoreFocus: true });
};
this._tabGroupMenuResize = () => this.closeTabGroupMenu();
document.addEventListener('pointerdown', this._tabGroupMenuOutside, true);
document.addEventListener('keydown', this._tabGroupMenuKeydown, true);
window.addEventListener('resize', this._tabGroupMenuResize);
menu.addEventListener('keydown', (keyEvent) => {
const buttons = [...menu.querySelectorAll('button')];
const at = buttons.indexOf(document.activeElement);
if (keyEvent.key === 'ArrowDown' || keyEvent.key === 'ArrowUp') {
keyEvent.preventDefault();
buttons[(at + (keyEvent.key === 'ArrowDown' ? 1 : -1) + buttons.length) % buttons.length]?.focus();
} else if (keyEvent.key === 'Home' || keyEvent.key === 'End') {
keyEvent.preventDefault();
buttons[keyEvent.key === 'Home' ? 0 : buttons.length - 1]?.focus();
} else if (keyEvent.key === 'Tab') {
// Tab would walk out and leave the popup on screen: dismiss to the row.
keyEvent.preventDefault();
this.closeTabGroupMenu({ restoreFocus: true });
}
});
// Focus leaving by any other route (a click elsewhere, a programmatic move).
// Hops between the menu's own items are not a departure.
menu.addEventListener('focusout', (focusEvent) => {
if (focusEvent.relatedTarget && menu.contains(focusEvent.relatedTarget)) return;
if (this._tabGroupMenu === menu) this.closeTabGroupMenu();
});
menu.querySelector('button')?.focus();
return true;
}
// ─── Inline group rename ───────────────────────────────────────────
/**
* Rename a group in place. Shares the session rename's ownership handle
* (`_activeRename`), so starting one cancels the other and only the CURRENT
* editor may release the render guard. Enter or blur commits, Escape cancels,
* IME composition keys belong to the IME. The commit goes through the edit
* coordinator, so it is serialized behind any write already in flight.
*/
startTabGroupRename(groupId) {
if (!this.tabLayout?.groups?.some((candidate) => candidate.id === groupId)) return false;
// Cancelling another editor re-renders the rail, so look the header up after.
this._activeRename?.cancel();
const group = this.tabLayout?.groups?.find((candidate) => candidate.id === groupId);
const header = this.$('sessionTabs')?.querySelector(`[data-tab-group-header="${CSS.escape(groupId)}"]`);
const label = header?.querySelector('.tab-layout-group-name');
if (!group || !label) return false;
this._inlineRenameActive = true;
const input = document.createElement('input');
input.type = 'text';
input.className = 'tab-layout-group-rename-input';
input.value = group.name;
input.maxLength = 60;
input.setAttribute('aria-label', 'Group name');
label.classList.add('tab-layout-group-name--renaming');
label.replaceChildren(input);
// The header toggles collapse on click and opens its menu on right-click;
// neither may fire from inside the editor.
for (const type of ['click', 'contextmenu', 'pointerdown']) input.addEventListener(type, (e) => e.stopPropagation());
let settled = false;
const handle = { groupId, cancel: () => settle(false) };
const settle = (commit) => {
if (settled) return;
settled = true;
const name = input.value.trim();
// Only the current editor owns the guard: a newer rename keeps it.
if (this._activeRename !== handle) return;
this._activeRename = null;
this._inlineRenameActive = false;
const current = this.tabLayout?.groups?.find((candidate) => candidate.id === groupId);
if (commit && current && name && name !== current.name) {
if (this.editTabLayout({ type: 'renameGroup', groupId, name }, `group:${groupId}`)) return;
}
this._tabFocusIdentity = `group:${groupId}`;
this._tabRefocusAfterEdit = true;
this._fullRenderSessionTabs();
};
this._activeRename = handle;
input.addEventListener('keydown', (e) => {
e.stopPropagation();
if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Enter') {
e.preventDefault();
settle(true);
} else if (e.key === 'Escape') {
e.preventDefault();
settle(false);
}
});
input.addEventListener('blur', () => settle(true));
input.focus();
input.select();
return true;
}
// ─── Pointer drag in the grouped rail ──────────────────────────────
/**
* Drag rows between groups and reorder groups, in the GROUPED rail only.
* Pointer Events (mouse and pen; touch keeps scrolling the rail), bound once
* on the container, which survives every re-render. The flat rail and the
* header strip keep the HTML5 drag in setupTabDragHandlers() untouched.
* Keyboard equivalents live in the row and group menus.
*/
_bindTabLayoutPointerDrag(container) {
if (!container || container._tabLayoutDragBound) return;
container._tabLayoutDragBound = true;
container.addEventListener('pointerdown', (e) => this._onTabLayoutPointerDown(e, container));
container.addEventListener('pointermove', (e) => this._onTabLayoutPointerMove(e, container));
container.addEventListener('pointerup', (e) => this._finishTabLayoutPointerDrag(e, container));
container.addEventListener('pointercancel', () => this._cancelTabLayoutPointerDrag(container));
container.addEventListener('lostpointercapture', () => this._cancelTabLayoutPointerDrag(container));
}
_onTabLayoutPointerDown(e, container) {
if (e.button !== 0 || e.pointerType === 'touch' || !container.classList.contains('session-tabs--grouped')) return;
if (this._inlineRenameActive || !this._tabLayoutEditable()) return;
// Controls keep their own click; only the row body or the header drags.
if (e.target.closest('.tab-actions, .tab-badge, .tab-layout-group-menu, button, input, [onclick*="stopPropagation"]')) return;
const header = e.target.closest('[data-tab-group-header]');
const row = header ? null : e.target.closest('.session-tab');
let source = null;
if (header) source = { type: 'group', groupId: header.dataset.tabGroupHeader };
else if (row?.dataset.webviewId) source = { type: 'ref', ref: { kind: 'webview', id: row.dataset.webviewId } };
else if (row?.dataset.id) source = { type: 'ref', ref: { kind: 'session', id: row.dataset.id } };
if (!source) return;
this._tabLayoutDrag = { pointerId: e.pointerId, x: e.clientX, y: e.clientY, source, origin: header || row, active: false, target: null };
}
/** What a pointer at (x, y) would drop onto, from the rendered rail. */
_tabLayoutDropTarget(x, y, container) {
const hit = document.elementFromPoint(x, y);
if (!hit || !container.contains(hit)) return null;
const row = hit.closest('.session-tab');
const section = hit.closest('.tab-layout-group');
const sectionGroup = section ? section.dataset.tabGroupId || null : undefined;
// A sorted rail paints its own order, so a row can only be dropped INTO a
// group, never between two rows.
if (row && section && !this.isTabRailSorted()) {
const ref = row.dataset.webviewId ? { kind: 'webview', id: row.dataset.webviewId } : { kind: 'session', id: row.dataset.id };
const rect = row.getBoundingClientRect();
return { type: 'ref', ref, groupId: sectionGroup, placement: y >= rect.top + rect.height / 2 ? 'after' : 'before', element: row };
}
if (sectionGroup === undefined) return null;
const element = section.querySelector(':scope > .tab-layout-group-header');
return sectionGroup === null ? { type: 'ungrouped', element } : { type: 'group', groupId: sectionGroup, element };
}
_clearTabLayoutDropMarks(container) {
container.querySelectorAll('.tab-layout-drop-before, .tab-layout-drop-after, .tab-layout-drop-into').forEach((el) =>
el.classList.remove('tab-layout-drop-before', 'tab-layout-drop-after', 'tab-layout-drop-into')
);
}
_onTabLayoutPointerMove(e, container) {
const drag = this._tabLayoutDrag;
if (!drag || drag.pointerId !== e.pointerId) return;
if (!drag.active) {
if (Math.hypot(e.clientX - drag.x, e.clientY - drag.y) < 6) return;
drag.active = true;
drag.origin.classList.add('tab-layout-dragging');
container.classList.add('tab-layout-drag-active');
this.closeTabGroupMenu();
this.closeTabRailActionMenu?.();
try {
container.setPointerCapture(e.pointerId);
} catch {}
this._tabLayoutDragKeydown = (keyEvent) => {
if (keyEvent.key !== 'Escape') return;
keyEvent.preventDefault();
keyEvent.stopImmediatePropagation();
this._cancelTabLayoutPointerDrag(container);
};
document.addEventListener('keydown', this._tabLayoutDragKeydown, true);
}
e.preventDefault();
const target = this._tabLayoutDropTarget(e.clientX, e.clientY, container);
this._clearTabLayoutDropMarks(container);
drag.target = target;
if (!target?.element) return;
const cls = target.type === 'ref' && drag.source.type === 'ref' ? `tab-layout-drop-${target.placement}` : 'tab-layout-drop-into';
target.element.classList.add(cls);
}
_cancelTabLayoutPointerDrag(container) {
const drag = this._tabLayoutDrag;
if (!drag) return;
this._tabLayoutDrag = null;
drag.origin?.classList.remove('tab-layout-dragging');
container?.classList.remove('tab-layout-drag-active');
if (container) this._clearTabLayoutDropMarks(container);
if (this._tabLayoutDragKeydown) document.removeEventListener('keydown', this._tabLayoutDragKeydown, true);
this._tabLayoutDragKeydown = null;
if (drag.active) {
// The click that ends a drag must not also select the row or toggle the header.
const swallow = (clickEvent) => {
clickEvent.stopPropagation();
clickEvent.preventDefault();
};
window.addEventListener('click', swallow, { capture: true, once: true });
setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0);
}
}
_finishTabLayoutPointerDrag(e, container) {
const drag = this._tabLayoutDrag;
if (!drag || drag.pointerId !== e.pointerId) return;
const target = drag.active ? this._tabLayoutDropTarget(e.clientX, e.clientY, container) || drag.target : null;
this._cancelTabLayoutPointerDrag(container);
if (!target) return;
const operation = window.CodemanTabLayout.dropOperation(this.tabLayout, drag.source, target, this._tabLayoutParents());
if (!operation) return;
const identity = drag.source.type === 'group' ? `group:${drag.source.groupId}` : `${drag.source.ref.kind}:${drag.source.ref.id}`;
this.editTabLayout(operation, identity);
}
// ─── Unsaved edits across a reload ─────────────────────────────────
/**
* The page is going away with edits not yet confirmed: send them with a
* keepalive PUT (it outlives the page) AND keep a copy in sessionStorage. If
* the keepalive lands, the copy replays to no change after reload; if it lost
* a race, the copy is rebased onto the fresh layout and saved properly.
*/
_persistPendingTabLayoutEdits() {
const editor = this._tabLayoutEditor;
const operations = editor?.pendingOperations?.() || [];
if (!operations.length) return false;
try {
sessionStorage.setItem('codeman:tab-layout-pending', JSON.stringify({ operations }));
} catch {}
try {
const layout = editor.getLayout();
void fetch('/api/tab-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ baseVersion: editor.baseVersion(), layout: { ...layout, updatedAt: layout.updatedAt || new Date().toISOString() } }),
keepalive: true,
}).catch(() => {});
} catch {}
return true;
}
_restorePendingTabLayoutEdits() {
let operations;
try {
const raw = sessionStorage.getItem('codeman:tab-layout-pending');
if (!raw) return false;
sessionStorage.removeItem('codeman:tab-layout-pending');
operations = JSON.parse(raw)?.operations;
} catch {
return false;
}
if (!Array.isArray(operations) || !operations.length || !this.tabLayout || !window.CodemanTabLayout) return false;
return this._ensureTabLayoutEditor().restore(operations);
}
// Set up drag-and-drop handlers on tab elements
setupTabDragHandlers() {
const container = this.$('sessionTabs');
@@ -6557,7 +7149,9 @@ class CodemanApp {
* each group on its own (`putLegacyOrder`), so nothing moves there, no
* session:orderChanged comes back, and this client would keep a swapped
* sessionOrder (and Alt+N targets) that no other device shares. Same reason
* drag is off in the grouped rail. Any other layout: always allowed.
* the HTML5 flat-order drag is off in the grouped rail (its own pointer drag
* and the row menu's moves go through moveRef instead, which can cross a
* group). Any other layout: always allowed.
*/
_canSwapActiveTabWith(neighbourId) {
const projection = this._projectTabGroups();