From d421d210575285cdbf0b6158f27e2848c1097faf Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:22:30 +0000 Subject: [PATCH 1/6] fix(app-shell): cited-section locator tells an unlisted same-titled heading from an undrawn one, and opens a heading that reads as nothing at once Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc Co-authored-by: Claude --- .../src/views/recordSectionAnchor.test.tsx | 81 +++++++- .../src/views/recordSectionAnchor.ts | 186 ++++++++++++++++-- 2 files changed, 246 insertions(+), 21 deletions(-) diff --git a/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx index 788137c615a..57e841173dd 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx @@ -60,24 +60,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 +109,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: 0 }]); 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 +136,56 @@ 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('objectstack#37562 N6 — counts every place a face draws a same-titled heading the outline does not list; CONTROL: other titles and fenced code count none', () => { + const unlisted = (value: string, field = 'content'): number | undefined => + sectionCandidates(FIELDS, { [field]: value }, 'scope')[0]?.unlisted; + const atx = '# Scope'; + expect(unlisted(['Scope', '-----', '', atx].join('\n'))).toBe(1); + expect(unlisted(['Sco', 'pe', '===', '', atx].join('\n'))).toBe(1); + expect(unlisted(['> # Scope', '', atx].join('\n'))).toBe(1); + expect(unlisted(['- # Scope', '', atx].join('\n'))).toBe(1); + expect(unlisted(['1. ## Scope', '', atx].join('\n'))).toBe(1); + expect(unlisted([' # Scope', '', atx].join('\n'))).toBe(1); + expect(unlisted(['

Scope

', '', atx].join('\n'))).toBe(1); + // An html body: a heading tag left unclosed, and one opened inside another. + expect(unlisted('

Scope

x

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

About

Scope

Scope

', 'legal')).toBe(1); + // CONTROL: other titles, a rule under a blank line, a list item, fenced code. + expect(unlisted(['Preface', '=======', '', '> # Intro', '', '---', '', '- Scope', '', atx].join('\n'))).toBe(0); + expect(unlisted(['```', 'Scope', '===', '> # Scope', '```', '', atx].join('\n'))).toBe(0); + expect(unlisted('

Scope


Scope
', 'legal')).toBe(0); + }); + 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 +250,27 @@ 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('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..03e5ab195de 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.ts +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.ts @@ -23,22 +23,27 @@ * 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 - * 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. + * face draws exactly as many headings of that reading as the outline lists, + * and the body holds no place outside the outline that could draw a heading + * of that reading: 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, and one of each would leave the count equal while doing it, so then + * the field is opened instead. * - * - 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: no drawing of the face can change that answer. * - 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. So does a heading whose body holds + * a same-titled heading the outline does not list. * - 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'; /** The attribute a marked heading carries. */ export const RECORD_SECTION_TARGET_ATTR = 'data-record-section-target'; @@ -83,6 +88,13 @@ 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 places of the body, outside the outline, could draw a heading + * that reads the same (a setext heading, one in a quote or a list item, a + * raw heading tag): any one leaves the count unable to say which drawn + * heading is the cited one. + */ + unlisted: number; } /** What a drawn section resolved to: the field's row, and the heading when it is drawn. */ @@ -90,6 +102,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 +114,136 @@ export function headingReading(text: string): string { return text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ''); } +const isBlank = (c: string | undefined): boolean => c === ' ' || c === '\t'; + +/** Whether `line` opens or closes a fenced code block, as the spec's outline reads one. */ +function isFence(line: string): boolean { + let i = 0; + while (i < line.length && isBlank(line[i])) i++; + return line.startsWith('```', i) || line.startsWith('~~~', i); +} + +/** A setext underline: up to three blanks, a run of `=` or of `-`, trailing blanks. */ +function isSetextUnderline(line: string): boolean { + let i = 0; + while (i < 3 && line[i] === ' ') i++; + const mark = line[i]; + if (mark !== '=' && mark !== '-') return false; + while (line[i] === mark) i++; + while (isBlank(line[i])) i++; + return i === line.length; +} + +/** + * The text of an ATX heading behind a container prefix (blanks, `>` quotes, + * list markers), or `undefined` when `line` is no such heading. A forward + * scan: a body is author-written, so no pattern that can backtrack. + */ +function containedAtxText(line: string): string | undefined { + let i = 0; + for (;;) { + while (isBlank(line[i])) i++; + if (line[i] === '>') { + i++; + continue; + } + if ((line[i] === '-' || line[i] === '*' || line[i] === '+') && isBlank(line[i + 1])) { + i++; + continue; + } + let j = i; + while (j - i < 9 && line[j] !== undefined && line[j] >= '0' && line[j] <= '9') j++; + if (j > i && (line[j] === '.' || line[j] === ')') && isBlank(line[j + 1])) { + i = j + 1; + continue; + } + break; + } + let level = 0; + while (line[i + level] === '#') level++; + if (level < 1 || level > 6) return undefined; + const after = line[i + level]; + return after === undefined || isBlank(after) ? line.slice(i + level) : undefined; +} + +/** 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 place in `value` that a face could draw as a heading the + * outline (`headings`) does not list. Markdown: a setext heading, an ATX + * heading behind a quote, a list marker or a blank, and a line holding a raw + * heading tag; fenced code draws none. HTML: a heading tag the outline does + * not list (one left unclosed, or opened inside another). + */ +function unlistedHeadingTexts(value: string, html: boolean, headings: readonly BodyHeading[]): string[] { + const listed = new Set(headings.map((h) => h.start)); + const out: string[] = []; + if (html) { + // 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(' 0 && isSetextUnderline(line)) { + out.push(paragraph.join(' ')); + paragraph = []; + continue; + } + const atx = containedAtxText(line); + const lower = line.toLowerCase(); + let tag = false; + for (let at = lower.indexOf('= 0 && !tag; at = lower.indexOf(' 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 unlisted = + face === 'text' || reading === '' + ? 0 + : unlistedHeadingTexts(value, face === 'html', headings).filter((t) => headingReading(t) === reading).length; + out.push({ field, face, reading, ordinal, count, unlisted }); } return out; } @@ -131,8 +282,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 +292,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 === '') 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 +323,9 @@ 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, or a heading that reads as nothing — and + * otherwise once {@link RECORD_SECTION_SETTLE_MS} pass without the heading). 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. @@ -209,7 +363,7 @@ export function focusRecordSection( finish(); pending.unmark = markSection(target.heading); scrollTo(target.heading); - } else if (target?.face === 'text') { + } else if (target?.fieldOnly) { finish(); scrollTo(target.field); } From 590e20b184d87e310c86df4cf6dd9245702b7f5b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:31:35 +0000 Subject: [PATCH 2/6] test(app-shell): the setext case's candidate counts its unlisted heading Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc Co-authored-by: Claude --- ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx index 57e841173dd..5cc67260866 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx @@ -109,7 +109,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, unlisted: 0 }]); + 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'); From c41e2768d34596930bd8076a40993328b1763412 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:33:30 +0000 Subject: [PATCH 3/6] chore(changeset): app-shell cited-section locator edges Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc Co-authored-by: Claude --- .changeset/37562-section-locate-edges.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .changeset/37562-section-locate-edges.md diff --git a/.changeset/37562-section-locate-edges.md b/.changeset/37562-section-locate-edges.md new file mode 100644 index 00000000000..d6462b19d55 --- /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 a heading that reads as nothing opens its field at once + +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 holds both a same-titled heading the outline does not list (a setext heading, one in a quote or a list item, a raw heading tag) 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. The body is now read for such headings as well, and when it holds one the field is opened instead of a heading that may be another section. A cited heading with no letter or digit, which no drawn heading can be matched to, now scrolls to its field as soon as the field is drawn, instead of after the four-second settle; a titled heading that is not drawn yet still waits for it. From 6e26af7980fbcc116fa908689f46e5700b0633ad Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:35:32 +0000 Subject: [PATCH 4/6] fix(app-shell,fields): count a markdown body's unlisted headings from the field's own parse Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc Co-authored-by: Claude --- ...cordDetailView.citedSection-37365.test.tsx | 4 +- .../src/views/recordSectionAnchor.test.tsx | 100 +++++++-- .../src/views/recordSectionAnchor.ts | 200 ++++++++---------- .../__tests__/markdownHeadings-37562.test.tsx | 73 +++++++ ui/packages/fields/src/index.tsx | 10 + .../fields/src/widgets/MarkdownContent.tsx | 16 +- .../fields/src/widgets/markdownHeadings.ts | 67 ++++++ 7 files changed, 334 insertions(+), 136 deletions(-) create mode 100644 ui/packages/fields/src/__tests__/markdownHeadings-37562.test.tsx create mode 100644 ui/packages/fields/src/widgets/markdownHeadings.ts 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 5cc67260866..6b466e66a02 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(); @@ -166,24 +170,59 @@ describe('objectstack#37365 — locateSection finds the drawn heading', () => { expect(locateSection(document.body, sectionCandidates(FIELDS, { content: control }, 'scope'))?.heading?.id).toBe('atx'); }); - it('objectstack#37562 N6 — counts every place a face draws a same-titled heading the outline does not list; CONTROL: other titles and fenced code count none', () => { - const unlisted = (value: string, field = 'content'): number | undefined => - sectionCandidates(FIELDS, { [field]: value }, 'scope')[0]?.unlisted; - const atx = '# Scope'; - expect(unlisted(['Scope', '-----', '', atx].join('\n'))).toBe(1); - expect(unlisted(['Sco', 'pe', '===', '', atx].join('\n'))).toBe(1); - expect(unlisted(['> # Scope', '', atx].join('\n'))).toBe(1); - expect(unlisted(['- # Scope', '', atx].join('\n'))).toBe(1); - expect(unlisted(['1. ## Scope', '', atx].join('\n'))).toBe(1); - expect(unlisted([' # Scope', '', atx].join('\n'))).toBe(1); - expect(unlisted(['

Scope

', '', atx].join('\n'))).toBe(1); - // An html body: a heading tag left unclosed, and one opened inside another. - expect(unlisted('

Scope

x

Scope', 'legal')).toBe(1); - expect(unlisted('

About

Scope

Scope

', 'legal')).toBe(1); - // CONTROL: other titles, a rule under a blank line, a list item, fenced code. - expect(unlisted(['Preface', '=======', '', '> # Intro', '', '---', '', '- Scope', '', atx].join('\n'))).toBe(0); - expect(unlisted(['```', 'Scope', '===', '> # Scope', '```', '', atx].join('\n'))).toBe(0); - expect(unlisted('

Scope


Scope
', 'legal')).toBe(0); + 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')); + expect(heading.scrollIntoView).toHaveBeenCalledTimes(1); }); it('a heading with no letter or digit opens the field; CONTROL: a titled heading beside it is marked', () => { @@ -271,6 +310,29 @@ describe('objectstack#37365 — focusRecordSection', () => { 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 03e5ab195de..270b4cc6835 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.ts +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.ts @@ -24,26 +24,29 @@ * 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, - * and the body holds no place outside the outline that could draw a heading - * of that reading: 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, and one of each would leave the count equal while doing it, so then - * the field is opened instead. + * 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, 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 * as soon as it is drawn. So is a heading with no letter or digit, which no - * reading tells apart: no drawing of the face can change that answer. + * 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, once - * {@link RECORD_SECTION_SETTLE_MS} pass. So does a heading whose body holds - * a same-titled heading the outline does not list. + * {@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, 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'; @@ -89,12 +92,13 @@ export interface SectionCandidate { /** How many of the field's headings, in all, read the same: what the drawn face must match. */ count: number; /** - * How many places of the body, outside the outline, could draw a heading - * that reads the same (a setext heading, one in a quote or a list item, a - * raw heading tag): any one leaves the count unable to say which drawn - * heading is the cited one. + * 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; + unlisted: number | undefined; } /** What a drawn section resolved to: the field's row, and the heading when it is drawn. */ @@ -114,58 +118,6 @@ export function headingReading(text: string): string { return text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ''); } -const isBlank = (c: string | undefined): boolean => c === ' ' || c === '\t'; - -/** Whether `line` opens or closes a fenced code block, as the spec's outline reads one. */ -function isFence(line: string): boolean { - let i = 0; - while (i < line.length && isBlank(line[i])) i++; - return line.startsWith('```', i) || line.startsWith('~~~', i); -} - -/** A setext underline: up to three blanks, a run of `=` or of `-`, trailing blanks. */ -function isSetextUnderline(line: string): boolean { - let i = 0; - while (i < 3 && line[i] === ' ') i++; - const mark = line[i]; - if (mark !== '=' && mark !== '-') return false; - while (line[i] === mark) i++; - while (isBlank(line[i])) i++; - return i === line.length; -} - -/** - * The text of an ATX heading behind a container prefix (blanks, `>` quotes, - * list markers), or `undefined` when `line` is no such heading. A forward - * scan: a body is author-written, so no pattern that can backtrack. - */ -function containedAtxText(line: string): string | undefined { - let i = 0; - for (;;) { - while (isBlank(line[i])) i++; - if (line[i] === '>') { - i++; - continue; - } - if ((line[i] === '-' || line[i] === '*' || line[i] === '+') && isBlank(line[i + 1])) { - i++; - continue; - } - let j = i; - while (j - i < 9 && line[j] !== undefined && line[j] >= '0' && line[j] <= '9') j++; - if (j > i && (line[j] === '.' || line[j] === ')') && isBlank(line[j + 1])) { - i = j + 1; - continue; - } - break; - } - let level = 0; - while (line[i + level] === '#') level++; - if (level < 1 || level > 6) return undefined; - const after = line[i + level]; - return after === undefined || isBlank(after) ? line.slice(i + level) : undefined; -} - /** 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; @@ -178,16 +130,13 @@ function blankEntities(text: string): string { } /** - * The texts of every place in `value` that a face could draw as a heading the - * outline (`headings`) does not list. Markdown: a setext heading, an ATX - * heading behind a quote, a list marker or a blank, and a line holding a raw - * heading tag; fenced code draws none. HTML: a heading tag the outline does - * not list (one left unclosed, or opened inside another). + * 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 unlistedHeadingTexts(value: string, html: boolean, headings: readonly BodyHeading[]): string[] { +function unlistedHtmlHeadingTexts(value: string, headings: readonly BodyHeading[]): string[] { const listed = new Set(headings.map((h) => h.start)); const out: string[] = []; - if (html) { + { // 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(); @@ -209,39 +158,50 @@ function unlistedHeadingTexts(value: string, html: boolean, headings: readonly B } return out; } - let inFence = false; - let offset = 0; - let paragraph: string[] = []; - for (const raw of value.split('\n')) { - const start = offset; - offset += raw.length + 1; - const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw; - if (isFence(line)) { - inFence = !inFence; - paragraph = []; - continue; - } - if (inFence || listed.has(start) || line.trim() === '') { - paragraph = []; - continue; - } - if (paragraph.length > 0 && isSetextUnderline(line)) { - out.push(paragraph.join(' ')); - paragraph = []; - continue; - } - const atx = containedAtxText(line); - const lower = line.toLowerCase(); - let tag = false; - for (let at = lower.indexOf('= 0 && !tag; at = 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 { + const count = candidate.unlisted === undefined ? pendingUnlisted.get(candidate) : undefined; + return count ? { ...candidate, unlisted: count() } : candidate; } /** @@ -266,11 +226,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; + 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 - : unlistedHeadingTexts(value, face === 'html', headings).filter((t) => headingReading(t) === reading).length; - out.push({ field, face, reading, ordinal, count, unlisted }); + : 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; } @@ -292,7 +258,7 @@ 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, fieldOnly: true }; + 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, ); @@ -324,8 +290,11 @@ 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 (at once when the field is the whole - * answer — a `textarea` body, or a heading that reads as nothing — and - * otherwise once {@link RECORD_SECTION_SETTLE_MS} pass without the heading). With + * 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. @@ -343,6 +312,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 } = {}; @@ -358,7 +328,7 @@ 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); @@ -370,13 +340,19 @@ export function focusRecordSection( }; 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..b04f2cd5647 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -5555,5 +5555,15 @@ 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, so +// react-markdown stays in the lazy chunk `MarkdownContent` already lives in. +export function loadDrawnMarkdownHeadings(): Promise { + return import('./widgets/markdownHeadings.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..b7a8fdba604 100644 --- a/ui/packages/fields/src/widgets/MarkdownContent.tsx +++ b/ui/packages/fields/src/widgets/MarkdownContent.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import ReactMarkdown, { type Components } from 'react-markdown'; +import ReactMarkdown, { type Components, type Options } from 'react-markdown'; import remarkGfm from 'remark-gfm'; import rehypeSanitize from 'rehype-sanitize'; import { RICH_TEXT_SANITIZE_SCHEMA } from './sanitizedHtml.js'; @@ -17,6 +17,16 @@ import { */ export type MarkdownFace = RichTextFace; +/** + * The remark plugins a markdown value is parsed with: GitHub Flavored Markdown. + * `./markdownHeadings.ts` reads the drawn headings through the same list, so a + * reader of the face and the face never disagree on what is a heading. + */ +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]]; + /** In the cell face no heading element is drawn (see `cellFaceHeadings`). */ const CELL_COMPONENTS: Components = cellFaceHeadings('data-markdown-heading'); @@ -31,8 +41,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..a1ee3f54f6a --- /dev/null +++ b/ui/packages/fields/src/widgets/markdownHeadings.ts @@ -0,0 +1,67 @@ +/** + * 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` (`./MarkdownContent.tsx`), + * 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 (`loadDrawnMarkdownHeadings` in the package index), so + * react-markdown stays in the lazy chunk the face lives in. + */ +import Markdown from 'react-markdown'; +import { MARKDOWN_REHYPE_PLUGINS, MARKDOWN_REMARK_PLUGINS } from './MarkdownContent.js'; + +/** 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; +} From 6ef69f4f25c6658d8b2774ff39752ff404b0db3b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:45:13 +0000 Subject: [PATCH 5/6] fix(app-shell): keep a pending markdown count readable once the reader loads; changesets for the parse-based count Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc Co-authored-by: Claude --- .changeset/37562-fields-drawn-markdown-headings.md | 10 ++++++++++ .changeset/37562-section-locate-edges.md | 4 ++-- .../app-shell/src/views/recordSectionAnchor.test.tsx | 2 +- ui/packages/app-shell/src/views/recordSectionAnchor.ts | 6 ++++-- 4 files changed, 17 insertions(+), 5 deletions(-) create mode 100644 .changeset/37562-fields-drawn-markdown-headings.md 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 index d6462b19d55..e45bfdf3052 100644 --- a/.changeset/37562-section-locate-edges.md +++ b/.changeset/37562-section-locate-edges.md @@ -2,9 +2,9 @@ '@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 a heading that reads as nothing opens its field at once +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 holds both a same-titled heading the outline does not list (a setext heading, one in a quote or a list item, a raw heading tag) 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. The body is now read for such headings as well, and when it holds one the field is opened instead of a heading that may be another section. A cited heading with no letter or digit, which no drawn heading can be matched to, now scrolls to its field as soon as the field is drawn, instead of after the four-second settle; a titled heading that is not drawn yet still waits for it. +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/recordSectionAnchor.test.tsx b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx index 6b466e66a02..a25b0ba7a01 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx @@ -221,7 +221,7 @@ describe('objectstack#37365 — locateSection finds the drawn heading', () => { 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')); + await vi.waitFor(() => expect(heading.getAttribute(RECORD_SECTION_TARGET_ATTR)).toBe('true'), { timeout: 5000 }); expect(heading.scrollIntoView).toHaveBeenCalledTimes(1); }); diff --git a/ui/packages/app-shell/src/views/recordSectionAnchor.ts b/ui/packages/app-shell/src/views/recordSectionAnchor.ts index 270b4cc6835..c5fa5fb7134 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.ts +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.ts @@ -200,8 +200,10 @@ const pendingUnlisted = new WeakMap number | undefined>( /** `candidate`, with its unlisted count read now when it was pending. */ function withUnlistedCount(candidate: SectionCandidate): SectionCandidate { - const count = candidate.unlisted === undefined ? pendingUnlisted.get(candidate) : undefined; - return count ? { ...candidate, unlisted: count() } : candidate; + 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 }; } /** From c3f7728e8e1e8936502601e58c22b21980bcc96b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 19:07:43 +0000 Subject: [PATCH 6/6] fix(fields): load the heading reader through MarkdownContent so the markdown chunk stays lazy Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc Co-authored-by: Claude --- ui/packages/fields/src/index.tsx | 7 +++--- .../fields/src/widgets/MarkdownContent.tsx | 19 +++++++--------- .../fields/src/widgets/markdownHeadings.ts | 22 ++++++++++++++----- 3 files changed, 28 insertions(+), 20 deletions(-) diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index b04f2cd5647..0fce0654531 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -5558,10 +5558,11 @@ 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, so -// react-markdown stays in the lazy chunk `MarkdownContent` already lives in. +// 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/markdownHeadings.js').then((m) => m.drawnMarkdownHeadings); + return import('./widgets/MarkdownContent.js').then((m) => m.drawnMarkdownHeadings); } export type { DrawnMarkdownHeading } from './widgets/markdownHeadings.js'; diff --git a/ui/packages/fields/src/widgets/MarkdownContent.tsx b/ui/packages/fields/src/widgets/MarkdownContent.tsx index b7a8fdba604..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, type Options } from 'react-markdown'; -import remarkGfm from 'remark-gfm'; -import rehypeSanitize from 'rehype-sanitize'; -import { RICH_TEXT_SANITIZE_SCHEMA } from './sanitizedHtml.js'; +import ReactMarkdown, { type Components } from 'react-markdown'; +import { MARKDOWN_REHYPE_PLUGINS, MARKDOWN_REMARK_PLUGINS } from './markdownHeadings.js'; import { RICH_TEXT_CELL_FACE_CLASS, RICH_TEXT_DOCUMENT_CLASS, @@ -18,14 +16,13 @@ import { export type MarkdownFace = RichTextFace; /** - * The remark plugins a markdown value is parsed with: GitHub Flavored Markdown. - * `./markdownHeadings.ts` reads the drawn headings through the same list, so a - * reader of the face and the face never disagree on what is a heading. + * 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 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]]; +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'); diff --git a/ui/packages/fields/src/widgets/markdownHeadings.ts b/ui/packages/fields/src/widgets/markdownHeadings.ts index a1ee3f54f6a..09bd6cc6e38 100644 --- a/ui/packages/fields/src/widgets/markdownHeadings.ts +++ b/ui/packages/fields/src/widgets/markdownHeadings.ts @@ -10,18 +10,28 @@ * 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` (`./MarkdownContent.tsx`), - * and the tree is read after the last of them, so the headings answered are the + * `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 (`loadDrawnMarkdownHeadings` in the package index), so - * react-markdown stays in the lazy chunk the face lives in. + * 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 from 'react-markdown'; -import { MARKDOWN_REHYPE_PLUGINS, MARKDOWN_REMARK_PLUGINS } from './MarkdownContent.js'; +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 {