Skip to content

feat(markdown): opt-in source ranges on parsed blocks - #5290

Merged
cixzhang merged 1 commit into
meta:mainfrom
lexs:md-source-ranges
Aug 23, 2026
Merged

cixzhang merged 1 commit into
meta:mainfrom
lexs:md-source-ranges

Conversation

@lexs

@lexs lexs commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

What

parseMarkdown(source, {sourceRanges: true}) gives every top-level block a range — the
[start, end) offsets it occupies in the string that was passed in:

const blocks = parseMarkdown(source, {sourceRanges: true});
source.slice(...blocks[0].range!); // the block's own markdown, verbatim

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 fence
characters, 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

  • Link reference definitions. parseMarkdownImpl parses cleaned — the input with
    definition lines stripped — so offsets taken there drift for everything after the first
    definition. extractLinkDefinitions now also returns a line map and the ranges are
    reported against the string the caller passed.
  • Streaming. parseMarkdownIncremental parses 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 autolink already does.
  • Fenced code owns its blank lines. Block ends are derived positionally (a block runs to
    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.
  • Nested blocks carry no range. A list item's or blockquote's children are parsed from
    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-range on 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).

@vercel

vercel Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
astryx Ready Ready Preview Aug 21, 2026 9:51am

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 21, 2026
@github-actions github-actions Bot added community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge labels Aug 21, 2026
@lexs
lexs force-pushed the md-source-ranges branch from c3a6945 to 0920f28 Compare August 21, 2026 09:30
@github-actions

github-actions Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

🧪 Sandbox Preview

View Sandbox for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

Modified Components

Markdown (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 3073 -
Complexity N/A Very High (205) -

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.8KB 1.2KB

Accessibility Audit

Status: No accessibility violations detected.


Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

github-actions Bot added a commit that referenced this pull request Aug 21, 2026
github-actions Bot added a commit that referenced this pull request Aug 21, 2026
`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.
@lexs

lexs commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

A note on the pr-a11y red that was on this PR earlier, in case it comes back and confuses a reviewer.

It failed twice with one [serious] color-contrast violation on Markdown / Streaming, and the report names the node:

<span class="astryx1hc1fzr astryx19991ni astryx80gvsz …">brary</span>

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: input.indexOf(unsettledText, …) was running on every streamed chunk even with sourceRanges off. That is pointless work on the hot path — it is now gated on the option — but the violation is in the fade timing, not in anything the parser produced. Everything is green as of the latest push.

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 Markdown — just say the word.

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]

@github-actions github-actions Bot removed the needs:code-review High-risk change (new package/component/API) — needs human code review before merge label Aug 23, 2026
@cixzhang
cixzhang merged commit e93acd6 into meta:main Aug 23, 2026
21 checks passed
cixzhang added a commit that referenced this pull request Aug 23, 2026
`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.

This branch was successfully deployed

1 active deployment
Preview — e73c331a Deployed Aug 21, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot. community Authored by a community contributor (not on the eng/design team)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants