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 ])("renders each block as the whole text renders it, at every streamed prefix: %j", (text) => {
35 for (let end = 0; end <= text.length; end++) {
36 const source = text.slice(0, end);
37 const blocks = splitMarkdownBlocks(source);
38 expect(blocks?.join("")).toBe(source);
39 expect(blocks!.map(html).join("")).toBe(html(source));
40 }
41 });
42
43 it("splits only between closed blocks", () => {
44 expect(splitMarkdownBlocks("a\n\n```\nb\n\nc\n```\n\n- d\n\n- e\n\nf")).toEqual([
45 "a\n\n",
46 "```\nb\n\nc\n```\n\n- d\n\n- e\n\n",
47 "f",
48 ]);
49 });
50
51 it.each([
52 "[ref]\n\n[ref]: /later",
53 "a[^x]\n\n[^x]: note",
54 "<details>\n\nbody\n\n</details>",
55 ":::note\n\ncontent\n\n:::",
56 "$$\na\n\nb\n$$",
57 "a\r\n\r\nb",
58 ])("keeps text with document-wide syntax whole: %j", (text) => {
59 expect(splitMarkdownBlocks(text)).toBeNull();
60 });
61});