Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Preserve sidebar focus when the open row appears late (#5648)

Nick Gomez60a51c6a63b7
diff --git a/.changeset/late-sidebar-focus.md b/.changeset/late-sidebar-focus.md
new file mode 100644
index 000000000..662d9a80c
--- /dev/null
+++ b/.changeset/late-sidebar-focus.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Keep sidebar focus and scroll position steady when the open document appears during a background refresh, while highlighting its row and preparing it for entry when focus is elsewhere.
diff --git a/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx b/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
index 689d44444..c6f97af86 100644
--- a/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
+++ b/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
@@ -1,10 +1,12 @@
/** Exercises `render` + `userEvent` under the jsdom substrate (precedent #43). */
import { FileTree } from '@pierre/trees';
-import { cleanup, render, screen } from '@testing-library/react';
+import { FileTree as PierreFileTree } from '@pierre/trees/react';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useRef, useState } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { Input } from '@/components/ui/input';
import { revealActiveRow } from './file-tree-reveal';
import { useSelectionMirror } from './use-selection-mirror';
@@ -20,12 +22,14 @@ interface StubItem {
getFocusCount: () => number;
}
-type ExpansionOnlyModel = Pick<StubModel, 'getItem' | 'getSelectedPaths' | 'getFocusedPath'>;
+type ExpansionOnlyModel = Omit<StubModel, 'addPath'>;
interface StubModel {
getItem: (path: string) => StubItem | null;
getSelectedPaths: () => string[];
getFocusedPath: () => string | null;
+ getFileTreeContainer: () => undefined;
+ scrollToPath: () => void;
addPath: (path: string) => void;
}
@@ -64,6 +68,8 @@ function makeStubModel(paths: string[]): StubModel {
.filter(([, it]) => it.isSelected())
.map(([p]) => p),
getFocusedPath: () => focusedPath,
+ getFileTreeContainer: () => undefined,
+ scrollToPath: () => {},
addPath,
};
}
@@ -86,6 +92,7 @@ function Harness({ initialPath, model }: { initialPath: string | null; model: Ha
'',
suppressSelectionRef,
treePathsSignature,
+ { activeSelectionId: activeTreePath, ready: true },
);
return (
@@ -118,6 +125,45 @@ function Harness({ initialPath, model }: { initialPath: string | null; model: Ha
);
}
+function MountedMirror({
+ model,
+ activePath,
+ revision,
+ secondModel,
+}: {
+ model: FileTree;
+ activePath: string;
+ revision: string;
+ secondModel?: FileTree;
+}) {
+ const suppressSelectionRef = useRef(false);
+ useSelectionMirror(model, activePath, '', suppressSelectionRef, revision, {
+ activeSelectionId: activePath,
+ ready: true,
+ });
+ return (
+ <>
+ <Input aria-label="Editor control" />
+ <PierreFileTree model={model} />
+ {secondModel && <PierreFileTree model={secondModel} />}
+ </>
+ );
+}
+
+function mountedRow(model: FileTree, path: string): HTMLElement {
+ const row = model
+ .getFileTreeContainer()
+ ?.shadowRoot?.querySelector<HTMLElement>(`[role="treeitem"][data-item-path="${path}"]`);
+ if (!row) throw new Error(`Tree row is not mounted: ${path}`);
+ return row;
+}
+
+async function focusMountedRow(model: FileTree, path: string): Promise<void> {
+ await waitFor(() => mountedRow(model, path));
+ await act(async () => mountedRow(model, path).focus());
+ expect(model.getFileTreeContainer()?.shadowRoot?.activeElement).toBe(mountedRow(model, path));
+}
+
describe('FileTree selection-mirror (Tier-3 mount)', () => {
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
@@ -221,6 +267,8 @@ describe('FileTree selection-mirror (Tier-3 mount)', () => {
.filter(([, it]) => it.isSelected())
.map(([p]) => p),
getFocusedPath: () => null,
+ getFileTreeContainer: () => undefined,
+ scrollToPath: () => {},
};
function PartiallyHiddenHarness() {
const suppressSelectionRef = useRef(false);
@@ -230,6 +278,8 @@ describe('FileTree selection-mirror (Tier-3 mount)', () => {
'parent/.hidden-child.md',
'parent/',
suppressSelectionRef,
+ '',
+ { activeSelectionId: 'parent/child', ready: true },
);
return null;
}
@@ -280,6 +330,8 @@ describe('FileTree selection-mirror (Tier-3 mount)', () => {
getItem: (path: string) => items.get(path) ?? null,
getSelectedPaths: () => [],
getFocusedPath: () => null,
+ getFileTreeContainer: () => undefined,
+ scrollToPath: () => {},
};
function AncestorHarness() {
const suppressSelectionRef = useRef(false);
@@ -289,6 +341,8 @@ describe('FileTree selection-mirror (Tier-3 mount)', () => {
'parent/child.md',
'parent/',
suppressSelectionRef,
+ '',
+ { activeSelectionId: 'parent/child', ready: true },
);
return null;
}
@@ -371,20 +425,109 @@ describe('FileTree selection-mirror (Tier-3 mount)', () => {
expect(model.getSelectedPaths()).toEqual(['A.md']);
});
- test('an activation whose row appears only on a later repopulation claims keyboard focus', async () => {
- const user = userEvent.setup();
- const model = makeStubModel(['folder/', 'B.md']);
- render(<Harness initialPath="A.md" model={model} />);
-
- model.getItem('folder/')?.focus();
+ test('a late open row is selected without taking focus from the file tree', async () => {
+ const model = new FileTree({ paths: ['folder/', 'B.md'] });
+ const { rerender } = render(
+ <MountedMirror model={model} activePath="A.md" revision="before-arrival" />,
+ );
+ await focusMountedRow(model, 'folder/');
expect(model.getFocusedPath()).toBe('folder/');
expect(model.getSelectedPaths()).toEqual([]);
- model.addPath('A.md');
- await user.click(screen.getByTestId('repopulate'));
+ await act(async () => model.resetPaths(['folder/', 'A.md', 'B.md']));
+ rerender(<MountedMirror model={model} activePath="A.md" revision="after-arrival" />);
+
+ await waitFor(() => expect(model.getSelectedPaths()).toEqual(['A.md']));
+ expect(model.getFocusedPath()).toBe('folder/');
+ expect(model.getFileTreeContainer()?.shadowRoot?.activeElement).toBe(
+ mountedRow(model, 'folder/'),
+ );
+ });
+
+ test('a returning open row leaves keyboard focus on the file row in use', async () => {
+ const model = new FileTree({ paths: ['folder/', 'A.md', 'B.md'] });
+ const { rerender } = render(
+ <MountedMirror model={model} activePath="A.md" revision="initial" />,
+ );
+ await waitFor(() => expect(model.getSelectedPaths()).toEqual(['A.md']));
+ await act(async () => model.resetPaths(['folder/', 'B.md']));
+ rerender(<MountedMirror model={model} activePath="A.md" revision="missing" />);
+ await focusMountedRow(model, 'folder/');
+ await act(async () => model.resetPaths(['folder/', 'A.md', 'B.md']));
+ rerender(<MountedMirror model={model} activePath="A.md" revision="returned" />);
+
+ await waitFor(() => expect(model.getSelectedPaths()).toEqual(['A.md']));
+ expect(model.getFocusedPath()).toBe('folder/');
+ expect(model.getFileTreeContainer()?.shadowRoot?.activeElement).toBe(
+ mountedRow(model, 'folder/'),
+ );
+ });
+
+ test('a late open row becomes the entry point while editor focus stays outside', async () => {
+ const model = new FileTree({ paths: ['folder/', 'B.md'] });
+ const { rerender } = render(
+ <MountedMirror model={model} activePath="A.md" revision="before-arrival" />,
+ );
+ await focusMountedRow(model, 'folder/');
+ const editor = screen.getByRole('textbox', { name: 'Editor control' });
+ await act(async () => editor.focus());
+
+ await act(async () => model.resetPaths(['folder/', 'A.md', 'B.md']));
+ rerender(<MountedMirror model={model} activePath="A.md" revision="after-arrival" />);
+
+ await waitFor(() => expect(model.getSelectedPaths()).toEqual(['A.md']));
expect(model.getFocusedPath()).toBe('A.md');
- expect(model.getSelectedPaths()).toEqual(['A.md']);
+ expect(document.activeElement).toBe(editor);
+ });
+
+ test('a late open row leaves a second tree in control of DOM focus', async () => {
+ const model = new FileTree({ paths: ['folder/', 'B.md'] });
+ const secondModel = new FileTree({ paths: ['Project/skill.md'] });
+ const { rerender } = render(
+ <MountedMirror
+ model={model}
+ activePath="A.md"
+ revision="before-arrival"
+ secondModel={secondModel}
+ />,
+ );
+ await focusMountedRow(secondModel, 'Project/');
+
+ await act(async () => model.resetPaths(['folder/', 'A.md', 'B.md']));
+ rerender(
+ <MountedMirror
+ model={model}
+ activePath="A.md"
+ revision="after-arrival"
+ secondModel={secondModel}
+ />,
+ );
+
+ await waitFor(() => expect(model.getSelectedPaths()).toEqual(['A.md']));
+ expect(model.getFocusedPath()).toBe('A.md');
+ expect(document.activeElement).toBe(secondModel.getFileTreeContainer());
+ expect(secondModel.getFileTreeContainer()?.shadowRoot?.activeElement).toBe(
+ mountedRow(secondModel, 'Project/'),
+ );
+ });
+
+ test('a true activation focuses its row while the file tree owns DOM focus', async () => {
+ const model = new FileTree({ paths: ['folder/', 'A.md', 'B.md'] });
+ const { rerender } = render(
+ <MountedMirror model={model} activePath="A.md" revision="initial" />,
+ );
+ await focusMountedRow(model, 'folder/');
+
+ rerender(<MountedMirror model={model} activePath="B.md" revision="initial" />);
+
+ await waitFor(() => expect(model.getSelectedPaths()).toEqual(['B.md']));
+ expect(model.getFocusedPath()).toBe('B.md');
+ await waitFor(() =>
+ expect(model.getFileTreeContainer()?.shadowRoot?.activeElement).toBe(
+ mountedRow(model, 'B.md'),
+ ),
+ );
});
test('re-activating a document after the active path was cleared claims keyboard focus', async () => {
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index a413e967c..feeb50b72 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -133,7 +133,6 @@ import {
hasSupportedDocumentExtension,
validateAndCoerceRenameDestination,
} from '@/components/file-tree-rename-validation';
-import { revealActiveRow } from '@/components/file-tree-reveal';
import {
previewTabIdForTreePath,
resolveFileTreeSelection,
@@ -1100,19 +1099,27 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
selectedFolderPath,
navigationPath: activeNavigationPath,
} = resolveFileTreeSelection(activeTarget, isNewTabActive ? null : activeDocName);
- const baseActiveTreePath = selectedFilePath
- ? docNameToTreePath(
- selectedFilePath,
- documents.find(
- (d): d is DocumentEntry => isDocumentEntry(d) && d.docName === selectedFilePath,
- )?.docExt,
- )
+ const baseActiveTreeSelection: { treePath: string; selectionId: string } | null = selectedFilePath
+ ? {
+ treePath: docNameToTreePath(
+ selectedFilePath,
+ documents.find(
+ (d): d is DocumentEntry => isDocumentEntry(d) && d.docName === selectedFilePath,
+ )?.docExt,
+ ),
+ selectionId: docTabId(selectedFilePath),
+ }
: selectedFolderPath
- ? folderPathToTreeDirectoryPath(selectedFolderPath)
+ ? {
+ treePath: folderPathToTreeDirectoryPath(selectedFolderPath),
+ selectionId: folderTabId(selectedFolderPath),
+ }
: activeTarget?.kind === 'asset'
- ? activeTarget.assetPath
+ ? { treePath: activeTarget.assetPath, selectionId: assetTabId(activeTarget.assetPath) }
: null;
+ const baseActiveTreePath = baseActiveTreeSelection?.treePath ?? null;
const activeTreePath = creationDirCleared ? null : baseActiveTreePath;
+ const activeSelectionId = baseActiveTreeSelection?.selectionId ?? null;
const handoffInstallStates = useInstalledAgents().states;
const { dispatch: dispatchHandoff } = useHandoffDispatch();
@@ -1526,6 +1533,7 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
activeAncestorTreePathsSignature,
suppressSelectionRef,
treePathsSignature,
+ { activeSelectionId, ready: !loading },
);
// biome-ignore lint/correctness/useExhaustiveDependencies: setCreationDirCleared is a stable state setter; baseActiveTreePath is the sole trigger.
@@ -1538,12 +1546,6 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
for (const listener of handleListenersRef.current) listener();
}, [creationDirCleared]);
- // biome-ignore lint/correctness/useExhaustiveDependencies: activeAncestorTreePathsSignature + treePathsSignature are re-run triggers — the row's visible index shifts when ancestors expand or the tree repopulates.
- useEffect(() => {
- if (loading || !activeTreePath) return;
- revealActiveRow(model, activeTreePath);
- }, [activeTreePath, activeAncestorTreePathsSignature, treePathsSignature, loading, model]);
-
useEffect(() => {
return model.subscribe(() => {
if (model.isSearchOpen()) return;
diff --git a/packages/app/src/components/use-selection-mirror.ts b/packages/app/src/components/use-selection-mirror.ts
index 35a242ad4..708306108 100644
--- a/packages/app/src/components/use-selection-mirror.ts
+++ b/packages/app/src/components/use-selection-mirror.ts
@@ -1,5 +1,6 @@
import type { FileTreeDirectoryHandle, FileTree as PierreFileTreeModel } from '@pierre/trees';
import { type RefObject, useEffect, useRef } from 'react';
+import { revealActiveRow } from './file-tree-reveal';
export function asDirectoryHandle(
item: ReturnType<PierreFileTreeModel['getItem']>,
@@ -30,6 +31,17 @@ function keyboardFocusIsHeldByAnotherRow(
return focusedPath !== null && focusedPath !== activeTreePath;
}
+function fileTreeHasDOMFocus(model: PierreFileTreeModel): boolean {
+ const container = model.getFileTreeContainer();
+ if (!container) return false;
+ let activeElement = container.ownerDocument.activeElement;
+ while (activeElement) {
+ if (container.contains(activeElement)) return true;
+ activeElement = activeElement.shadowRoot?.activeElement ?? null;
+ }
+ return false;
+}
+
function deselectAllTreeItems(model: PierreFileTreeModel): void {
for (const selectedPath of model.getSelectedPaths()) {
model.getItem(selectedPath)?.deselect();
@@ -42,10 +54,12 @@ export function useSelectionMirror(
activeAncestorTreePathsSignature: string,
suppressSelectionRef: RefObject<boolean>,
treePathsSignature: string,
+ { activeSelectionId, ready }: { activeSelectionId: string | null; ready: boolean },
): void {
- const lastActiveTreePathRef = useRef<string | null>(null);
+ const lastActiveSelectionIdRef = useRef<string | null>(null);
+ const lastReadyTreePathRef = useRef<string | null>(null);
- // biome-ignore lint/correctness/useExhaustiveDependencies: `treePathsSignature` is a re-run trigger, not a value read in the closure — it forces the mirror to re-assert selection after `model.resetPaths` rebuilds the tree. Sibling pattern: the reset + reveal-active-row effects in FileTree.tsx.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: treePathsSignature reasserts selection after model.resetPaths rebuilds the tree.
useEffect(() => {
const releaseSelectionSuppression = () => {
queueMicrotask(() => {
@@ -54,11 +68,14 @@ export function useSelectionMirror(
};
suppressSelectionRef.current = true;
if (!activeTreePath) {
- lastActiveTreePathRef.current = null;
+ lastActiveSelectionIdRef.current = null;
+ lastReadyTreePathRef.current = null;
deselectAllTreeItems(model);
releaseSelectionSuppression();
return;
}
+ const activeSelectionChanged = lastActiveSelectionIdRef.current !== activeSelectionId;
+ lastActiveSelectionIdRef.current = activeSelectionId;
const ancestorPaths = activeAncestorTreePathsSignature
? activeAncestorTreePathsSignature.split('\0')
: [];
@@ -70,30 +87,36 @@ export function useSelectionMirror(
}
const item = model.getItem(activeTreePath);
if (!item) {
- lastActiveTreePathRef.current = null;
+ lastReadyTreePathRef.current = null;
deselectAllTreeItems(model);
releaseSelectionSuppression();
return;
}
- const activeTreePathChanged = lastActiveTreePathRef.current !== activeTreePath;
- lastActiveTreePathRef.current = activeTreePath;
- const claimKeyboardFocus = () => {
- if (!activeTreePathChanged && keyboardFocusIsHeldByAnotherRow(model, activeTreePath)) {
- return;
- }
- item.focus();
- };
- if (model.getSelectedPaths().length > 1 && item.isSelected()) {
- claimKeyboardFocus();
+ if (!(model.getSelectedPaths().length > 1 && item.isSelected())) {
+ selectOnlyTreeItem(model, item);
+ }
+ if (!ready) {
+ lastReadyTreePathRef.current = null;
releaseSelectionSuppression();
return;
}
- selectOnlyTreeItem(model, item);
- claimKeyboardFocus();
+ const rowBecameReady = lastReadyTreePathRef.current !== activeTreePath;
+ lastReadyTreePathRef.current = activeTreePath;
+ const treeHasDOMFocus = fileTreeHasDOMFocus(model);
+ if (
+ activeSelectionChanged ||
+ (!treeHasDOMFocus &&
+ (rowBecameReady || !keyboardFocusIsHeldByAnotherRow(model, activeTreePath)))
+ ) {
+ item.focus();
+ if (!treeHasDOMFocus) revealActiveRow(model, activeTreePath);
+ }
releaseSelectionSuppression();
}, [
activeAncestorTreePathsSignature,
activeTreePath,
+ activeSelectionId,
+ ready,
model,
suppressSelectionRef,
treePathsSignature,
diff --git a/packages/app/tests/stress/reveal-on-activate.e2e.ts b/packages/app/tests/stress/reveal-on-activate.e2e.ts
index b26a19b02..40c8db838 100644
--- a/packages/app/tests/stress/reveal-on-activate.e2e.ts
+++ b/packages/app/tests/stress/reveal-on-activate.e2e.ts
@@ -1,6 +1,9 @@
-import { readdirSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { readdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { DocumentListSuccessSchema } from '@inkeep/open-knowledge-core/schemas/api';
import type { Page } from '@playwright/test';
-import { expect, test } from './_helpers';
+import { type ApiHelpers, expect, test } from './_helpers';
async function deletePathIfExists(baseURL: string, kind: 'file' | 'folder', path: string) {
const response = await fetch(`${baseURL}/api/delete-path`, {
@@ -40,6 +43,10 @@ test.beforeEach(async ({ api, workerServer }) => {
await api.createPage('sidebar-folder/nested-doc.md');
});
+test.afterEach(async ({ page }) => {
+ await page.unrouteAll({ behavior: 'wait' });
+});
+
const sidebar = (page: Page) => page.locator('[data-slot="sidebar-container"]');
const fileRow = (page: Page, fileName: string) =>
sidebar(page).getByRole('treeitem', { name: fileName, exact: true });
@@ -86,6 +93,175 @@ async function collapseFolder(page: Page) {
await folderRow(page).press('ArrowLeft');
}
+async function prepareLateRow(page: Page, api: ApiHelpers, { initiallyVisible = false } = {}) {
+ const docName = `zz-late-${randomUUID()}`;
+ let includeRow = initiallyVisible;
+ await page.route(
+ (url) => url.pathname === '/api/documents' && url.searchParams.get('showAll') === 'true',
+ async (route) => {
+ const response = await route.fetch({
+ headers: { ...route.request().headers(), accept: 'application/json' },
+ });
+ const body = DocumentListSuccessSchema.parse(await response.json());
+ await route.fulfill({
+ response,
+ json: {
+ ...body,
+ documents: body.documents.filter(
+ (entry) => includeRow || entry.kind !== 'document' || entry.docName !== docName,
+ ),
+ },
+ });
+ },
+ );
+ await api.createPage(`${docName}.md`);
+ await api.replaceDoc(docName, '# Late row content\n');
+ await gotoAndAwaitTree(page, `/#/${docName}`);
+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)');
+ await expect(editor).toContainText('Late row content');
+ await expect(fileRow(page, `${docName}.md`)).toHaveCount(initiallyVisible ? 1 : 0);
+ const tree = sidebar(page)
+ .getByRole('tree')
+ .filter({ has: page.getByRole('treeitem', { name: 'sidebar-folder', exact: true }) });
+ const scroller = tree.locator('[data-file-tree-virtualized-scroll]');
+ const viewportHeight = await scroller.evaluate((element) => element.clientHeight);
+ const rowHeight = await folderRow(page).evaluate(
+ (element) => element.getBoundingClientRect().height,
+ );
+ const fillerCount = Math.ceil(viewportHeight / rowHeight);
+ const fillerNames = Array.from(
+ { length: fillerCount },
+ (_, index) => `filler-${docName}-${String(index).padStart(String(fillerCount).length, '0')}.md`,
+ );
+ for (const name of fillerNames) await api.createPage(name);
+ await expect(folderRow(page)).toHaveAttribute(
+ 'aria-setsize',
+ String(fillerCount + (initiallyVisible ? 3 : 2)),
+ );
+ await scroller.evaluate((element) => {
+ element.scrollTop = 0;
+ });
+ return {
+ editor,
+ scroller,
+ row: fileRow(page, `${docName}.md`),
+ async arrive() {
+ const previousCount = Number(await folderRow(page).getAttribute('aria-setsize'));
+ const addedCount = includeRow ? 1 : 2;
+ includeRow = true;
+ await api.createPage(`arrival-${randomUUID()}.md`);
+ await expect(folderRow(page)).toHaveAttribute(
+ 'aria-setsize',
+ String(previousCount + addedCount),
+ );
+ await expect(fileRow(page, `${docName}.md`)).toHaveAttribute('aria-selected', 'true');
+ },
+ };
+}
+
+test('a late open row preserves file-tree focus and the viewport', async ({ page, api }) => {
+ const { scroller, row, arrive } = await prepareLateRow(page, api);
+ await folderRow(page).focus();
+ await expect(folderRow(page)).toBeFocused();
+ const scrollBefore = await scroller.evaluate((element) => element.scrollTop);
+
+ await arrive();
+
+ await expect.soft(folderRow(page)).toBeFocused();
+ expect.soft(await scroller.evaluate((element) => element.scrollTop)).toBe(scrollBefore);
+ await expect(row).toHaveAttribute('aria-selected', 'true');
+ await page.keyboard.press('ArrowRight');
+ await expect(folderRow(page)).toHaveAttribute('aria-expanded', 'true');
+});
+
+test('a background refresh preserves a viewport scrolled away from the focused open row', async ({
+ page,
+ api,
+}) => {
+ const { scroller, row, arrive } = await prepareLateRow(page, api, { initiallyVisible: true });
+ await row.focus();
+ await expect(row).toBeFocused();
+ await scroller.evaluate((element) => {
+ element.scrollTop = 0;
+ });
+ await expect(row).not.toBeInViewport();
+ await expect(row).toBeFocused();
+ const scrollBefore = await scroller.evaluate((element) => element.scrollTop);
+
+ await arrive();
+
+ await expect(row).toBeFocused();
+ expect(await scroller.evaluate((element) => element.scrollTop)).toBe(scrollBefore);
+});
+
+test('a late open row is revealed while editor focus remains and becomes the entry row', async ({
+ page,
+ api,
+}) => {
+ const { editor, scroller, row, arrive } = await prepareLateRow(page, api);
+ await editor.focus();
+ await expect(editor).toBeFocused();
+ const scrollBefore = await scroller.evaluate((element) => element.scrollTop);
+
+ await arrive();
+
+ await expect(editor).toBeFocused();
+ await expect(row).toHaveAttribute('tabindex', '0');
+ await expect(row).toBeInViewport();
+ expect(await scroller.evaluate((element) => element.scrollTop)).toBeGreaterThan(scrollBefore);
+
+ await page.getByRole('button', { name: 'New folder', exact: true }).focus();
+ await page.keyboard.press('Tab');
+ await expect(row).toBeFocused();
+ await editor.focus();
+ await row.click();
+ await expect(row).toBeFocused();
+});
+
+test('a visibility refresh selects the open MDX row without taking sidebar focus', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const docName = `.late-${randomUUID()}`;
+ await api.createPage(`${docName}.mdx`);
+ writeFileSync(join(workerServer.contentDir, `${docName}.mdx`), '# Hidden late row\n');
+ await gotoAndAwaitTree(page, `/#/${docName}`);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)')).toContainText(
+ 'Hidden late row',
+ );
+ await expect(page.getByTestId('not-in-sidebar-flip-hidden-files')).toBeVisible();
+ const requested = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ await page.route(
+ (url) => url.pathname === '/api/documents' && url.searchParams.get('showAll') === 'true',
+ async (route) => {
+ requested.resolve();
+ await release.promise;
+ await route.continue();
+ },
+ );
+ try {
+ await page.getByTestId('not-in-sidebar-flip-hidden-files').click();
+ await requested.promise;
+ await folderRow(page).focus();
+ await expect(folderRow(page)).toBeFocused();
+ release.resolve();
+
+ await expect(fileRow(page, `${docName}.mdx`)).toHaveAttribute('aria-selected', 'true');
+ await expect.soft(folderRow(page)).toBeFocused();
+ await page.keyboard.press('ArrowRight');
+ await expect.soft(folderRow(page)).toHaveAttribute('aria-expanded', 'true');
+ } finally {
+ release.resolve();
+ await page.unrouteAll({ behavior: 'wait' });
+ }
+ await page.getByRole('button', { name: 'Tree view options' }).click();
+ await page.getByTestId('tree-options-show-hidden-files').click();
+ await expect(page.getByTestId('not-in-sidebar-indicator')).toBeVisible();
+ await expect(fileRow(page, `${docName}.mdx`)).toHaveCount(0);
+});
+
test('direct URL load reveals nested doc on first paint', async ({ page }) => {
await gotoAndAwaitTree(page, `/#/sidebar-folder/nested-doc`);
await fileRow(page, 'nested-doc.md').waitFor({ state: 'visible', timeout: 15_000 });