diff --git a/.changeset/37562-fields-drawn-markdown-headings.md b/.changeset/37562-fields-drawn-markdown-headings.md new file mode 100644 index 00000000000..ae1725020fe --- /dev/null +++ b/.changeset/37562-fields-drawn-markdown-headings.md @@ -0,0 +1,10 @@ +--- +'@object-ui/fields': patch +--- + +feat(fields): read the headings a markdown value's document face draws, from the face's own parse + +Clause-②: yes (widening) +Metadata-protocol: none + +`@object-ui/fields` exports `loadDrawnMarkdownHeadings()`, which loads on demand and answers `drawnMarkdownHeadings(value)`: each heading the markdown `document` face draws, with its text and where it starts in the value (none for the footnote section's `Footnotes` label, which the pipeline adds), and the `DrawnMarkdownHeading` type. It runs the face's own pipeline (react-markdown with the GitHub Flavored Markdown and sanitize plugins `MarkdownContent` draws with), so a reader that must agree with the drawn page counts what is drawn by construction, and react-markdown stays in the lazy chunk the face already lives in. The face draws exactly as before. diff --git a/.changeset/37562-section-locate-edges.md b/.changeset/37562-section-locate-edges.md new file mode 100644 index 00000000000..e45bfdf3052 --- /dev/null +++ b/.changeset/37562-section-locate-edges.md @@ -0,0 +1,10 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): a record opened at a cited section no longer marks a same-titled heading the outline does not list, and opens its field at once when no heading can be told apart + +Clause-②: no +Metadata-protocol: none + +A record opened from a citation chip (`?section=ANCHOR`) finds the cited heading among the field's drawn headings that read the same, by count. When the body draws both a same-titled heading the outline does not list (a setext heading, one in a quote, a list item or a footnote, the footnote section's label) and a listed heading the face does not draw (one inside a raw HTML block), the two counts agreed while the index pointed at the wrong heading. A markdown body's unlisted headings are now counted from the field's own parse (`@object-ui/fields`' `loadDrawnMarkdownHeadings`, loaded on demand), so they are the headings the face draws; an html body's from its heading tags. When the body draws one, the field is opened instead of a heading that may be another section. That field, like the field of a cited heading with no letter or digit, is now scrolled to as soon as it is drawn instead of after the four-second settle; a titled heading that is not drawn yet still waits for it. diff --git a/ui/packages/app-shell/src/views/RecordDetailView.citedSection-37365.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.citedSection-37365.test.tsx index 6c47e78a154..465f2c9501b 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.citedSection-37365.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.citedSection-37365.test.tsx @@ -239,8 +239,8 @@ describe('a record opened at a cited section (objectstack#37365)', () => { const field = () => dup.container.querySelector('[data-detail-field="content"]'); await waitFor(() => expect(field()?.querySelectorAll('h1')).toHaveLength(2), { timeout: 4000 }); // Both drawn headings read `Scope`; the outline lists one. Nothing is - // marked, and once the settle (RECORD_SECTION_SETTLE_MS) passes the field - // is scrolled to. + // marked, and the field is scrolled to: at once, since the face's parse + // draws a same-titled heading the outline does not list (objectstack#37562 N3). expect(marked(dup.container)).toHaveLength(0); await waitFor(() => expect(scrolled).toEqual([field()]), { timeout: 7000 }); expect(marked(dup.container)).toHaveLength(0); diff --git a/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx index 788137c615a..a25b0ba7a01 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx @@ -12,11 +12,12 @@ * draws a different number of same-titled headings than the outline lists, the * field is opened rather than a heading that may be another one. */ -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { headingsOf } from '@objectstack/spec/ai'; import { RECORD_SECTION_TARGET_ATTR, focusRecordSection, + loadSectionHeadingReader, locateSection, sectionCandidates, } from './recordSectionAnchor'; @@ -43,6 +44,9 @@ function row(field: string, inner: string): string { return `
${inner}
`; } +// The markdown face's parse, loaded once, as the record page loads it. +beforeAll(() => loadSectionHeadingReader()); + afterEach(() => { document.body.innerHTML = ''; vi.useRealTimers(); @@ -60,24 +64,24 @@ describe('objectstack#37365 — sectionCandidates derives the anchor as the serv const server = headingsOf(MARKDOWN, false).map((h) => h.anchor); expect(server).toEqual(['intro', 'scope', 'scope-2']); expect(sectionCandidates(FIELDS, RECORD, 'scope')).toEqual([ - { field: 'content', face: 'markdown', reading: 'scope', ordinal: 0, count: 2 }, + { field: 'content', face: 'markdown', reading: 'scope', ordinal: 0, count: 2, unlisted: 0 }, ]); expect(sectionCandidates(FIELDS, RECORD, 'scope-2')).toEqual([ - { field: 'content', face: 'markdown', reading: 'scope', ordinal: 1, count: 2 }, + { field: 'content', face: 'markdown', reading: 'scope', ordinal: 1, count: 2, unlisted: 0 }, ]); }); it('reads an html body as html', () => { expect(headingsOf(HTML, true).map((h) => h.anchor)).toContain('data-privacy'); expect(sectionCandidates(FIELDS, RECORD, 'data-privacy')).toEqual([ - { field: 'legal', face: 'html', reading: 'dataprivacy', ordinal: 0, count: 1 }, + { field: 'legal', face: 'html', reading: 'dataprivacy', ordinal: 0, count: 1, unlisted: 0 }, ]); }); it('a `textarea` body is a candidate drawn as text', () => { const record = { ...RECORD, summary: '# Steps\n\nDo it.' }; expect(sectionCandidates(FIELDS, record, 'steps')).toEqual([ - { field: 'summary', face: 'text', reading: 'steps', ordinal: 0, count: 1 }, + { field: 'summary', face: 'text', reading: 'steps', ordinal: 0, count: 1, unlisted: 0 }, ]); }); @@ -109,7 +113,7 @@ describe('objectstack#37365 — locateSection finds the drawn heading', () => { const body = ['Scope', '=====', '', 'x', '', '# Scope', '', 'y'].join('\n'); expect(headingsOf(body, false).map((h) => h.anchor)).toEqual(['scope']); const candidates = sectionCandidates(FIELDS, { content: body }, 'scope'); - expect(candidates).toEqual([{ field: 'content', face: 'markdown', reading: 'scope', ordinal: 0, count: 1 }]); + expect(candidates).toEqual([{ field: 'content', face: 'markdown', reading: 'scope', ordinal: 0, count: 1, unlisted: 1 }]); document.body.innerHTML = row('content', '

Scope

x

Scope

y

'); const target = locateSection(document.body, candidates); expect(target?.field.getAttribute('data-detail-field')).toBe('content'); @@ -136,6 +140,91 @@ describe('objectstack#37365 — locateSection finds the drawn heading', () => { expect(locateSection(document.body, sectionCandidates(FIELDS, { content: control }, 'scope'))?.heading?.id).toBe('real'); }); + it('objectstack#37562 N6 — one unlisted same-titled heading plus one listed-but-undrawn heading opens the field, never a heading; CONTROL: the first Scope a paragraph line, the cited heading is marked', () => { + // A setext `Scope` the outline does not list, and `# Scope` inside a raw + // HTML block that the outline lists and the face does not draw: the face + // draws two `Scope`s and the outline lists two, so the count agrees while + // index 0 of the drawn ones is the setext heading, not the cited one. + const body = ['Scope', '=====', '', 'x', '', '
', '# Scope', '
', '', '# Scope', '', 'y'].join('\n'); + expect(headingsOf(body, false).map((h) => h.anchor)).toEqual(['scope', 'scope-2']); + document.body.innerHTML = row( + 'content', + '

Scope

x

# Scope

Scope

y

', + ); + for (const anchor of ['scope', 'scope-2']) { + const candidates = sectionCandidates(FIELDS, { content: body }, anchor); + expect(candidates).toEqual([ + { field: 'content', face: 'markdown', reading: 'scope', ordinal: anchor === 'scope' ? 0 : 1, count: 2, unlisted: 1 }, + ]); + const target = locateSection(document.body, candidates); + expect(target?.field.getAttribute('data-detail-field')).toBe('content'); + expect(target?.heading).toBeUndefined(); + } + // CONTROL: the first `Scope` a paragraph line, which no face draws as a + // heading; with the HTML block gone the outline and the face agree. + const control = ['Scope', '', 'x', '', '# Scope', '', 'y'].join('\n'); + expect(sectionCandidates(FIELDS, { content: control }, 'scope')).toEqual([ + { field: 'content', face: 'markdown', reading: 'scope', ordinal: 0, count: 1, unlisted: 0 }, + ]); + document.body.innerHTML = row('content', '

Scope

x

Scope

y

'); + expect(locateSection(document.body, sectionCandidates(FIELDS, { content: control }, 'scope'))?.heading?.id).toBe('atx'); + }); + + it.each([ + ['a setext heading', ['Scope', '-----']], + ['a two-line setext heading', ['Sco', 'pe', '===']], + ['a setext heading inside a quote', ['> Scope', '> ---']], + ['a setext heading under a comment line', ['', 'Scope', '---']], + ['a setext heading under a link definition', ['[a]: https://example.com', 'Scope', '===']], + ['a setext heading under indented code', [' code', 'Scope', '---']], + ['an ATX heading behind a quote', ['> # Scope']], + ['an ATX heading in a list item', ['1. ## Scope']], + ['an ATX heading behind blanks', [' # Scope']], + ['an ATX heading in a footnote', ['x[^1]', '', '[^1]: # Scope']], + ])('objectstack#37562 S1 — %s, which the face draws, counts as unlisted', (_shape, lines) => { + const value = [...lines, '', '# Scope'].join('\n'); + expect(sectionCandidates(FIELDS, { content: value }, 'scope')[0]?.unlisted).toBe(1); + }); + + it("objectstack#37562 S1 — the footnote section's Footnotes label counts against a cited `Footnotes`; CONTROL: with no footnote, none", () => { + const value = ['# Footnotes', '', 'x[^1]', '', '[^1]: y'].join('\n'); + expect(sectionCandidates(FIELDS, { content: value }, 'footnotes')[0]?.unlisted).toBe(1); + expect(sectionCandidates(FIELDS, { content: '# Footnotes\n\nx' }, 'footnotes')[0]?.unlisted).toBe(0); + }); + + it.each([ + ['a raw heading tag', ['

Scope

']], + ['an indented code line', [' # Scope']], + ['a lazy quote line over a rule', ['> Scope', '---']], + ['fenced code', ['```', 'Scope', '===', '> # Scope', '```']], + ['other titles, a rule under a blank line, a plain list item', ['Preface', '=======', '', '> # Intro', '', '---', '', '- Scope']], + ])('objectstack#37562 N1 — %s, which the face never draws, does not count', (_shape, lines) => { + const value = [...lines, '', '# Scope'].join('\n'); + expect(sectionCandidates(FIELDS, { content: value }, 'scope')[0]?.unlisted).toBe(0); + }); + + it('an html body counts a heading tag left unclosed or opened inside another; CONTROL: hr and header tags count none', () => { + const unlisted = (value: string): number | undefined => sectionCandidates(FIELDS, { legal: value }, 'scope')[0]?.unlisted; + expect(unlisted('

Scope

x

Scope')).toBe(1); + expect(unlisted('

About

Scope

Scope

')).toBe(1); + expect(unlisted('

Scope


Scope
')).toBe(0); + }); + + it('objectstack#37562 — before the face’s parse loads, a markdown count is not trusted; once it loads, the heading is marked', async () => { + vi.resetModules(); + const fresh = await import('./recordSectionAnchor'); + const candidates = fresh.sectionCandidates(FIELDS, RECORD, 'scope'); + expect(candidates[0].unlisted).toBeUndefined(); + document.body.innerHTML = row('content', '

Intro

Scope

Scope

'); + expect(fresh.locateSection(document.body, candidates)?.heading).toBeUndefined(); + const heading = document.getElementById('s')!; + heading.scrollIntoView = vi.fn(); + fresh.focusRecordSection(document.body, candidates, 5000); + expect(heading.hasAttribute(RECORD_SECTION_TARGET_ATTR)).toBe(false); + await vi.waitFor(() => expect(heading.getAttribute(RECORD_SECTION_TARGET_ATTR)).toBe('true'), { timeout: 5000 }); + expect(heading.scrollIntoView).toHaveBeenCalledTimes(1); + }); + it('a heading with no letter or digit opens the field; CONTROL: a titled heading beside it is marked', () => { const body = ['# ???', '', 'x', '', '# Intro', '', 'y'].join('\n'); const [blank, intro] = headingsOf(body, false); @@ -200,6 +289,50 @@ describe('objectstack#37365 — focusRecordSection', () => { expect(document.querySelector(`[${RECORD_SECTION_TARGET_ATTR}]`)).toBeNull(); }); + it('objectstack#37562 N7 — a heading that reads as nothing scrolls to the field at once; CONTROL: a titled heading not yet drawn still waits for the settle', () => { + vi.useFakeTimers(); + const body = ['# ???', '', 'x', '', '# Intro', '', 'y'].join('\n'); + const [blank, intro] = headingsOf(body, false); + document.body.innerHTML = row('content', '

loading

'); + const field = document.querySelector('[data-detail-field="content"]')!; + const scroll = vi.fn(); + field.scrollIntoView = scroll; + focusRecordSection(document.body, sectionCandidates(FIELDS, { content: body }, blank.anchor), 50); + expect(scroll).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(60); + expect(scroll).toHaveBeenCalledTimes(1); + expect(document.querySelector(`[${RECORD_SECTION_TARGET_ATTR}]`)).toBeNull(); + // CONTROL: `Intro` is not drawn yet, so the page waits for it until the settle. + scroll.mockClear(); + focusRecordSection(document.body, sectionCandidates(FIELDS, { content: body }, intro.anchor), 50); + expect(scroll).not.toHaveBeenCalled(); + vi.advanceTimersByTime(60); + expect(scroll).toHaveBeenCalledTimes(1); + }); + + it('objectstack#37562 N3 — a body drawing a same-titled heading the outline does not list scrolls to the field at once; CONTROL: without it, an undrawn heading still waits for the settle', () => { + vi.useFakeTimers(); + const body = ['Scope', '=====', '', 'x', '', '# Scope', '', 'y'].join('\n'); + document.body.innerHTML = row('content', '

Scope

x

Scope

y

'); + const field = document.querySelector('[data-detail-field="content"]')!; + const scroll = vi.fn(); + field.scrollIntoView = scroll; + focusRecordSection(document.body, sectionCandidates(FIELDS, { content: body }, 'scope'), 50); + expect(scroll).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(60); + expect(scroll).toHaveBeenCalledTimes(1); + expect(document.querySelector(`[${RECORD_SECTION_TARGET_ATTR}]`)).toBeNull(); + // CONTROL: the setext heading titled otherwise and `Scope` not drawn yet. + scroll.mockClear(); + document.body.innerHTML = row('content', '

Preface

x

loading

'); + document.querySelector('[data-detail-field="content"]')!.scrollIntoView = scroll; + const control = ['Preface', '=======', '', 'x', '', '# Scope', '', 'y'].join('\n'); + focusRecordSection(document.body, sectionCandidates(FIELDS, { content: control }, 'scope'), 50); + expect(scroll).not.toHaveBeenCalled(); + vi.advanceTimersByTime(60); + expect(scroll).toHaveBeenCalledTimes(1); + }); + it('a heading never drawn settles on the field, with no error', () => { vi.useFakeTimers(); document.body.innerHTML = row('content', '

Scope is not a heading here

'); diff --git a/ui/packages/app-shell/src/views/recordSectionAnchor.ts b/ui/packages/app-shell/src/views/recordSectionAnchor.ts index f7629ec5c42..c5fa5fb7134 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.ts +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.ts @@ -23,22 +23,30 @@ * than by bare position keeps a heading of another title that the outline does * not list (a setext heading, an empty one, one inside a quote) from shifting * every later one onto the wrong section. The count is trusted only when the - * face draws exactly as many headings of that reading as the outline lists: a + * face draws exactly as many headings of that reading as the outline lists, + * and the body draws no heading of that reading the outline does not list: a * same-titled heading the outline does not list, or a listed one the face does - * not draw, would move the index onto another heading, so then the field is - * opened instead. + * not draw, would move the index onto another heading, and one of each would + * leave the count equal while doing it, so then the field is opened instead. + * A markdown body's unlisted headings are counted from the face's own parse + * (`@object-ui/fields`' `loadDrawnMarkdownHeadings`, loaded on demand), so they + * are the ones drawn by construction; an html body's from its heading tags. * - * - A `textarea` body draws no heading elements, so the field is scrolled to. + * - A `textarea` body draws no heading elements, so the field is scrolled to + * as soon as it is drawn. So is a heading with no letter or digit, which no + * reading tells apart, and one whose body draws a same-titled heading the + * outline does not list: no drawing of the face can change those answers. * - A heading that is not drawn (the face has not rendered it, reads it * differently, or draws a different number of same-titled headings than the - * outline lists) also scrolls to the field, with no error. So does a heading - * with no letter or digit, which no reading tells apart. + * outline lists) also scrolls to the field, with no error, once + * {@link RECORD_SECTION_SETTLE_MS} pass. * - An anchor no field resolves (a stale one: the heading was renamed or * removed) opens the record at its top, as if no section were named. * * Nothing here re-verifies a citation: the anchor is only a place to open at. */ -import { headingsOf } from '@objectstack/spec/ai'; +import { headingsOf, stripBodyTags, type BodyHeading } from '@objectstack/spec/ai'; +import { loadDrawnMarkdownHeadings, type DrawnMarkdownHeading } from '@object-ui/fields'; /** The attribute a marked heading carries. */ export const RECORD_SECTION_TARGET_ATTR = 'data-record-section-target'; @@ -83,6 +91,14 @@ export interface SectionCandidate { ordinal: number; /** How many of the field's headings, in all, read the same: what the drawn face must match. */ count: number; + /** + * How many headings that read the same the body draws and the outline does + * not list (a setext heading, one in a quote, a list item or a footnote, the + * footnote section's label): any one leaves the count unable to say which + * drawn heading is the cited one. `undefined` while the markdown face's + * parse is not loaded: the count is then not trusted. + */ + unlisted: number | undefined; } /** What a drawn section resolved to: the field's row, and the heading when it is drawn. */ @@ -90,6 +106,11 @@ export interface SectionTarget { field: HTMLElement; face: SectionFace; heading?: HTMLElement; + /** + * The field is the whole answer, whatever the face goes on to draw: it draws + * no heading elements (`textarea`), or the heading reads as nothing. + */ + fieldOnly?: true; } /** `text`'s letters and digits of every script, lowercased. */ @@ -97,6 +118,94 @@ export function headingReading(text: string): string { return text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ''); } +/** A raw heading tag's opener (`` or `
`) at `at` of `lower`. */ +function isHeadingOpener(lower: string, at: number): boolean { + const level = lower.charCodeAt(at + 2) - 48; + return lower.startsWith('= 1 && level <= 6 && !/^[a-z0-9_]$/.test(lower[at + 3] ?? ''); +} + +/** The entities the spec's outline decodes, each one a character no reading keeps. */ +function blankEntities(text: string): string { + return text.replace(/&(?:nbsp|lt|gt|quot|amp|#39);/g, ' '); +} + +/** + * The texts of every heading tag in an html `value` that the outline + * (`headings`) does not list: one left unclosed, or opened inside another. + */ +function unlistedHtmlHeadingTexts(value: string, headings: readonly BodyHeading[]): string[] { + const listed = new Set(headings.map((h) => h.start)); + const out: string[] = []; + { + // Every search remembers where it landed and starts no earlier than an + // earlier one, so the scan stays linear however many openers are unclosed. + const lower = value.toLowerCase(); + let gt = -2; + let closer = -2; + for (let at = lower.indexOf('= 0; at = lower.indexOf('', at); + if (gt < 0) break; + if (closer !== -1 && closer < gt) closer = lower.indexOf('= 0 && next < end; next = lower.indexOf(' DrawnMarkdownHeading[]) | undefined; +let readerLoading: Promise | undefined; + +/** + * Loads the markdown face's heading reader, once. A load that fails leaves + * the reader unloaded, so a markdown body's count stays untrusted (the field + * is opened, never a heading that may be another section) and a later call + * tries again. + */ +export function loadSectionHeadingReader(): Promise { + if (readDrawnMarkdown) return Promise.resolve(); + readerLoading ??= loadDrawnMarkdownHeadings().then( + (read) => { + readDrawnMarkdown = read; + }, + () => { + readerLoading = undefined; + }, + ); + return readerLoading; +} + +/** + * How many headings reading `reading` the markdown `value` draws that are not + * the outline's headings of that reading (`listedAt`, their starts), or + * `undefined` while the reader is not loaded. + */ +function unlistedMarkdownCount(value: string, reading: string, listedAt: ReadonlySet): number | undefined { + if (!readDrawnMarkdown) return undefined; + return readDrawnMarkdown(value).filter( + (h) => headingReading(h.text) === reading && (h.start === undefined || !listedAt.has(h.start)), + ).length; +} + +/** A markdown candidate counted before the reader loaded: how to count it once it has. */ +const pendingUnlisted = new WeakMap number | undefined>(); + +/** `candidate`, with its unlisted count read now when it was pending. */ +function withUnlistedCount(candidate: SectionCandidate): SectionCandidate { + if (candidate.unlisted !== undefined) return candidate; + const unlisted = pendingUnlisted.get(candidate)?.(); + // Still unread (the reader did not load): the same candidate, so a later read finds its count. + return unlisted === undefined ? candidate : { ...candidate, unlisted }; +} + /** * The fields of `record` whose body holds `anchor`, in `fields`' order. Empty * when the anchor is stale, or names no long-text field the record holds. @@ -119,7 +228,17 @@ export function sectionCandidates( const readings = headings.map((h) => headingReading(h.heading)); const ordinal = readings.slice(0, at).filter((r) => r === reading).length; const count = readings.filter((r) => r === reading).length; - out.push({ field, face, reading, ordinal, count }); + const listedAt = new Set(headings.filter((_, i) => readings[i] === reading).map((h) => h.start)); + const countMarkdown = (): number | undefined => unlistedMarkdownCount(value, reading, listedAt); + const unlisted = + face === 'text' || reading === '' + ? 0 + : face === 'html' + ? unlistedHtmlHeadingTexts(value, headings).filter((t) => headingReading(t) === reading).length + : countMarkdown(); + const candidate: SectionCandidate = { field, face, reading, ordinal, count, unlisted }; + if (unlisted === undefined) pendingUnlisted.set(candidate, countMarkdown); + out.push(candidate); } return out; } @@ -131,8 +250,9 @@ function escapeAttr(value: string): string { /** * The drawn place of the first candidate whose field is on the page: the - * field's row, with the heading when the face draws it, and draws as many - * headings of its reading as the outline lists. `undefined` when no + * field's row, with the heading when the face draws it, draws as many + * headings of its reading as the outline lists, and the body holds no + * same-titled heading the outline does not list. `undefined` when no * candidate's field is drawn. */ export function locateSection(root: ParentNode, candidates: readonly SectionCandidate[]): SectionTarget | undefined { @@ -140,11 +260,12 @@ export function locateSection(root: ParentNode, candidates: readonly SectionCand const field = root.querySelector(`[${DETAIL_FIELD_ATTR}="${escapeAttr(candidate.field)}"]`); if (!field) continue; const { face } = candidate; - if (face === 'text' || candidate.reading === '') return { field, face }; + if (face === 'text' || candidate.reading === '' || (candidate.unlisted ?? 0) > 0) return { field, face, fieldOnly: true }; const drawn = Array.from(field.querySelectorAll('h1, h2, h3, h4, h5, h6')).filter( (el) => headingReading(el.textContent ?? '') === candidate.reading, ); - const heading = drawn.length === candidate.count ? drawn[candidate.ordinal] : undefined; + const counted = candidate.unlisted === 0 && drawn.length === candidate.count; + const heading = counted ? drawn[candidate.ordinal] : undefined; return heading ? { field, face, heading } : { field, face }; } return undefined; @@ -170,8 +291,12 @@ function scrollIntoStart(el: HTMLElement): void { /** * Opens the page at the cited section once it is drawn: the heading scrolled - * to and marked, or the field scrolled to (a `textarea` body at once, any - * other once {@link RECORD_SECTION_SETTLE_MS} pass without the heading). With + * to and marked, or the field scrolled to (at once when the field is the whole + * answer — a `textarea` body, a heading that reads as nothing, or one whose + * body draws a same-titled heading the outline does not list — and otherwise + * once {@link RECORD_SECTION_SETTLE_MS} pass without the heading). A markdown + * candidate counted before the face's parse loaded is counted once it has + * (`loadSectionHeadingReader`); until then no heading is trusted. With * no candidate, or no candidate field drawn by then, nothing moves. Answers * the cleanup, which also takes the mark off: a page opened at another * section, or at the same one again, marks only the section it opens. @@ -189,6 +314,7 @@ export function focusRecordSection( if (mayScroll()) scrollIntoStart(el); }; if (candidates.length === 0) return () => {}; + let current = candidates.map(withUnlistedCount); let done = false; let observer: MutationObserver | undefined; const pending: { timer?: ReturnType; unmark?: () => void } = {}; @@ -204,25 +330,31 @@ export function focusRecordSection( }; const attempt = (): void => { if (done) return; - const target = locateSection(root, candidates); + const target = locateSection(root, current); if (target?.heading) { finish(); pending.unmark = markSection(target.heading); scrollTo(target.heading); - } else if (target?.face === 'text') { + } else if (target?.fieldOnly) { finish(); scrollTo(target.field); } }; attempt(); if (done) return cleanup; + if (current.some((c) => c.unlisted === undefined)) { + void loadSectionHeadingReader().then(() => { + current = current.map(withUnlistedCount); + attempt(); + }); + } if (typeof MutationObserver === 'function') { observer = new MutationObserver(attempt); observer.observe(root, { childList: true, subtree: true, characterData: true }); } pending.timer = setTimeout(() => { if (done) return; - const target = locateSection(root, candidates); + const target = locateSection(root, current); finish(); if (target?.heading) { pending.unmark = markSection(target.heading); diff --git a/ui/packages/fields/src/__tests__/markdownHeadings-37562.test.tsx b/ui/packages/fields/src/__tests__/markdownHeadings-37562.test.tsx new file mode 100644 index 00000000000..0f747e2c4b6 --- /dev/null +++ b/ui/packages/fields/src/__tests__/markdownHeadings-37562.test.tsx @@ -0,0 +1,73 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#37562 — `drawnMarkdownHeadings` answers the headings the + * markdown `document` face draws, read from the face's own pipeline, so a + * reader that must agree with the drawn page counts what is drawn by + * construction: every shape below is pinned against the face, not against a + * second markdown reader. + */ +import { describe, expect, it } from 'vitest'; +import React from 'react'; +import { render } from '@testing-library/react'; +import MarkdownContent from '../widgets/MarkdownContent'; +import { drawnMarkdownHeadings } from '../widgets/markdownHeadings'; +import { loadDrawnMarkdownHeadings } from '../index'; + +const texts = (value: string): string[] => drawnMarkdownHeadings(value).map((h) => h.text); + +/** What the face itself draws, read off the DOM: the reader must answer the same. */ +function drawnByFace(value: string): string[] { + const { container, unmount } = render(React.createElement(MarkdownContent, { value })); + const out = Array.from(container.querySelectorAll('h1, h2, h3, h4, h5, h6')).map((h) => h.textContent ?? ''); + unmount(); + return out; +} + +describe('objectstack#37562 — drawnMarkdownHeadings reads the face’s own parse', () => { + it('answers each heading with its text and where it starts', () => { + const value = ['# Intro', '', 'x', '', '## Data & *privacy*', '', 'y'].join('\n'); + expect(drawnMarkdownHeadings(value)).toEqual([ + { text: 'Intro', start: 0 }, + { text: 'Data & privacy', start: value.indexOf('## Data') }, + ]); + }); + + it.each([ + ['a setext heading inside a quote', ['> Scope', '> ---'], ['Scope']], + ['a setext heading under a comment line', ['', 'Scope', '---'], ['Scope']], + ['a setext heading under a link definition', ['[a]: https://example.com', 'Scope', '==='], ['Scope']], + ['a setext heading under indented code', [' code', 'Scope', '---'], ['Scope']], + ['an ATX heading in a footnote, with the Footnotes label the section draws', ['x[^1]', '', '[^1]: # Scope'], ['Footnotes', 'Scope']], + ['an ATX heading behind a quote or a list marker', ['> # Scope', '', '- # Scope'], ['Scope', 'Scope']], + ])('S1 — %s is drawn, and answered', (_shape, lines, expected) => { + const value = lines.join('\n'); + expect(texts(value)).toEqual(expected); + expect(drawnByFace(value)).toEqual(expected); + }); + + it.each([ + ['a raw heading tag', ['

Scope

']], + ['an indented code line', [' # Scope']], + ['a lazy quote line over a rule', ['> Scope', '---']], + ['fenced code', ['```', 'Scope', '===', '# Scope', '```']], + ])('N1 — %s draws no heading, and is not answered', (_shape, lines) => { + const value = lines.join('\n'); + expect(texts(value)).toEqual([]); + expect(drawnByFace(value)).toEqual([]); + }); + + it('the Footnotes label starts nowhere in the value', () => { + expect(drawnMarkdownHeadings(['x[^1]', '', '[^1]: y'].join('\n'))).toEqual([{ text: 'Footnotes', start: undefined }]); + }); + + it('the package index loads the same reader', async () => { + expect(await loadDrawnMarkdownHeadings()).toBe(drawnMarkdownHeadings); + }); +}); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 571c2035067..0fce0654531 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -5555,5 +5555,16 @@ export { useUploadingScope, UploadingScopeProvider } from './widgets/uploadingSc export { useUploadingSignal } from './widgets/useUploadingSignal.js'; export type { UploadingScope } from './widgets/uploadingScope.js'; +// The headings a markdown value's `document` face draws, read from the face's +// own parse (`./widgets/markdownHeadings.ts`, objectstack#37562): a reader that +// must agree with the drawn page (the record page opening a cited section) +// counts them here, never with a second markdown reader. Loaded on demand +// through `MarkdownContent`, the module the face itself loads on demand, so +// react-markdown stays in that lazy chunk. +export function loadDrawnMarkdownHeadings(): Promise { + return import('./widgets/MarkdownContent.js').then((m) => m.drawnMarkdownHeadings); +} +export type { DrawnMarkdownHeading } from './widgets/markdownHeadings.js'; + // Initialize registry registerAllFields(); diff --git a/ui/packages/fields/src/widgets/MarkdownContent.tsx b/ui/packages/fields/src/widgets/MarkdownContent.tsx index 0a397905956..4589270e780 100644 --- a/ui/packages/fields/src/widgets/MarkdownContent.tsx +++ b/ui/packages/fields/src/widgets/MarkdownContent.tsx @@ -1,8 +1,6 @@ import React from 'react'; import ReactMarkdown, { type Components } from 'react-markdown'; -import remarkGfm from 'remark-gfm'; -import rehypeSanitize from 'rehype-sanitize'; -import { RICH_TEXT_SANITIZE_SCHEMA } from './sanitizedHtml.js'; +import { MARKDOWN_REHYPE_PLUGINS, MARKDOWN_REMARK_PLUGINS } from './markdownHeadings.js'; import { RICH_TEXT_CELL_FACE_CLASS, RICH_TEXT_DOCUMENT_CLASS, @@ -17,6 +15,15 @@ import { */ export type MarkdownFace = RichTextFace; +/** + * The plugin lists this face draws with, and the reader of the headings it + * draws, which runs the same lists (objectstack#37562). They live in + * `./markdownHeadings.ts` and are answered from here, so the one module the + * package loads on demand for markdown is this one: a module both loaded on + * demand and imported statically would not leave the eager chunk. + */ +export { MARKDOWN_REHYPE_PLUGINS, MARKDOWN_REMARK_PLUGINS, drawnMarkdownHeadings } from './markdownHeadings.js'; + /** In the cell face no heading element is drawn (see `cellFaceHeadings`). */ const CELL_COMPONENTS: Components = cellFaceHeadings('data-markdown-heading'); @@ -31,8 +38,8 @@ export default function MarkdownContent({ value, face = 'document' }: { value: s return (
{value} diff --git a/ui/packages/fields/src/widgets/markdownHeadings.ts b/ui/packages/fields/src/widgets/markdownHeadings.ts new file mode 100644 index 00000000000..09bd6cc6e38 --- /dev/null +++ b/ui/packages/fields/src/widgets/markdownHeadings.ts @@ -0,0 +1,77 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The headings a markdown value's `document` face draws (objectstack#37562). + * + * The value is run through the face's own pipeline: react-markdown with + * `MARKDOWN_REMARK_PLUGINS` and `MARKDOWN_REHYPE_PLUGINS`, the lists + * `./MarkdownContent.tsx` draws with, declared here once for both, and the + * tree is read after the last of them, so the headings answered are the + * ones drawn, by construction: a setext heading, one inside a quote, a list item + * or a footnote, and the `Footnotes` label the footnote section draws are + * answered; a raw heading tag, a heading-shaped line in code and a line the + * parse reads as something else are not. + * + * Loaded on demand through `./MarkdownContent.tsx` (`loadDrawnMarkdownHeadings` + * in the package index), so react-markdown stays in the lazy chunk the face + * lives in. + */ +import Markdown, { type Options } from 'react-markdown'; +import remarkGfm from 'remark-gfm'; +import rehypeSanitize from 'rehype-sanitize'; +import { RICH_TEXT_SANITIZE_SCHEMA } from './sanitizedHtml.js'; + +/** The remark plugins a markdown value is parsed with: GitHub Flavored Markdown. */ +export const MARKDOWN_REMARK_PLUGINS: NonNullable = [remarkGfm]; + +/** The rehype plugins the parsed value is drawn through: sanitized, against the `html` / `richtext` schema. */ +export const MARKDOWN_REHYPE_PLUGINS: NonNullable = [[rehypeSanitize, RICH_TEXT_SANITIZE_SCHEMA]]; + +/** One drawn heading: its text as the face draws it, and where it starts in the value (none for a heading the pipeline adds). */ +export interface DrawnMarkdownHeading { + text: string; + start: number | undefined; +} + +/** The part of a drawn tree's node this reader looks at. */ +interface DrawnNode { + type: string; + tagName?: string; + value?: string; + children?: DrawnNode[]; + position?: { start?: { offset?: number } }; +} + +const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']); + +function textOf(node: DrawnNode): string { + if (node.type === 'text') return node.value ?? ''; + return (node.children ?? []).map(textOf).join(''); +} + +/** The headings `value` draws in the markdown `document` face, in document order. */ +export function drawnMarkdownHeadings(value: string): DrawnMarkdownHeading[] { + let drawn: DrawnNode | undefined; + const readTree = () => (tree: DrawnNode) => { + drawn = tree; + }; + // `Markdown` holds no hooks: called as a function it runs the face's + // pipeline once, and `readTree` sees the tree after every plugin the face uses. + Markdown({ children: value, remarkPlugins: MARKDOWN_REMARK_PLUGINS, rehypePlugins: [...MARKDOWN_REHYPE_PLUGINS, readTree] }); + const out: DrawnMarkdownHeading[] = []; + const walk = (node: DrawnNode): void => { + if (node.type === 'element' && node.tagName && HEADING_TAGS.has(node.tagName)) { + out.push({ text: textOf(node), start: node.position?.start?.offset }); + return; + } + node.children?.forEach(walk); + }; + if (drawn) walk(drawn); + return out; +}