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