Put a linked heading at the top of the view

A heading link showed its heading in the center of the view, also for a
heading in another file. The text to read then started low on the
screen. An outline jump used the same scroll.

- Write and Source put a heading target at the top, with a gap of 24
  pixels. Other targets, such as a search match or a backlink, stay in
  the center.
- Read puts the heading at the top. The scroll margin of the heading
  keeps the gap.

The sectionLinks smoke test checks the position in Write and Read, also
for a heading in another file. Card bf263f80.
This commit is contained in:
Knotty Wyvern
2026-11-03 00:23:17 -07:00
parent 0ab7fe0c64
commit 18031e34e4
4 changed files with 27 additions and 5 deletions
+1 -1
View File
@@ -103,7 +103,7 @@ Read follows CommonMark: a single line break inside a paragraph is a space. To s
- Ctrl+click a link in Write or Source. In Read, a normal click follows the link. - Ctrl+click a link in Write or Source. In Read, a normal click follows the link.
- A workspace file link opens in a new tab and keeps the current document open. - A workspace file link opens in a new tab and keeps the current document open.
- A heading link, such as `guide.md#save-your-work` or `#save-your-work`, scrolls to that heading. - A heading link, such as `guide.md#save-your-work` or `#save-your-work`, puts that heading at the top of the view. A heading near the end of a short document stays lower.
- A wiki link, such as `[[Meeting notes]]`, finds the note by name anywhere in the workspace. If two notes have the same name, use a relative or workspace path. - A wiki link, such as `[[Meeting notes]]`, finds the note by name anywhere in the workspace. If two notes have the same name, use a relative or workspace path.
- The **Backlinks** section below the outline lists notes that link to the current note. Select an entry to open it. - The **Backlinks** section below the outline lists notes that link to the current note. Select an entry to open it.
+6 -2
View File
@@ -13,6 +13,7 @@
import type { Chrome, OpenBuffer } from "$lib/workspace/types"; import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api"; import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks"; import { linkCandidates } from "$lib/workspace/markdownLinks";
import { documentHeadings } from "$lib/workspace/headingLinks";
import { editImageSource, imageSource } from "./imageSource"; import { editImageSource, imageSource } from "./imageSource";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml"; import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle, pastedImageSource } from "$lib/workspace/media"; import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle, pastedImageSource } from "$lib/workspace/media";
@@ -434,8 +435,11 @@
const view = editor; const view = editor;
if (!view || line == null) return; if (!view || line == null) return;
untrack(() => { untrack(() => {
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from; const number = Math.min(view.state.doc.lines, Math.max(1, line));
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })]; const anchor = view.state.doc.line(number).from;
// A heading starts the text to read, so it goes to the top, as in Read. Other lines, such as a search match, stay in the center.
const heading = markdownDocument && documentHeadings(view.state.doc.toString()).some(entry => entry.line === number);
const effects = [EditorView.scrollIntoView(anchor, heading ? { y: "start", yMargin: 24 } : { y: "center" })];
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); }); foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
view.dispatch({ selection: { anchor }, effects }); view.dispatch({ selection: { anchor }, effects });
view.focus(); view.focus();
+2 -1
View File
@@ -102,7 +102,8 @@
[...el.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6")].filter(heading => !heading.classList.contains("document-title"))[index]; [...el.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6")].filter(heading => !heading.classList.contains("document-title"))[index];
if (!target) return; if (!target) return;
currentHeadings?.reveal(target); currentHeadings?.reveal(target);
target.scrollIntoView({ block: "center" }); // The heading starts the text to read, so it goes to the top. Its scroll margin keeps a gap above it (reading.css).
target.scrollIntoView({ block: "start" });
el.focus({ preventScroll: true }); el.focus({ preventScroll: true });
}); });
return renderDiagrams(el, () => cancelled); return renderDiagrams(el, () => cancelled);
+18 -1
View File
@@ -26,7 +26,7 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
const url = new URL(smokeUrl).href; const url = new URL(smokeUrl).href;
const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n'); const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n');
const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n'; const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n';
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n'; const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n\n' + filler;
async function writerJump(label, line) { async function writerJump(label, line) {
const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first(); const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first();
await link.click({ modifiers: ['Control'] }); await link.click({ modifiers: ['Control'] });
@@ -57,6 +57,16 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom; return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom;
}, text); }, text);
} }
// A heading link puts the heading at the top of the view, below a gap of about 24 pixels.
// The last heading of a short document cannot reach the top, so the checks use headings with text below them.
async function headingAtTop(selector, text, scroller) {
await page.waitForFunction(({ selector, text, scroller }) => [...document.querySelectorAll(selector)].some(node => {
const offset = node.textContent.includes(text) ? node.getBoundingClientRect().top - node.closest(scroller).getBoundingClientRect().top : -1;
return offset >= 0 && offset <= 60;
}), { selector, text, scroller });
}
const writerHeadingAtTop = text => headingAtTop('.cm-line.writer-heading', text, '.cm-scroller');
const readerHeadingAtTop = text => headingAtTop('.reading h2', text, '.md-page');
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) { for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height:1000 }); await page.setViewportSize({ width, height:1000 });
await page.goto(url); await page.goto(url);
@@ -72,10 +82,12 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
await page.getByRole('button', { name:'Hide outline', exact:true }).click(); await page.getByRole('button', { name:'Hide outline', exact:true }).click();
} }
await writerJump('Windows setup', await jumpLine('## Windows installer')); await writerJump('Windows setup', await jumpLine('## Windows installer'));
await writerHeadingAtTop('Windows installer');
await top(); await top();
await writerJump('Windows setup', await jumpLine('## Windows installer')); await writerJump('Windows setup', await jumpLine('## Windows installer'));
await top(); await top();
await writerJump('macOS setup', await jumpLine('## macOS installer')); await writerJump('macOS setup', await jumpLine('## macOS installer'));
await writerHeadingAtTop('macOS installer (Apple Silicon)');
await top(); await top();
await writerJump('Linux setup', await jumpLine('## Linux')); await writerJump('Linux setup', await jumpLine('## Linux'));
await page.screenshot({ path:`${output}/writer-${theme}-${width}.png` }); await page.screenshot({ path:`${output}/writer-${theme}-${width}.png` });
@@ -91,14 +103,19 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
const view = node ? EditorView.findFromDOM(node) : null; const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).text === '## Café setup' && view.state.selection.main.head > 100; return view && view.state.doc.lineAt(view.state.selection.main.head).text === '## Café setup' && view.state.selection.main.head > 100;
}); });
// The card case: a link to a heading in another file.
await writerHeadingAtTop('Café setup');
await page.screenshot({ path:`${output}/other-file-${theme}-${width}.png` });
assert.equal(await page.getByRole('tab', { name:'a.md', exact:true }).count(), 1); assert.equal(await page.getByRole('tab', { name:'a.md', exact:true }).count(), 1);
await page.getByRole('tab', { name:'a.md', exact:true }).click(); await page.getByRole('tab', { name:'a.md', exact:true }).click();
await top(); await top();
await chooseView(page, 'Read'); await chooseView(page, 'Read');
await readerJump('Windows setup', 'Windows installer'); await readerJump('Windows setup', 'Windows installer');
await readerHeadingAtTop('Windows installer');
await page.screenshot({ path:`${output}/reading-${theme}-${width}.png` }); await page.screenshot({ path:`${output}/reading-${theme}-${width}.png` });
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; }); await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('macOS setup', 'macOS installer (Apple Silicon)'); await readerJump('macOS setup', 'macOS installer (Apple Silicon)');
await readerHeadingAtTop('macOS installer (Apple Silicon)');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; }); await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)'); await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await chooseView(page, 'Split'); await chooseView(page, 'Split');