Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): keep split-view tab strips aligned after restore (PRD-8161) (#3694)
Andrew Mikofalvyf4aa8f215ee0
diff --git a/.changeset/split-header-groups-follow-resolved-layout.md b/.changeset/split-header-groups-follow-resolved-layout.mdnew file mode 100644index 000000000..6d068acdd--- /dev/null+++ b/.changeset/split-header-groups-follow-resolved-layout.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Reopening a window with side by side editor panes no longer leaves the tab strips sitting off to one side of the panes they label. Panes have a minimum width, so a restored layout that asks for narrower panes than that gets them widened back to it, with the space reclaimed from whichever panes have room to give it up. The tab strips above kept the saved proportions instead, so with four panes open a strip could sit most of a tab's width away from its own pane. They now follow the widths the panes end up at, so they line up as soon as the window opens rather than only after the next thing that resizes the panes.diff --git a/packages/app/src/components/EditorWorkspace.dom.test.tsx b/packages/app/src/components/EditorWorkspace.dom.test.tsxindex b0fdf80f3..9ed8f53d3 100644--- a/packages/app/src/components/EditorWorkspace.dom.test.tsx+++ b/packages/app/src/components/EditorWorkspace.dom.test.tsx@@ -422,6 +422,74 @@ describe('EditorWorkspace', () => {);});+ test('adopts the resolved pane layout on a header canvas that mounts after it', () => {+ // The real header canvas is portaled into the app header, so it can mount a+ // commit after the panel group reports its layout. A restored session+ // reports once, on mount: if that report is lost the tab groups keep the+ // persisted percentages while the panes render the layout the pane minimum+ // forced, and nothing ever reconciles them.+ const view = render(+ <EditorWorkspace+ renderHeader={() => <header data-testid="main-editor-header" />}+ renderPane={({ pane }) => <div data-testid={`pane-body-${pane.id}`} />}+ />,+ );+ expect(view.container.querySelector('[data-editor-pane-tab-group]')).toBeNull();++ // What the panel group resolves once MIN_EDITOR_PANE_WIDTH raises pane-b:+ // not the 60/40 the panes carry as their persisted size.+ act(() => layoutChange?.({ 'editor-pane:pane-a': 45, 'editor-pane:pane-b': 55 }));++ view.rerender(+ <EditorWorkspace+ renderHeader={(tabs) => <header data-testid="main-editor-header">{tabs}</header>}+ renderPane={({ pane }) => <div data-testid={`pane-body-${pane.id}`} />}+ />,+ );++ const headerGroups = [+ ...view.container.querySelectorAll<HTMLElement>('[data-editor-pane-tab-group]'),+ ];+ expect(headerGroups).toHaveLength(2);+ expect(headerGroups[0]?.style.flexGrow).toBe('45');+ expect(headerGroups[1]?.style.flexGrow).toBe('55');+ });++ test('does not replay a resolved layout onto a different pane set', () => {+ // The replay is keyed on the pane set it was resolved for. A layout the+ // group resolved for {pane-a, pane-b} describes nothing about a workspace+ // that now holds {pane-a, pane-c}, and replaying it would hold the+ // surviving strip at a share the panes no longer render — the mirror image+ // of the misalignment this fix removes. The mocked group does not report+ // again on re-render, which is what isolates the guard here.+ const workspace = () => (+ <EditorWorkspace+ renderHeader={(tabs) => <header data-testid="main-editor-header">{tabs}</header>}+ renderPane={({ pane }) => <div data-testid={`pane-body-${pane.id}`} />}+ />+ );+ const view = render(workspace());+ act(() => layoutChange?.({ 'editor-pane:pane-a': 45, 'editor-pane:pane-b': 55 }));+ expect(+ view.container.querySelector<HTMLElement>('[data-editor-pane-tab-group]')?.style.flexGrow,+ ).toBe('45');++ // pane-b is gone and pane-a carries a new size, so the stale 45 and the+ // value this pane set actually renders are distinguishable.+ panes = [+ { ...multiPaneFixture[0], size: 70 },+ { ...multiPaneFixture[1], id: 'pane-c', size: 30 },+ ];+ view.rerender(workspace());++ const groups = [+ ...view.container.querySelectorAll<HTMLElement>('[data-editor-pane-tab-group]'),+ ];+ expect(groups.map((group) => group.dataset.editorPaneTabGroup)).toEqual(['pane-a', 'pane-c']);+ expect(groups[0]?.style.flexGrow).toBe('70');+ expect(groups[1]?.style.flexGrow).toBe('30');+ });+test('omits the focused tab-strip accent in single-pane mode', () => {panes = [{diff --git a/packages/app/src/components/EditorWorkspace.tsx b/packages/app/src/components/EditorWorkspace.tsxindex 32bb30a0b..5718ad130 100644--- a/packages/app/src/components/EditorWorkspace.tsx+++ b/packages/app/src/components/EditorWorkspace.tsx@@ -105,6 +105,10 @@ function PaneStripDropTarget({data-editor-pane-tab-group={paneId}data-editor-pane-focused={isFocused || undefined}className="relative h-full min-w-0 shrink basis-0"+ // First-paint value only. `applyHeaderLayout` overwrites this with the+ // layout the panel group resolved, which is not what `size` describes+ // once a pane minimum is in play. Keep the prop: without it a group has+ // no width on any commit before the group has reported.style={{ flexGrow: size }}>{children}@@ -391,7 +395,15 @@ export function EditorWorkspace({);const [parkingHost, setParkingHost] = useState<HTMLElement | null>(null);const focusFrameRef = useRef<number | null>(null);- const headerCanvasRef = useRef<HTMLDivElement>(null);+ const [headerCanvas, setHeaderCanvas] = useState<HTMLDivElement | null>(null);+ /**+ * The last layout the pane group resolved, tagged with the pane set it was+ * resolved for — see `syncHeaderLayout`.+ */+ const resolvedPaneLayoutRef = useRef<{+ paneKey: string;+ layout: Record<string, number>;+ } | null>(null);const paneKey = panes.map((pane) => pane.id).join('\u0000');const savedLayout = Object.fromEntries(panes.map((pane) => [`editor-pane:${pane.id}`, pane.size]),@@ -416,6 +428,43 @@ export function EditorWorkspace({'--editor-workspace-min-width': `max(100%, ${panes.length * MIN_EDITOR_PANE_WIDTH}px)`,} as CSSProperties;+ function applyHeaderLayout(layout: Record<string, number>) {+ const groups = headerCanvas?.querySelectorAll<HTMLElement>('[data-editor-pane-tab-group]');+ groups?.forEach((group) => {+ const paneId = group.dataset.editorPaneTabGroup;+ const size = paneId ? layout[`editor-pane:${paneId}`] : undefined;+ if (size !== undefined) group.style.setProperty('flex-grow', String(size));+ });+ }++ // The panel group resolves a layout the persisted percentages do not+ // describe: any pane whose share falls under MIN_EDITOR_PANE_WIDTH is raised+ // to it, and the shortfall is reclaimed from the panes in index order, the+ // first one with room to give absorbing what it can before the next, until+ // the shortfall is covered. The tab groups carry no minimum of their own, so+ // rendering them from `pane.size` puts them on different geometry than the+ // panes they label.+ //+ // Re-applying after every commit is what makes them agree. The header canvas+ // is portaled into the app header and can mount a commit AFTER the panel+ // group reports its layout, and for a restored session that first report is+ // the only one — a write aimed at a canvas that does not exist yet is lost+ // with nothing to trigger a retry, which is how a reloaded four-pane split+ // came back with its tab strips ~92px off its panes. Holding the canvas as+ // state rather than a ref is what guarantees the retry: whatever commit+ // mounts it re-renders this component, so the replay cannot depend on the+ // caller's `renderHeader` happening to change identity at the same time.+ //+ // Splitting or closing a pane re-renders the groups from `pane.size` too, but+ // the resolved layout for the previous pane set says nothing about the new+ // one, so it is only replayed while the pane set is unchanged. `key={paneKey}`+ // on the group means a changed pane set remounts it and it reports again,+ // which refreshes this before the effect runs.+ useLayoutEffect(() => {+ const resolved = resolvedPaneLayoutRef.current;+ if (resolved?.paneKey === paneKey) applyHeaderLayout(resolved.layout);+ });+useEffect(() => {return () => {if (focusFrameRef.current !== null) cancelAnimationFrame(focusFrameRef.current);@@ -581,21 +630,15 @@ export function EditorWorkspace({}function syncHeaderScroll(event: UIEvent<HTMLDivElement>) {- headerCanvasRef.current?.style.setProperty(+ headerCanvas?.style.setProperty('transform',`translateX(-${event.currentTarget.scrollLeft}px)`,);}function syncHeaderLayout(layout: Record<string, number>) {- const groups = headerCanvasRef.current?.querySelectorAll<HTMLElement>(- '[data-editor-pane-tab-group]',- );- groups?.forEach((group) => {- const paneId = group.dataset.editorPaneTabGroup;- const size = paneId ? layout[`editor-pane:${paneId}`] : undefined;- if (size !== undefined) group.style.setProperty('flex-grow', String(size));- });+ resolvedPaneLayoutRef.current = { paneKey, layout };+ applyHeaderLayout(layout);}function paneLabel(paneId: string): string {@@ -668,7 +711,7 @@ export function EditorWorkspace({const headerTabs = (<div data-editor-header-tab-groups="" className="h-full min-w-0 flex-1 overflow-hidden"><div- ref={headerCanvasRef}+ ref={setHeaderCanvas}data-editor-header-tab-canvas=""className="flex h-full min-w-(--editor-workspace-min-width)"style={canvasStyle}diff --git a/packages/app/tests/stress/editor-split-view.e2e.ts b/packages/app/tests/stress/editor-split-view.e2e.tsindex de4f21a67..595ac91d6 100644--- a/packages/app/tests/stress/editor-split-view.e2e.ts+++ b/packages/app/tests/stress/editor-split-view.e2e.ts@@ -36,36 +36,155 @@ async function paneWidths(page: Page): Promise<number[]> {);}+/**+ * Full geometry behind the alignment check. The assertion below reports a+ * single worst-case number, and a bare "91.71875" on a CI machine nobody can+ * attach to says nothing about which pane drifted, in which direction, or+ * whether the two canvases were even the same width. Sampling the whole picture+ * and printing it on failure is what makes a headless-only misalignment+ * diagnosable from the log alone.+ */+interface HeaderAlignmentSample {+ worst: number;+ worstLabel: string;+ scrollLeft: number;+ headerCanvas: { left: number; width: number; transform: string; minWidth: string };+ workspaceCanvas: { left: number; width: number; minWidth: string };+ headerHost: { left: number; width: number; cssVar: string };+ groups: Array<{+ paneId: string;+ groupLeft: number;+ groupRight: number;+ groupWidth: number;+ groupFlexGrow: string;+ paneLeft: number;+ paneRight: number;+ paneWidth: number;+ dLeft: number;+ dRight: number;+ dWidth: number;+ }>;+}++async function sampleHeaderAlignment(page: Page): Promise<HeaderAlignmentSample> {+ return page.evaluate(() => {+ const round = (value: number) => Math.round(value * 1000) / 1000;+ const groups = Array.from(+ document.querySelectorAll<HTMLElement>('[data-editor-pane-tab-group]'),+ );+ const workspace = document.querySelector<HTMLElement>('[data-editor-workspace]');+ const headerCanvasEl = document.querySelector<HTMLElement>('[data-editor-header-tab-canvas]');+ const workspaceCanvasEl = document.querySelector<HTMLElement>('[data-editor-workspace-canvas]');+ const headerHostEl = document.querySelector<HTMLElement>('[data-editor-header-tabs]');++ const rows = groups.map((group) => {+ const paneId =+ group+ .querySelector<HTMLElement>('[data-editor-pane-tabs]')+ ?.getAttribute('data-editor-pane-tabs') ?? '';+ const pane = paneId+ ? document.querySelector<HTMLElement>(`section[data-editor-pane-id="${paneId}"]`)+ : null;+ const groupRect = group.getBoundingClientRect();+ const paneRect = pane?.getBoundingClientRect();+ return {+ paneId,+ groupLeft: round(groupRect.left),+ groupRight: round(groupRect.right),+ groupWidth: round(groupRect.width),+ groupFlexGrow: getComputedStyle(group).flexGrow,+ paneLeft: round(paneRect?.left ?? Number.NaN),+ paneRight: round(paneRect?.right ?? Number.NaN),+ paneWidth: round(paneRect?.width ?? Number.NaN),+ dLeft: paneRect+ ? round(Math.abs(groupRect.left - paneRect.left))+ : Number.POSITIVE_INFINITY,+ dRight: paneRect+ ? round(Math.abs(groupRect.right - paneRect.right))+ : Number.POSITIVE_INFINITY,+ dWidth: paneRect+ ? round(Math.abs(groupRect.width - paneRect.width))+ : Number.POSITIVE_INFINITY,+ };+ });++ const tops = groups.map((group) => group.getBoundingClientRect().top);+ const topDelta = tops.length > 0 ? Math.max(...tops) - Math.min(...tops) : 0;++ // No groups at all is a regression, not alignment: every delta below is+ // missing, so `worst` would otherwise bottom out at 0 and report perfect+ // alignment on a header that stopped rendering or an attribute rename.+ let worst = groups.length === 0 ? Number.POSITIVE_INFINITY : round(topDelta);+ let worstLabel = groups.length === 0 ? 'noGroups' : 'topDelta';+ for (const row of rows) {+ for (const key of ['dLeft', 'dRight', 'dWidth'] as const) {+ if (row[key] > worst) {+ worst = row[key];+ worstLabel = `${key}@${row.paneId}`;+ }+ }+ }++ const measure = (element: HTMLElement | null) => ({+ left: round(element?.getBoundingClientRect().left ?? Number.NaN),+ width: round(element?.getBoundingClientRect().width ?? Number.NaN),+ });++ return {+ worst,+ worstLabel,+ scrollLeft: workspace?.scrollLeft ?? Number.NaN,+ headerCanvas: {+ ...measure(headerCanvasEl),+ transform: headerCanvasEl ? getComputedStyle(headerCanvasEl).transform : 'none',+ minWidth: headerCanvasEl ? getComputedStyle(headerCanvasEl).minWidth : '',+ },+ workspaceCanvas: {+ ...measure(workspaceCanvasEl),+ minWidth: workspaceCanvasEl ? getComputedStyle(workspaceCanvasEl).minWidth : '',+ },+ headerHost: {+ ...measure(headerHostEl),+ cssVar: headerHostEl+ ? getComputedStyle(headerHostEl).getPropertyValue('--editor-header-tabs-width')+ : '',+ },+ groups: rows,+ };+ });+}++/**+ * `JSON.stringify` renders every non-finite number as `null`, which is how the+ * sample's own sentinels get erased: a group with no pane at all and a+ * measurement that was simply unavailable print identically, and a header+ * canvas that never mounted logs as one carrying defaults — the exact failure+ * this assertion exists to catch, disguised as a healthy one.+ */+function jsonSafe(_key: string, value: unknown): unknown {+ return typeof value === 'number' && !Number.isFinite(value) ? String(value) : value;+}+async function expectHeaderGroupsAlignedWithPanes(page: Page): Promise<void> {- await expect- .poll(() =>- page.evaluate(() => {- const groups = Array.from(- document.querySelectorAll<HTMLElement>('[data-editor-pane-tab-group]'),- );- const groupTops = groups.map((group) => group.getBoundingClientRect().top);- const deltas = groups.flatMap((group) => {- const paneId = group- .querySelector<HTMLElement>('[data-editor-pane-tabs]')- ?.getAttribute('data-editor-pane-tabs');- const pane = paneId- ? document.querySelector<HTMLElement>(`section[data-editor-pane-id="${paneId}"]`)- : null;- if (!pane) return [Number.POSITIVE_INFINITY];-- const groupRect = group.getBoundingClientRect();- const paneRect = pane.getBoundingClientRect();- return [- Math.abs(groupRect.left - paneRect.left),- Math.abs(groupRect.right - paneRect.right),- Math.abs(groupRect.width - paneRect.width),- ];- });- const topDelta = groupTops.length > 0 ? Math.max(...groupTops) - Math.min(...groupTops) : 0;- return Math.max(topDelta, ...deltas);- }),- )- .toBeLessThanOrEqual(1);+ // Collected rather than reassigned: a sample that never completed has to be+ // distinguishable from one that did, and a `const` array also keeps the reads+ // below out of the narrowing hole a `let` assigned inside a callback falls in.+ const seen: HeaderAlignmentSample[] = [];+ try {+ await expect+ .poll(async () => {+ const next = await sampleHeaderAlignment(page);+ seen.push(next);+ return next.worst;+ })+ .toBeLessThanOrEqual(1);+ } catch (error) {+ const last = seen.at(-1);+ console.error(+ `[header-alignment] ${last ? JSON.stringify(last, jsonSafe) : '<no sample completed>'}`,+ );+ throw error;+ }}function tabInPane(page: Page, paneId: string, tabId: string): Locator {@@ -611,6 +730,87 @@ test.describe('vertical editor splits', () => {await expect(remainingTabs).toHaveAttribute('data-active-tab', 'true');await expect(remainingTabs.getByTestId('editor-new-tab-placeholder-button')).toBeVisible();});++ // A restored session can carry pane percentages that the pane minimum+ // overrides: the panel group raises every undersized pane to+ // MIN_EDITOR_PANE_WIDTH and reclaims the shortfall from the panes in index+ // order, so the geometry it renders is not the geometry the percentages+ // describe. The header tab groups mirror the same workspace and have no+ // minimum of their own, so they only stay aligned if they are driven by the+ // layout the panel group resolved rather than by the persisted percentages.+ test('restored pane sizes below the pane minimum keep header groups aligned', async ({+ page,+ api,+ }) => {+ const suffix = testId();+ const docs = ['alpha', 'bravo', 'charlie', 'delta'].map((label) => ({+ name: `minclamp-${label}-${suffix}`,+ markdown: `# ${label}-${suffix}\n\n${label} body`,+ }));+ await api.seedDocs(docs);+ await page.setViewportSize(WIDE_VIEWPORT);+ await page.goto(`/#/${docs[0].name}`);+ await waitForActiveProviderSynced(page);+ await expect(editorForDoc(page, docs[0].name)).toBeVisible();+ await expect(page.getByRole('button', { name: 'Share doc' })).toBeVisible();++ for (const doc of docs.slice(1)) {+ await page+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs]')+ .getByTestId('editor-new-tab-button')+ .click();+ await openDocFromSidebar(page, doc.name);+ const ids = await paneIds(page);+ const focusedPaneId = ids.at(-1);+ expect(focusedPaneId).toBeTruthy();+ if (!focusedPaneId) return;+ await dragTabToPaneEdge(+ page,+ tabInPane(page, focusedPaneId, doc.name),+ focusedPaneId,+ 'right',+ );+ await expect(paneTabs(page)).toHaveCount(ids.length + 1);+ }+ await expect(paneTabs(page)).toHaveCount(4);++ // Percentages a real drag can persist, and which the pane minimum then+ // overrides on the next restore: the last two panes resolve well under+ // MIN_EDITOR_PANE_WIDTH at this viewport.+ const skewed = [55, 20, 12.5, 12.5];+ await page.evaluate((sizes) => {+ const key = `ok-editor-tabs-v1:${window.location.origin}`;+ const raw = localStorage.getItem(key);+ if (!raw) throw new Error('no persisted editor session');+ const session = JSON.parse(raw) as { panes?: Array<{ size?: number }> };+ if (session.panes?.length !== sizes.length) {+ throw new Error(`expected ${sizes.length} persisted panes`);+ }+ session.panes.forEach((pane, index) => {+ pane.size = sizes[index];+ });+ localStorage.setItem(key, JSON.stringify(session));+ }, skewed);++ await page.reload();+ await waitForActiveProviderSynced(page);+ await expect(paneTabs(page)).toHaveCount(4);+ await expectHeaderGroupsAlignedWithPanes(page);++ // The clamp really did engage. A lower bound alone cannot show that: it+ // holds just as well when every pane was already above the minimum and+ // there was never anything to diverge from. Pinning the smallest pane AT+ // the minimum is what proves the resolved layout left the persisted one,+ // so the day a wider viewport or a retuned fixture stops reproducing the+ // clamp this fails instead of passing vacuously.+ const widths = await paneWidths(page);+ const smallest = Math.min(...widths);+ expect(smallest).toBeGreaterThanOrEqual(MIN_EDITOR_PANE_WIDTH - 1);+ expect(smallest).toBeLessThanOrEqual(MIN_EDITOR_PANE_WIDTH + 1);+ // ...and the persisted share it was raised from really was smaller.+ const totalWidth = widths.reduce((sum, width) => sum + width, 0);+ expect(smallest).toBeGreaterThan((Math.min(...skewed) / 100) * totalWidth + 1);+ });});async function windowHash(page: Page): Promise<string> {