@kushagradhawan/kookie-blocks 0.1.10 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/cjs/components/index.d.ts +1 -0
  2. package/dist/cjs/components/index.d.ts.map +1 -1
  3. package/dist/cjs/components/index.js +1 -1
  4. package/dist/cjs/components/index.js.map +2 -2
  5. package/dist/cjs/components/markdown/StreamingMarkdown.d.ts +78 -0
  6. package/dist/cjs/components/markdown/StreamingMarkdown.d.ts.map +1 -0
  7. package/dist/cjs/components/markdown/StreamingMarkdown.js +2 -0
  8. package/dist/cjs/components/markdown/StreamingMarkdown.js.map +7 -0
  9. package/dist/cjs/components/markdown/createMarkdownComponents.d.ts +27 -0
  10. package/dist/cjs/components/markdown/createMarkdownComponents.d.ts.map +1 -0
  11. package/dist/cjs/components/markdown/createMarkdownComponents.js +3 -0
  12. package/dist/cjs/components/markdown/createMarkdownComponents.js.map +7 -0
  13. package/dist/cjs/components/markdown/index.d.ts +6 -0
  14. package/dist/cjs/components/markdown/index.d.ts.map +1 -0
  15. package/dist/cjs/components/markdown/index.js +2 -0
  16. package/dist/cjs/components/markdown/index.js.map +7 -0
  17. package/dist/cjs/components/markdown/types.d.ts +32 -0
  18. package/dist/cjs/components/markdown/types.d.ts.map +1 -0
  19. package/dist/cjs/components/markdown/types.js +2 -0
  20. package/dist/cjs/components/markdown/types.js.map +7 -0
  21. package/dist/cjs/components/markdown/utils/markdownStreaming.d.ts +32 -0
  22. package/dist/cjs/components/markdown/utils/markdownStreaming.d.ts.map +1 -0
  23. package/dist/cjs/components/markdown/utils/markdownStreaming.js +5 -0
  24. package/dist/cjs/components/markdown/utils/markdownStreaming.js.map +7 -0
  25. package/dist/esm/components/index.d.ts +1 -0
  26. package/dist/esm/components/index.d.ts.map +1 -1
  27. package/dist/esm/components/index.js +1 -1
  28. package/dist/esm/components/index.js.map +2 -2
  29. package/dist/esm/components/markdown/StreamingMarkdown.d.ts +78 -0
  30. package/dist/esm/components/markdown/StreamingMarkdown.d.ts.map +1 -0
  31. package/dist/esm/components/markdown/StreamingMarkdown.js +2 -0
  32. package/dist/esm/components/markdown/StreamingMarkdown.js.map +7 -0
  33. package/dist/esm/components/markdown/createMarkdownComponents.d.ts +27 -0
  34. package/dist/esm/components/markdown/createMarkdownComponents.d.ts.map +1 -0
  35. package/dist/esm/components/markdown/createMarkdownComponents.js +3 -0
  36. package/dist/esm/components/markdown/createMarkdownComponents.js.map +7 -0
  37. package/dist/esm/components/markdown/index.d.ts +6 -0
  38. package/dist/esm/components/markdown/index.d.ts.map +1 -0
  39. package/dist/esm/components/markdown/index.js +2 -0
  40. package/dist/esm/components/markdown/index.js.map +7 -0
  41. package/dist/esm/components/markdown/types.d.ts +32 -0
  42. package/dist/esm/components/markdown/types.d.ts.map +1 -0
  43. package/dist/esm/components/markdown/types.js +1 -0
  44. package/dist/esm/components/markdown/types.js.map +7 -0
  45. package/dist/esm/components/markdown/utils/markdownStreaming.d.ts +32 -0
  46. package/dist/esm/components/markdown/utils/markdownStreaming.d.ts.map +1 -0
  47. package/dist/esm/components/markdown/utils/markdownStreaming.js +5 -0
  48. package/dist/esm/components/markdown/utils/markdownStreaming.js.map +7 -0
  49. package/package.json +10 -1
  50. package/src/components/index.ts +1 -0
  51. package/src/components/markdown/StreamingMarkdown.tsx +183 -0
  52. package/src/components/markdown/createMarkdownComponents.tsx +206 -0
  53. package/src/components/markdown/index.ts +8 -0
  54. package/src/components/markdown/types.ts +31 -0
  55. package/src/components/markdown/utils/markdownStreaming.ts +297 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/components/markdown/createMarkdownComponents.tsx"],
4
+ "sourcesContent": ["import React, { type ReactNode } from \"react\";\nimport type { Components } from \"react-markdown\";\nimport { Blockquote, Box, Code, Flex, Heading, Text, Table } from \"@kushagradhawan/kookie-ui\";\nimport { CodeBlock } from \"../code\";\nimport type { MarkdownComponentOptions, MarkdownChildrenProps } from \"./types\";\n\n/**\n * Extracts language from className (e.g., \"language-typescript\" -> \"typescript\")\n */\nfunction extractLanguage(className?: string): string {\n if (!className) {\n return \"text\";\n }\n const match = className.match(/language-([\\w-]+)/i);\n return match?.[1] ?? \"text\";\n}\n\n/**\n * Extracts code string from ReactNode children\n */\nfunction extractCode(children?: ReactNode): string {\n let code = \"\";\n if (!children) {\n return code;\n }\n if (typeof children === \"string\") {\n code = children;\n } else if (Array.isArray(children)) {\n code = children.map((child) => (typeof child === \"string\" ? child : \"\")).join(\"\");\n }\n // Trim trailing newlines but preserve internal whitespace\n return code.replace(/^\\n+|\\n+$/g, \"\");\n}\n\n/**\n * Creates markdown component mappings that work with both react-markdown and MDX.\n * Uses KookieUI components for consistent styling across all projects.\n *\n * @param options - Optional configuration for component behavior\n * @returns Component mappings for markdown/MDX renderers\n *\n * @example\n * ```tsx\n * // In react-markdown\n * <ReactMarkdown components={createMarkdownComponents()}>\n * {content}\n * </ReactMarkdown>\n *\n * // In MDX\n * export function useMDXComponents(components: MDXComponents) {\n * return {\n * ...createMarkdownComponents(),\n * ...components,\n * };\n * }\n * ```\n */\nexport function createMarkdownComponents(options: MarkdownComponentOptions = {}): Components {\n const { codeBlockCollapsible = false, imageComponent, inlineCodeHighContrast = true } = options;\n\n return {\n // Headings with consistent visual hierarchy\n h1: ({ children }: MarkdownChildrenProps) => (\n <Heading size=\"8\" weight=\"medium\" as=\"h1\" style={{ marginTop: \"1rem\", marginBottom: \"0.5rem\" }}>\n {children}\n </Heading>\n ),\n h2: ({ children }: MarkdownChildrenProps) => (\n <Heading weight=\"medium\" size=\"5\" as=\"h2\" style={{ marginTop: \"0.875rem\", marginBottom: \"0.5rem\" }}>\n {children}\n </Heading>\n ),\n h3: ({ children }: MarkdownChildrenProps) => (\n <Heading weight=\"medium\" size=\"4\" as=\"h3\" style={{ marginTop: \"0.75rem\", marginBottom: \"0.5rem\" }}>\n {children}\n </Heading>\n ),\n h4: ({ children }: MarkdownChildrenProps) => (\n <Heading weight=\"medium\" size=\"3\" as=\"h4\" style={{ marginTop: \"0.625rem\", marginBottom: \"0.5rem\" }}>\n {children}\n </Heading>\n ),\n h5: ({ children }: MarkdownChildrenProps) => (\n <Heading weight=\"medium\" size=\"3\" as=\"h5\" style={{ marginTop: \"0.5rem\", marginBottom: \"0.5rem\" }}>\n {children}\n </Heading>\n ),\n h6: ({ children }: MarkdownChildrenProps) => (\n <Heading weight=\"medium\" size=\"3\" as=\"h6\" style={{ marginTop: \"0.5rem\", marginBottom: \"0.5rem\" }}>\n {children}\n </Heading>\n ),\n\n // Paragraph text\n p: ({ children }: MarkdownChildrenProps) => (\n <Text size=\"3\" as=\"p\" style={{ lineHeight: \"1.6\" }}>\n {children}\n </Text>\n ),\n\n // Code - inline vs block\n code: ({ className, children, inline }: { className?: string; children?: ReactNode; inline?: boolean }) => {\n const code = extractCode(children);\n\n // Block code: has className (language) OR is not marked as inline\n // Inline code: explicitly marked as inline=true, or no className and short single-line content\n const isInlineCode = inline === true || (inline === undefined && !className && !code.includes(\"\\n\") && code.length < 100);\n\n if (isInlineCode) {\n return (\n <Code highContrast={inlineCodeHighContrast} size=\"3\">\n {code}\n </Code>\n );\n }\n\n return (\n <Box my=\"2\" style={{ minWidth: 0 }}>\n <CodeBlock code={code} language={extractLanguage(className)} collapsible={codeBlockCollapsible} />\n </Box>\n );\n },\n\n // Lists\n ul: ({ children }: MarkdownChildrenProps) => (\n <ul style={{ marginTop: \"0.5rem\", marginBottom: \"0.5rem\", lineHeight: \"1.6\", paddingLeft: \"1.5rem\", listStyleType: \"disc\" }}>{children}</ul>\n ),\n ol: ({ children }: MarkdownChildrenProps) => (\n <ol style={{ marginTop: \"0.5rem\", marginBottom: \"0.5rem\", lineHeight: \"1.6\", paddingLeft: \"1.5rem\", listStyleType: \"decimal\" }}>{children}</ol>\n ),\n li: ({ children }: MarkdownChildrenProps) => <li style={{ marginBottom: \"0.25rem\", lineHeight: \"1.6\" }}>{children}</li>,\n\n // Blockquote\n blockquote: ({ children }: MarkdownChildrenProps) => <Blockquote>{children}</Blockquote>,\n\n // Links\n a: ({ href, children }: { href?: string; children?: ReactNode }) => (\n <a href={href} style={{ color: \"var(--accent-9)\", textDecoration: \"underline\" }}>\n {children}\n </a>\n ),\n\n // Text styling\n strong: ({ children }: MarkdownChildrenProps) => (\n <Text weight=\"medium\" style={{ lineHeight: \"1.6\" }}>\n {children}\n </Text>\n ),\n em: ({ children }: MarkdownChildrenProps) => <Text style={{ lineHeight: \"1.6\", fontStyle: \"italic\" }}>{children}</Text>,\n\n // Horizontal rule\n hr: () => (\n <hr\n style={{\n color: \"var(--gray-6)\",\n marginTop: \"0.5rem\",\n marginBottom: \"0.5rem\",\n height: \"1px\",\n width: \"100%\",\n opacity: 0.5,\n }}\n />\n ),\n\n // Pre wrapper (pass through to let code handle it)\n pre: ({ children }: MarkdownChildrenProps) => <>{children}</>,\n\n // Tables using KookieUI\n table: ({ children }: MarkdownChildrenProps) => (\n <Box my=\"2\" style={{ overflowX: \"auto\" }}>\n <Table.Root size=\"2\" variant=\"ghost\">\n {children}\n </Table.Root>\n </Box>\n ),\n thead: ({ children }: MarkdownChildrenProps) => <Table.Header>{children}</Table.Header>,\n tbody: ({ children }: MarkdownChildrenProps) => <Table.Body>{children}</Table.Body>,\n tr: ({ children }: MarkdownChildrenProps) => <Table.Row>{children}</Table.Row>,\n th: ({ children }: MarkdownChildrenProps) => <Table.ColumnHeaderCell>{children}</Table.ColumnHeaderCell>,\n td: ({ children }: MarkdownChildrenProps) => <Table.Cell>{children}</Table.Cell>,\n\n // HTML elements for raw HTML support\n sub: ({ children }: MarkdownChildrenProps) => <sub>{children}</sub>,\n sup: ({ children }: MarkdownChildrenProps) => <sup>{children}</sup>,\n br: () => <br />,\n\n // Images - use custom component if provided\n img: imageComponent\n ? (props: React.ImgHTMLAttributes<HTMLImageElement>) => {\n const { src, alt, width, height } = props;\n if (!src || typeof src !== \"string\") return null;\n return imageComponent({\n src,\n alt: alt ?? \"Image\",\n width: width ? String(width) : undefined,\n height: height ? String(height) : undefined,\n });\n }\n : undefined,\n\n // Details/Summary for expandable sections\n details: ({ children }: MarkdownChildrenProps) => <details style={{ padding: \"0.5rem 0\" }}>{children}</details>,\n summary: ({ children }: MarkdownChildrenProps) => <summary style={{ cursor: \"pointer\", fontWeight: 500 }}>{children}</summary>,\n };\n}\n\n"],
5
+ "mappings": "AAAA,OAAOA,MAA+B,QAEtC,OAAS,cAAAC,EAAY,OAAAC,EAAK,QAAAC,EAAY,WAAAC,EAAS,QAAAC,EAAM,SAAAC,MAAa,4BAClE,OAAS,aAAAC,MAAiB,UAM1B,SAASC,EAAgBC,EAA4B,CACnD,OAAKA,EAGSA,EAAU,MAAM,oBAAoB,IACnC,CAAC,GAAK,OAHZ,MAIX,CAKA,SAASC,EAAYC,EAA8B,CACjD,IAAIC,EAAO,GACX,OAAKD,GAGD,OAAOA,GAAa,SACtBC,EAAOD,EACE,MAAM,QAAQA,CAAQ,IAC/BC,EAAOD,EAAS,IAAKE,GAAW,OAAOA,GAAU,SAAWA,EAAQ,EAAG,EAAE,KAAK,EAAE,GAG3ED,EAAK,QAAQ,aAAc,EAAE,GAR3BA,CASX,CAyBO,SAASE,EAAyBC,EAAoC,CAAC,EAAe,CAC3F,KAAM,CAAE,qBAAAC,EAAuB,GAAO,eAAAC,EAAgB,uBAAAC,EAAyB,EAAK,EAAIH,EAExF,MAAO,CAEL,GAAI,CAAC,CAAE,SAAAJ,CAAS,IACdX,EAAA,cAACI,EAAA,CAAQ,KAAK,IAAI,OAAO,SAAS,GAAG,KAAK,MAAO,CAAE,UAAW,OAAQ,aAAc,QAAS,GAC1FO,CACH,EAEF,GAAI,CAAC,CAAE,SAAAA,CAAS,IACdX,EAAA,cAACI,EAAA,CAAQ,OAAO,SAAS,KAAK,IAAI,GAAG,KAAK,MAAO,CAAE,UAAW,WAAY,aAAc,QAAS,GAC9FO,CACH,EAEF,GAAI,CAAC,CAAE,SAAAA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M,EAAM,OAAN,KAAcK,CAAS,EACxE,MAAO,CAAC,CAAE,SAAAA,CAAS,IAA6BX,EAAA,cAACM,EAAM,KAAN,KAAYK,CAAS,EACtE,GAAI,CAAC,CAAE,SAAAA,CAAS,IAA6BX,EAAA,cAACM,EAAM,IAAN,KAAWK,CAAS,EAClE,GAAI,CAAC,CAAE,SAAAA,CAAS,IAA6BX,EAAA,cAACM,EAAM,iBAAN,KAAwBK,CAAS,EAC/E,GAAI,CAAC,CAAE,SAAAA,CAAS,IAA6BX,EAAA,cAACM,EAAM,KAAN,KAAYK,CAAS,EAGnE,IAAK,CAAC,CAAE,SAAAA,CAAS,IAA6BX,EAAA,cAAC,WAAKW,CAAS,EAC7D,IAAK,CAAC,CAAE,SAAAA,CAAS,IAA6BX,EAAA,cAAC,WAAKW,CAAS,EAC7D,GAAI,IAAMX,EAAA,cAAC,SAAG,EAGd,IAAKiB,EACAI,GAAqD,CACpD,KAAM,CAAE,IAAAC,EAAK,IAAAC,EAAK,MAAAC,EAAO,OAAAC,CAAO,EAAIJ,EACpC,MAAI,CAACC,GAAO,OAAOA,GAAQ,SAAiB,KACrCL,EAAe,CACpB,IAAAK,EACA,IAAKC,GAAO,QACZ,MAAOC,EAAQ,OAAOA,CAAK,EAAI,OAC/B,OAAQC,EAAS,OAAOA,CAAM,EAAI,MACpC,CAAC,CACH,EACA,OAGJ,QAAS,CAAC,CAAE,SAAAd,CAAS,IAA6BX,EAAA,cAAC,WAAQ,MAAO,CAAE,QAAS,UAAW,GAAIW,CAAS,EACrG,QAAS,CAAC,CAAE,SAAAA,CAAS,IAA6BX,EAAA,cAAC,WAAQ,MAAO,CAAE,OAAQ,UAAW,WAAY,GAAI,GAAIW,CAAS,CACtH,CACF",
6
+ "names": ["React", "Blockquote", "Box", "Code", "Heading", "Text", "Table", "CodeBlock", "extractLanguage", "className", "extractCode", "children", "code", "child", "createMarkdownComponents", "options", "codeBlockCollapsible", "imageComponent", "inlineCodeHighContrast", "inline", "href", "props", "src", "alt", "width", "height"]
7
+ }
@@ -0,0 +1,6 @@
1
+ export { StreamingMarkdown } from "./StreamingMarkdown";
2
+ export type { StreamingMarkdownOptions } from "./StreamingMarkdown";
3
+ export { createMarkdownComponents } from "./createMarkdownComponents";
4
+ export type { MarkdownComponentOptions, MarkdownChildrenProps } from "./types";
5
+ export { completeUnterminatedMarkdown, parseMarkdownIntoBlocks } from "./utils/markdownStreaming";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/components/markdown/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,YAAY,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAEpE,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,YAAY,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAE/E,OAAO,EAAE,4BAA4B,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC"}
@@ -0,0 +1,2 @@
1
+ import{StreamingMarkdown as e}from"./StreamingMarkdown";import{createMarkdownComponents as t}from"./createMarkdownComponents";import{completeUnterminatedMarkdown as a,parseMarkdownIntoBlocks as m}from"./utils/markdownStreaming";export{e as StreamingMarkdown,a as completeUnterminatedMarkdown,t as createMarkdownComponents,m as parseMarkdownIntoBlocks};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/components/markdown/index.ts"],
4
+ "sourcesContent": ["export { StreamingMarkdown } from \"./StreamingMarkdown\";\nexport type { StreamingMarkdownOptions } from \"./StreamingMarkdown\";\n\nexport { createMarkdownComponents } from \"./createMarkdownComponents\";\nexport type { MarkdownComponentOptions, MarkdownChildrenProps } from \"./types\";\n\nexport { completeUnterminatedMarkdown, parseMarkdownIntoBlocks } from \"./utils/markdownStreaming\";\n\n"],
5
+ "mappings": "AAAA,OAAS,qBAAAA,MAAyB,sBAGlC,OAAS,4BAAAC,MAAgC,6BAGzC,OAAS,gCAAAC,EAA8B,2BAAAC,MAA+B",
6
+ "names": ["StreamingMarkdown", "createMarkdownComponents", "completeUnterminatedMarkdown", "parseMarkdownIntoBlocks"]
7
+ }
@@ -0,0 +1,32 @@
1
+ import type { ReactNode } from "react";
2
+ /**
3
+ * Options for customizing markdown component behavior
4
+ */
5
+ export type MarkdownComponentOptions = {
6
+ /**
7
+ * Whether code blocks should be collapsible
8
+ * @default false
9
+ */
10
+ codeBlockCollapsible?: boolean;
11
+ /**
12
+ * Custom image component
13
+ */
14
+ imageComponent?: (props: {
15
+ src?: string;
16
+ alt?: string;
17
+ width?: string;
18
+ height?: string;
19
+ }) => ReactNode;
20
+ /**
21
+ * Whether to use high contrast for inline code
22
+ * @default true
23
+ */
24
+ inlineCodeHighContrast?: boolean;
25
+ };
26
+ /**
27
+ * Common props for markdown child components
28
+ */
29
+ export type MarkdownChildrenProps = {
30
+ children?: ReactNode;
31
+ };
32
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/components/markdown/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAEvC;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACrC;;;OAGG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAE/B;;OAEG;IACH,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,SAAS,CAAC;IAEvG;;;OAGG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAClC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,QAAQ,CAAC,EAAE,SAAS,CAAC;CACtB,CAAC"}
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Utilities for handling streaming markdown content.
3
+ * Completes unterminated markdown blocks to enable proper parsing during streaming.
4
+ */
5
+ /**
6
+ * Completes unterminated markdown syntax at the end of content.
7
+ * This allows streaming markdown to be parsed correctly even when syntax is incomplete.
8
+ *
9
+ * Handles:
10
+ * - Headings (# Heading)
11
+ * - Inline code (`code)
12
+ * - Bold (**text or __text)
13
+ * - Italic (*text or _text)
14
+ * - Links ([text](url or [text]()
15
+ * - Code blocks (```language\ncode)
16
+ * - Lists (- item or * item or 1. item)
17
+ * - Blockquotes (> text)
18
+ * - Strikethrough (~~text)
19
+ */
20
+ export declare function completeUnterminatedMarkdown(content: string): string;
21
+ /**
22
+ * Parses markdown content into blocks for efficient rendering.
23
+ * Each block is a separate markdown token that can be memoized independently.
24
+ *
25
+ * @param content - The markdown content to parse
26
+ * @param parser - Optional parser function (defaults to using marked.lexer)
27
+ * @returns Array of markdown block strings
28
+ */
29
+ export declare function parseMarkdownIntoBlocks(content: string, parser?: (content: string) => Array<{
30
+ raw?: string;
31
+ }>): string[];
32
+ //# sourceMappingURL=markdownStreaming.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdownStreaming.d.ts","sourceRoot":"","sources":["../../../../../src/components/markdown/utils/markdownStreaming.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA2IH;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAsGpE;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,KAAK,CAAC;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GACpD,MAAM,EAAE,CAuBV"}
@@ -0,0 +1,5 @@
1
+ function f(e,r){const n=r==="**"?"\\*\\*":"__",t=new RegExp(n,"g");if((e.match(t)||[]).length%2===0)return!1;const i=e.lastIndexOf(r);return i===-1?!1:e.slice(i+r.length).length>0}function h(e){if((e.match(/~~/g)||[]).length%2===0)return!1;const n=e.lastIndexOf("~~");return n===-1?!1:e.slice(n+2).length>0}function g(e,r,n){if(n!=="*")return!1;const t=r===0||e[r-1]===`
2
+ `,s=r<e.length-1&&e[r+1]===" ";return t&&s}function u(e,r){let n=0,t=-1;for(let i=0;i<e.length;i++)if(e[i]===r){if(g(e,i,r))continue;const a=i>0&&e[i-1]===r,l=i<e.length-1&&e[i+1]===r;if(a||l){l&&i++;continue}n++,t=i}return n%2===0||t===-1?!1:t===e.length-1?t>0:e.slice(t+1).length>0}function m(e){const r=/```/g,n=[];let t;for(;(t=r.exec(e))!==null;)n.push(t.index);return n.length%2===1}function d(e){if(!e.trim())return e;const r=e.trimEnd(),n=e.slice(r.length);let t=r;if(t.match(/```[\w-]*$/)&&!t.includes("```\n")&&!t.match(/```[\w-]+\n/)||m(t))return t+="\n```",t+n;if((t.replace(/```[\w-]*/g,"").match(/`/g)||[]).length%2===1)return t+="`",t+n;if(t.match(/\[([^\]]*)\]\(([^)]*)$/))return t+=")",t+n;if(f(t,"**"))return t+="**",t+n;if(f(t,"__"))return t+="__",t+n;if(h(t))return t+="~~",t+n;const o=t.split(`
3
+ `),c=o[o.length-1];return c.match(/^#{1,6}\s+.+$/)||c.match(/^(\s*)([-*+]|\d+\.)\s+.+$/)||c.match(/^>\s+.+$/)?(t+=`
4
+ `,t+n):u(t,"*")?(t+="*",t+n):(u(t,"_")&&(t+="_"),t+n)}function p(e,r){if(!e.trim())return[];const n=d(e);return r?r(n).map(s=>"raw"in s&&typeof s.raw=="string"?s.raw:"").filter(s=>!!s.trim()):[n]}export{d as completeUnterminatedMarkdown,p as parseMarkdownIntoBlocks};
5
+ //# sourceMappingURL=markdownStreaming.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/components/markdown/utils/markdownStreaming.ts"],
4
+ "sourcesContent": ["/**\n * Utilities for handling streaming markdown content.\n * Completes unterminated markdown blocks to enable proper parsing during streaming.\n */\n\n/**\n * Checks if there's an unpaired double marker (** or __) with content after the last opener.\n * Returns true only if there's text after the unclosed marker (not just the marker itself).\n */\nfunction hasUnpairedDoubleMarkerWithContent(content: string, marker: string): boolean {\n const escaped = marker === \"**\" ? \"\\\\*\\\\*\" : \"__\";\n const regex = new RegExp(escaped, \"g\");\n const matches = content.match(regex) || [];\n\n if (matches.length % 2 === 0) {\n return false; // All paired\n }\n\n // Find the last occurrence of the marker - there should be content after it\n const lastIndex = content.lastIndexOf(marker);\n if (lastIndex === -1) {\n return false;\n }\n\n // Check if there's actual content after the marker\n const afterMarker = content.slice(lastIndex + marker.length);\n return afterMarker.length > 0;\n}\n\n/**\n * Checks if there's an unpaired strikethrough with content after the last opener.\n */\nfunction hasUnpairedStrikethroughWithContent(content: string): boolean {\n const matches = content.match(/~~/g) || [];\n\n if (matches.length % 2 === 0) {\n return false; // All paired\n }\n\n // Find the last occurrence - there should be content after it\n const lastIndex = content.lastIndexOf(\"~~\");\n if (lastIndex === -1) {\n return false;\n }\n\n const afterMarker = content.slice(lastIndex + 2);\n return afterMarker.length > 0;\n}\n\n/**\n * Checks if a marker at position i is a list marker (at start of line followed by space).\n */\nfunction isListMarker(content: string, i: number, marker: string): boolean {\n // Only * can be a list marker (not _)\n if (marker !== \"*\") {\n return false;\n }\n\n // Check if at start of line (or start of content)\n const isStartOfLine = i === 0 || content[i - 1] === \"\\n\";\n // Check if followed by space\n const followedBySpace = i < content.length - 1 && content[i + 1] === \" \";\n\n return isStartOfLine && followedBySpace;\n}\n\n/**\n * Checks if there's an unpaired single italic marker (* or _) that needs closing.\n * Must distinguish from bold markers (** or __) and list markers (* ).\n *\n * Returns true if:\n * - There's an odd number of single markers (not part of double markers or list markers)\n * - Either there's content after the last marker, OR the content ends with the marker\n */\nfunction hasUnpairedItalicWithContent(content: string, marker: string): boolean {\n // Count single markers (not part of double markers or list markers)\n let singleCount = 0;\n let lastSingleIndex = -1;\n\n for (let i = 0; i < content.length; i++) {\n if (content[i] === marker) {\n // Check if it's a list marker\n if (isListMarker(content, i, marker)) {\n continue;\n }\n\n // Check if it's part of a double marker\n const prevIsMarker = i > 0 && content[i - 1] === marker;\n const nextIsMarker = i < content.length - 1 && content[i + 1] === marker;\n\n if (prevIsMarker || nextIsMarker) {\n // Part of ** or __, skip\n if (nextIsMarker) {\n i++; // Skip the next one too\n }\n continue;\n }\n\n singleCount++;\n lastSingleIndex = i;\n }\n }\n\n if (singleCount % 2 === 0) {\n return false; // All paired\n }\n\n if (lastSingleIndex === -1) {\n return false;\n }\n\n // If content ends with the marker, it's an opener that needs closing\n // (e.g., \"*text* more *\" - the last * is a new opener)\n // BUT only if there's content before it (not just a lone marker)\n if (lastSingleIndex === content.length - 1) {\n // Must have content before the marker for it to be a meaningful opener\n return lastSingleIndex > 0;\n }\n\n // Otherwise, check if there's content after the last unpaired marker\n const afterMarker = content.slice(lastSingleIndex + 1);\n return afterMarker.length > 0;\n}\n\n/**\n * Checks if content has an unclosed code block.\n * Returns true if the last ``` opens a block that isn't closed.\n */\nfunction hasUnclosedCodeBlock(content: string): boolean {\n // Find all ``` occurrences\n const fenceRegex = /```/g;\n const matches: number[] = [];\n let match;\n\n while ((match = fenceRegex.exec(content)) !== null) {\n matches.push(match.index);\n }\n\n // Odd number of fences means unclosed\n return matches.length % 2 === 1;\n}\n\n/**\n * Completes unterminated markdown syntax at the end of content.\n * This allows streaming markdown to be parsed correctly even when syntax is incomplete.\n *\n * Handles:\n * - Headings (# Heading)\n * - Inline code (`code)\n * - Bold (**text or __text)\n * - Italic (*text or _text)\n * - Links ([text](url or [text]()\n * - Code blocks (```language\\ncode)\n * - Lists (- item or * item or 1. item)\n * - Blockquotes (> text)\n * - Strikethrough (~~text)\n */\nexport function completeUnterminatedMarkdown(content: string): string {\n if (!content.trim()) {\n return content;\n }\n\n // Work backwards from the end to find the last incomplete markdown pattern\n const trimmed = content.trimEnd();\n const trailingWhitespace = content.slice(trimmed.length);\n let result = trimmed;\n\n // Check for incomplete code fence without newline yet (e.g., \"```python\" with no \\n)\n // This must come before the code block check\n const incompleteFenceMatch = result.match(/```[\\w-]*$/);\n if (incompleteFenceMatch && !result.includes(\"```\\n\") && !result.match(/```[\\w-]+\\n/)) {\n // Code fence just started, hasn't gotten content yet - add newline and closing\n result += \"\\n```\";\n return result + trailingWhitespace;\n }\n\n // Check for incomplete code blocks using fence counting\n if (hasUnclosedCodeBlock(result)) {\n result += \"\\n```\";\n return result + trailingWhitespace;\n }\n\n // Check for incomplete inline code (backticks)\n // Count backticks that are NOT part of code fences\n // First, remove all code fence markers to count only inline backticks\n const withoutFences = result.replace(/```[\\w-]*/g, \"\");\n const backtickCount = (withoutFences.match(/`/g) || []).length;\n if (backtickCount % 2 === 1) {\n result += \"`\";\n return result + trailingWhitespace;\n }\n\n // Check for incomplete links [text](url\n const linkMatch = result.match(/\\[([^\\]]*)\\]\\(([^)]*)$/);\n if (linkMatch) {\n // Incomplete link - close the URL part\n result += \")\";\n return result + trailingWhitespace;\n }\n\n // Check for incomplete bold (**text or __text)\n // Only complete if there's actual content after the marker\n if (hasUnpairedDoubleMarkerWithContent(result, \"**\")) {\n result += \"**\";\n return result + trailingWhitespace;\n }\n\n if (hasUnpairedDoubleMarkerWithContent(result, \"__\")) {\n result += \"__\";\n return result + trailingWhitespace;\n }\n\n // Check for incomplete strikethrough (~~text)\n if (hasUnpairedStrikethroughWithContent(result)) {\n result += \"~~\";\n return result + trailingWhitespace;\n }\n\n // Check structural elements BEFORE italic to avoid false positives\n // (e.g., \"* item\" is a list, not italic)\n const lines = result.split(\"\\n\");\n const lastLine = lines[lines.length - 1];\n\n // Check for incomplete headings (# Heading without newline)\n // Look for # at the start of the last line\n if (lastLine.match(/^#{1,6}\\s+.+$/)) {\n // Heading without trailing newline - add one for proper parsing\n result += \"\\n\";\n return result + trailingWhitespace;\n }\n\n // Check for incomplete list items (- item, * item, 1. item)\n // Look for list markers at the start of the last line\n if (lastLine.match(/^(\\s*)([-*+]|\\d+\\.)\\s+.+$/)) {\n // List item without trailing newline - add one for proper parsing\n result += \"\\n\";\n return result + trailingWhitespace;\n }\n\n // Check for incomplete blockquotes (> text)\n if (lastLine.match(/^>\\s+.+$/)) {\n // Blockquote without trailing newline - add one for proper parsing\n result += \"\\n\";\n return result + trailingWhitespace;\n }\n\n // Check for incomplete italic (*text or _text) AFTER structural elements\n // This prevents \"* item\" from being treated as italic\n if (hasUnpairedItalicWithContent(result, \"*\")) {\n result += \"*\";\n return result + trailingWhitespace;\n }\n\n if (hasUnpairedItalicWithContent(result, \"_\")) {\n result += \"_\";\n return result + trailingWhitespace;\n }\n\n return result + trailingWhitespace;\n}\n\n/**\n * Parses markdown content into blocks for efficient rendering.\n * Each block is a separate markdown token that can be memoized independently.\n *\n * @param content - The markdown content to parse\n * @param parser - Optional parser function (defaults to using marked.lexer)\n * @returns Array of markdown block strings\n */\nexport function parseMarkdownIntoBlocks(\n content: string,\n parser?: (content: string) => Array<{ raw?: string }>\n): string[] {\n if (!content.trim()) {\n return [];\n }\n\n // Complete unterminated markdown blocks for streaming support\n const completedContent = completeUnterminatedMarkdown(content);\n\n // If no parser provided, return the content as a single block\n // This allows usage without marked dependency\n if (!parser) {\n return [completedContent];\n }\n\n const tokens = parser(completedContent);\n return tokens\n .map((token) => {\n if (\"raw\" in token && typeof token.raw === \"string\") {\n return token.raw;\n }\n return \"\";\n })\n .filter((raw) => Boolean(raw.trim()));\n}\n\n"],
5
+ "mappings": "AASA,SAASA,EAAmCC,EAAiBC,EAAyB,CACpF,MA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CA,GAAU,IACHA,EAASD,IAGdX,EAA6BY,EAAQ,GAAG,IAC1CA,GAAU,KACHA,EAASD,EAIpB,CAUO,SAASI,EACdzB,EACA0B,EACU,CACV,GAAI,CAAC1B,EAAQ,KAAK,EAChB,MAAO,CAAC,EAIV,MAAM2B,EAAmBR,EAA6BnB,CAAO,EAI7D,OAAK0B,EAIUA,EAAOC,CAAgB,EAEnC,IAAKC,GACA,QAASA,GAAS,OAAOA,EAAM,KAAQ,SAClCA,EAAM,IAER,EACR,EACA,OAAQC,GAAQ,EAAQA,EAAI,KAAK,CAAE,EAX7B,CAACF,CAAgB,CAY5B",
6
+ "names": ["hasUnpairedDoubleMarkerWithContent", "content", "marker", "escaped", "regex", "lastIndex", "hasUnpairedStrikethroughWithContent", "isListMarker", "i", "isStartOfLine", "followedBySpace", "hasUnpairedItalicWithContent", "singleCount", "lastSingleIndex", "prevIsMarker", "nextIsMarker", "hasUnclosedCodeBlock", "fenceRegex", "matches", "match", "completeUnterminatedMarkdown", "trimmed", "trailingWhitespace", "result", "lines", "lastLine", "parseMarkdownIntoBlocks", "parser", "completedContent", "token", "raw"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kushagradhawan/kookie-blocks",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/KushagraDhawan1997/kookie-blocks.git"
@@ -93,6 +93,10 @@
93
93
  "dependencies": {
94
94
  "@hugeicons/core-free-icons": "^2.0.0",
95
95
  "@hugeicons/react": "^1.1.1",
96
+ "harden-react-markdown": "^1.1.0",
97
+ "react-markdown": "^9.0.1",
98
+ "rehype-raw": "^7.0.0",
99
+ "remark-gfm": "^4.0.0",
96
100
  "shiki": "^1.24.2"
97
101
  },
98
102
  "peerDependencies": {
@@ -100,6 +104,11 @@
100
104
  "react": "^18.0.0 || ^19.0.0",
101
105
  "react-dom": "^18.0.0 || ^19.0.0"
102
106
  },
107
+ "peerDependenciesMeta": {
108
+ "marked": {
109
+ "optional": true
110
+ }
111
+ },
103
112
  "devDependencies": {
104
113
  "@eslint/js": "^9.18.0",
105
114
  "@types/react": "^19.0.2",
@@ -1,2 +1,3 @@
1
1
  export * from './code';
2
2
  export * from './hero';
3
+ export * from './markdown';
@@ -0,0 +1,183 @@
1
+ "use client";
2
+
3
+ import React, { memo, useMemo, type ReactNode } from "react";
4
+ import ReactMarkdown, { type Components } from "react-markdown";
5
+ import remarkGfm from "remark-gfm";
6
+ import rehypeRaw from "rehype-raw";
7
+ import hardenReactMarkdown from "harden-react-markdown";
8
+ import { Box, Flex } from "@kushagradhawan/kookie-ui";
9
+ import { createMarkdownComponents } from "./createMarkdownComponents";
10
+ import { completeUnterminatedMarkdown, parseMarkdownIntoBlocks } from "./utils/markdownStreaming";
11
+ import type { MarkdownComponentOptions } from "./types";
12
+
13
+ const HardenedMarkdown = hardenReactMarkdown(ReactMarkdown);
14
+
15
+ const LINK_PREFIXES = ["https://", "http://", "/"];
16
+ const IMAGE_PREFIXES = ["https://", "http://", "/", "data:"];
17
+ const ALLOWED_PROTOCOLS = ["mailto:", "tel:", "data:", "http:", "https:"];
18
+ const DEFAULT_APP_ORIGIN = typeof window !== "undefined" && window.location?.origin ? window.location.origin : "https://app.kookie.ai";
19
+
20
+ /**
21
+ * Options for StreamingMarkdown component
22
+ */
23
+ export type StreamingMarkdownOptions = MarkdownComponentOptions & {
24
+ /**
25
+ * Security origin for link/image validation
26
+ * @default window.location.origin or "https://app.kookie.ai"
27
+ */
28
+ defaultOrigin?: string;
29
+
30
+ /**
31
+ * Whether to enable block-level memoization for performance
32
+ * Recommended for streaming scenarios where content updates frequently
33
+ * @default true
34
+ */
35
+ enableBlockMemoization?: boolean;
36
+
37
+ /**
38
+ * Custom parser for splitting content into blocks
39
+ * If not provided, content will be rendered as a single block
40
+ * For optimal streaming performance, use marked.lexer with GFM enabled
41
+ */
42
+ blockParser?: (content: string) => Array<{ raw?: string }>;
43
+
44
+ /**
45
+ * Override default component mappings
46
+ */
47
+ components?: Partial<Components>;
48
+ };
49
+
50
+ type StreamingMarkdownProps = {
51
+ /**
52
+ * Markdown content to render (supports streaming/incomplete markdown)
53
+ */
54
+ content: string;
55
+
56
+ /**
57
+ * Unique identifier for this markdown instance (used for keys)
58
+ */
59
+ id: string;
60
+
61
+ /**
62
+ * Optional configuration
63
+ */
64
+ options?: StreamingMarkdownOptions;
65
+ };
66
+
67
+ type MarkdownBlockProps = {
68
+ content: string;
69
+ defaultOrigin: string;
70
+ components: Components;
71
+ };
72
+
73
+ /**
74
+ * Resolves the default origin for security validation
75
+ */
76
+ function resolveDefaultOrigin(customOrigin?: string): string {
77
+ if (customOrigin) {
78
+ return customOrigin;
79
+ }
80
+ return DEFAULT_APP_ORIGIN;
81
+ }
82
+
83
+ /**
84
+ * Memoized markdown block component for efficient streaming rendering
85
+ */
86
+ const MarkdownBlock = memo(
87
+ ({ content, defaultOrigin, components }: MarkdownBlockProps) => {
88
+ return (
89
+ <Box width="100%">
90
+ <HardenedMarkdown
91
+ defaultOrigin={defaultOrigin}
92
+ allowedLinkPrefixes={LINK_PREFIXES}
93
+ allowedImagePrefixes={IMAGE_PREFIXES}
94
+ allowedProtocols={ALLOWED_PROTOCOLS}
95
+ allowDataImages
96
+ components={components}
97
+ remarkPlugins={[remarkGfm]}
98
+ rehypePlugins={[rehypeRaw]}
99
+ >
100
+ {content}
101
+ </HardenedMarkdown>
102
+ </Box>
103
+ );
104
+ },
105
+ (previous, next) => previous.content === next.content && previous.defaultOrigin === next.defaultOrigin && previous.components === next.components
106
+ );
107
+
108
+ MarkdownBlock.displayName = "MarkdownBlock";
109
+
110
+ /**
111
+ * StreamingMarkdown - A drop-in markdown renderer designed for AI streaming.
112
+ *
113
+ * Features:
114
+ * - Unterminated block parsing (handles incomplete markdown during streaming)
115
+ * - Block-level memoization for performance
116
+ * - Security hardening (validates links/images)
117
+ * - GitHub Flavored Markdown support
118
+ * - KookieUI component integration
119
+ * - Code syntax highlighting via CodeBlock
120
+ *
121
+ * @example
122
+ * ```tsx
123
+ * import { StreamingMarkdown } from '@kushagradhawan/kookie-blocks';
124
+ * import { marked } from 'marked';
125
+ *
126
+ * function ChatMessage({ message }) {
127
+ * return (
128
+ * <StreamingMarkdown
129
+ * content={message.content}
130
+ * id={message.id}
131
+ * options={{
132
+ * blockParser: (content) => marked.lexer(content, { gfm: true }),
133
+ * enableBlockMemoization: true,
134
+ * }}
135
+ * />
136
+ * );
137
+ * }
138
+ * ```
139
+ */
140
+ export function StreamingMarkdown({ content, id, options = {} }: StreamingMarkdownProps) {
141
+ const { defaultOrigin: customOrigin, enableBlockMemoization = true, blockParser, components: customComponents = {}, ...componentOptions } = options;
142
+
143
+ // Resolve security origin
144
+ const defaultOrigin = useMemo(() => resolveDefaultOrigin(customOrigin), [customOrigin]);
145
+
146
+ // Create component mappings with custom overrides
147
+ const markdownComponents = useMemo(() => {
148
+ const baseComponents = createMarkdownComponents(componentOptions);
149
+ return {
150
+ ...baseComponents,
151
+ ...customComponents,
152
+ };
153
+ }, [componentOptions, customComponents]);
154
+
155
+ // Parse content into blocks for memoization (if enabled and parser provided)
156
+ const blocks = useMemo(() => {
157
+ if (!enableBlockMemoization || !blockParser) {
158
+ // No block splitting - just complete unterminated markdown
159
+ const completed = completeUnterminatedMarkdown(content);
160
+ return completed.trim() ? [completed] : [];
161
+ }
162
+
163
+ return parseMarkdownIntoBlocks(content, blockParser);
164
+ }, [content, enableBlockMemoization, blockParser]);
165
+
166
+ if (!blocks.length) {
167
+ return null;
168
+ }
169
+
170
+ // Single block - no need for wrapper
171
+ if (blocks.length === 1) {
172
+ return <MarkdownBlock content={blocks[0]} defaultOrigin={defaultOrigin} components={markdownComponents} />;
173
+ }
174
+
175
+ // Multiple blocks - render with flex wrapper
176
+ return (
177
+ <Flex direction="column" gap="2" width="100%">
178
+ {blocks.map((block, index) => (
179
+ <MarkdownBlock key={`${id}-block-${index}`} content={block} defaultOrigin={defaultOrigin} components={markdownComponents} />
180
+ ))}
181
+ </Flex>
182
+ );
183
+ }
@@ -0,0 +1,206 @@
1
+ import React, { type ReactNode } from "react";
2
+ import type { Components } from "react-markdown";
3
+ import { Blockquote, Box, Code, Flex, Heading, Text, Table } from "@kushagradhawan/kookie-ui";
4
+ import { CodeBlock } from "../code";
5
+ import type { MarkdownComponentOptions, MarkdownChildrenProps } from "./types";
6
+
7
+ /**
8
+ * Extracts language from className (e.g., "language-typescript" -> "typescript")
9
+ */
10
+ function extractLanguage(className?: string): string {
11
+ if (!className) {
12
+ return "text";
13
+ }
14
+ const match = className.match(/language-([\w-]+)/i);
15
+ return match?.[1] ?? "text";
16
+ }
17
+
18
+ /**
19
+ * Extracts code string from ReactNode children
20
+ */
21
+ function extractCode(children?: ReactNode): string {
22
+ let code = "";
23
+ if (!children) {
24
+ return code;
25
+ }
26
+ if (typeof children === "string") {
27
+ code = children;
28
+ } else if (Array.isArray(children)) {
29
+ code = children.map((child) => (typeof child === "string" ? child : "")).join("");
30
+ }
31
+ // Trim trailing newlines but preserve internal whitespace
32
+ return code.replace(/^\n+|\n+$/g, "");
33
+ }
34
+
35
+ /**
36
+ * Creates markdown component mappings that work with both react-markdown and MDX.
37
+ * Uses KookieUI components for consistent styling across all projects.
38
+ *
39
+ * @param options - Optional configuration for component behavior
40
+ * @returns Component mappings for markdown/MDX renderers
41
+ *
42
+ * @example
43
+ * ```tsx
44
+ * // In react-markdown
45
+ * <ReactMarkdown components={createMarkdownComponents()}>
46
+ * {content}
47
+ * </ReactMarkdown>
48
+ *
49
+ * // In MDX
50
+ * export function useMDXComponents(components: MDXComponents) {
51
+ * return {
52
+ * ...createMarkdownComponents(),
53
+ * ...components,
54
+ * };
55
+ * }
56
+ * ```
57
+ */
58
+ export function createMarkdownComponents(options: MarkdownComponentOptions = {}): Components {
59
+ const { codeBlockCollapsible = false, imageComponent, inlineCodeHighContrast = true } = options;
60
+
61
+ return {
62
+ // Headings with consistent visual hierarchy
63
+ h1: ({ children }: MarkdownChildrenProps) => (
64
+ <Heading size="8" weight="medium" as="h1" style={{ marginTop: "1rem", marginBottom: "0.5rem" }}>
65
+ {children}
66
+ </Heading>
67
+ ),
68
+ h2: ({ children }: MarkdownChildrenProps) => (
69
+ <Heading weight="medium" size="5" as="h2" style={{ marginTop: "0.875rem", marginBottom: "0.5rem" }}>
70
+ {children}
71
+ </Heading>
72
+ ),
73
+ h3: ({ children }: MarkdownChildrenProps) => (
74
+ <Heading weight="medium" size="4" as="h3" style={{ marginTop: "0.75rem", marginBottom: "0.5rem" }}>
75
+ {children}
76
+ </Heading>
77
+ ),
78
+ h4: ({ children }: MarkdownChildrenProps) => (
79
+ <Heading weight="medium" size="3" as="h4" style={{ marginTop: "0.625rem", marginBottom: "0.5rem" }}>
80
+ {children}
81
+ </Heading>
82
+ ),
83
+ h5: ({ children }: MarkdownChildrenProps) => (
84
+ <Heading weight="medium" size="3" as="h5" style={{ marginTop: "0.5rem", marginBottom: "0.5rem" }}>
85
+ {children}
86
+ </Heading>
87
+ ),
88
+ h6: ({ children }: MarkdownChildrenProps) => (
89
+ <Heading weight="medium" size="3" as="h6" style={{ marginTop: "0.5rem", marginBottom: "0.5rem" }}>
90
+ {children}
91
+ </Heading>
92
+ ),
93
+
94
+ // Paragraph text
95
+ p: ({ children }: MarkdownChildrenProps) => (
96
+ <Text size="3" as="p" style={{ lineHeight: "1.6" }}>
97
+ {children}
98
+ </Text>
99
+ ),
100
+
101
+ // Code - inline vs block
102
+ code: ({ className, children, inline }: { className?: string; children?: ReactNode; inline?: boolean }) => {
103
+ const code = extractCode(children);
104
+
105
+ // Block code: has className (language) OR is not marked as inline
106
+ // Inline code: explicitly marked as inline=true, or no className and short single-line content
107
+ const isInlineCode = inline === true || (inline === undefined && !className && !code.includes("\n") && code.length < 100);
108
+
109
+ if (isInlineCode) {
110
+ return (
111
+ <Code highContrast={inlineCodeHighContrast} size="3">
112
+ {code}
113
+ </Code>
114
+ );
115
+ }
116
+
117
+ return (
118
+ <Box my="2" style={{ minWidth: 0 }}>
119
+ <CodeBlock code={code} language={extractLanguage(className)} collapsible={codeBlockCollapsible} />
120
+ </Box>
121
+ );
122
+ },
123
+
124
+ // Lists
125
+ ul: ({ children }: MarkdownChildrenProps) => (
126
+ <ul style={{ marginTop: "0.5rem", marginBottom: "0.5rem", lineHeight: "1.6", paddingLeft: "1.5rem", listStyleType: "disc" }}>{children}</ul>
127
+ ),
128
+ ol: ({ children }: MarkdownChildrenProps) => (
129
+ <ol style={{ marginTop: "0.5rem", marginBottom: "0.5rem", lineHeight: "1.6", paddingLeft: "1.5rem", listStyleType: "decimal" }}>{children}</ol>
130
+ ),
131
+ li: ({ children }: MarkdownChildrenProps) => <li style={{ marginBottom: "0.25rem", lineHeight: "1.6" }}>{children}</li>,
132
+
133
+ // Blockquote
134
+ blockquote: ({ children }: MarkdownChildrenProps) => <Blockquote>{children}</Blockquote>,
135
+
136
+ // Links
137
+ a: ({ href, children }: { href?: string; children?: ReactNode }) => (
138
+ <a href={href} style={{ color: "var(--accent-9)", textDecoration: "underline" }}>
139
+ {children}
140
+ </a>
141
+ ),
142
+
143
+ // Text styling
144
+ strong: ({ children }: MarkdownChildrenProps) => (
145
+ <Text weight="medium" style={{ lineHeight: "1.6" }}>
146
+ {children}
147
+ </Text>
148
+ ),
149
+ em: ({ children }: MarkdownChildrenProps) => <Text style={{ lineHeight: "1.6", fontStyle: "italic" }}>{children}</Text>,
150
+
151
+ // Horizontal rule
152
+ hr: () => (
153
+ <hr
154
+ style={{
155
+ color: "var(--gray-6)",
156
+ marginTop: "0.5rem",
157
+ marginBottom: "0.5rem",
158
+ height: "1px",
159
+ width: "100%",
160
+ opacity: 0.5,
161
+ }}
162
+ />
163
+ ),
164
+
165
+ // Pre wrapper (pass through to let code handle it)
166
+ pre: ({ children }: MarkdownChildrenProps) => <>{children}</>,
167
+
168
+ // Tables using KookieUI
169
+ table: ({ children }: MarkdownChildrenProps) => (
170
+ <Box my="2" style={{ overflowX: "auto" }}>
171
+ <Table.Root size="2" variant="ghost">
172
+ {children}
173
+ </Table.Root>
174
+ </Box>
175
+ ),
176
+ thead: ({ children }: MarkdownChildrenProps) => <Table.Header>{children}</Table.Header>,
177
+ tbody: ({ children }: MarkdownChildrenProps) => <Table.Body>{children}</Table.Body>,
178
+ tr: ({ children }: MarkdownChildrenProps) => <Table.Row>{children}</Table.Row>,
179
+ th: ({ children }: MarkdownChildrenProps) => <Table.ColumnHeaderCell>{children}</Table.ColumnHeaderCell>,
180
+ td: ({ children }: MarkdownChildrenProps) => <Table.Cell>{children}</Table.Cell>,
181
+
182
+ // HTML elements for raw HTML support
183
+ sub: ({ children }: MarkdownChildrenProps) => <sub>{children}</sub>,
184
+ sup: ({ children }: MarkdownChildrenProps) => <sup>{children}</sup>,
185
+ br: () => <br />,
186
+
187
+ // Images - use custom component if provided
188
+ img: imageComponent
189
+ ? (props: React.ImgHTMLAttributes<HTMLImageElement>) => {
190
+ const { src, alt, width, height } = props;
191
+ if (!src || typeof src !== "string") return null;
192
+ return imageComponent({
193
+ src,
194
+ alt: alt ?? "Image",
195
+ width: width ? String(width) : undefined,
196
+ height: height ? String(height) : undefined,
197
+ });
198
+ }
199
+ : undefined,
200
+
201
+ // Details/Summary for expandable sections
202
+ details: ({ children }: MarkdownChildrenProps) => <details style={{ padding: "0.5rem 0" }}>{children}</details>,
203
+ summary: ({ children }: MarkdownChildrenProps) => <summary style={{ cursor: "pointer", fontWeight: 500 }}>{children}</summary>,
204
+ };
205
+ }
206
+
@@ -0,0 +1,8 @@
1
+ export { StreamingMarkdown } from "./StreamingMarkdown";
2
+ export type { StreamingMarkdownOptions } from "./StreamingMarkdown";
3
+
4
+ export { createMarkdownComponents } from "./createMarkdownComponents";
5
+ export type { MarkdownComponentOptions, MarkdownChildrenProps } from "./types";
6
+
7
+ export { completeUnterminatedMarkdown, parseMarkdownIntoBlocks } from "./utils/markdownStreaming";
8
+