|
1 | 1 | import type { Root, RootContent } from "mdast"; |
2 | 2 | import remarkParse from "remark-parse"; |
| 3 | +import remarkGfm from "remark-gfm"; |
| 4 | +import remarkMath from "remark-math"; |
3 | 5 | import { unified } from "unified"; |
4 | 6 |
|
5 | 7 | export type TextDirection = "ltr" | "rtl"; |
@@ -32,6 +34,7 @@ export function textDirection(text: string): TextDirection | undefined { |
32 | 34 | } |
33 | 35 |
|
34 | 36 | const markdownParser = unified().use(remarkParse).freeze(); |
| 37 | +const nativeMarkdownParser = unified().use(remarkParse).use(remarkGfm).use(remarkMath).freeze(); |
35 | 38 |
|
36 | 39 | function maskTextRanges( |
37 | 40 | text: string, |
@@ -165,14 +168,24 @@ export function markdownPreview(markdown: string, maxChars: number) { |
165 | 168 | export function markdownWithDirection(markdown: string, direction: TextDirection | undefined) { |
166 | 169 | if (!direction) return markdown; |
167 | 170 | const offsets: number[] = []; |
168 | | - const visit = (node: Root | RootContent): void => { |
| 171 | + const visit = (node: Root | RootContent, parent?: Root | RootContent): void => { |
169 | 172 | if (node.type === "paragraph" || node.type === "heading") { |
170 | | - const offset = node.children[0]?.position?.start.offset; |
171 | | - if (offset !== undefined) offsets.push(offset); |
| 173 | + let offset = node.children[0]?.position?.start.offset; |
| 174 | + if (offset !== undefined) { |
| 175 | + // Keep the native admonition marker at the start of its quote line. |
| 176 | + const alert = |
| 177 | + parent?.type === "blockquote" && parent.children[0] === node |
| 178 | + ? /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\][\t ]*(?:\r?\n[\t ]*(?:>[\t ]*)*|$)/i.exec( |
| 179 | + markdown.slice(offset, node.position?.end.offset), |
| 180 | + ) |
| 181 | + : null; |
| 182 | + if (alert) offset += alert[0].length; |
| 183 | + if (offset < (node.position?.end.offset ?? markdown.length)) offsets.push(offset); |
| 184 | + } |
172 | 185 | } |
173 | | - if ("children" in node) node.children.forEach(visit); |
| 186 | + if ("children" in node) node.children.forEach((child) => visit(child, node)); |
174 | 187 | }; |
175 | | - visit(markdownParser.parse(markdown)); |
| 188 | + visit(nativeMarkdownParser.parse(markdown)); |
176 | 189 | const mark = direction === "rtl" ? "\u200f" : "\u200e"; |
177 | 190 | for (const offset of offsets.reverse()) { |
178 | 191 | markdown = markdown.slice(0, offset) + mark + markdown.slice(offset); |
|
0 commit comments