Skip to content

fix(Markdown): pair emphasis and strong markers by CommonMark's rules - #7051

Merged
cixzhang merged 2 commits into
mainfrom
fix/markdown-nested-emphasis
Oct 7, 2026
Merged

cixzhang merged 2 commits into
mainfrom
fix/markdown-nested-emphasis

Conversation

@cixzhang

@cixzhang cixzhang commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

User impact

A reader of *see **bold** more* — emphasis with bold inside, which RichText writes whenever a person bolds a word inside italic text — saw in Markdown three separate italic pieces and no bold; *see **bold*** lost the bold and showed a stray **. The same document reads correctly in RichText, so the two surfaces disagreed, and every RichText export of this form rendered wrong in Markdown.

Problem and solution fit

  • Why it occurs: Markdown's inline parser paired each *, **, _, or __ with the next identical marker in the text, so the first ** of a nested strong closed the surrounding emphasis.
  • Why it matters: spec:AST-061 FR7 (strong, emphasis, and the rest expose the same semantics on every surface) and component:Markdown FR23.

Runs of * and _ are now paired as CommonMark 0.31 §6.2 specifies: each run is left- or right-flanking by the characters around it (an underscore run only outside a word), each closer takes the nearest compatible opener, two delimiters make strong and one makes emphasis, and the rule of three stops runs that can both open and close from pairing across a multiple of three. Unpaired runs stay text. Strikethrough, code, links, escapes, and everything else are unchanged.

***text*** still renders as strong around emphasis (<strong><em>), where CommonMark's reference output puts emphasis outside. It is the order Markdown has always rendered and RichText draws, both elements are present and announced either way, and changing it would change every released document that uses it; the consumer docs now say so.

Robustness

Markdown renders chat and model output, so no input may hang or crash it:

  • The pairing pass is linear: runs live on a linked stack and leave it once used, paired across, or unable to pair, as commonmark.js does, so each search visits only runs still on it and nothing is re-marked between a pair.
  • Emphasis nests at most 100 levels deep (as markdown-it caps nesting); a pair that would nest deeper stays text, along with the runs between it. The depth is tracked on the stack, so checking it costs nothing extra. Every recursive walk of the tree — the AST projection and the renderer — is therefore bounded by the cap.

Streaming: an unfinished **bold now closes before its trailing space, so a partial line keeps its formatting under the new flanking rules.

Expected behavior and authority

spec:AST-061 FR7 and component:Markdown FR23 (current), using CommonMark 0.31 §6.2 for the pairing rules.

Smallest restoration

The emphasis branch of the inline parser and one pairing pass after it (parser.ts); one line in the streaming closer. No public API, node, or renderer change.

Evidence

  • 37 CommonMark §6.2 examples (350–460, including 413–418, 420–424, 442–453, 459–460) produce CommonMark's output; *a\*b* is <em>a*b</em>.
  • The RichText forms *see **bold***, *see **bold** more*, **bold *both***, _see __bold__ more_, and *see **bold** and **more*** nest as written; Markdown renders the <strong> inside the <em> with no stray markers.
  • ***both*** and foo***bar***baz keep strong outside emphasis.
  • Red arm: with the previous parser, 30 of the CommonMark and RichText-form tests fail.
  • Pathological inputs: CommonMark's "nested strong emph" at 10,000 levels (137 KB), openers with no closers, 8,000 openers then 8,000 closers, closers with no openers, and runs summing to a multiple of three each parse without throwing within the time budget; 50 levels nest exactly, 51 levels nest 50 and leave the outer runs as text, and Markdown renders the 10,000-level input (50 <em>, 50 <strong>) without exhausting the stack. Alone, the 10,000-level input parses in about 0.1 s (about 90 ms at 112 KB). The test budget is 5 s per parse, because the UI suite runs in parallel and its timings vary tenfold under load; the previous pass took 50–200 s on the nested inputs.
  • Red arms for robustness: without the cap, the 51-level test fails and the 8,000/8,000 input and the 10,000-level render overflow the stack; with the previous pairing pass, the nested inputs time out (50 s and 136 s) and the render overflows.
  • Streaming: the bold and italic "never shows raw syntax" tests pass.
  • Performance: the FR23 benchmark passes at both sizes in isolation (latest: 200 sections 1.11, 500 sections 0.93; budget 1.25).

Scope

  • One defect is restored.
  • Separable contradictory or unsettled tagalongs were removed or split.
  • No new public API, visual representation, default, or interaction model is hidden under the bug-fix label.
  • Public text and artifacts contain no internal Meta context.

Testing

  • vitest run --project ui packages/core/src/Markdown packages/core/src/Outline (perf run separately): 767 passed, three runs in a row; packages/richtext: 346 passed.
  • Markdown.fr23.perf.test.ts alone: pass.
  • pnpm -F @astryxdesign/core build; tsc; check:use-client; check:changesets: pass.
  • pnpm storybook:build, then the RichText and core Markdown Playwright specs in Chrome: 59 passed.
  • Changeset: core patch [fix].

@vercel

vercel Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
astryx Ready Ready Preview Oct 7, 2026 12:36am UTC

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 6, 2026
@astracat-bot

astracat-bot Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

AI review status for this pull request.

Review status Updated
⏳ Waiting for review (for maintainers only) Oct 7, 2026, 1:11 AM UTC

@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR

🧪 Sandbox Preview

View Sandbox for this PR

No new or modified components detected.

Bundle Size Summary

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

Accessibility Audit

Status: No accessibility violations detected.

Visual Regression

16 of 424 shot(s) changed.

A change here is a question, not a failure: check whether the after is the
picture you intended. Record that review on the PR. Baseline maintenance is an
explicit dispatch of CI; this report never rewrites the baseline or adds a release gate.

component story theme mode pixels
Chat Full AI Chat probe light 155,733
Chat Full AI Chat probe dark 155,005
Chat Default neutral dark 33,205
Chat Default neutral light 32,876
Chat Empty State probe light 23,531
Chat Empty State probe dark 22,622
ChatAutoScroll Scroll Behavior Comparison neutral dark 15,378
ChatAutoScroll Scroll Behavior Comparison neutral light 14,107
Chat With Attachments probe light 13,229
Chat With Attachments probe dark 11,065
Markdown Default probe dark 897
Markdown Default probe light 897
Markdown Default neutral dark 882
Markdown Default neutral light 858
FileInput Default neutral light 44
FileInput Default neutral dark 42

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

@astracat-bot astracat-bot Bot 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.

Requesting one change: emphasis can now nest thousands deep, and Markdown cannot render that.

A crafted message, *a **a repeated 2,000 times, then b, then a** a* repeated 2,000 times (28 KB), fails to render in Chrome with "Maximum call stack size exceeded", so the reader sees an error instead of the message. The previous parser rendered it flat in a few milliseconds. Pairing is also quadratic in the nesting: in Node, 56 KB of this input takes 3 seconds and 112 KB takes 13 seconds before the render fails, and 48 KB of *a runs followed by b* runs takes 4 seconds. Each closer walks back over every run already used, and each pair marks every index between its runs. Markdown renders chat and model output, so one hostile or broken message can freeze and blank a reader's view. Two changes would close this: cap emphasis nesting at a fixed depth and leave deeper runs as text, and unlink used runs from the delimiter stack, as CommonMark's reference implementation does, so each search skips them. A test with CommonMark's nested strong emphasis input at 10,000 levels would guard both.

The rest holds. All 132 CommonMark emphasis examples produce CommonMark's output except three where *** keeps strong outside emphasis on purpose, and five that need inline HTML or angle-bracket autolinks, which Markdown does not parse. Against commonmark.js on 28,000 random strings, the only other differences come from emoji: commonmark.js reads half of a surrogate pair beside a run, while this change reads the whole character as the spec defines it. Markdown and RichText now agree on all 17 nested forms I tried, including a plugin node inside nested marks (7 before). The 118 stories that render Markdown render it the same, while streaming shows raw markers on fewer partial lines (16 instead of 35 in my sample) and closes before trailing spaces as described. The FR23 benchmark stays within budget over three isolated rounds on each side, and ordinary documents parse as fast as before. 30 of the 46 new tests fail on the previous parser, and 759 core tests, 346 RichText tests, the build, tsc and the Changeset check pass, with all 59 Chrome tests.

On ***both***: keeping strong outside emphasis is stated in the Changeset and the code. It differs from CommonMark only in which tag is outermost, renders the same bold italic, and keeps the tree shape Markdown has always produced.

[Automated review]

@astracat-bot astracat-bot Bot 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.

Approving. The pairing pass is now linear and nesting stops at 100 levels, so the inputs from my last review parse in milliseconds and render.

  • Timing alone: CommonMark's nested strong emphasis input parses in 35 ms at 109 KB, where it took 13 seconds before, and in 181 ms at 438 KB. Time doubles as the input doubles from 27 KB to 438 KB, and the other pathological inputs scale the same way, so the tests' 5-second budgets sit far above it.
  • In Chrome, the same inputs from 14 KB to 140 KB render with no stack error and no React error, nesting 100 levels deep and leaving the rest as text. The 137 KB, 10,000-level input parses in 68 ms.
  • Nothing else moved. The 132 CommonMark emphasis examples give the same results as the last head, the 28,000-string comparison with commonmark.js gives identical counts, Markdown and RichText still agree on all 17 nested forms, and streaming shows raw markers on the same 16 partial lines.
  • 767 core tests, 346 RichText tests, the builds, tsc, lint and the Changeset check pass. The FR23 benchmark stays within budget in isolation, and ordinary documents parse as fast as on main. The 59 Chrome tests pass apart from the known flaky plugin-node test, which flakes on main too. The docs now state the strong-around-emphasis order and the depth limit, and the change merges cleanly with main, including the link destination fix.

[Automated review]

@cixzhang
cixzhang merged commit 9051ea5 into main Oct 7, 2026
45 checks passed
@cixzhang
cixzhang deleted the fix/markdown-nested-emphasis branch October 7, 2026 02:08
cixzhang pushed a commit that referenced this pull request Oct 21, 2026
<!-- template: bug-fix.md -->

## User impact

An app that builds Astryx from source with the documented Next.js setup, but sets no browserslist or targets a browser without Unicode property escapes (such as Safari 11), fails `next build --webpack` with `Unknown property: L` (also `Zs`, `Letter`). The errors point at `Avatar.tsx`, `Markdown/parser.ts` and `Markdown/plugins/headingLinks.ts`, package source the app cannot change, and come from both the PostCSS pass and the JavaScript compile. Any import from the package root reaches them.

## Problem and solution fit

- Why it fails: with no targets, or old ones, `next/babel`'s preset-env rewrites every `\p{…}` regex literal with transform-unicode-property-regex. Next's bundled copy of that transform loads `regenerate-unicode-properties` at runtime, which Next does not ship, so it throws (Next 16.3.6 and 16.4.2 alike).
- Why it harms the task: the throw stops the whole build.
- Why that matters: the app cannot fix it in its own code, and the error names a Unicode property, not the missing target.

## Expected behavior and authority

This is a regression of a settled case. #5450 hit this failure in `NumberInput/numberParser.ts` and builds those expressions with `new RegExp(...)`; its comment records why, and notes that property escapes need no transform in any browser this package supports. #6698, #6911 and #7051 later added four new literals and reintroduced it.

## Smallest restoration

- The four literals become `new RegExp(...)` with the same pattern and flags, built once at module load as before.
- Each site's comment names the cause and when a literal is safe again: once Next's bundled Babel ships the Unicode data.
- A source-build test fails when a Core module writes a property escape as a regex literal.

## Evidence

- Reproduction before the change: a clean registry install of main's documented Next.js example (`apps/example-nextjs-source`, hoisted, browserslist removed). `next build --webpack` fails in the PostCSS pass (`Avatar.tsx: Unknown property: L`) and in the JavaScript compile (`Unknown property: L`, `Zs`, `Letter` from the three files).
- Result after the change: the same install, with this change applied to Core's source, compiles and prerenders, and all 226 rendered class names have a rule in the emitted CSS.
- Representative unchanged path: the Avatar and Markdown suites pass unchanged.
- Regression test or other mutation-sensitive proof: `unicodePropertyEscapes.source-build.test.mjs` fails on main listing the four literals, and passes here.

## Scope

- [x] One defect is restored.
- [x] Separable contradictory or unsettled tagalongs were removed or split.
- [x] No new public API, visual representation, default, or interaction model is hidden under the bug-fix label.
- [x] Public text and artifacts contain no internal Meta context.

## Testing

- `pnpm exec vitest run --project ui packages/core/src/Avatar packages/core/src/Markdown packages/core/src/unicodePropertyEscapes.source-build.test.mjs`: 50 files, 1,158 tests pass (the new test alone fails on main).
- `next build --webpack` on the clean install, no browserslist: fails on main in both passes; passes with this change (226 of 226 rendered classes have a rule).
- `pnpm -F @astryxdesign/core typecheck`, ESLint and Prettier on the touched files, `pnpm check:repo`, changeset coverage: pass.

This branch was successfully deployed

1 active deployment
Preview — f1d54fd4 Deployed Oct 7, 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant