Open History to see the last commit
1import {
2 CHAT_MARKDOWN_REHYPE_PLUGINS,
3 CHAT_MARKDOWN_REMARK_PLUGINS,
4} from "@t3tools/shared/markdownPipeline";
5import { renderToStaticMarkup } from "react-dom/server";
6import ReactMarkdown from "react-markdown";
7import { describe, expect, it } from "vite-plus/test";
8
9import { splitMarkdownBlocks } from "./markdownStreamBlocks";
10
11// Whitespace between top-level blocks collapses in the rendered message.
12const html = (source: string) =>
13 renderToStaticMarkup(
14 <ReactMarkdown
15 remarkPlugins={CHAT_MARKDOWN_REMARK_PLUGINS}
16 rehypePlugins={CHAT_MARKDOWN_REHYPE_PLUGINS}
17 >
18 {source}
19 </ReactMarkdown>,
20 )
21 .replace(/>\s+</g, "><")
22 .trim();
23
24describe("splitMarkdownBlocks", () => {
25 it.each([
26 "# Title\n\nFirst paragraph with `code` and **bold**.\n\nSecond [link](https://example.com).",
27 "- one\n- two\n\n- loose three\n\n continued\n\nAfter the list.",
28 "1. first\n\n2. second\n\nText\n\n3) restarted",
29 "```ts\nconst a = 1;\n\n\nconst b = 2;\n```\n\nafter\n\n~~~\nx\n\n~~~~\n\ny\n~~~\n\nend",
30 "> quote\n\n> another quote\n\n> [!NOTE]\n> alert",
31 "| a | b |\n| - | - |\n| 1 | 2 |\n\nAfter the table.",
32 "para\n\n indented code\n\nnext",
33 "Setext\n===\n\nnext\n---\n\n- [ ] task\n- [x] done",
34 "- a\n\n ```\n x\n\n```\n\nb",
35 "- a\n\n ```\n x\n\ny\n\n ```\n\nb",
36 ])("renders each block as the whole text renders it, at every streamed prefix: %j", (text) => {
37 for (let end = 0; end <= text.length; end++) {
38 const source = text.slice(0, end);
39 const blocks = splitMarkdownBlocks(source);
40 expect(blocks?.join("")).toBe(source);
41 expect(blocks!.map(html).join("")).toBe(html(source));
42 }
43 });
44
45 it("splits only between closed blocks", () => {
46 expect(splitMarkdownBlocks("a\n\n```\nb\n\nc\n```\n\n- d\n\n- e\n\nf")).toEqual([
47 "a\n\n",
48 "```\nb\n\nc\n```\n\n- d\n\n- e\n\n",
49 "f",
50 ]);
51 });
52
53 it.each([
54 "[ref]\n\n[ref]: /later",
55 "a[^x]\n\n[^x]: note",
56 "<details>\n\nbody\n\n</details>",
57 ":::note\n\ncontent\n\n:::",
58 "$$\na\n\nb\n$$",
59 "a\r\n\r\nb",
60 ])("keeps text with document-wide syntax whole: %j", (text) => {
61 expect(splitMarkdownBlocks(text)).toBeNull();
62 });
63});