Repository navigation
feat(markdown): opt-in source ranges on parsed blocks - #5290
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
PR Analysis Report📚 Storybook PreviewView Storybook for this PR 🧪 Sandbox PreviewView Sandbox for this PR Modified ComponentsMarkdown (@astryxdesign/core) · View in Storybook
Bundle Size Summary
Accessibility AuditStatus: No accessibility violations detected. Generated by PR Enrichment workflow | Storybook | Sandbox | View full report |
`parseMarkdown(source, {sourceRanges: true})` gives every top-level block a
`range` — the `[start, end)` offsets it occupies in the source passed in — so
a consumer holding that source can slice the original markdown for a block
instead of reconstructing it from the node or from the rendered DOM.
Reconstruction is lossy where slicing is not: escapes, the exact emphasis and
fence characters, heading depth past the clamp, table alignment.
Off by default, and the field is absent unless asked for, so no existing node
or comparison changes.
Two things the offsets get right that a naive implementation does not: link
reference definitions are stripped before the block loop runs, so ranges are
mapped back through that removal onto the string the caller passed; and
`parseMarkdownIncremental` parses slices, so its blocks report absolute
offsets as the document streams — including a list whose halves arrived in
different chunks and were merged. Flipping the option invalidates the settled
cache the way `autolink` already does.
A range covers the block's own lines verbatim, so slicing and re-parsing
returns the same node. Blocks nested in a list item or a blockquote carry no
range: they are parsed from text reassembled without their markers, so an
offset into it would not address the document.
|
A note on the It failed twice with one That's a fragment of "library" caught mid-fade — one of the streaming fade-in spans, sampled by axe while it is still partially transparent. The story drives itself with const chunkSize = Math.floor(Math.random() * 8) + 2;
const delay = 30 + Math.random() * 60;so where the audit lands in the animation differs run to run, which is why the same story passes on other PRs (and passed on #5288, which actually touches the component — this one is parser-only and changes no rendering). I did fix one real thing on my side in the meantime rather than just re-rolling: Happy to send a separate PR making that story deterministic (fixed chunk size and delay, or a seeded RNG) so the audit stops being a coin flip for anyone touching |
cixzhang
left a comment
There was a problem hiding this comment.
Thanks — this is careful work, and the copy-out case is one we want. Merging.
Two things I'm taking on rather than asking you for. SourceRange wants to be an object rather than a tuple so line numbers can be added to it later without a break, and top-level-only means selecting a single bullet out of a list still can't be sliced — nested blocks need line spans, since a blockquote child's text isn't contiguous in the source. Both are ours, and both land before the next release.
[Reviewed by Robohands]
`BlockNode.range` becomes `{start, end}` instead of `[start, end]`. Same two
numbers, same meaning; `source.slice(range.start, range.end)` replaces
`source.slice(...range)`.
A tuple is closed: the only way to say where a block is in line numbers as
well as offsets would be a second field with a second name, and `BlockNode`
would carry two spellings of one concept forever. An object takes optional
`startLine`/`endLine` additively, whenever a consumer needs them. Nothing here
adds them — this is the shape only.
`sourceRanges` is unreleased (core is published at 0.4.7 and this landed in
#5290 today), so no installed consumer can be broken by the change.
Also adds the cache assertion parser.perf.test.ts was missing: streaming a
document rebuilds a median of 2 blocks per chunk at 50, 200 and 500
paragraphs, and asking for source ranges costs exactly zero extra rebuilds.
Integers, not milliseconds — a position-tracking implementation that dropped
the settled cache each chunk would pass any time budget loose enough not to
flake, and fails this immediately.
What
parseMarkdown(source, {sourceRanges: true})gives every top-level block arange— the[start, end)offsets it occupies in the string that was passed in:Off by default, and the field is absent unless asked for, so no existing node, snapshot or
comparison changes.
Why
I render agent answers with
<Markdown>and need the markdown behind what is on screen —copying a text selection out of a chat transcript as markdown. Today that means walking the
rendered DOM and rebuilding the markdown from it, which is lossy in ways slicing the source
never is: escapes (
\*literal\*comes back as emphasis), the exact emphasis and fencecharacters, heading depth past the h6 clamp, table alignment, whether a bare fence said
plaintext. With ranges, a consumer that still holds the source slices it instead.The parts that aren't obvious
parseMarkdownImplparsescleaned— the input withdefinition lines stripped — so offsets taken there drift for everything after the first
definition.
extractLinkDefinitionsnow also returns a line map and the ranges arereported against the string the caller passed.
parseMarkdownIncrementalparses three different slices (settled prefix,delta, trimmed unsettled tail), so each is parsed with a base offset and the blocks come
out absolute; a list whose halves arrive in different chunks and get merged spans both.
Flipping the option invalidates the settled cache, the way
autolinkalready does.the line before the next one starts, blank lines trimmed), which is wrong for an
unterminated fence mid-stream, so the fence states its own end.
text reassembled without their markers, so an offset into it wouldn't address the document.
Say the word if you'd rather they carried one — it means threading a base offset through
those two recursive parses.
What I deliberately left out
Emitting the ranges from
<Markdown>as a DOM attribute (data-md-rangeon each block,behind a prop), which is what my consumer ultimately needs to map a DOM selection back to
source. I'd rather you pick that API than have me guess it — happy to follow up with it, or
to fold it into this PR if you tell me the shape you want.
Test plan
npx vitest run packages/core/src/Markdown packages/core/src/List packages/core/src/Outline— 380 pass. Nine new cases: every block type in one document, the link-definition mapping,
absolute offsets while streaming character by character, a merged list spanning both halves,
an unterminated fence keeping its blank lines, flipping the option on an existing state, and
a property check that every range slices to something that re-parses to the same node
(including a CRLF document).