Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Preserve scroll position after link hover (PRD-8729) (#4722)
sarah5647449b9aca
diff --git a/.changeset/preserve-reading-position-on-link-hover.md b/.changeset/preserve-reading-position-on-link-hover.mdnew file mode 100644index 000000000..be2551aee--- /dev/null+++ b/.changeset/preserve-reading-position-on-link-hover.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Moving the pointer away from a hovered link no longer resets your reading position when the preview closes.diff --git a/knip.config.ts b/knip.config.tsindex 659eef71e..5b8951125 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -143,15 +143,11 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: [- '@types/shell-quote',- ],+ ignoreDependencies: ['@types/shell-quote'],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],- ignoreDependencies: [- 'yjs',- ],+ ignoreDependencies: ['yjs'],},'packages/desktop': {entry: [diff --git a/packages/app/src/editor/interaction-layer.dom.test.ts b/packages/app/src/editor/interaction-layer.dom.test.tsnew file mode 100644index 000000000..386baf515--- /dev/null+++ b/packages/app/src/editor/interaction-layer.dom.test.ts@@ -0,0 +1,132 @@+import { afterEach, describe, expect, test } from 'vitest';+import { createInteractionLayer, type InteractionLayerHandle } from './interaction-layer';++const layers: InteractionLayerHandle[] = [];++function createFocusFixture() {+ const editor = document.createElement('div');+ editor.tabIndex = 0;++ const chip = document.createElement('button');+ chip.dataset.markId = 'link-1';+ editor.append(chip);++ const unrelated = document.createElement('button');+ document.body.append(editor, unrelated);++ const layer = createInteractionLayer({ editor: { editorView: { dom: editor } } });+ layers.push(layer);+ layer.register({ nodeId: 'link-1', type: 'internalLink', controls: {} });++ return { chip, editor, layer, unrelated };+}++function appendPropPanelWithFocusableChild(): HTMLButtonElement {+ const panel = document.createElement('div');+ panel.setAttribute('data-ok-prop-panel', 'internal-link');+ const panelButton = document.createElement('button');+ panel.append(panelButton);+ document.body.append(panel);+ return panelButton;+}++function appendLayerSpawnedWithFocusableChild(): HTMLButtonElement {+ const spawned = document.createElement('div');+ spawned.setAttribute('data-ok-layer-spawned', '');+ const spawnedButton = document.createElement('button');+ spawned.append(spawnedButton);+ document.body.append(spawned);+ return spawnedButton;+}++function appendInteractionLayerWithFocusableChild(): HTMLButtonElement {+ const wrapper = document.createElement('div');+ wrapper.setAttribute('data-ok-interaction-layer', '');+ const wrapperButton = document.createElement('button');+ wrapper.append(wrapperButton);+ document.body.append(wrapper);+ return wrapperButton;+}++afterEach(() => {+ for (const layer of layers.splice(0)) layer.destroy();+ document.body.replaceChildren();+});++describe('createInteractionLayer focus ownership', () => {+ test('deactivation restores a connected chip that owned focus at activation', () => {+ const { chip, layer, unrelated } = createFocusFixture();++ chip.focus();+ expect(document.activeElement).toBe(chip);+ layer.setActiveNode('link-1');++ unrelated.focus();+ expect(document.activeElement).toBe(unrelated);+ layer.setActiveNode(null);++ expect(document.activeElement).toBe(chip);+ });++ test('deactivation without a chip owner preserves unrelated focus', () => {+ const { layer, unrelated } = createFocusFixture();++ unrelated.focus();+ expect(document.activeElement).toBe(unrelated);+ layer.setActiveNode('link-1');+ layer.setActiveNode(null);++ expect(document.activeElement).toBe(unrelated);+ });++ test('deactivation returns focus to the editor when the closing panel owned it', () => {+ const { editor, layer } = createFocusFixture();++ layer.setActiveNode('link-1');+ const panelButton = appendPropPanelWithFocusableChild();+ panelButton.focus();+ expect(document.activeElement).toBe(panelButton);++ layer.setActiveNode(null);++ expect(document.activeElement).toBe(editor);+ });++ test('deactivation returns focus to the editor when a layer-spawned element owned it', () => {+ const { editor, layer } = createFocusFixture();+ const spawnedButton = appendLayerSpawnedWithFocusableChild();++ layer.setActiveNode('link-1');+ spawnedButton.focus();+ expect(document.activeElement).toBe(spawnedButton);++ layer.setActiveNode(null);++ expect(document.activeElement).toBe(editor);+ });++ test('deactivation returns focus to the editor when a layer toolbar control owned it', () => {+ const { editor, layer } = createFocusFixture();+ const toolbarButton = appendInteractionLayerWithFocusableChild();++ layer.setActiveNode('link-1');+ toolbarButton.focus();+ expect(document.activeElement).toBe(toolbarButton);++ layer.setActiveNode(null);++ expect(document.activeElement).toBe(editor);+ });++ test('deactivation falls back to the editor when the captured chip left the document', () => {+ const { chip, editor, layer } = createFocusFixture();++ chip.focus();+ layer.setActiveNode('link-1');+ chip.remove();++ layer.setActiveNode(null);++ expect(document.activeElement).toBe(editor);+ });+});diff --git a/packages/app/src/editor/interaction-layer.tsx b/packages/app/src/editor/interaction-layer.tsxindex 59ff7f312..9d29ee36b 100644--- a/packages/app/src/editor/interaction-layer.tsx+++ b/packages/app/src/editor/interaction-layer.tsx@@ -264,7 +264,8 @@ export function createInteractionLayer(}, HOVER_CLOSE_DELAY);};- let lastActivator: HTMLElement | null = null;+ type FocusOwner = { kind: 'none' } | { kind: 'activator'; element: HTMLElement };+ let focusOwner: FocusOwner = { kind: 'none' };let restoringFocus = false;const restoreFocusTo = (target: HTMLElement): void => {try {@@ -281,18 +282,28 @@ export function createInteractionLayer(if (typeof document !== 'undefined') {const active = document.activeElement as HTMLElement | null;if (active && isPotentialChipElement(active, activeId)) {- lastActivator = active;+ focusOwner = { kind: 'activator', element: active };} else {- lastActivator = null;+ focusOwner = { kind: 'none' };}+ } else {+ focusOwner = { kind: 'none' };}return;}+ const owner = focusOwner;+ focusOwner = { kind: 'none' };if (typeof document === 'undefined') return;- const target = lastActivator;- lastActivator = null;- if (target && document.contains(target) && typeof target.focus === 'function') {- restoreFocusTo(target);+ if (owner.kind === 'none') {+ const active = document.activeElement;+ if (+ !active?.closest(+ '[data-ok-prop-panel], [data-ok-layer-spawned], [data-ok-interaction-layer]',+ )+ )+ return;+ } else if (document.contains(owner.element) && typeof owner.element.focus === 'function') {+ restoreFocusTo(owner.element);return;}const dom = editorDom ?? getEditorDom(editor);diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.tsindex a28cc2b18..8a60e5826 100644--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts@@ -1,4 +1,3 @@-import { readFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.tsindex 4fc2c11f9..6fcdc23f2 100644--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { normalizeBridge } from '@inkeep/open-knowledge-core';import { updateYFragment } from '@tiptap/y-tiptap';diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.tsindex 9f2f6feb6..40b5cdfd6 100644--- a/packages/app/tests/integration/interior-edit-freshness.test.ts+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.tsindex 2a085742b..93666af70 100644--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.tsindex 878d5196b..867598d34 100644--- a/packages/app/tests/integration/producer-guard-wiring.test.ts+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.tsindex 4ada3cf26..0970ac12f 100644--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts@@ -1,4 +1,3 @@-import { randomUUID } from 'node:crypto';import { afterEach, describe, expect, test } from 'vitest';import { agentWriteMd, createTestServer, type TestServer } from './test-harness';diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.tsindex cbe2b705f..b632185e1 100644--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts@@ -1,4 +1,3 @@-import { execFileSync } from 'node:child_process';import { randomUUID } from 'node:crypto';import { join } from 'node:path';diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.tsindex 89bc9b4d9..c530ce4ba 100644--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts@@ -1,4 +1,3 @@-import { randomUUID } from 'node:crypto';import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';import type * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.tsindex a78aeb0e4..d3767adc9 100644--- a/packages/app/tests/integration/undo-after-rollback.test.ts+++ b/packages/app/tests/integration/undo-after-rollback.test.ts@@ -1,4 +1,3 @@-import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.tsindex e7cc69c3f..b076f955c 100644--- a/packages/app/tests/integration/undo-recycle-reset.test.ts+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts@@ -1,4 +1,3 @@-import { writeFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.tsindex 9ddcd0730..7935e35f8 100644--- a/packages/app/tests/integration/undo-rederive-survival.test.ts+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts@@ -1,4 +1,3 @@-import { prependFrontmatter } from '@inkeep/open-knowledge-core';import { Plugin, PluginKey } from '@tiptap/pm/state';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';diff --git a/packages/app/tests/stress/ux-interactions.e2e.ts b/packages/app/tests/stress/ux-interactions.e2e.tsindex 966bb0455..b0750b9b9 100644--- a/packages/app/tests/stress/ux-interactions.e2e.ts+++ b/packages/app/tests/stress/ux-interactions.e2e.ts@@ -1,8 +1,9 @@import { randomUUID } from 'node:crypto';-import type { Page } from '@playwright/test';+import type { Locator, Page } from '@playwright/test';import {type ApiHelpers,expect,+ TOOLBAR_OVERLAP_PX,test,waitForActiveProviderSynced as waitForProvider,} from './_helpers';@@ -18,6 +19,135 @@ function uniqueDocName(label: string): string {return `test-ux-${label}-${randomUUID().slice(0, 8)}`;}+const hoverScrollCases = [+ {+ id: 'internal-markdown',+ chipSelector: 'span[data-link]',+ linkText: 'Internal target',+ panelKind: 'internal-link',+ markdown: (targetDoc: string) => `[Internal target](${targetDoc}.md)`,+ },+ {+ id: 'wiki',+ chipSelector: '[data-wiki-link]',+ linkText: 'Wiki target',+ panelKind: 'wiki-link',+ markdown: (targetDoc: string) => `[[${targetDoc}|Wiki target]]`,+ },+] as const;++function longDocumentWithLink(link: string): string {+ const paragraphs = Array.from(+ { length: 140 },+ (_, index) =>+ `Paragraph ${index}: ${'Open Knowledge interaction test filler text. '.repeat(18)}`,+ );+ paragraphs.splice(80, 0, link);+ return `# Long source\n\n${paragraphs.join('\n\n')}\n`;+}++const SCROLL_SETTLE_STABLE_FRAMES = 3;+const SCROLL_SETTLE_MAX_FRAMES = 180;+const WHEEL_STEP_MIN_PX = 100;+const WHEEL_STEP_MAX_PX = 1200;+const CHIP_HOVER_BOTTOM_MARGIN_PX = 40;+const SCROLL_CLAMP_TOLERANCE_PX = 2;++async function waitForScrollToSettle(scroller: Locator): Promise<number> {+ return scroller.evaluate(+ (element, { requiredStableFrames, maxFrames }) =>+ new Promise<number>((resolve, reject) => {+ let previous = element.scrollTop;+ let stableFrames = 0;+ let frames = 0;+ const sample = () => {+ const current = element.scrollTop;+ stableFrames = current === previous ? stableFrames + 1 : 0;+ previous = current;+ if (stableFrames >= requiredStableFrames) {+ resolve(current);+ return;+ }+ frames += 1;+ if (frames >= maxFrames) {+ reject(+ new Error(+ `Editor scroll did not settle within ${maxFrames} frames; last scrollTop ${current}`,+ ),+ );+ return;+ }+ requestAnimationFrame(sample);+ };+ requestAnimationFrame(sample);+ }),+ {+ requiredStableFrames: SCROLL_SETTLE_STABLE_FRAMES,+ maxFrames: SCROLL_SETTLE_MAX_FRAMES,+ },+ );+}++async function bringLinkIntoViewWithWheel(+ page: Page,+ scroller: Locator,+ chip: Locator,+): Promise<void> {+ const scrollerBox = await scroller.boundingBox();+ if (!scrollerBox) throw new Error('Editor scroll container has no bounding box');+ await page.mouse.move(scrollerBox.x + scrollerBox.width - 20, scrollerBox.y + 80);++ const readScrollTop = async (): Promise<number> =>+ scroller.evaluate((element) => element.scrollTop);++ for (let attempt = 0; attempt < 80; attempt += 1) {+ const state = await chip.evaluate(+ (element, { toolbarPx, bottomMarginPx }) => {+ const scrollContainer = element.closest<HTMLElement>(+ '[data-testid="editor-scroll-container"]',+ );+ if (!scrollContainer) throw new Error('Link is outside the editor scroll container');+ const linkRect = element.getBoundingClientRect();+ const portRect = scrollContainer.getBoundingClientRect();+ return {+ delta: linkRect.top - (portRect.top + portRect.height * 0.5),+ scrollTop: scrollContainer.scrollTop,+ maxScrollTop: scrollContainer.scrollHeight - scrollContainer.clientHeight,+ visible:+ linkRect.top >= portRect.top + toolbarPx &&+ linkRect.bottom <= portRect.bottom - bottomMarginPx,+ };+ },+ { toolbarPx: TOOLBAR_OVERLAP_PX, bottomMarginPx: CHIP_HOVER_BOTTOM_MARGIN_PX },+ );+ if (state.visible) {+ await waitForScrollToSettle(scroller);+ return;+ }++ const magnitude = Math.min(+ WHEEL_STEP_MAX_PX,+ Math.max(WHEEL_STEP_MIN_PX, Math.abs(state.delta)),+ );+ const step = state.delta < 0 ? -magnitude : magnitude;+ const canScrollFurther =+ step < 0+ ? state.scrollTop > SCROLL_CLAMP_TOLERANCE_PX+ : state.scrollTop < state.maxScrollTop - SCROLL_CLAMP_TOLERANCE_PX;+ if (!canScrollFurther) {+ throw new Error(+ `Editor scroll container is clamped at scrollTop ${state.scrollTop} of ${state.maxScrollTop}; cannot wheel the link into view`,+ );+ }+ await page.mouse.wheel(0, step);+ await (step < 0+ ? expect.poll(readScrollTop).toBeLessThan(state.scrollTop)+ : expect.poll(readScrollTop).toBeGreaterThan(state.scrollTop));+ }++ throw new Error('Could not bring the link into view with wheel input');+}+async function openFreshDoc(api: ApiHelpers, page: Page, label: string): Promise<string> {const docName = uniqueDocName(label);await api.createPage(`${docName}.md`);@@ -288,6 +418,57 @@ test('sidebar folder: row click navigates to folder overview; treeitem toggles eawait expect(nestedFile).toBeVisible();});+for (const hoverScrollCase of hoverScrollCases) {+ test(`LINK-HOVER-SCROLL-${hoverScrollCase.id}: first hover preview dismissal preserves the reading position`, async ({+ page,+ api,+ }) => {+ const sourceDoc = uniqueDocName(`hover-scroll-${hoverScrollCase.id}`);+ const targetDoc = uniqueDocName(`hover-scroll-target-${hoverScrollCase.id}`);+ await api.seedDocs([+ {+ name: sourceDoc,+ markdown: longDocumentWithLink(hoverScrollCase.markdown(targetDoc)),+ },+ { name: targetDoc, markdown: '# Target\n\nTarget body.\n' },+ ]);++ await page.goto('/');+ const sourceRow = page.getByRole('treeitem', { name: `${sourceDoc}.md`, exact: true });+ await expect(sourceRow).toBeVisible();+ await sourceRow.click();+ await waitForProvider(page);++ const editor = page+ .locator('.ProseMirror:not(.composer-prosemirror)')+ .filter({ hasText: 'Paragraph 139' });+ await expect(editor).toBeAttached();+ const scroller = page.getByTestId('editor-scroll-container').filter({ has: editor }).first();+ await expect(scroller).toBeVisible();+ await expect(sourceRow).toBeFocused();++ const chip = editor.locator(hoverScrollCase.chipSelector, {+ hasText: hoverScrollCase.linkText,+ });+ await expect(chip).toBeAttached();+ await bringLinkIntoViewWithWheel(page, scroller, chip);++ const scrollBeforeHover = await waitForScrollToSettle(scroller);+ expect(scrollBeforeHover).toBeGreaterThan(500);++ await chip.hover();+ const panel = page.locator(`[data-ok-prop-panel="${hoverScrollCase.panelKind}"]`);+ await expect(panel).toBeVisible();++ await page.mouse.move(4, 4);+ await expect(panel).toBeHidden();+ await expect(sourceRow).toBeFocused();+ const scrollAfterDismissal = await waitForScrollToSettle(scroller);++ expect(scrollAfterDismissal).toBe(scrollBeforeHover);+ });+}+test('markdown link edit dialog preserves page mode while clearing and updates the href target', async ({page,api,diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex 2a597ec3d..f4cc8a286 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,4 +1,3 @@-import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 01ef76a9f..8fb428b90 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,4 +1,3 @@-import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex fb0ba5a7c..fc267cbea 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex fa3cfcd86..bfd7e3109 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 8be632ba4..4d3250d3a 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,4 +1,3 @@-export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');