11import { describe , expect , it , vi } from "vite-plus/test" ;
2+ import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath" ;
23import type { MarkdownNode } from "react-native-nitro-markdown/headless" ;
34
45import { parseNativeMarkdownMath } from "./nativeMarkdownMath" ;
56
6- // The native binding returns code spans with text children. Keep that boundary
7- // explicit while exercising the real Markdown parser's delimiter precedence .
7+ // Use CommonMark tokenization at the native code-span boundary: a regex would
8+ // incorrectly accept adjacent backtick runs as separate spans .
89function codeSpans ( source : string ) : MarkdownNode {
9- return {
10- type : "document" ,
11- children : [ ...source . matchAll ( / ` ( [ ^ ` ] + ) ` / g) ] . map ( ( match ) => ( {
12- type : "code_inline" ,
13- children : [ { type : "text" , content : match [ 1 ] ! } ] ,
14- } ) ) ,
10+ const tree = parseMarkdownWithMath ( source ) ;
11+ const children : MarkdownNode [ ] = [ ] ;
12+ const visit = ( node : typeof tree | ( typeof tree . children ) [ number ] ) : void => {
13+ if ( node . type === "inlineCode" ) {
14+ children . push ( { type : "code_inline" , children : [ { type : "text" , content : node . value } ] } ) ;
15+ } else if ( "children" in node ) {
16+ node . children . forEach ( visit ) ;
17+ }
1518 } ;
19+ visit ( tree ) ;
20+ return { type : "document" , children } ;
1621}
1722
1823describe ( "native math parsing" , ( ) => {
@@ -30,6 +35,16 @@ describe("native math parsing", () => {
3035 ] ) ;
3136 } ) ;
3237
38+ it . each ( [
39+ [ String . raw `\(x\)\(y\)` , [ "math_inline" , "math_inline" ] , [ "x" , "y" ] ] ,
40+ [ String . raw `\[x\]\(y\)\[z\]` , [ "math_block" , "math_inline" , "math_block" ] , [ "x" , "y" , "z" ] ] ,
41+ [ "`code`\\(x\\)`more`" , [ "code_inline" , "math_inline" , "code_inline" ] , [ "code" , "x" , "more" ] ] ,
42+ ] ) ( "keeps adjacent formulas and code separate: %s" , ( source , types , contents ) => {
43+ const nodes = parseNativeMarkdownMath ( source , codeSpans ) . children ?? [ ] ;
44+ expect ( nodes . map ( ( node ) => node . type ) ) . toEqual ( types ) ;
45+ expect ( nodes . map ( ( node ) => node . content ?? node . children ?. [ 0 ] ?. content ) ) . toEqual ( contents ) ;
46+ } ) ;
47+
3348 it . each ( [
3449 "Pay $20 or $30." ,
3550 String . raw `Unfinished \[\sqrt{x}` ,
0 commit comments