feat(header): resizable toolbar divider that collapses the usage readings as it narrows

This commit is contained in:
Devvyn committed 2026-10-23 19:01:06 +08:00
1 parent 002de32a08
commit fa2d75c951
9 files changed
+467 -1

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
'aicodeman': minor
---
Drag the line between the session tabs and the header toolbar to resize the toolbar. Dragging it right narrows the toolbar, which then wraps onto a second line instead of squeezing out the tabs, and the usage readings shed their labels, then their provider names, then their percentages as it narrows; double-click, Home or Escape resets it. Arrow keys resize it from the keyboard, and the width is remembered on the device.
+1
View File
@@ -26,6 +26,7 @@ export const BROWSER_TEST_GLOBS = [
'test/tab-rail-search.browser.test.ts',
'test/tab-focus.browser.test.ts',
'test/session-sidebar-ux.browser.test.ts',
'test/header-divider.browser.test.ts',
'test/session-options-responsive.browser.test.ts',
'test/inline-rename.test.ts',
'test/opencode-resize.test.ts',
+2
View File
@@ -120,6 +120,7 @@ run('minify sanitize-html.js', 'npx esbuild dist/web/public/sanitize-html.js --m
run('minify tab-layout-browser.js', 'npx esbuild dist/web/public/tab-layout-browser.js --minify --outfile=dist/web/public/tab-layout-browser.js --allow-overwrite');
run('minify app.js', 'npx esbuild dist/web/public/app.js --minify --outfile=dist/web/public/app.js --allow-overwrite');
run('minify tab-rail-resize.js', 'npx esbuild dist/web/public/tab-rail-resize.js --minify --outfile=dist/web/public/tab-rail-resize.js --allow-overwrite');
run('minify header-divider.js', 'npx esbuild dist/web/public/header-divider.js --minify --outfile=dist/web/public/header-divider.js --allow-overwrite');
run('minify terminal-ui.js', 'npx esbuild dist/web/public/terminal-ui.js --minify --outfile=dist/web/public/terminal-ui.js --allow-overwrite');
run('minify respawn-ui.js', 'npx esbuild dist/web/public/respawn-ui.js --minify --outfile=dist/web/public/respawn-ui.js --allow-overwrite');
run('minify ralph-panel.js', 'npx esbuild dist/web/public/ralph-panel.js --minify --outfile=dist/web/public/ralph-panel.js --allow-overwrite');
@@ -149,6 +150,7 @@ console.log('\n[build] content-hash cache busting');
'tab-layout-browser.js',
'app.js',
'tab-rail-resize.js',
'header-divider.js',
'terminal-ui.js',
'respawn-ui.js',
'ralph-panel.js',
+3 -1
View File
@@ -3680,7 +3680,9 @@ class CodemanApp {
seg('mo', pct(usage?.monthly), false),
].filter(Boolean);
if (!windows.length) return '';
const label = labelled ? `<span class="pu-provider">${provider}</span>` : '';
// data-short is what the narrowest header densities show instead of the name (header-divider.js).
const short = { Claude: 'CL', Codex: 'CX', Copilot: 'CP' }[provider] ?? provider.slice(0, 2).toUpperCase();
const label = labelled ? `<span data-short="${short}" class="pu-provider">${provider}</span>` : '';
return `<span class="pu-row">${label}<span class="pu-windows">${windows.join('<span class="pu-sep">·</span>')}</span></span>`;
};
const rows = [row('Claude', data, true), row('Codex', data.codex, false), row('Copilot', data.copilot, false)].filter(
+160
View File
@@ -0,0 +1,160 @@
/**
* @fileoverview A draggable divider on the left edge of the header's right-hand toolbar.
*
* Dragging it left gives the toolbar (stats, plan usage, buttons) more room; dragging it right narrows the
* toolbar, which then wraps onto a second line instead of squeezing the session tabs out. The width is a
* device-local convenience kept in localStorage; double-click or Home resets it. The handle is absolutely
* positioned inside #headerRight, so it takes no layout room and is simply hidden where the tabs are not in
* the header (sidebar, vertical rail, phones).
*
* @loadorder after app.js; self-contained, no CodemanApp dependency.
*/
(function () {
const STORAGE_KEY = 'codeman-header-right-width';
const MIN_WIDTH = 160;
const MIN_TABS_ROOM = 240;
const KEY_STEP = 16;
/** Keep a requested toolbar width between the minimum and what leaves the tabs some room. */
function clampWidth(width, headerWidth, brandWidth) {
const max = Math.max(MIN_WIDTH, headerWidth - brandWidth - MIN_TABS_ROOM);
return Math.round(Math.min(max, Math.max(MIN_WIDTH, width)));
}
/**
* How much of the usage readings to show for a toolbar this wide. The narrower the toolbar, the more of
* the labels go: window labels first, then provider names (shortened), then the percentages (the rings
* stay, and the chip's tooltip keeps the numbers).
*/
function densityFor(width) {
if (width >= 560) return '';
if (width >= 400) return 'tight';
if (width >= 280) return 'dense';
return 'tiny';
}
function readStored() {
try {
const value = Number(localStorage.getItem(STORAGE_KEY));
return Number.isFinite(value) && value > 0 ? value : null;
} catch {
return null;
}
}
function writeStored(width) {
try {
if (width === null) localStorage.removeItem(STORAGE_KEY);
else localStorage.setItem(STORAGE_KEY, String(width));
} catch {
/* storage blocked: the width lasts until the page reloads */
}
}
function init() {
const header = document.querySelector('.header');
const right = document.getElementById('headerRight');
if (!header || !right || right.querySelector('.header-divider')) return;
const brand = header.querySelector('.header-brand');
const root = document.documentElement;
const handle = document.createElement('div');
handle.className = 'header-divider';
handle.setAttribute('role', 'separator');
handle.setAttribute('aria-orientation', 'vertical');
handle.setAttribute('aria-label', 'Resize the toolbar (double-click to reset)');
handle.tabIndex = 0;
right.insertBefore(handle, right.firstChild);
const bounds = () => ({ header: header.clientWidth, brand: brand ? brand.offsetWidth : 0 });
const current = () => right.getBoundingClientRect().width;
/** The narrowest the toolbar can be without a reading poking out past its left edge (the divider). */
function contentMinimum() {
const style = getComputedStyle(right);
const frame = parseFloat(style.paddingLeft) + parseFloat(style.paddingRight) + parseFloat(style.borderLeftWidth);
let widest = 0;
for (const child of right.children) {
if (child === handle || child.offsetParent === null) continue;
widest = Math.max(widest, child.getBoundingClientRect().width, child.scrollWidth);
}
return Math.ceil(widest + frame);
}
function setDensity(width) {
const density = densityFor(width);
if (density) root.setAttribute('data-header-density', density);
else root.removeAttribute('data-header-density');
}
function apply(width, persist) {
if (width === null) {
root.style.removeProperty('--header-right-width');
root.removeAttribute('data-header-right-width');
root.removeAttribute('data-header-density');
handle.removeAttribute('aria-valuenow');
if (persist) writeStored(null);
return;
}
const { header: h, brand: b } = bounds();
let clamped = clampWidth(width, h, b);
root.setAttribute('data-header-right-width', 'set');
// A narrower toolbar sheds labels, which shrinks the readings, which lowers the minimum: settle
// on a width no reading overflows at the density that width gets.
for (let i = 0; i < 3; i++) {
root.style.setProperty('--header-right-width', clamped + 'px');
setDensity(clamped);
const floor = contentMinimum();
if (clamped >= floor) break;
clamped = floor;
}
handle.setAttribute('aria-valuenow', String(clamped));
if (persist) writeStored(clamped);
}
handle.addEventListener('pointerdown', (event) => {
if (event.button !== 0) return;
event.preventDefault();
handle.setPointerCapture?.(event.pointerId);
document.body.classList.add('header-divider-dragging');
const onMove = (e) => apply(header.getBoundingClientRect().right - e.clientX - 12, false);
const onUp = () => {
handle.removeEventListener('pointermove', onMove);
handle.removeEventListener('pointerup', onUp);
handle.removeEventListener('pointercancel', onUp);
document.body.classList.remove('header-divider-dragging');
const width = Number.parseFloat(root.style.getPropertyValue('--header-right-width'));
if (Number.isFinite(width)) writeStored(width);
};
handle.addEventListener('pointermove', onMove);
handle.addEventListener('pointerup', onUp);
handle.addEventListener('pointercancel', onUp);
});
handle.addEventListener('dblclick', () => apply(null, true));
handle.addEventListener('keydown', (event) => {
if (event.key === 'Home' || event.key === 'Escape') {
apply(null, true);
} else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
const step = event.key === 'ArrowLeft' ? KEY_STEP : -KEY_STEP;
apply(current() + step, true);
} else {
return;
}
event.preventDefault();
});
window.addEventListener('resize', () => {
const width = Number.parseFloat(root.style.getPropertyValue('--header-right-width'));
if (Number.isFinite(width)) apply(width, false);
});
const stored = readStored();
if (stored !== null) apply(stored, false);
}
window.CodemanHeaderDivider = { clampWidth, densityFor, MIN_WIDTH, MIN_TABS_ROOM };
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
else init();
})();
+1
View File
@@ -4345,6 +4345,7 @@
<script defer src="tab-layout-browser.js"></script>
<script defer src="app.js"></script>
<script defer src="tab-rail-resize.js"></script>
<script defer src="header-divider.js"></script>
<script defer src="terminal-ui.js"></script>
<script defer src="terminal-tile.js"></script>
<script defer src="terminal-split.js"></script>
+91
View File
@@ -2249,6 +2249,97 @@ html[data-tab-orientation='vertical'].tab-rail-compact
margin-left: auto;
padding-left: 0.75rem;
border-left: 1px solid var(--glass-border);
position: relative;
}
/* Draggable edge of the toolbar (header-divider.js). Absolute, so it takes no layout room and the
existing border-left stays the visible line. */
.header-divider {
position: absolute;
top: 0;
bottom: 0;
left: -6px;
width: 12px;
cursor: col-resize;
touch-action: none;
z-index: 2;
}
.header-divider:hover,
.header-divider:focus-visible {
background: color-mix(in srgb, var(--accent) 24%, transparent);
outline: none;
}
.header-divider:focus-visible {
box-shadow: inset 0 0 0 2px var(--accent);
}
/* A width the user chose: the toolbar keeps it and wraps onto a second line when its content is wider. */
html[data-header-right-width]:not([data-tab-orientation='vertical']):not([data-session-list='sidebar'])
body:not(.solo-mode)
.header-right {
flex: 0 0 var(--header-right-width);
width: var(--header-right-width);
flex-wrap: wrap;
justify-content: flex-end;
align-content: center;
row-gap: 0.25rem;
min-height: var(--header-height);
}
/* The narrower the toolbar, the less each usage reading shows (data-header-density, header-divider.js):
tight drops the window and CPU/MEM labels, dense shortens the provider names, tiny keeps only the rings.
The same rules apply under every header-stats style. */
html[data-header-density] .header-system-stats .stat-label,
html[data-header-density] .header-plan-usage .pu-label {
display: none;
}
html[data-header-density] .header-system-stats,
html[data-header-density] .header-plan-usage {
gap: 8px;
padding: 0 8px;
}
html[data-header-density='dense'] .header-plan-usage .pu-provider,
html[data-header-density='tiny'] .header-plan-usage .pu-provider {
font-size: 0;
}
html[data-header-density='dense'] .header-plan-usage .pu-provider::after,
html[data-header-density='tiny'] .header-plan-usage .pu-provider::after {
content: attr(data-short);
font-size: 0.6rem;
}
html[data-header-density='tiny'] .header-system-stats .stat-value,
html[data-header-density='tiny'] .header-plan-usage .pu-val {
display: none;
}
body.header-divider-dragging,
body.header-divider-dragging * {
cursor: col-resize !important;
user-select: none !important;
}
/* Only where the tabs share the header with the toolbar. */
html[data-tab-orientation='vertical'] .header-divider,
html[data-session-list='sidebar'] .header-divider,
body.solo-mode .header-divider {
display: none;
}
@media (max-width: 768px) {
.header-divider {
display: none;
}
html[data-header-right-width] .header-right {
flex: 0 1 auto;
width: auto;
}
}
/* Connection Indicator */
+130
View File
@@ -0,0 +1,130 @@
/** Real Chromium: dragging the header divider resizes the toolbar and wraps it onto a second line. */
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { chromium, type Browser, type Page } from 'playwright';
const dir = resolve(import.meta.dirname, '../src/web/public');
const styles = readFileSync(resolve(dir, 'styles.css'), 'utf8');
const controller = readFileSync(resolve(dir, 'header-divider.js'), 'utf8');
const page = (root = 'data-tab-orientation="horizontal" data-session-list="header"') => `<!doctype html>
<html ${root}><head><style>${styles}</style></head><body>
<div class="app"><header class="header">
<div class="header-brand"><span class="logo">Codeman</span></div>
<div class="session-tabs-host"><div class="session-tabs" id="sessionTabs"></div></div>
<div class="header-right" id="headerRight">
<div class="header-plan-usage" style="width:230px;flex:none">usage</div>
<div class="header-system-stats" style="width:200px;flex:none">stats</div>
<button class="btn-icon-header">a</button><button class="btn-icon-header">b</button>
</div>
</header></div>
</body></html>`;
describe('header divider (real Chromium)', () => {
let browser: Browser;
let p: Page;
beforeAll(async () => {
browser = await chromium.launch();
});
afterAll(async () => {
await browser.close();
});
async function open(html: string) {
p = await browser.newPage({ viewport: { width: 1400, height: 600 } });
await p.setContent(html);
await p.addScriptTag({ content: controller });
}
const box = (sel: string) => p.locator(sel).evaluate((el) => el.getBoundingClientRect().toJSON());
it('narrows the toolbar and wraps it onto a second line when dragged right, and resets on double-click', async () => {
await open(page());
const before = await box('#headerRight');
const handle = await box('.header-divider');
const y = handle.top + handle.height / 2;
await p.mouse.move(handle.left + 6, y);
await p.mouse.down();
await p.mouse.move(handle.left + 6 + 330, y, { steps: 6 });
await p.mouse.up();
const after = await box('#headerRight');
expect(after.width).toBeLessThan(before.width - 250);
expect(after.height).toBeGreaterThan(before.height + 10);
// setContent gives an opaque origin: storage is blocked, and the drag must still work.
expect(await p.evaluate(() => document.documentElement.style.getPropertyValue('--header-right-width'))).not.toBe(
''
);
const tabs = await box('.session-tabs-host');
expect(tabs.width).toBeGreaterThan(before.width);
await p.locator('.header-divider').dblclick();
const reset = await box('#headerRight');
expect(Math.abs(reset.width - before.width)).toBeLessThan(2);
expect(await p.evaluate(() => document.documentElement.style.getPropertyValue('--header-right-width'))).toBe('');
await p.close();
});
it('drops usage labels, then provider names, then percentages as the toolbar narrows', async () => {
const chip =
'<div class="header-plan-usage" id="planUsageChip"><span class="pu-row"><span data-short="CL" class="pu-provider">Claude</span>' +
'<span class="pu-windows"><span class="pu-win"><span class="pu-ring"></span><span class="pu-label">5h</span><span class="pu-val">49%</span></span></span></span></div>';
await open(page('data-header-stats="compact" data-tab-orientation="horizontal" data-session-list="header"'));
await p.evaluate((html) => document.getElementById('headerRight')!.insertAdjacentHTML('beforeend', html), chip);
const visible = (sel: string) => p.locator(sel).isVisible();
expect(await visible('.pu-label')).toBe(true);
const sizes: Array<[number, string]> = [
[450, 'tight'],
[330, 'dense'],
[200, 'tiny'],
];
for (const [width, density] of sizes) {
const handle = await box('.header-divider');
const header = await box('.header');
await p.mouse.move(handle.left + 6, handle.top + handle.height / 2);
await p.mouse.down();
await p.mouse.move(header.right - width - 12, handle.top + handle.height / 2, { steps: 5 });
await p.mouse.up();
expect(await p.evaluate(() => document.documentElement.dataset.headerDensity)).toBe(density);
}
expect(await visible('.pu-label')).toBe(false);
expect(await visible('.pu-val')).toBe(false);
expect(await p.locator('.pu-provider').evaluate((el) => getComputedStyle(el, '::after').content)).toBe('"CL"');
await p.close();
});
it('stops the divider at the widest reading so nothing pokes out past it', async () => {
await open(page());
const handle = await box('.header-divider');
const header = await box('.header');
await p.mouse.move(handle.left + 6, handle.top + handle.height / 2);
await p.mouse.down();
await p.mouse.move(header.right - 20, handle.top + handle.height / 2, { steps: 8 });
await p.mouse.up();
const right = await box('#headerRight');
const edge = right.left + 1;
const lefts = await p
.locator('#headerRight > :not(.header-divider)')
.evaluateAll((els) => els.map((el) => el.getBoundingClientRect().left));
for (const left of lefts) expect(left).toBeGreaterThanOrEqual(edge);
await p.close();
});
it('resizes from the keyboard', async () => {
await open(page());
const before = await box('#headerRight');
await p.locator('.header-divider').focus();
await p.keyboard.press('ArrowRight');
await p.keyboard.press('ArrowRight');
const after = await box('#headerRight');
expect(after.width).toBeLessThan(before.width - 20);
await p.keyboard.press('Home');
expect(Math.abs((await box('#headerRight')).width - before.width)).toBeLessThan(2);
await p.close();
});
it('is hidden when the tabs live in the sidebar', async () => {
await open(page('data-tab-orientation="horizontal" data-session-list="sidebar"'));
expect(await p.locator('.header-divider').isVisible()).toBe(false);
await p.close();
});
});
+74
View File
@@ -0,0 +1,74 @@
/**
* @fileoverview The draggable divider at the left edge of the header toolbar: the width clamp keeps the tabs
* some room, the controller is wired into the page and build, and the stored width is device-local.
*/
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
const publicDir = resolve(import.meta.dirname, '../src/web/public');
const read = (name: string) => readFileSync(resolve(publicDir, name), 'utf8');
const buildJs = readFileSync(resolve(import.meta.dirname, '../scripts/build.mjs'), 'utf8');
function load() {
const window: Record<string, unknown> = {};
const context = vm.createContext({
window,
document: { readyState: 'loading', addEventListener: () => {}, querySelector: () => null },
localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },
});
vm.runInContext(read('header-divider.js'), context, { filename: 'header-divider.js' });
return window.CodemanHeaderDivider as {
clampWidth: (w: number, header: number, brand: number) => number;
densityFor: (w: number) => string;
MIN_WIDTH: number;
MIN_TABS_ROOM: number;
};
}
describe('header divider', () => {
it('clamps the toolbar between its minimum and what leaves the tabs room', () => {
const { clampWidth, MIN_WIDTH, MIN_TABS_ROOM } = load();
expect(clampWidth(10, 1600, 120)).toBe(MIN_WIDTH);
expect(clampWidth(5000, 1600, 120)).toBe(1600 - 120 - MIN_TABS_ROOM);
expect(clampWidth(420.4, 1600, 120)).toBe(420);
});
it('shows less of the usage readings the narrower the toolbar gets', () => {
const { densityFor } = load();
expect([700, 560, 559, 400, 399, 280, 279, 160].map(densityFor)).toEqual([
'',
'',
'tight',
'tight',
'dense',
'dense',
'tiny',
'tiny',
]);
});
it('never goes below the minimum even in a header too narrow for the tabs room', () => {
const { clampWidth, MIN_WIDTH } = load();
expect(clampWidth(400, 300, 100)).toBe(MIN_WIDTH);
});
it('is wired into the page and the build, and hides where the tabs are not in the header', () => {
expect(read('index.html')).toContain('<script defer src="header-divider.js"></script>');
expect(buildJs).toContain("run('minify header-divider.js'");
expect(buildJs).toMatch(/HASHABLE[\s\S]{0,1500}'header-divider\.js'/);
const css = read('styles.css');
expect(css).toContain('.header-divider');
expect(css).toMatch(/data-session-list='sidebar'\] \.header-divider/);
expect(css).toMatch(/data-tab-orientation='vertical'\] \.header-divider/);
});
it('keeps the width on the device only and offers a keyboard reset', () => {
const js = read('header-divider.js');
expect(js).toContain('localStorage');
expect(js).not.toContain('/api/settings');
expect(js).toMatch(/key === 'Home'/);
expect(js).toContain("addEventListener('dblclick'");
});
});