markdown-flow-ui 0.2.36-dev.1 → 0.3.0

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 (128) hide show
  1. package/README.md +12 -12
  2. package/dist/_virtual/index.es4.js +5 -5
  3. package/dist/_virtual/index.es5.js +5 -5
  4. package/dist/_virtual/index4.cjs +1 -1
  5. package/dist/_virtual/index5.cjs +1 -1
  6. package/dist/_virtual/variable-marker.cjs +2 -0
  7. package/dist/_virtual/variable-marker.cjs.map +1 -0
  8. package/dist/_virtual/variable-marker.es.js +5 -0
  9. package/dist/_virtual/variable-marker.es.js.map +1 -0
  10. package/dist/components/ContentRender/ContentRender.cjs +2 -2
  11. package/dist/components/ContentRender/ContentRender.cjs.map +1 -1
  12. package/dist/components/ContentRender/ContentRender.es.js +206 -205
  13. package/dist/components/ContentRender/ContentRender.es.js.map +1 -1
  14. package/dist/components/ContentRender/utils/inline-code-ranges.cjs +9 -9
  15. package/dist/components/ContentRender/utils/inline-code-ranges.cjs.map +1 -1
  16. package/dist/components/ContentRender/utils/inline-code-ranges.d.ts +3 -0
  17. package/dist/components/ContentRender/utils/inline-code-ranges.es.js +185 -161
  18. package/dist/components/ContentRender/utils/inline-code-ranges.es.js.map +1 -1
  19. package/dist/components/ContentRender/utils/mermaid-parse.cjs +4 -4
  20. package/dist/components/ContentRender/utils/mermaid-parse.cjs.map +1 -1
  21. package/dist/components/ContentRender/utils/mermaid-parse.es.js +53 -48
  22. package/dist/components/ContentRender/utils/mermaid-parse.es.js.map +1 -1
  23. package/dist/components/ContentRender/utils/split-content.cjs +6 -6
  24. package/dist/components/ContentRender/utils/split-content.cjs.map +1 -1
  25. package/dist/components/ContentRender/utils/split-content.d.ts +1 -0
  26. package/dist/components/ContentRender/utils/split-content.es.js +361 -313
  27. package/dist/components/ContentRender/utils/split-content.es.js.map +1 -1
  28. package/dist/components/MarkdownFlowEditor/MarkdownFlowEditor.cjs +1 -1
  29. package/dist/components/MarkdownFlowEditor/MarkdownFlowEditor.cjs.map +1 -1
  30. package/dist/components/MarkdownFlowEditor/MarkdownFlowEditor.es.js +278 -283
  31. package/dist/components/MarkdownFlowEditor/MarkdownFlowEditor.es.js.map +1 -1
  32. package/dist/components/MarkdownFlowEditor/components/VariableSelect.cjs +1 -1
  33. package/dist/components/MarkdownFlowEditor/components/VariableSelect.cjs.map +1 -1
  34. package/dist/components/MarkdownFlowEditor/components/VariableSelect.es.js +57 -58
  35. package/dist/components/MarkdownFlowEditor/components/VariableSelect.es.js.map +1 -1
  36. package/dist/components/MarkdownFlowEditor/locales/ar-SA.json.cjs +1 -1
  37. package/dist/components/MarkdownFlowEditor/locales/ar-SA.json.d.ts +1 -1
  38. package/dist/components/MarkdownFlowEditor/locales/ar-SA.json.es.js +1 -1
  39. package/dist/components/MarkdownFlowEditor/locales/de-DE.json.cjs +1 -1
  40. package/dist/components/MarkdownFlowEditor/locales/de-DE.json.d.ts +1 -1
  41. package/dist/components/MarkdownFlowEditor/locales/de-DE.json.es.js +19 -19
  42. package/dist/components/MarkdownFlowEditor/locales/en-US.json.cjs +1 -1
  43. package/dist/components/MarkdownFlowEditor/locales/en-US.json.d.ts +1 -1
  44. package/dist/components/MarkdownFlowEditor/locales/en-US.json.es.js +5 -5
  45. package/dist/components/MarkdownFlowEditor/locales/es-ES.json.cjs +1 -1
  46. package/dist/components/MarkdownFlowEditor/locales/es-ES.json.d.ts +1 -1
  47. package/dist/components/MarkdownFlowEditor/locales/es-ES.json.es.js +1 -1
  48. package/dist/components/MarkdownFlowEditor/locales/fil-PH.json.cjs +1 -1
  49. package/dist/components/MarkdownFlowEditor/locales/fil-PH.json.d.ts +1 -1
  50. package/dist/components/MarkdownFlowEditor/locales/fil-PH.json.es.js +15 -15
  51. package/dist/components/MarkdownFlowEditor/locales/fr-FR.json.cjs +1 -1
  52. package/dist/components/MarkdownFlowEditor/locales/fr-FR.json.d.ts +1 -1
  53. package/dist/components/MarkdownFlowEditor/locales/fr-FR.json.es.js +13 -13
  54. package/dist/components/MarkdownFlowEditor/locales/ja-JP.json.cjs +1 -1
  55. package/dist/components/MarkdownFlowEditor/locales/ja-JP.json.d.ts +1 -1
  56. package/dist/components/MarkdownFlowEditor/locales/ja-JP.json.es.js +1 -1
  57. package/dist/components/MarkdownFlowEditor/locales/th-TH.json.cjs +1 -1
  58. package/dist/components/MarkdownFlowEditor/locales/th-TH.json.d.ts +1 -1
  59. package/dist/components/MarkdownFlowEditor/locales/th-TH.json.es.js +1 -1
  60. package/dist/components/MarkdownFlowEditor/locales/ur-PK.json.cjs +1 -1
  61. package/dist/components/MarkdownFlowEditor/locales/ur-PK.json.d.ts +1 -1
  62. package/dist/components/MarkdownFlowEditor/locales/ur-PK.json.es.js +1 -1
  63. package/dist/components/MarkdownFlowEditor/locales/vi-VN.json.cjs +1 -1
  64. package/dist/components/MarkdownFlowEditor/locales/vi-VN.json.d.ts +1 -1
  65. package/dist/components/MarkdownFlowEditor/locales/vi-VN.json.es.js +15 -15
  66. package/dist/components/MarkdownFlowEditor/locales/zh-CN.json.cjs +1 -1
  67. package/dist/components/MarkdownFlowEditor/locales/zh-CN.json.d.ts +1 -1
  68. package/dist/components/MarkdownFlowEditor/locales/zh-CN.json.es.js +1 -1
  69. package/dist/components/MarkdownFlowEditor/plugins/SyntaxHighlighter.cjs +3 -3
  70. package/dist/components/MarkdownFlowEditor/plugins/SyntaxHighlighter.cjs.map +1 -1
  71. package/dist/components/MarkdownFlowEditor/plugins/SyntaxHighlighter.es.js +177 -176
  72. package/dist/components/MarkdownFlowEditor/plugins/SyntaxHighlighter.es.js.map +1 -1
  73. package/dist/components/MarkdownFlowEditor/plugins/VariablePlaceholder.cjs +2 -1
  74. package/dist/components/MarkdownFlowEditor/plugins/VariablePlaceholder.cjs.map +1 -1
  75. package/dist/components/MarkdownFlowEditor/plugins/VariablePlaceholder.d.ts +3 -1
  76. package/dist/components/MarkdownFlowEditor/plugins/VariablePlaceholder.es.js +38 -55
  77. package/dist/components/MarkdownFlowEditor/plugins/VariablePlaceholder.es.js.map +1 -1
  78. package/dist/components/MarkdownFlowEditor/utils.cjs +1 -1
  79. package/dist/components/MarkdownFlowEditor/utils.cjs.map +1 -1
  80. package/dist/components/MarkdownFlowEditor/utils.d.ts +2 -2
  81. package/dist/components/MarkdownFlowEditor/utils.es.js +34 -31
  82. package/dist/components/MarkdownFlowEditor/utils.es.js.map +1 -1
  83. package/dist/components/ui/inputGroup/textarea.cjs +1 -1
  84. package/dist/components/ui/inputGroup/textarea.es.js +1 -1
  85. package/dist/lib/interaction-defaults.cjs +1 -1
  86. package/dist/lib/interaction-defaults.cjs.map +1 -1
  87. package/dist/lib/interaction-defaults.es.js +124 -133
  88. package/dist/lib/interaction-defaults.es.js.map +1 -1
  89. package/dist/lib/interaction-defaults.failure.test.d.ts +1 -0
  90. package/dist/node_modules/rc-input/es/BaseInput.cjs +1 -1
  91. package/dist/node_modules/rc-input/es/BaseInput.es.js +1 -1
  92. package/dist/node_modules/rc-textarea/es/ResizableTextArea.cjs +1 -1
  93. package/dist/node_modules/rc-textarea/es/ResizableTextArea.es.js +1 -1
  94. package/dist/node_modules/rc-textarea/es/TextArea.cjs +1 -1
  95. package/dist/node_modules/rc-textarea/es/TextArea.es.js +1 -1
  96. package/dist/node_modules/rc-textarea/es/index.cjs +1 -1
  97. package/dist/node_modules/rc-textarea/es/index.es.js +1 -1
  98. package/dist/node_modules/remark-flow/dist/escaping.cjs +2 -2
  99. package/dist/node_modules/remark-flow/dist/escaping.cjs.map +1 -1
  100. package/dist/node_modules/remark-flow/dist/escaping.es.js +128 -63
  101. package/dist/node_modules/remark-flow/dist/escaping.es.js.map +1 -1
  102. package/dist/node_modules/remark-flow/dist/index.cjs +1 -1
  103. package/dist/node_modules/remark-flow/dist/index.cjs.map +1 -1
  104. package/dist/node_modules/remark-flow/dist/index.es.js +49 -37
  105. package/dist/node_modules/remark-flow/dist/index.es.js.map +1 -1
  106. package/dist/node_modules/remark-flow/dist/interaction-parser.cjs +1 -1
  107. package/dist/node_modules/remark-flow/dist/interaction-parser.cjs.map +1 -1
  108. package/dist/node_modules/remark-flow/dist/interaction-parser.es.js +260 -255
  109. package/dist/node_modules/remark-flow/dist/interaction-parser.es.js.map +1 -1
  110. package/dist/node_modules/remark-flow/dist/interaction-plugin-core.cjs +1 -1
  111. package/dist/node_modules/remark-flow/dist/interaction-plugin-core.cjs.map +1 -1
  112. package/dist/node_modules/remark-flow/dist/interaction-plugin-core.es.js +71 -42
  113. package/dist/node_modules/remark-flow/dist/interaction-plugin-core.es.js.map +1 -1
  114. package/dist/node_modules/remark-flow/dist/interaction-syntax.cjs +1 -1
  115. package/dist/node_modules/remark-flow/dist/interaction-syntax.cjs.map +1 -1
  116. package/dist/node_modules/remark-flow/dist/interaction-syntax.es.js +501 -46
  117. package/dist/node_modules/remark-flow/dist/interaction-syntax.es.js.map +1 -1
  118. package/dist/node_modules/remark-flow/dist/variable-marker.cjs +2 -0
  119. package/dist/node_modules/remark-flow/dist/variable-marker.cjs.map +1 -0
  120. package/dist/node_modules/remark-flow/dist/variable-marker.es.js +77 -0
  121. package/dist/node_modules/remark-flow/dist/variable-marker.es.js.map +1 -0
  122. package/dist/node_modules/remark-flow/dist/variable-name.cjs +14 -1
  123. package/dist/node_modules/remark-flow/dist/variable-name.cjs.map +1 -1
  124. package/dist/node_modules/remark-flow/dist/variable-name.es.js +742 -25
  125. package/dist/node_modules/remark-flow/dist/variable-name.es.js.map +1 -1
  126. package/dist/node_modules/unified/lib/index.cjs +1 -1
  127. package/dist/node_modules/unified/lib/index.es.js +1 -1
  128. package/package.json +2 -2
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
12
12
  [![Storybook](https://img.shields.io/badge/Storybook-Enabled-ff69b4.svg)](https://storybook.js.org/)
13
13
 
14
- English | [简体中文](README_ZH-CN.md)
14
+ English | [Simplified Chinese](README_ZH-CN.md)
15
15
 
16
16
  </div>
17
17
 
@@ -90,24 +90,24 @@ can change that structure; typing an already received snapshot preserves it.
90
90
 
91
91
  ### Interactive Elements
92
92
 
93
- This variable-name policy matches AI-Shifu's existing MarkdownFlow 2.0
94
- implementation. It is a compatibility extension to the public MarkdownFlow
95
- specification, which currently restricts names to letters, digits, and underscores
96
- without surrounding whitespace.
93
+ Variable names are opaque Unicode text. Both ends are trimmed using the same
94
+ Unicode whitespace set as Python; internal spaces, punctuation, emoji, and single
95
+ braces are preserved. The trimmed name must be non-empty and contain no control
96
+ characters, line separators, or literal `}}`. The first literal `}}` closes the
97
+ marker. Quotes and backslashes remain part of the name.
97
98
 
98
- Variable names follow that backend rule: they are non-empty and contain no
99
- whitespace or braces. Question marks can remain in the name, so `?[%{{你的性别是?}} 男 | 女 | 秘密]` submits the unchanged key
100
- `你的性别是?`. Whitespace around the name inside `{{ }}` is trimmed. The name
101
- is a memory key; write the question text separately when it should be displayed.
102
- Existing identifier names such as `user_name` continue to work. Interaction
103
- delimiters retain their existing grammar.
99
+ Use padded markers such as `{{ Which [path] | level//hint...? }}` or
100
+ `%{{ name} }}`. Assignment markers remain atomic inside an interaction, so
101
+ `?[%{{ Which [path] | level//hint...? }} Yes | No]` stores the answer under that
102
+ exact name. Write the question text separately when it should be displayed.
103
+ Existing names and compact markers such as `{{user_name}}` continue to work.
104
104
 
105
105
  ```tsx
106
106
  import { MarkdownFlow } from "markdown-flow-ui";
107
107
 
108
108
  function InteractiveExample() {
109
109
  const content = `
110
- Choose your language: ?[%{{lang}} English | 中文 | Español]
110
+ Choose your language: ?[%{{lang}} English | French | Spanish]
111
111
 
112
112
  Your name: ?[%{{name}} Enter your name...]
113
113
 
@@ -1,8 +1,8 @@
1
- import { getDefaultExportFromCjs as r } from "./_commonjsHelpers.es.js";
2
- import { __require as s } from "../node_modules/classnames/index.es.js";
3
- var e = s();
4
- const t = /* @__PURE__ */ r(e);
1
+ import { getDefaultExportFromCjs as e } from "./_commonjsHelpers.es.js";
2
+ import { __require as r } from "../node_modules/extend/index.es.js";
3
+ var t = r();
4
+ const a = /* @__PURE__ */ e(t);
5
5
  export {
6
- t as default
6
+ a as default
7
7
  };
8
8
  //# sourceMappingURL=index.es4.js.map
@@ -1,8 +1,8 @@
1
- import { getDefaultExportFromCjs as e } from "./_commonjsHelpers.es.js";
2
- import { __require as r } from "../node_modules/extend/index.es.js";
3
- var t = r();
4
- const a = /* @__PURE__ */ e(t);
1
+ import { getDefaultExportFromCjs as r } from "./_commonjsHelpers.es.js";
2
+ import { __require as s } from "../node_modules/classnames/index.es.js";
3
+ var e = s();
4
+ const t = /* @__PURE__ */ r(e);
5
5
  export {
6
- a as default
6
+ t as default
7
7
  };
8
8
  //# sourceMappingURL=index.es5.js.map
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./_commonjsHelpers.cjs"),r=require("../node_modules/classnames/index.cjs");var s=r.__require();const t=e.getDefaultExportFromCjs(s);exports.default=t;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./_commonjsHelpers.cjs"),t=require("../node_modules/extend/index.cjs");var r=t.__require();const o=e.getDefaultExportFromCjs(r);exports.default=o;
2
2
  //# sourceMappingURL=index4.cjs.map
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./_commonjsHelpers.cjs"),t=require("../node_modules/extend/index.cjs");var r=t.__require();const o=e.getDefaultExportFromCjs(r);exports.default=o;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./_commonjsHelpers.cjs"),r=require("../node_modules/classnames/index.cjs");var s=r.__require();const t=e.getDefaultExportFromCjs(s);exports.default=t;
2
2
  //# sourceMappingURL=index5.cjs.map
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var e={};exports.__exports=e;
2
+ //# sourceMappingURL=variable-marker.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"variable-marker.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,5 @@
1
+ var r = {};
2
+ export {
3
+ r as __exports
4
+ };
5
+ //# sourceMappingURL=variable-marker.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"variable-marker.es.js","sources":[],"sourcesContent":[],"names":[],"mappings":";"}
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("react/jsx-runtime"),r=require("react"),lt=require("./utils/sanitize-invalid-tag-name.cjs"),dt=require("./utils/strip-svg-text-line-breaks.cjs");;/* empty css */;/* empty css */;/* empty css */;/* empty css */const Qe=require("./CodeBlock.cjs"),mt=require("./plugins/CustomVariable.cjs"),ye=require("./plugins/MermaidChart.cjs"),ze=require("./utils/custom-variable-props.cjs"),We=require("./utils/highlight-languages.cjs"),we=require("./utils/mermaid-parse.cjs"),Ge=require("./utils/inline-code-ranges.cjs"),Oe=require("./utils/markdown-plugins.cjs"),ve=require("./utils/normalize-inline-html.cjs"),ke=require("./utils/escape-typed-metadata.cjs"),pt=require("./IframeSandbox.cjs"),O=require("./utils/typewriter-pacing.cjs"),Fe=require("./utils/split-content.cjs"),ft=require("../../lib/interaction-defaults.cjs"),$e=require("../../lib/locale.cjs"),Re=require("./contentRenderI18n.cjs"),ee=require("./utils/video-markdown-run.cjs"),He=require("../../node_modules/unified/lib/index.cjs"),ht=require("../../node_modules/remark-rehype/lib/index.cjs"),gt=require("../../node_modules/rehype-raw/lib/index.cjs"),xt=require("../../node_modules/rehype-highlight/lib/index.cjs"),vt=require("../../node_modules/rehype-katex/lib/index.cjs"),Ue=require("../../node_modules/react-markdown/lib/index.cjs"),yt=2,Ce=({svg:t,inline:s=!1})=>{const a=r.useRef(null),c=s?"span":"div";return r.useEffect(()=>{const u=a.current;if(!u)return;const d=u.shadowRoot??u.attachShadow({mode:"open"}),v="content-render-svg-style";let g=d.getElementById(v);g||(g=document.createElement("style"),g.id=v,g.textContent=`
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("react/jsx-runtime"),ze=require("../../_virtual/index.cjs"),r=require("react"),dt=require("./utils/sanitize-invalid-tag-name.cjs"),mt=require("./utils/strip-svg-text-line-breaks.cjs");;/* empty css */;/* empty css */;/* empty css */;/* empty css */const Oe=require("./CodeBlock.cjs"),pt=require("./plugins/CustomVariable.cjs"),ye=require("./plugins/MermaidChart.cjs"),We=require("./utils/custom-variable-props.cjs"),Ge=require("./utils/highlight-languages.cjs"),we=require("./utils/mermaid-parse.cjs"),Fe=require("./utils/inline-code-ranges.cjs"),Ue=require("./utils/markdown-plugins.cjs"),ve=require("./utils/normalize-inline-html.cjs"),ke=require("./utils/escape-typed-metadata.cjs"),ft=require("./IframeSandbox.cjs"),O=require("./utils/typewriter-pacing.cjs"),$e=require("./utils/split-content.cjs"),ht=require("../../lib/interaction-defaults.cjs"),He=require("../../lib/locale.cjs"),Re=require("./contentRenderI18n.cjs"),ee=require("./utils/video-markdown-run.cjs"),_e=require("../../node_modules/unified/lib/index.cjs"),gt=require("../../node_modules/remark-rehype/lib/index.cjs"),xt=require("../../node_modules/rehype-raw/lib/index.cjs"),vt=require("../../node_modules/rehype-highlight/lib/index.cjs"),yt=require("../../node_modules/rehype-katex/lib/index.cjs"),Ke=require("../../node_modules/react-markdown/lib/index.cjs"),wt=2,Ce=({svg:t,inline:s=!1})=>{const a=r.useRef(null),i=s?"span":"div";return r.useEffect(()=>{const l=a.current;if(!l)return;const d=l.shadowRoot??l.attachShadow({mode:"open"}),v="content-render-svg-style";let g=d.getElementById(v);g||(g=document.createElement("style"),g.id=v,g.textContent=`
2
2
  svg { height: auto; display: inline-block; }
3
3
  svg.content-render-svg-el--responsive { width: 100%; max-width: 100%; }
4
4
  svg.content-render-svg-el--fixed { max-width: none; }
5
- `,d.appendChild(g)),Array.from(d.childNodes).filter(l=>l!==g).forEach(l=>d.removeChild(l));const y=document.createElement("template"),R=dt.stripSvgTextLineBreaks(t);y.innerHTML=R,d.append(y.content.cloneNode(!0));let b=!1,k=!1;d.querySelectorAll("svg").forEach(l=>{const E=l.getAttribute("viewBox");if(!E)return;const V=E.trim().split(/[\s,]+/).map(j=>Number(j));if(V.length!==4||V.some(Number.isNaN))return;const[,,I,C]=V,U=l.getAttribute("width"),D=l.getAttribute("height"),K=j=>{if(!j)return!1;const B=j.trim().toLowerCase();return B==="auto"||B.endsWith("%")},te=j=>{if(!j)return null;const B=j.trim().toLowerCase();if(B==="auto"||B.endsWith("%"))return null;const H=Number.parseFloat(B);return Number.isNaN(H)?null:H},ie=K(U),ue=K(D),ne=!U||U==="0",re=!D||D==="0",le=te(U),oe=te(D);if(ie||ue||ne&&re||le===I&&oe===C){b=!0,l.classList.add("content-render-svg-el--responsive"),l.classList.remove("content-render-svg-el--fixed"),l.style.width="100%",l.style.height="auto",!l.style.aspectRatio&&C>0&&(l.style.aspectRatio=`${I} / ${C}`);return}k=!0,l.classList.add("content-render-svg-el--fixed"),l.classList.remove("content-render-svg-el--responsive"),ne&&I>0&&l.setAttribute("width",`${I}`),re&&C>0&&l.setAttribute("height",`${C}`)});const f=b&&!k;u.classList.toggle("content-render-svg--responsive",f),u.classList.toggle("content-render-svg--fixed",!f)},[t]),o.jsx(c,{className:"content-render-svg-scroll",children:o.jsx(c,{className:"content-render-svg",ref:u=>{a.current=u}})})},ce=r.createContext(null),Ke=t=>{const{receivedTree:s,...a}=t,c=r.useContext(ce),u=r.useContext(Qe.CodeBlockContext);if(!c)throw new Error("Markdown code renderer requires ContentRender context.");const{className:d,children:v,...g}=a;if(/language-(\w+)/.exec(d||"")?.[1]==="mermaid"){const R=v?.toString().replace(/\n$/,"")||"",b=we.mermaidBlockIsComplete(c.current.renderContent,R),k=s?!b:b;return o.jsx(ye.default,{chart:R,frozen:k,messages:c.current.mermaidMessages})}return o.jsx("code",{className:d,...g,dir:g.dir??(u?void 0:"ltr"),children:v})},Ye=[ze.preserveCustomVariableProperties,gt.default,lt.sanitizeInvalidTagName,ze.restoreCustomVariableProperties],Xe=[[xt.default,{languages:We.highlightLanguages,subset:We.subsetLanguages}],vt.default],wt=[...Ye,...Xe],Te=({content:t,components:s,locale:a})=>{const c=Re.getContentRenderLocaleTexts(a);return o.jsx("div",{className:"markdown-renderer",children:o.jsx(Ue.Markdown,{remarkPlugins:Oe.remarkPlugins,rehypePlugins:wt,remarkRehypeOptions:{footnoteLabel:c.footnoteLabel,footnoteBackLabel:(u,d)=>{const v=String(u+1)+(d>1?`-${d}`:"");return c.footnoteBackLabel.replace("{reference}",v)}},components:s,children:t})})},kt=function(){this.parser=()=>({type:"root",children:[]})},Ct=({plan:t,renderedSegments:s,components:a,locale:c})=>{const u=r.useMemo(()=>{const R=Re.getContentRenderLocaleTexts(c),b=He.unified().use(Oe.remarkPlugins).use(ht.default,{allowDangerousHtml:!0,footnoteLabel:R.footnoteLabel,footnoteBackLabel:(l,E)=>R.footnoteBackLabel.replace("{reference}",String(l+1)+(E>1?`-${E}`:""))}).use(Ye),k=He.unified().use(Xe),f=b.runSync(ee.cloneVideoMarkdownSourceTree(t),t.markdownSource);return ee.prepareVideoMarkdownRun(t,f,l=>k.runSync(l,t.fullSource))},[t,c]),d=r.useMemo(()=>ee.projectVideoMarkdownRun(u,s),[u,s]),v=r.useRef(a);v.current=a;const g=r.useRef(new Map),J=r.useMemo(()=>{const R=new Set,b=f=>{f.type==="element"&&R.add(f.tagName),"children"in f&&f.children.forEach(b)};b(u.tree);const k={};for(const f of R){if(!g.current.has(f)){const l=({node:E,children:V,...I})=>{const C=ee.getVideoMarkdownNodeState(E);if(C?.svg)return C.svgSource?o.jsx(Ce,{svg:C.svgSource,inline:!0}):null;if(C?.atomic)return C.active?o.jsx(o.Fragment,{children:V}):null;if(C?.active===!1&&f!=="a")return null;const D=v.current[f],K=C?.active===!1?{...I,href:void 0,tabIndex:-1}:I;return D?r.createElement(D,{...K,node:E,...D===Ke?{receivedTree:!0}:{}},V):r.createElement(f,K,V)};l.displayName=`StableMarkdown(${f})`,g.current.set(f,l)}k[f]=g.current.get(f)}return k},[u]),y=r.useMemo(()=>[()=>()=>d],[d]);return o.jsx("div",{className:"markdown-renderer",children:o.jsx(Ue.Markdown,{remarkPlugins:[kt],rehypePlugins:y,components:J,children:""})})},$=t=>t.type==="markdown"&&t.immediate===!0,Tt=t=>{if(t.length<=1)return t;const s=[];return t.forEach(a=>{if(a.type==="sandbox"||$(a)){s.push(a);return}const c=s[s.length-1];if(c&&c.type!=="sandbox"&&!$(c)){s[s.length-1]={type:"markdown",value:`${c.value}${a.value}`};return}s.push({type:"markdown",value:a.value})}),s},Rt=(t,s,a)=>{if(t.length>=s.length)return t;const c=a.find(({start:v,end:g})=>v<t.length&&t.length<g);if(!c)return t;const u=/^`+/.exec(s.slice(c.start))?.[0];if(!u||t.length<c.start+u.length)return t;const d=c.end-u.length;return t.length>d?t+u.slice(t.length-d):t+(t.endsWith("`")?" ":"")+u},_e=(t,s,a,c,u=0)=>{const d=Rt(t,s,a);return ke.escapeTypedMarkdownMetadata(t,c,u)+d.slice(t.length)},bt=(t,s)=>{const a=Math.max(1,s),c=Array.from(t);return{chunk:c.slice(0,a).join(""),rest:c.slice(a).join("")}},St=(t,s)=>t===s?!0:!t||!s||t.length!==s.length?!1:t.every((a,c)=>a===s[c]),Mt=t=>{const s=r.useRef(t);return St(s.current,t)||(s.current=t),s.current},jt=({content:t,contentType:s,locale:a,lang:c,dir:u,customRenderBar:d,onSend:v,typingSpeed:g=30,enableTypewriter:J=!1,typewriterPacing:y="fixed",onTypeFinished:R,onTypewriterStateChange:b,userInput:k,interactionDefaultValueOptions:f,defaultButtonText:l,defaultInputText:E,defaultSelectedValues:V,readonly:I=!1,confirmButtonText:C,copyButtonText:U,copiedButtonText:D,sandboxLoadingText:K,sandboxStyleLoadingText:te,sandboxScriptLoadingText:ie,disableSandboxLoadingOverlay:ue=!1,sandboxFullscreenButtonText:ne,sandboxExitFullscreenButtonText:re,sandboxMode:le="content",onClickCustomButtonAfterContent:oe,beforeSend:de})=>{const z=Re.getContentRenderLocaleTexts(a),j=r.useMemo(()=>({loading:z.mermaidLoadingText,emptyChart:z.mermaidEmptyChartText,error:z.mermaidErrorText}),[z]),B=u??$e.getMarkdownFlowDirection(a),H=c??$e.getMarkdownFlowLanguage(a),be=C||z.confirmButtonText,Se=U||z.copyButtonText,Me=D||z.copiedButtonText,Ze=ne||z.sandboxFullscreenButtonText,Je=re||z.sandboxExitFullscreenButtonText,p=!!J&&(!s||s==="text"),S=r.useMemo(()=>Fe.normalizeWrappedSandboxContent(t),[t]),N=r.useMemo(()=>Ge.getMarkdownSourceAnalysis(S),[S]),w=r.useMemo(()=>{const e=Tt(Fe.splitContentSegments(S,!0,!0,N));return S!==t&&e.length&&(e[0].type==="sandbox"||$(e[0]))?[{type:"text",value:""},...e]:e},[t,S,N]),Y=w.some(e=>e.type==="sandbox"||$(e)),h=Y?w.filter(e=>e.type!=="sandbox"&&!$(e)).map(e=>e.value).join(""):S,je=Math.max(0,g),et=y==="fixed"?h:void 0,[A,Be]=r.useState(()=>p?"":h),se=r.useRef(A),q=r.useRef(""),P=r.useRef({tokens:[],head:0,trailingGrapheme:""}),_=r.useRef(0),Ne=r.useRef(p),qe=r.useRef(y),Le=r.useRef(h),me=r.useRef(t),pe=r.useRef(!1),[tt,nt]=r.useState(0);r.useEffect(()=>{const e=Ne.current,n=qe.current,i=Le.current,m=!!q.current,T=me.current!==t,xe=T&&t.startsWith(me.current);me.current=t,Ne.current=p,qe.current=y,Le.current=h,(T||p!==e)&&(pe.current=!1);const X=()=>{q.current="",P.current={tokens:[],head:0,trailingGrapheme:""},_.current=0},Z=M=>{se.current=M,Be(M)};if(!p){X(),Z(h);return}e||(X(),Z(""));let L=e?se.current:"";if(!h.startsWith(L)){if(X(),!xe){Z(h),y==="content-aware"&&(P.current={tokens:[],head:0,trailingGrapheme:O.getTrailingTypewriterGrapheme(h)});return}let M=0;for(;M<L.length&&M<h.length&&L[M]===h[M];)M+=1;L=L.slice(0,M),Z(L)}let Q=h.slice(L.length);if(!Q){q.current="",_.current=0,P.current=y==="content-aware"?{tokens:[],head:0,trailingGrapheme:O.getTrailingTypewriterGrapheme(L)}:{tokens:[],head:0,trailingGrapheme:""};return}if(y==="content-aware"){const M=i.slice(L.length);if(e&&n==="content-aware"&&h.startsWith(i)&&q.current===M){const F=O.appendContentAwareTypewriterQueue(P.current,h.slice(i.length));P.current=F.queue,F.immediateChunk&&(Q=Q.slice(F.immediateChunk.length),Z(`${L}${F.immediateChunk}`))}else{const F=O.appendContentAwareTypewriterQueue({tokens:[],head:0,trailingGrapheme:O.getTrailingTypewriterGrapheme(L)},Q);P.current=F.queue,F.immediateChunk&&(Q=Q.slice(F.immediateChunk.length),Z(`${L}${F.immediateChunk}`)),_.current=0}}else P.current={tokens:[],head:0,trailingGrapheme:""},_.current=0;q.current=Q,!m&&Q&&nt(M=>M+1)},[t,h,p,y]),r.useEffect(()=>{p&&(pe.current||q.current||A!==h||(pe.current=!0,R?.()))},[t,h,A,p,R]),r.useEffect(()=>{if(!p||!q.current)return;const e=window.setTimeout(()=>{if(!q.current)return;let n="";if(y==="content-aware"){const m=O.consumeContentAwareTypewriterQueue(P.current,_.current+O.CONTENT_AWARE_TYPEWRITER_TICK_BUDGET);n=m.chunk,P.current=m.queue,O.isContentAwareTypewriterQueueEmpty(m.queue)?_.current=0:_.current=m.remainingBudget}else n=bt(q.current,yt).chunk;if(!n)return;q.current=q.current.slice(n.length),q.current||(P.current=y==="content-aware"?{tokens:[],head:0,trailingGrapheme:P.current.trailingGrapheme}:{tokens:[],head:0,trailingGrapheme:""},_.current=0);const i=`${se.current}${n}`;se.current=i,Be(i)},je);return()=>window.clearTimeout(e)},[A,et,p,y,je,tt]);const W=r.useMemo(()=>{let e=0;return w.map(n=>{if(!p)return n;if(n.type==="sandbox"||$(n))return A.length>=e?n:{...n,value:""};const i=A.slice(e,e+n.value.length);return e+=n.value.length,{...n,value:i}})},[w,A,p]),Ae=r.useMemo(()=>({isTypewriterEnabled:p,isTyping:p&&A!==h,isComplete:A===h,renderedLength:t.length-w.reduce((e,n,i)=>e+n.value.length-W[i].value.length,0),totalLength:t.length}),[t,h,A,p,w,W]);r.useEffect(()=>{b?.(Ae)},[b,Ae]);const fe=r.useMemo(()=>{let e=0;return w.map(n=>{const i=e;return e+=n.value.length,i})},[w]),ae=r.useMemo(()=>p?w.map(e=>e.type==="sandbox"||$(e)?[]:e.value===S?N.inline:Ge.getInlineCodeRanges(e.value)):[],[p,w,S,N]),rt=r.useMemo(()=>Y?W.map((e,n)=>e.type==="sandbox"||$(e)?e.value:p?_e(e.value,w[n].value,ae[n]??[],N.metadata,fe[n]):ke.escapeTypedMarkdownMetadata(e.value,N.metadata,fe[n])):[],[Y,p,W,ae,w,N.metadata,fe]),ot=r.useMemo(()=>{const e=[];w.forEach((n,i)=>{const m=e.at(-1);n.type!=="sandbox"&&m&&!m.sandbox?m.indices.push(i):e.push({indices:[i],sandbox:n.type==="sandbox"})});for(const n of e)if(!n.sandbox&&n.indices.some(i=>$(w[i]))){const i=n.indices.map(T=>w[T]),m=i.map(T=>T.value).join("");n.plan=ee.createVideoMarkdownRunPlan(i,m===S?N:void 0)}return e},[w,S,N]),G=Y?W.map(e=>e.value).join(""):p?A:S,st=r.useMemo(()=>d?ve.normalizeInlineHtml(G):"",[d,G]),Pe=r.useMemo(()=>Y?"":ve.normalizeInlineHtml(p?_e(G,S,ae[0]??[],N.metadata):ke.escapeTypedMarkdownMetadata(G,N.metadata)),[S,Y,p,G,ae,N.metadata]),he=r.useMemo(()=>ft.getInteractionDefaultValues(G,k,f),[f,G,k]),Ee=l?.trim()||he.buttonText,Ve=E?.trim()||he.inputText,at=r.useMemo(()=>k?k.split(",").map(e=>e.trim()).filter(Boolean):void 0,[k]),ct=V?.length?V:he.selectedValues||at,Ie=Mt(ct),x=r.useRef({direction:B,language:H,mermaidMessages:j,beforeSend:de,locale:a,onClickCustomButtonAfterContent:oe,onSend:v,readonly:I,renderContent:G,resolvedConfirmButtonText:be,resolvedCopiedButtonText:Me,resolvedCopyButtonText:Se,resolvedDefaultButtonText:Ee,resolvedDefaultInputText:Ve,resolvedDefaultSelectedValues:Ie});x.current={direction:B,language:H,mermaidMessages:j,beforeSend:de,locale:a,onClickCustomButtonAfterContent:oe,onSend:v,readonly:I,renderContent:G,resolvedConfirmButtonText:be,resolvedCopiedButtonText:Me,resolvedCopyButtonText:Se,resolvedDefaultButtonText:Ee,resolvedDefaultInputText:Ve,resolvedDefaultSelectedValues:Ie};const ge=r.useMemo(()=>({"custom-button-after-content":({children:e})=>o.jsx("button",{className:"content-render-custom-button-after-content",onClick:x.current.onClickCustomButtonAfterContent,children:o.jsx("span",{className:"content-render-custom-button-after-content-inner",children:e})}),"custom-variable":e=>o.jsx(mt.default,{...e,readonly:x.current.readonly,defaultButtonText:x.current.resolvedDefaultButtonText,defaultInputText:x.current.resolvedDefaultInputText,defaultSelectedValues:x.current.resolvedDefaultSelectedValues,onSend:x.current.onSend,beforeSend:x.current.beforeSend,locale:x.current.locale,dir:x.current.direction,lang:x.current.language,confirmButtonText:x.current.resolvedConfirmButtonText}),code:Ke,table:({...e})=>o.jsx("div",{className:"content-render-table-container",children:o.jsx("table",{className:"content-render-table",...e})}),th:({...e})=>o.jsx("th",{className:"content-render-th",...e}),td:({...e})=>o.jsx("td",{className:"content-render-td",...e}),tr:({...e})=>o.jsx("tr",{className:"content-render-tr",...e}),li:({node:e,...n})=>{const i=e?.properties?.className;return typeof i=="string"&&i.includes("task-list-item")||Array.isArray(i)&&i.includes("task-list-item")?o.jsx("li",{className:"content-render-task-list-item",...n}):o.jsx("li",{...n})},ol:({...e})=>o.jsx("ol",{className:"content-render-ol",...e}),ul:({...e})=>o.jsx("ul",{className:"content-render-ul",...e}),input:({...e})=>e.type==="checkbox"?o.jsx("input",{type:"checkbox",className:"content-render-checkbox",disabled:!0,...e}):o.jsx("input",{...e}),a:({children:e,...n})=>o.jsx("a",{target:"_blank",rel:"noopener noreferrer",...n,children:e}),pre:e=>o.jsx(Qe.default,{...e,copyButtonText:x.current.resolvedCopyButtonText,copiedButtonText:x.current.resolvedCopiedButtonText})}),[]),it=r.useMemo(()=>we.parseMarkdownSegments(Pe),[Pe]),ut=(e,n)=>{const i=ve.normalizeInlineHtml(e);return we.parseMarkdownSegments(i).map((T,xe)=>{const X=`${n}-${T.type}-${xe}`;return T.type==="text"?o.jsx(ce.Provider,{value:x,children:o.jsx(Te,{locale:a,components:ge,content:T.value})},X):T.type==="mermaid"?o.jsx(ye.default,{chart:T.value,frozen:!T.complete,messages:j},X):T.type==="svg"?o.jsx(Ce,{svg:T.value},X):null})},De=d?o.jsx("div",{className:"content-render-custom-bar",children:r.createElement(d,{content:t,displayContent:st,onSend:v})}):null;return Y?o.jsxs("div",{className:"content-render markdown-body",dir:B,lang:H,children:[ot.map(e=>{const n=e.indices[0],i=W[n];return e.sandbox?i.value?o.jsx(pt.default,{hideFullScreen:!0,type:"sandbox",content:i.value,className:"content-render-iframe",locale:a,dir:B,lang:H,loadingText:K,styleLoadingText:te,scriptLoadingText:ie,disableLoadingOverlay:ue,fullScreenButtonText:Ze,exitFullScreenButtonText:Je,mode:le},`sandbox-${n}`):null:e.plan?o.jsx(ce.Provider,{value:x,children:o.jsx(Ct,{locale:a,components:ge,plan:e.plan,renderedSegments:e.indices.map(m=>W[m])})},`md-${n}`):e.indices.map(m=>o.jsx(r.Fragment,{children:W[m].type==="markdown"&&W[m].pending?null:ut(rt[m],`md-${m}`)},`md-${m}`))}),De]}):o.jsxs("div",{className:"content-render markdown-body",dir:B,lang:H,children:[it.map((e,n)=>{if(e.type==="text")return o.jsx(ce.Provider,{value:x,children:o.jsx(Te,{locale:a,components:ge,content:e.value})},n);if(e.type==="mermaid")return o.jsx(ye.default,{chart:e.value,frozen:!e.complete,messages:j},n);if(e.type==="svg")return o.jsx(Ce,{svg:e.value},n)}),De]})};exports.MarkdownRenderer=Te;exports.default=jt;
5
+ `,d.appendChild(g)),Array.from(d.childNodes).filter(u=>u!==g).forEach(u=>d.removeChild(u));const y=document.createElement("template"),R=mt.stripSvgTextLineBreaks(t);y.innerHTML=R,d.append(y.content.cloneNode(!0));let b=!1,k=!1;d.querySelectorAll("svg").forEach(u=>{const E=u.getAttribute("viewBox");if(!E)return;const V=E.trim().split(/[\s,]+/).map(j=>Number(j));if(V.length!==4||V.some(Number.isNaN))return;const[,,I,C]=V,U=u.getAttribute("width"),D=u.getAttribute("height"),K=j=>{if(!j)return!1;const B=j.trim().toLowerCase();return B==="auto"||B.endsWith("%")},te=j=>{if(!j)return null;const B=j.trim().toLowerCase();if(B==="auto"||B.endsWith("%"))return null;const H=Number.parseFloat(B);return Number.isNaN(H)?null:H},ie=K(U),ue=K(D),ne=!U||U==="0",re=!D||D==="0",le=te(U),oe=te(D);if(ie||ue||ne&&re||le===I&&oe===C){b=!0,u.classList.add("content-render-svg-el--responsive"),u.classList.remove("content-render-svg-el--fixed"),u.style.width="100%",u.style.height="auto",!u.style.aspectRatio&&C>0&&(u.style.aspectRatio=`${I} / ${C}`);return}k=!0,u.classList.add("content-render-svg-el--fixed"),u.classList.remove("content-render-svg-el--responsive"),ne&&I>0&&u.setAttribute("width",`${I}`),re&&C>0&&u.setAttribute("height",`${C}`)});const f=b&&!k;l.classList.toggle("content-render-svg--responsive",f),l.classList.toggle("content-render-svg--fixed",!f)},[t]),o.jsx(i,{className:"content-render-svg-scroll",children:o.jsx(i,{className:"content-render-svg",ref:l=>{a.current=l}})})},ce=r.createContext(null),Ye=t=>{const{receivedTree:s,...a}=t,i=r.useContext(ce),l=r.useContext(Oe.CodeBlockContext);if(!i)throw new Error("Markdown code renderer requires ContentRender context.");const{className:d,children:v,...g}=a;if(/language-(\w+)/.exec(d||"")?.[1]==="mermaid"){const R=v?.toString().replace(/\n$/,"")||"",b=we.mermaidBlockIsComplete(i.current.renderContent,R),k=s?!b:b;return o.jsx(ye.default,{chart:R,frozen:k,messages:i.current.mermaidMessages})}return o.jsx("code",{className:d,...g,dir:g.dir??(l?void 0:"ltr"),children:v})},Xe=[We.preserveCustomVariableProperties,xt.default,dt.sanitizeInvalidTagName,We.restoreCustomVariableProperties],Ze=[[vt.default,{languages:Ge.highlightLanguages,subset:Ge.subsetLanguages}],yt.default],kt=[...Xe,...Ze],Te=({content:t,components:s,locale:a})=>{const i=Re.getContentRenderLocaleTexts(a);return o.jsx("div",{className:"markdown-renderer",children:o.jsx(Ke.Markdown,{remarkPlugins:Ue.remarkPlugins,rehypePlugins:kt,remarkRehypeOptions:{footnoteLabel:i.footnoteLabel,footnoteBackLabel:(l,d)=>{const v=String(l+1)+(d>1?`-${d}`:"");return i.footnoteBackLabel.replace("{reference}",v)}},components:s,children:t})})},Ct=function(){this.parser=()=>({type:"root",children:[]})},Tt=({plan:t,renderedSegments:s,components:a,locale:i})=>{const l=r.useMemo(()=>{const R=Re.getContentRenderLocaleTexts(i),b=_e.unified().use(Ue.remarkPlugins).use(gt.default,{allowDangerousHtml:!0,footnoteLabel:R.footnoteLabel,footnoteBackLabel:(u,E)=>R.footnoteBackLabel.replace("{reference}",String(u+1)+(E>1?`-${E}`:""))}).use(Xe),k=_e.unified().use(Ze),f=b.runSync(ee.cloneVideoMarkdownSourceTree(t),t.markdownSource);return ee.prepareVideoMarkdownRun(t,f,u=>k.runSync(u,t.fullSource))},[t,i]),d=r.useMemo(()=>ee.projectVideoMarkdownRun(l,s),[l,s]),v=r.useRef(a);v.current=a;const g=r.useRef(new Map),J=r.useMemo(()=>{const R=new Set,b=f=>{f.type==="element"&&R.add(f.tagName),"children"in f&&f.children.forEach(b)};b(l.tree);const k={};for(const f of R){if(!g.current.has(f)){const u=({node:E,children:V,...I})=>{const C=ee.getVideoMarkdownNodeState(E);if(C?.svg)return C.svgSource?o.jsx(Ce,{svg:C.svgSource,inline:!0}):null;if(C?.atomic)return C.active?o.jsx(o.Fragment,{children:V}):null;if(C?.active===!1&&f!=="a")return null;const D=v.current[f],K=C?.active===!1?{...I,href:void 0,tabIndex:-1}:I;return D?r.createElement(D,{...K,node:E,...D===Ye?{receivedTree:!0}:{}},V):r.createElement(f,K,V)};u.displayName=`StableMarkdown(${f})`,g.current.set(f,u)}k[f]=g.current.get(f)}return k},[l]),y=r.useMemo(()=>[()=>()=>d],[d]);return o.jsx("div",{className:"markdown-renderer",children:o.jsx(Ke.Markdown,{remarkPlugins:[Ct],rehypePlugins:y,components:J,children:""})})},$=t=>t.type==="markdown"&&t.immediate===!0,Rt=t=>{if(t.length<=1)return t;const s=[];return t.forEach(a=>{if(a.type==="sandbox"||$(a)){s.push(a);return}const i=s[s.length-1];if(i&&i.type!=="sandbox"&&!$(i)){s[s.length-1]={type:"markdown",value:`${i.value}${a.value}`};return}s.push({type:"markdown",value:a.value})}),s},bt=(t,s,a)=>{if(t.length>=s.length)return t;const i=a.find(({start:v,end:g})=>v<t.length&&t.length<g);if(!i)return t;const l=/^`+/.exec(s.slice(i.start))?.[0];if(!l||t.length<i.start+l.length)return t;const d=i.end-l.length;return t.length>d?t+l.slice(t.length-d):t+(t.endsWith("`")?" ":"")+l},Qe=(t,s,a,i,l=0)=>{const d=bt(t,s,a);return ke.escapeTypedMarkdownMetadata(t,i,l)+d.slice(t.length)},St=(t,s)=>{const a=Math.max(1,s),i=Array.from(t);return{chunk:i.slice(0,a).join(""),rest:i.slice(a).join("")}},Mt=(t,s)=>t===s?!0:!t||!s||t.length!==s.length?!1:t.every((a,i)=>a===s[i]),jt=t=>{const s=r.useRef(t);return Mt(s.current,t)||(s.current=t),s.current},Bt=({content:t,contentType:s,locale:a,lang:i,dir:l,customRenderBar:d,onSend:v,typingSpeed:g=30,enableTypewriter:J=!1,typewriterPacing:y="fixed",onTypeFinished:R,onTypewriterStateChange:b,userInput:k,interactionDefaultValueOptions:f,defaultButtonText:u,defaultInputText:E,defaultSelectedValues:V,readonly:I=!1,confirmButtonText:C,copyButtonText:U,copiedButtonText:D,sandboxLoadingText:K,sandboxStyleLoadingText:te,sandboxScriptLoadingText:ie,disableSandboxLoadingOverlay:ue=!1,sandboxFullscreenButtonText:ne,sandboxExitFullscreenButtonText:re,sandboxMode:le="content",onClickCustomButtonAfterContent:oe,beforeSend:de})=>{const z=Re.getContentRenderLocaleTexts(a),j=r.useMemo(()=>({loading:z.mermaidLoadingText,emptyChart:z.mermaidEmptyChartText,error:z.mermaidErrorText}),[z]),B=l??He.getMarkdownFlowDirection(a),H=i??He.getMarkdownFlowLanguage(a),be=C||z.confirmButtonText,Se=U||z.copyButtonText,Me=D||z.copiedButtonText,Je=ne||z.sandboxFullscreenButtonText,et=re||z.sandboxExitFullscreenButtonText,p=!!J&&(!s||s==="text"),S=r.useMemo(()=>$e.normalizeWrappedSandboxContent(t),[t]),N=r.useMemo(()=>Fe.getMarkdownSourceAnalysis(S),[S]),w=r.useMemo(()=>{const e=Rt($e.splitContentSegments(S,!0,!0,N));return S!==t&&e.length&&(e[0].type==="sandbox"||$(e[0]))?[{type:"text",value:""},...e]:e},[t,S,N]),Y=w.some(e=>e.type==="sandbox"||$(e)),h=Y?w.filter(e=>e.type!=="sandbox"&&!$(e)).map(e=>e.value).join(""):S,je=Math.max(0,g),tt=y==="fixed"?h:void 0,[A,Be]=r.useState(()=>p?"":h),se=r.useRef(A),q=r.useRef(""),P=r.useRef({tokens:[],head:0,trailingGrapheme:""}),_=r.useRef(0),Ne=r.useRef(p),qe=r.useRef(y),Le=r.useRef(h),me=r.useRef(t),pe=r.useRef(!1),[nt,rt]=r.useState(0);r.useEffect(()=>{const e=Ne.current,n=qe.current,c=Le.current,m=!!q.current,T=me.current!==t,xe=T&&t.startsWith(me.current);me.current=t,Ne.current=p,qe.current=y,Le.current=h,(T||p!==e)&&(pe.current=!1);const X=()=>{q.current="",P.current={tokens:[],head:0,trailingGrapheme:""},_.current=0},Z=M=>{se.current=M,Be(M)};if(!p){X(),Z(h);return}e||(X(),Z(""));let L=e?se.current:"";if(!h.startsWith(L)){if(X(),!xe){Z(h),y==="content-aware"&&(P.current={tokens:[],head:0,trailingGrapheme:O.getTrailingTypewriterGrapheme(h)});return}let M=0;for(;M<L.length&&M<h.length&&L[M]===h[M];)M+=1;L=L.slice(0,M),Z(L)}let Q=h.slice(L.length);if(!Q){q.current="",_.current=0,P.current=y==="content-aware"?{tokens:[],head:0,trailingGrapheme:O.getTrailingTypewriterGrapheme(L)}:{tokens:[],head:0,trailingGrapheme:""};return}if(y==="content-aware"){const M=c.slice(L.length);if(e&&n==="content-aware"&&h.startsWith(c)&&q.current===M){const F=O.appendContentAwareTypewriterQueue(P.current,h.slice(c.length));P.current=F.queue,F.immediateChunk&&(Q=Q.slice(F.immediateChunk.length),Z(`${L}${F.immediateChunk}`))}else{const F=O.appendContentAwareTypewriterQueue({tokens:[],head:0,trailingGrapheme:O.getTrailingTypewriterGrapheme(L)},Q);P.current=F.queue,F.immediateChunk&&(Q=Q.slice(F.immediateChunk.length),Z(`${L}${F.immediateChunk}`)),_.current=0}}else P.current={tokens:[],head:0,trailingGrapheme:""},_.current=0;q.current=Q,!m&&Q&&rt(M=>M+1)},[t,h,p,y]),r.useEffect(()=>{p&&(pe.current||q.current||A!==h||(pe.current=!0,R?.()))},[t,h,A,p,R]),r.useEffect(()=>{if(!p||!q.current)return;const e=window.setTimeout(()=>{if(!q.current)return;let n="";if(y==="content-aware"){const m=O.consumeContentAwareTypewriterQueue(P.current,_.current+O.CONTENT_AWARE_TYPEWRITER_TICK_BUDGET);n=m.chunk,P.current=m.queue,O.isContentAwareTypewriterQueueEmpty(m.queue)?_.current=0:_.current=m.remainingBudget}else n=St(q.current,wt).chunk;if(!n)return;q.current=q.current.slice(n.length),q.current||(P.current=y==="content-aware"?{tokens:[],head:0,trailingGrapheme:P.current.trailingGrapheme}:{tokens:[],head:0,trailingGrapheme:""},_.current=0);const c=`${se.current}${n}`;se.current=c,Be(c)},je);return()=>window.clearTimeout(e)},[A,tt,p,y,je,nt]);const W=r.useMemo(()=>{let e=0;return w.map(n=>{if(!p)return n;if(n.type==="sandbox"||$(n))return A.length>=e?n:{...n,value:""};const c=A.slice(e,e+n.value.length);return e+=n.value.length,{...n,value:c}})},[w,A,p]),Ae=r.useMemo(()=>({isTypewriterEnabled:p,isTyping:p&&A!==h,isComplete:A===h,renderedLength:t.length-w.reduce((e,n,c)=>e+n.value.length-W[c].value.length,0),totalLength:t.length}),[t,h,A,p,w,W]);r.useEffect(()=>{b?.(Ae)},[b,Ae]);const fe=r.useMemo(()=>{let e=0;return w.map(n=>{const c=e;return e+=n.value.length,c})},[w]),ae=r.useMemo(()=>p?w.map(e=>e.type==="sandbox"||$(e)?[]:e.value===S?N.inline:Fe.getInlineCodeRanges(e.value)):[],[p,w,S,N]),ot=r.useMemo(()=>Y?W.map((e,n)=>e.type==="sandbox"||$(e)?e.value:p?Qe(e.value,w[n].value,ae[n]??[],N.metadata,fe[n]):ke.escapeTypedMarkdownMetadata(e.value,N.metadata,fe[n])):[],[Y,p,W,ae,w,N.metadata,fe]),st=r.useMemo(()=>{const e=[];w.forEach((n,c)=>{const m=e.at(-1);n.type!=="sandbox"&&m&&!m.sandbox?m.indices.push(c):e.push({indices:[c],sandbox:n.type==="sandbox"})});for(const n of e)if(!n.sandbox&&n.indices.some(c=>$(w[c]))){const c=n.indices.map(T=>w[T]),m=c.map(T=>T.value).join("");n.plan=ee.createVideoMarkdownRunPlan(c,m===S?N:void 0)}return e},[w,S,N]),G=Y?W.map(e=>e.value).join(""):p?A:S,at=r.useMemo(()=>d?ve.normalizeInlineHtml(G):"",[d,G]),Pe=r.useMemo(()=>Y?"":ve.normalizeInlineHtml(p?Qe(G,S,ae[0]??[],N.metadata):ke.escapeTypedMarkdownMetadata(G,N.metadata)),[S,Y,p,G,ae,N.metadata]),he=r.useMemo(()=>ht.getInteractionDefaultValues(G,k,f),[f,G,k]),Ee=(u?ze.distExports.trimVariablePadding(u):void 0)||he.buttonText,Ve=E?.trim()||he.inputText,ct=r.useMemo(()=>k?k.split(",").map(e=>ze.distExports.trimVariablePadding(e)).filter(Boolean):void 0,[k]),it=V?.length?V:he.selectedValues||ct,Ie=jt(it),x=r.useRef({direction:B,language:H,mermaidMessages:j,beforeSend:de,locale:a,onClickCustomButtonAfterContent:oe,onSend:v,readonly:I,renderContent:G,resolvedConfirmButtonText:be,resolvedCopiedButtonText:Me,resolvedCopyButtonText:Se,resolvedDefaultButtonText:Ee,resolvedDefaultInputText:Ve,resolvedDefaultSelectedValues:Ie});x.current={direction:B,language:H,mermaidMessages:j,beforeSend:de,locale:a,onClickCustomButtonAfterContent:oe,onSend:v,readonly:I,renderContent:G,resolvedConfirmButtonText:be,resolvedCopiedButtonText:Me,resolvedCopyButtonText:Se,resolvedDefaultButtonText:Ee,resolvedDefaultInputText:Ve,resolvedDefaultSelectedValues:Ie};const ge=r.useMemo(()=>({"custom-button-after-content":({children:e})=>o.jsx("button",{className:"content-render-custom-button-after-content",onClick:x.current.onClickCustomButtonAfterContent,children:o.jsx("span",{className:"content-render-custom-button-after-content-inner",children:e})}),"custom-variable":e=>o.jsx(pt.default,{...e,readonly:x.current.readonly,defaultButtonText:x.current.resolvedDefaultButtonText,defaultInputText:x.current.resolvedDefaultInputText,defaultSelectedValues:x.current.resolvedDefaultSelectedValues,onSend:x.current.onSend,beforeSend:x.current.beforeSend,locale:x.current.locale,dir:x.current.direction,lang:x.current.language,confirmButtonText:x.current.resolvedConfirmButtonText}),code:Ye,table:({...e})=>o.jsx("div",{className:"content-render-table-container",children:o.jsx("table",{className:"content-render-table",...e})}),th:({...e})=>o.jsx("th",{className:"content-render-th",...e}),td:({...e})=>o.jsx("td",{className:"content-render-td",...e}),tr:({...e})=>o.jsx("tr",{className:"content-render-tr",...e}),li:({node:e,...n})=>{const c=e?.properties?.className;return typeof c=="string"&&c.includes("task-list-item")||Array.isArray(c)&&c.includes("task-list-item")?o.jsx("li",{className:"content-render-task-list-item",...n}):o.jsx("li",{...n})},ol:({...e})=>o.jsx("ol",{className:"content-render-ol",...e}),ul:({...e})=>o.jsx("ul",{className:"content-render-ul",...e}),input:({...e})=>e.type==="checkbox"?o.jsx("input",{type:"checkbox",className:"content-render-checkbox",disabled:!0,...e}):o.jsx("input",{...e}),a:({children:e,...n})=>o.jsx("a",{target:"_blank",rel:"noopener noreferrer",...n,children:e}),pre:e=>o.jsx(Oe.default,{...e,copyButtonText:x.current.resolvedCopyButtonText,copiedButtonText:x.current.resolvedCopiedButtonText})}),[]),ut=r.useMemo(()=>we.parseMarkdownSegments(Pe),[Pe]),lt=(e,n)=>{const c=ve.normalizeInlineHtml(e);return we.parseMarkdownSegments(c).map((T,xe)=>{const X=`${n}-${T.type}-${xe}`;return T.type==="text"?o.jsx(ce.Provider,{value:x,children:o.jsx(Te,{locale:a,components:ge,content:T.value})},X):T.type==="mermaid"?o.jsx(ye.default,{chart:T.value,frozen:!T.complete,messages:j},X):T.type==="svg"?o.jsx(Ce,{svg:T.value},X):null})},De=d?o.jsx("div",{className:"content-render-custom-bar",children:r.createElement(d,{content:t,displayContent:at,onSend:v})}):null;return Y?o.jsxs("div",{className:"content-render markdown-body",dir:B,lang:H,children:[st.map(e=>{const n=e.indices[0],c=W[n];return e.sandbox?c.type==="sandbox"&&c.value&&!c.pending?o.jsx(ft.default,{hideFullScreen:!0,type:"sandbox",content:c.value,className:"content-render-iframe",locale:a,dir:B,lang:H,loadingText:K,styleLoadingText:te,scriptLoadingText:ie,disableLoadingOverlay:ue,fullScreenButtonText:Je,exitFullScreenButtonText:et,mode:le},`sandbox-${n}`):null:e.plan?o.jsx(ce.Provider,{value:x,children:o.jsx(Tt,{locale:a,components:ge,plan:e.plan,renderedSegments:e.indices.map(m=>W[m])})},`md-${n}`):e.indices.map(m=>o.jsx(r.Fragment,{children:W[m].type==="markdown"&&W[m].pending?null:lt(ot[m],`md-${m}`)},`md-${m}`))}),De]}):o.jsxs("div",{className:"content-render markdown-body",dir:B,lang:H,children:[ut.map((e,n)=>{if(e.type==="text")return o.jsx(ce.Provider,{value:x,children:o.jsx(Te,{locale:a,components:ge,content:e.value})},n);if(e.type==="mermaid")return o.jsx(ye.default,{chart:e.value,frozen:!e.complete,messages:j},n);if(e.type==="svg")return o.jsx(Ce,{svg:e.value},n)}),De]})};exports.MarkdownRenderer=Te;exports.default=Bt;
6
6
  //# sourceMappingURL=ContentRender.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ContentRender.cjs","sources":["../../../src/components/ContentRender/ContentRender.tsx"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport ReactMarkdown from \"react-markdown\";\nimport rehypeHighlight from \"rehype-highlight\";\nimport rehypeKatex from \"rehype-katex\";\nimport rehypeRaw from \"rehype-raw\";\nimport { unified, type PluggableList, type Plugin } from \"unified\";\nimport remarkRehype from \"remark-rehype\";\nimport type { Element, Root } from \"hast\";\nimport { CustomRenderBarProps, OnSendContentParams } from \"../types\";\nimport { sanitizeInvalidTagName } from \"./utils/sanitize-invalid-tag-name\";\nimport { stripSvgTextLineBreaks } from \"./utils/strip-svg-text-line-breaks\";\nimport \"./contentRender.css\";\nimport \"./github-markdown-light.css\";\nimport \"highlight.js/styles/github.css\";\nimport \"katex/dist/katex.min.css\";\nimport CodeBlock, { CodeBlockContext } from \"./CodeBlock\";\nimport CustomButtonInputVariable, {\n ComponentsWithCustomVariable,\n} from \"./plugins/CustomVariable\";\nimport MermaidChart, { type MermaidChartProps } from \"./plugins/MermaidChart\";\nimport {\n preserveCustomVariableProperties,\n restoreCustomVariableProperties,\n} from \"./utils/custom-variable-props\";\nimport {\n highlightLanguages,\n subsetLanguages,\n} from \"./utils/highlight-languages\";\n// import { processMarkdownText } from \"./utils/process-markdown\";\nimport {\n parseMarkdownSegments,\n mermaidBlockIsComplete,\n} from \"./utils/mermaid-parse\";\nimport {\n getInlineCodeRanges,\n getMarkdownSourceAnalysis,\n} from \"./utils/inline-code-ranges\";\nimport { remarkPlugins } from \"./utils/markdown-plugins\";\nimport { normalizeInlineHtml } from \"./utils/normalize-inline-html\";\nimport {\n escapeTypedMarkdownMetadata,\n type MarkdownMetadataRange,\n} from \"./utils/escape-typed-metadata\";\nimport IframeSandbox from \"./IframeSandbox\";\nimport {\n appendContentAwareTypewriterQueue,\n CONTENT_AWARE_TYPEWRITER_TICK_BUDGET,\n consumeContentAwareTypewriterQueue,\n getTrailingTypewriterGrapheme,\n isContentAwareTypewriterQueueEmpty,\n type ContentAwareTypewriterQueue,\n} from \"./utils/typewriter-pacing\";\nimport {\n normalizeWrappedSandboxContent,\n splitContentSegments,\n type RenderSegment,\n} from \"./utils/split-content\";\nimport {\n getInteractionDefaultValues,\n type InteractionDefaultValueOptions,\n} from \"../../lib/interaction-defaults\";\nimport {\n getMarkdownFlowDirection,\n getMarkdownFlowLanguage,\n type MarkdownFlowLocale,\n} from \"../../lib/locale\";\nimport { getContentRenderLocaleTexts } from \"./contentRenderI18n\";\nimport {\n createVideoMarkdownRunPlan,\n cloneVideoMarkdownSourceTree,\n projectVideoMarkdownRun,\n prepareVideoMarkdownRun,\n getVideoMarkdownNodeState,\n type VideoMarkdownRunPlan,\n} from \"./utils/video-markdown-run\";\n\nconst FIXED_TYPEWRITER_CHUNK_SIZE = 2;\n\nexport type ContentRenderTypewriterPacing = \"fixed\" | \"content-aware\";\n\n// Define component Props type\nexport interface ContentRenderProps {\n content: string;\n contentType?: string;\n /** Locale used for built-in UI text when a more specific text prop is not provided. */\n locale?: MarkdownFlowLocale;\n /** Overrides the locale-derived language; omitted values inherit from the host. */\n lang?: string;\n /** Overrides locale-derived direction; omitted values inherit when no locale is set. */\n dir?: React.HTMLAttributes<HTMLDivElement>[\"dir\"];\n /**\n * Callback invoked when the custom button after content is clicked.\n * This button is rendered via the `<custom-button-after-content>` tag in markdown content.\n * @example\n * ```tsx\n * <ContentRender\n * content=\"Hello <custom-button-after-content>Ask</custom-button-after-content>\"\n * onClickCustomButtonAfterContent={() => console.log('Button clicked')}\n * />\n * ```\n */\n customRenderBar?: CustomRenderBarProps;\n onClickCustomButtonAfterContent?: () => void;\n onSend?: (content: OnSendContentParams) => void;\n typingSpeed?: number;\n /** Types prose only; following HTML renders progressively once preceding prose is displayed. */\n enableTypewriter?: boolean;\n /** Controls how much text is revealed per tick. Defaults to the legacy fixed pacing. */\n typewriterPacing?: ContentRenderTypewriterPacing;\n onTypeFinished?: () => void;\n onTypewriterStateChange?: (state: ContentRenderTypewriterState) => void;\n userInput?: string;\n interactionDefaultValueOptions?: InteractionDefaultValueOptions;\n defaultButtonText?: string;\n defaultInputText?: string; // Text input by user\n defaultSelectedValues?: string[]; // Default selected values for multi-select\n readonly?: boolean;\n // Multi-select confirm button text (i18n support)\n confirmButtonText?: string;\n // Copy button text (i18n support)\n copyButtonText?: string;\n // Copied state text (i18n support)\n copiedButtonText?: string;\n // Dynamic interaction format for multi-select support\n dynamicInteractionFormat?: string;\n // Loading text before first HTML block renders inside iframe (i18n support)\n sandboxLoadingText?: string;\n // Loading text while styles are being generated inside iframe\n sandboxStyleLoadingText?: string;\n // Loading text while scripts are being cached/executed inside iframe\n sandboxScriptLoadingText?: string;\n // Disable sandbox loading overlays when upper layers have already entered an error state\n disableSandboxLoadingOverlay?: boolean;\n // Fullscreen button text for iframe sandbox\n sandboxFullscreenButtonText?: string;\n // Exit fullscreen button text for iframe sandbox\n sandboxExitFullscreenButtonText?: string;\n // Sandbox render mode\n sandboxMode?: \"content\" | \"blackboard\";\n beforeSend?: (param: OnSendContentParams) => boolean;\n // tooltipMinLength?: number; // Control minimum character length for tooltip display, default 10\n}\n\nexport interface ContentRenderTypewriterState {\n isTypewriterEnabled: boolean;\n isTyping: boolean;\n isComplete: boolean;\n /** Received source units already displayed, including unpaced HTML. */\n renderedLength: number;\n totalLength: number;\n}\n\n// Render svg string via Shadow DOM to avoid markdown wrapping\nconst SvgBlockInShadow: React.FC<{ svg: string; inline?: boolean }> = ({\n svg,\n inline = false,\n}) => {\n const hostRef = useRef<HTMLElement | null>(null);\n const Wrapper = inline ? \"span\" : \"div\";\n\n useEffect(() => {\n const host = hostRef.current;\n if (!host) return;\n const shadowRoot = host.shadowRoot ?? host.attachShadow({ mode: \"open\" });\n const styleId = \"content-render-svg-style\";\n let styleEl = shadowRoot.getElementById(styleId) as HTMLStyleElement | null;\n\n if (!styleEl) {\n styleEl = document.createElement(\"style\");\n styleEl.id = styleId;\n // Keep intrinsic SVG width so the wrapper can scroll horizontally when needed\n styleEl.textContent = `\n svg { height: auto; display: inline-block; }\n svg.content-render-svg-el--responsive { width: 100%; max-width: 100%; }\n svg.content-render-svg-el--fixed { max-width: none; }\n `;\n shadowRoot.appendChild(styleEl);\n }\n\n const nodesToRemove = Array.from(shadowRoot.childNodes).filter(\n (node) => node !== styleEl\n );\n nodesToRemove.forEach((node) => shadowRoot.removeChild(node));\n\n const template = document.createElement(\"template\");\n const cleanedSvg = stripSvgTextLineBreaks(svg);\n template.innerHTML = cleanedSvg;\n shadowRoot.append(template.content.cloneNode(true));\n\n let hasResponsiveSvg = false;\n let hasFixedSvg = false;\n\n shadowRoot.querySelectorAll(\"svg\").forEach((svgEl) => {\n // Derive responsive sizing from viewBox so pure viewBox SVGs stay visible and fluid\n const viewBox = svgEl.getAttribute(\"viewBox\");\n if (!viewBox) return;\n\n const dimensions = viewBox\n .trim()\n .split(/[\\s,]+/)\n .map((value) => Number(value));\n\n if (dimensions.length !== 4 || dimensions.some(Number.isNaN)) return;\n\n const [, , viewBoxWidth, viewBoxHeight] = dimensions;\n const widthAttr = svgEl.getAttribute(\"width\");\n const heightAttr = svgEl.getAttribute(\"height\");\n const isRelativeLength = (value?: string | null) => {\n if (!value) return false;\n const normalized = value.trim().toLowerCase();\n return normalized === \"auto\" || normalized.endsWith(\"%\");\n };\n const toNumericLength = (value?: string | null) => {\n if (!value) return null;\n const normalized = value.trim().toLowerCase();\n if (normalized === \"auto\" || normalized.endsWith(\"%\")) {\n return null;\n }\n const parsed = Number.parseFloat(normalized);\n return Number.isNaN(parsed) ? null : parsed;\n };\n // Treat percentage/auto sizing as responsive so viewBox drives the layout\n const isWidthRelative = isRelativeLength(widthAttr);\n const isHeightRelative = isRelativeLength(heightAttr);\n const widthMissing = !widthAttr || widthAttr === \"0\";\n const heightMissing = !heightAttr || heightAttr === \"0\";\n const numericWidth = toNumericLength(widthAttr);\n const numericHeight = toNumericLength(heightAttr);\n const matchesViewBox =\n numericWidth === viewBoxWidth && numericHeight === viewBoxHeight;\n\n // Prefer responsive layout when sizing is relative or matches the viewBox\n const shouldUseResponsiveSize =\n isWidthRelative ||\n isHeightRelative ||\n (widthMissing && heightMissing) ||\n matchesViewBox;\n\n if (shouldUseResponsiveSize) {\n hasResponsiveSvg = true;\n svgEl.classList.add(\"content-render-svg-el--responsive\");\n svgEl.classList.remove(\"content-render-svg-el--fixed\");\n svgEl.style.width = \"100%\";\n svgEl.style.height = \"auto\";\n if (!svgEl.style.aspectRatio && viewBoxHeight > 0) {\n svgEl.style.aspectRatio = `${viewBoxWidth} / ${viewBoxHeight}`;\n }\n return;\n }\n\n hasFixedSvg = true;\n svgEl.classList.add(\"content-render-svg-el--fixed\");\n svgEl.classList.remove(\"content-render-svg-el--responsive\");\n if (widthMissing && viewBoxWidth > 0) {\n svgEl.setAttribute(\"width\", `${viewBoxWidth}`);\n }\n if (heightMissing && viewBoxHeight > 0) {\n svgEl.setAttribute(\"height\", `${viewBoxHeight}`);\n }\n });\n\n const hostResponsive = hasResponsiveSvg && !hasFixedSvg;\n host.classList.toggle(\"content-render-svg--responsive\", hostResponsive);\n host.classList.toggle(\"content-render-svg--fixed\", !hostResponsive);\n }, [svg]);\n\n return (\n <Wrapper className=\"content-render-svg-scroll\">\n <Wrapper\n className=\"content-render-svg\"\n ref={(node) => {\n hostRef.current = node;\n }}\n />\n </Wrapper>\n );\n};\n\n// Extended component interface\ntype CustomComponents = ComponentsWithCustomVariable & {\n \"custom-button-after-content\"?: React.ComponentType<{\n children: React.ReactNode;\n }>;\n};\n\ntype MarkdownComponentRuntimeValues = {\n direction?: ContentRenderProps[\"dir\"];\n language?: string;\n mermaidMessages: MermaidChartProps[\"messages\"];\n beforeSend?: (param: OnSendContentParams) => boolean;\n locale?: MarkdownFlowLocale;\n onClickCustomButtonAfterContent?: () => void;\n onSend?: (content: OnSendContentParams) => void;\n readonly: boolean;\n renderContent: string;\n resolvedConfirmButtonText: string;\n resolvedCopiedButtonText: string;\n resolvedCopyButtonText: string;\n resolvedDefaultButtonText?: string;\n resolvedDefaultInputText?: string;\n resolvedDefaultSelectedValues?: string[];\n};\n\nconst MarkdownComponentRuntimeContext =\n React.createContext<React.RefObject<MarkdownComponentRuntimeValues> | null>(\n null\n );\n\nconst MarkdownCode = (\n props: React.ComponentProps<\"code\"> & { receivedTree?: boolean }\n) => {\n const { receivedTree, ...codeProps } = props;\n const runtimeValuesRef = React.useContext(MarkdownComponentRuntimeContext);\n const isInCodeBlock = React.useContext(CodeBlockContext);\n if (!runtimeValuesRef) {\n throw new Error(\"Markdown code renderer requires ContentRender context.\");\n }\n const { className, children, ...rest } = codeProps as {\n className?: string;\n children?: React.ReactNode;\n dir?: string;\n };\n const match = /language-(\\w+)/.exec(className || \"\");\n const language = match?.[1];\n if (language === \"mermaid\") {\n const chartContent = children?.toString().replace(/\\n$/, \"\") || \"\";\n const complete = mermaidBlockIsComplete(\n runtimeValuesRef.current.renderContent,\n chartContent\n );\n // The received-tree path replaces standalone Mermaid segments, whose\n // unfinished charts freeze until the closing fence reaches the prose budget.\n const frozen = receivedTree ? !complete : complete;\n return (\n <MermaidChart\n chart={chartContent}\n frozen={frozen}\n messages={runtimeValuesRef.current.mermaidMessages}\n />\n );\n }\n\n return (\n <code\n className={className}\n {...rest}\n dir={rest.dir ?? (isInCodeBlock ? undefined : \"ltr\")}\n >\n {children}\n </code>\n );\n};\n\nconst sourceRehypePlugins: PluggableList = [\n preserveCustomVariableProperties,\n rehypeRaw,\n sanitizeInvalidTagName,\n restoreCustomVariableProperties,\n];\nconst formattingRehypePlugins: PluggableList = [\n [rehypeHighlight, { languages: highlightLanguages, subset: subsetLanguages }],\n rehypeKatex,\n];\nconst rehypePlugins: PluggableList = [\n ...sourceRehypePlugins,\n ...formattingRehypePlugins,\n];\n\nexport const MarkdownRenderer: React.FC<{\n content: string;\n components: CustomComponents;\n locale?: MarkdownFlowLocale;\n}> = ({ content: markdownContent, components, locale }) => {\n const texts = getContentRenderLocaleTexts(locale);\n return (\n <div className=\"markdown-renderer\">\n <ReactMarkdown\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n remarkRehypeOptions={{\n footnoteLabel: texts.footnoteLabel,\n footnoteBackLabel: (referenceIndex, rereferenceIndex) => {\n const reference =\n String(referenceIndex + 1) +\n (rereferenceIndex > 1 ? `-${rereferenceIndex}` : \"\");\n return texts.footnoteBackLabel.replace(\"{reference}\", reference);\n },\n }}\n components={components}\n >\n {markdownContent}\n </ReactMarkdown>\n </div>\n );\n};\n\n// ReactMarkdown still owns URL handling and JSX conversion. Its parser is\n// bypassed because the received source was already parsed and transformed.\nconst usePreparedTree: Plugin = function () {\n this.parser = () => ({ type: \"root\", children: [] });\n};\n\nconst StableVideoMarkdownRenderer: React.FC<{\n plan: VideoMarkdownRunPlan;\n renderedSegments: readonly RenderSegment[];\n components: CustomComponents;\n locale?: MarkdownFlowLocale;\n}> = ({ plan, renderedSegments, components, locale }) => {\n const prepared = useMemo(() => {\n const texts = getContentRenderLocaleTexts(locale);\n const sourceProcessor = unified()\n .use(remarkPlugins)\n .use(remarkRehype, {\n allowDangerousHtml: true,\n footnoteLabel: texts.footnoteLabel,\n footnoteBackLabel: (referenceIndex, rereferenceIndex) =>\n texts.footnoteBackLabel.replace(\n \"{reference}\",\n String(referenceIndex + 1) +\n (rereferenceIndex > 1 ? `-${rereferenceIndex}` : \"\")\n ),\n })\n .use(sourceRehypePlugins);\n const formattingProcessor = unified().use(formattingRehypePlugins);\n const tree = sourceProcessor.runSync(\n cloneVideoMarkdownSourceTree(plan),\n plan.markdownSource\n ) as Root;\n return prepareVideoMarkdownRun(\n plan,\n tree,\n (value) => formattingProcessor.runSync(value, plan.fullSource) as Root\n );\n }, [plan, locale]);\n const projected = useMemo(\n () => projectVideoMarkdownRun(prepared, renderedSegments),\n [prepared, renderedSegments]\n );\n const originalComponents = useRef(components);\n originalComponents.current = components;\n const wrappers = useRef(\n new Map<\n string,\n React.ComponentType<{\n node: Element;\n children?: React.ReactNode;\n }>\n >()\n );\n const stableComponents = useMemo(() => {\n const tags = new Set<string>();\n const collect = (node: Root | Root[\"children\"][number]) => {\n if (node.type === \"element\") tags.add(node.tagName);\n if (\"children\" in node) node.children.forEach(collect);\n };\n collect(prepared.tree!);\n const result: Record<\n string,\n React.ComponentType<{\n node: Element;\n children?: React.ReactNode;\n }>\n > = {};\n for (const tag of tags) {\n if (!wrappers.current.has(tag)) {\n const Component = ({\n node,\n children,\n ...props\n }: {\n node: Element;\n children?: React.ReactNode;\n }) => {\n const state = getVideoMarkdownNodeState(node);\n if (state?.svg) {\n return state.svgSource ? (\n <SvgBlockInShadow svg={state.svgSource} inline />\n ) : null;\n }\n if (state?.atomic) {\n return state.active ? <>{children}</> : null;\n }\n if (state?.active === false && tag !== \"a\") return null;\n const current = originalComponents.current as Record<\n string,\n React.ElementType\n >;\n const Original = current[tag];\n const visibleProps =\n state?.active === false\n ? { ...props, href: undefined, tabIndex: -1 }\n : props;\n return Original\n ? React.createElement(\n Original,\n {\n ...visibleProps,\n node,\n ...(Original === MarkdownCode ? { receivedTree: true } : {}),\n },\n children\n )\n : React.createElement(tag, visibleProps, children);\n };\n Component.displayName = `StableMarkdown(${tag})`;\n wrappers.current.set(tag, Component);\n }\n result[tag] = wrappers.current.get(tag)!;\n }\n return result as CustomComponents;\n }, [prepared]);\n const preparedPlugins = useMemo<PluggableList>(\n () => [() => () => projected],\n [projected]\n );\n return (\n <div className=\"markdown-renderer\">\n <ReactMarkdown\n remarkPlugins={[usePreparedTree]}\n rehypePlugins={preparedPlugins}\n components={stableComponents}\n >\n {\"\"}\n </ReactMarkdown>\n </div>\n );\n};\n\nconst isImmediateSegment = (segment: RenderSegment) =>\n segment.type === \"markdown\" && segment.immediate === true;\n\nconst mergeNonSandboxSegments = (segments: RenderSegment[]) => {\n if (segments.length <= 1) return segments;\n const merged: RenderSegment[] = [];\n\n segments.forEach((segment) => {\n if (segment.type === \"sandbox\" || isImmediateSegment(segment)) {\n merged.push(segment);\n return;\n }\n\n const last = merged[merged.length - 1];\n if (last && last.type !== \"sandbox\" && !isImmediateSegment(last)) {\n merged[merged.length - 1] = {\n type: \"markdown\",\n value: `${last.value}${segment.value}`,\n };\n return;\n }\n\n merged.push({ type: \"markdown\", value: segment.value });\n });\n\n return merged;\n};\n\nconst closeTypedInlineCode = (\n visible: string,\n source: string,\n ranges: ReturnType<typeof getInlineCodeRanges>\n) => {\n if (visible.length >= source.length) return visible;\n const range = ranges.find(\n ({ start, end }) => start < visible.length && visible.length < end\n );\n if (!range) return visible;\n const delimiter = /^`+/.exec(source.slice(range.start))?.[0];\n if (!delimiter || visible.length < range.start + delimiter.length) {\n return visible;\n }\n const closingStart = range.end - delimiter.length;\n if (visible.length > closingStart) {\n return visible + delimiter.slice(visible.length - closingStart);\n }\n // Close only the render copy so a typed prefix cannot activate code as HTML.\n return visible + (visible.endsWith(\"`\") ? \" \" : \"\") + delimiter;\n};\n\nconst protectTypedMarkdownPrefix = (\n visible: string,\n source: string,\n inlineCodeRanges: ReturnType<typeof getInlineCodeRanges>,\n metadataRanges: readonly MarkdownMetadataRange[],\n sourceOffset = 0\n) => {\n // Both protections use raw coordinates. Append any synthetic code delimiter\n // after escaping so encoded '<' characters cannot shift the typing budget.\n const closed = closeTypedInlineCode(visible, source, inlineCodeRanges);\n return (\n escapeTypedMarkdownMetadata(visible, metadataRanges, sourceOffset) +\n closed.slice(visible.length)\n );\n};\n\nconst splitTextByCharacterChunk = (value: string, chunkSize: number) => {\n const safeChunkSize = Math.max(1, chunkSize);\n const characters = Array.from(value);\n\n return {\n chunk: characters.slice(0, safeChunkSize).join(\"\"),\n rest: characters.slice(safeChunkSize).join(\"\"),\n };\n};\n\nconst areStringArraysEqual = (left?: string[], right?: string[]) => {\n if (left === right) {\n return true;\n }\n if (!left || !right || left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => value === right[index]);\n};\n\nconst useStableStringArray = (values?: string[]) => {\n const valuesRef = useRef<string[] | undefined>(values);\n\n if (!areStringArraysEqual(valuesRef.current, values)) {\n valuesRef.current = values;\n }\n\n return valuesRef.current;\n};\n\nconst ContentRender: React.FC<ContentRenderProps> = ({\n content,\n contentType,\n locale,\n lang,\n dir,\n customRenderBar,\n onSend,\n typingSpeed = 30,\n enableTypewriter = false,\n typewriterPacing = \"fixed\",\n onTypeFinished,\n onTypewriterStateChange,\n userInput,\n interactionDefaultValueOptions,\n defaultButtonText,\n defaultInputText,\n defaultSelectedValues,\n readonly = false,\n confirmButtonText,\n copyButtonText,\n copiedButtonText,\n sandboxLoadingText,\n sandboxStyleLoadingText,\n sandboxScriptLoadingText,\n disableSandboxLoadingOverlay = false,\n sandboxFullscreenButtonText,\n sandboxExitFullscreenButtonText,\n sandboxMode = \"content\",\n onClickCustomButtonAfterContent,\n beforeSend,\n // tooltipMinLength,\n}) => {\n const localeTexts = getContentRenderLocaleTexts(locale);\n const mermaidMessages = useMemo(\n () => ({\n loading: localeTexts.mermaidLoadingText,\n emptyChart: localeTexts.mermaidEmptyChartText,\n error: localeTexts.mermaidErrorText,\n }),\n [localeTexts]\n );\n const direction = dir ?? getMarkdownFlowDirection(locale);\n const language = lang ?? getMarkdownFlowLanguage(locale);\n const resolvedConfirmButtonText =\n confirmButtonText || localeTexts.confirmButtonText;\n const resolvedCopyButtonText = copyButtonText || localeTexts.copyButtonText;\n const resolvedCopiedButtonText =\n copiedButtonText || localeTexts.copiedButtonText;\n const resolvedSandboxFullscreenButtonText =\n sandboxFullscreenButtonText || localeTexts.sandboxFullscreenButtonText;\n const resolvedSandboxExitFullscreenButtonText =\n sandboxExitFullscreenButtonText ||\n localeTexts.sandboxExitFullscreenButtonText;\n const shouldApplyTypewriterByContentType =\n !contentType || contentType === \"text\";\n const isTypewriterEnabled =\n Boolean(enableTypewriter) && shouldApplyTypewriterByContentType;\n const sourceContent = useMemo(\n () => normalizeWrappedSandboxContent(content),\n [content]\n );\n const sourceAnalysis = useMemo(\n () => getMarkdownSourceAnalysis(sourceContent),\n [sourceContent]\n );\n // Parse the received source, never a typewriter-truncated HTML string.\n const sourceSegments = useMemo(() => {\n const segments = mergeNonSandboxSegments(\n splitContentSegments(sourceContent, true, true, sourceAnalysis)\n );\n if (\n sourceContent !== content &&\n segments.length &&\n (segments[0].type === \"sandbox\" || isImmediateSegment(segments[0]))\n ) {\n // The removed opening quote occupied a prose slot before the wrapper\n // completed. Retain its empty slot so the existing iframe keeps its key.\n return [{ type: \"text\" as const, value: \"\" }, ...segments];\n }\n return segments;\n }, [content, sourceContent, sourceAnalysis]);\n const hasRichSegments = sourceSegments.some(\n (segment) => segment.type === \"sandbox\" || isImmediateSegment(segment)\n );\n const typewriterContent = hasRichSegments\n ? sourceSegments\n .filter(\n (segment) =>\n segment.type !== \"sandbox\" && !isImmediateSegment(segment)\n )\n .map((segment) => segment.value)\n .join(\"\")\n : sourceContent;\n const typewriterTickMs = Math.max(0, typingSpeed);\n const fixedTypewriterContentVersion =\n typewriterPacing === \"fixed\" ? typewriterContent : undefined;\n const [displayContent, setDisplayContent] = useState(() =>\n isTypewriterEnabled ? \"\" : typewriterContent\n );\n const displayContentRef = useRef(displayContent);\n const pendingContentRef = useRef(\"\");\n const contentAwareQueueRef = useRef<ContentAwareTypewriterQueue>({\n tokens: [],\n head: 0,\n trailingGrapheme: \"\",\n });\n const contentAwareBudgetRef = useRef(0);\n const previousTypewriterEnabledRef = useRef(isTypewriterEnabled);\n const previousTypewriterPacingRef = useRef(typewriterPacing);\n const previousSourceContentRef = useRef(typewriterContent);\n const previousReceivedContentRef = useRef(content);\n const hasReportedTypeFinishedRef = useRef(false);\n const [typewriterWakeVersion, setTypewriterWakeVersion] = useState(0);\n\n useEffect(() => {\n const wasTypewriterEnabled = previousTypewriterEnabledRef.current;\n const previousTypewriterPacing = previousTypewriterPacingRef.current;\n const previousSourceContent = previousSourceContentRef.current;\n const wasPending = Boolean(pendingContentRef.current);\n const receivedContentChanged =\n previousReceivedContentRef.current !== content;\n const receivedContentAppended =\n receivedContentChanged &&\n content.startsWith(previousReceivedContentRef.current);\n previousReceivedContentRef.current = content;\n\n previousTypewriterEnabledRef.current = isTypewriterEnabled;\n previousTypewriterPacingRef.current = typewriterPacing;\n previousSourceContentRef.current = typewriterContent;\n\n if (\n receivedContentChanged ||\n isTypewriterEnabled !== wasTypewriterEnabled\n ) {\n hasReportedTypeFinishedRef.current = false;\n }\n\n const clearPendingContent = () => {\n pendingContentRef.current = \"\";\n contentAwareQueueRef.current = {\n tokens: [],\n head: 0,\n trailingGrapheme: \"\",\n };\n contentAwareBudgetRef.current = 0;\n };\n\n const updateDisplayContent = (nextContent: string) => {\n displayContentRef.current = nextContent;\n setDisplayContent(nextContent);\n };\n\n if (!isTypewriterEnabled) {\n clearPendingContent();\n updateDisplayContent(typewriterContent);\n return;\n }\n\n if (!wasTypewriterEnabled) {\n clearPendingContent();\n updateDisplayContent(\"\");\n }\n\n let visibleContent = !wasTypewriterEnabled ? \"\" : displayContentRef.current;\n\n if (!typewriterContent.startsWith(visibleContent)) {\n clearPendingContent();\n if (!receivedContentAppended) {\n updateDisplayContent(typewriterContent);\n if (typewriterPacing === \"content-aware\") {\n contentAwareQueueRef.current = {\n tokens: [],\n head: 0,\n trailingGrapheme: getTrailingTypewriterGrapheme(typewriterContent),\n };\n }\n return;\n }\n // A newly recognized HTML tag can replace a previously literal prefix.\n // Keep the shared prose visible and pace only the newly received prose.\n let sharedLength = 0;\n while (\n sharedLength < visibleContent.length &&\n sharedLength < typewriterContent.length &&\n visibleContent[sharedLength] === typewriterContent[sharedLength]\n ) {\n sharedLength += 1;\n }\n visibleContent = visibleContent.slice(0, sharedLength);\n updateDisplayContent(visibleContent);\n }\n\n let nextPendingContent = typewriterContent.slice(visibleContent.length);\n if (!nextPendingContent) {\n pendingContentRef.current = \"\";\n contentAwareBudgetRef.current = 0;\n contentAwareQueueRef.current =\n typewriterPacing === \"content-aware\"\n ? {\n tokens: [],\n head: 0,\n trailingGrapheme: getTrailingTypewriterGrapheme(visibleContent),\n }\n : { tokens: [], head: 0, trailingGrapheme: \"\" };\n return;\n }\n\n if (typewriterPacing === \"content-aware\") {\n const previousPendingContent = previousSourceContent.slice(\n visibleContent.length\n );\n const canAppendToCachedQueue =\n wasTypewriterEnabled &&\n previousTypewriterPacing === \"content-aware\" &&\n typewriterContent.startsWith(previousSourceContent) &&\n pendingContentRef.current === previousPendingContent;\n\n if (canAppendToCachedQueue) {\n const appended = appendContentAwareTypewriterQueue(\n contentAwareQueueRef.current,\n typewriterContent.slice(previousSourceContent.length)\n );\n contentAwareQueueRef.current = appended.queue;\n\n if (appended.immediateChunk) {\n nextPendingContent = nextPendingContent.slice(\n appended.immediateChunk.length\n );\n updateDisplayContent(`${visibleContent}${appended.immediateChunk}`);\n }\n } else {\n const appended = appendContentAwareTypewriterQueue(\n {\n tokens: [],\n head: 0,\n trailingGrapheme: getTrailingTypewriterGrapheme(visibleContent),\n },\n nextPendingContent\n );\n contentAwareQueueRef.current = appended.queue;\n\n if (appended.immediateChunk) {\n nextPendingContent = nextPendingContent.slice(\n appended.immediateChunk.length\n );\n updateDisplayContent(`${visibleContent}${appended.immediateChunk}`);\n }\n\n contentAwareBudgetRef.current = 0;\n }\n } else {\n contentAwareQueueRef.current = {\n tokens: [],\n head: 0,\n trailingGrapheme: \"\",\n };\n contentAwareBudgetRef.current = 0;\n }\n\n pendingContentRef.current = nextPendingContent;\n\n if (!wasPending && nextPendingContent) {\n setTypewriterWakeVersion((version) => version + 1);\n }\n }, [content, typewriterContent, isTypewriterEnabled, typewriterPacing]);\n\n useEffect(() => {\n if (!isTypewriterEnabled) {\n return;\n }\n\n if (\n hasReportedTypeFinishedRef.current ||\n pendingContentRef.current ||\n displayContent !== typewriterContent\n ) {\n return;\n }\n\n hasReportedTypeFinishedRef.current = true;\n onTypeFinished?.();\n }, [\n content,\n typewriterContent,\n displayContent,\n isTypewriterEnabled,\n onTypeFinished,\n ]);\n\n useEffect(() => {\n if (!isTypewriterEnabled || !pendingContentRef.current) {\n return undefined;\n }\n\n const typewriterTimer = window.setTimeout(() => {\n if (!pendingContentRef.current) {\n return;\n }\n\n let chunk = \"\";\n\n if (typewriterPacing === \"content-aware\") {\n const result = consumeContentAwareTypewriterQueue(\n contentAwareQueueRef.current,\n contentAwareBudgetRef.current + CONTENT_AWARE_TYPEWRITER_TICK_BUDGET\n );\n\n chunk = result.chunk;\n contentAwareQueueRef.current = result.queue;\n\n if (isContentAwareTypewriterQueueEmpty(result.queue)) {\n contentAwareBudgetRef.current = 0;\n } else {\n contentAwareBudgetRef.current = result.remainingBudget;\n }\n } else {\n const fixedChunk = splitTextByCharacterChunk(\n pendingContentRef.current,\n FIXED_TYPEWRITER_CHUNK_SIZE\n );\n chunk = fixedChunk.chunk;\n }\n\n if (!chunk) {\n return;\n }\n\n pendingContentRef.current = pendingContentRef.current.slice(chunk.length);\n if (!pendingContentRef.current) {\n contentAwareQueueRef.current =\n typewriterPacing === \"content-aware\"\n ? {\n tokens: [],\n head: 0,\n trailingGrapheme: contentAwareQueueRef.current.trailingGrapheme,\n }\n : { tokens: [], head: 0, trailingGrapheme: \"\" };\n contentAwareBudgetRef.current = 0;\n }\n\n const nextDisplayContent = `${displayContentRef.current}${chunk}`;\n displayContentRef.current = nextDisplayContent;\n setDisplayContent(nextDisplayContent);\n }, typewriterTickMs);\n\n return () => window.clearTimeout(typewriterTimer);\n }, [\n displayContent,\n fixedTypewriterContentVersion,\n isTypewriterEnabled,\n typewriterPacing,\n typewriterTickMs,\n typewriterWakeVersion,\n ]);\n\n const mergedRenderSegments = useMemo(() => {\n let textOffset = 0;\n return sourceSegments.map((segment) => {\n if (!isTypewriterEnabled) return segment;\n if (segment.type === \"sandbox\" || isImmediateSegment(segment)) {\n // HTML skips the prose budget only after earlier prose has caught up.\n // Retain its source slot so later updates keep the same render key.\n return displayContent.length >= textOffset\n ? segment\n : { ...segment, value: \"\" };\n }\n const value = displayContent.slice(\n textOffset,\n textOffset + segment.value.length\n );\n textOffset += segment.value.length;\n // Keep empty prose slots so an existing sandbox never changes its key.\n return { ...segment, value };\n });\n }, [sourceSegments, displayContent, isTypewriterEnabled]);\n const typewriterState = useMemo<ContentRenderTypewriterState>(\n () => ({\n isTypewriterEnabled,\n isTyping: isTypewriterEnabled && displayContent !== typewriterContent,\n isComplete: displayContent === typewriterContent,\n renderedLength:\n content.length -\n sourceSegments.reduce(\n (remaining, segment, index) =>\n remaining +\n segment.value.length -\n mergedRenderSegments[index].value.length,\n 0\n ),\n totalLength: content.length,\n }),\n [\n content,\n typewriterContent,\n displayContent,\n isTypewriterEnabled,\n sourceSegments,\n mergedRenderSegments,\n ]\n );\n\n useEffect(() => {\n onTypewriterStateChange?.(typewriterState);\n }, [onTypewriterStateChange, typewriterState]);\n const sourceSegmentOffsets = useMemo(() => {\n let offset = 0;\n return sourceSegments.map((segment) => {\n const start = offset;\n offset += segment.value.length;\n return start;\n });\n }, [sourceSegments]);\n const sourceInlineCodeRanges = useMemo(\n () =>\n isTypewriterEnabled\n ? sourceSegments.map((segment) =>\n segment.type === \"sandbox\" || isImmediateSegment(segment)\n ? []\n : segment.value === sourceContent\n ? sourceAnalysis.inline\n : getInlineCodeRanges(segment.value)\n )\n : [],\n [isTypewriterEnabled, sourceSegments, sourceContent, sourceAnalysis]\n );\n const safeRichMarkdownContent = useMemo(\n () =>\n hasRichSegments\n ? mergedRenderSegments.map((segment, index) =>\n segment.type === \"sandbox\" || isImmediateSegment(segment)\n ? segment.value\n : isTypewriterEnabled\n ? protectTypedMarkdownPrefix(\n segment.value,\n sourceSegments[index].value,\n sourceInlineCodeRanges[index] ?? [],\n sourceAnalysis.metadata,\n sourceSegmentOffsets[index]\n )\n : escapeTypedMarkdownMetadata(\n segment.value,\n sourceAnalysis.metadata,\n sourceSegmentOffsets[index]\n )\n )\n : [],\n [\n hasRichSegments,\n isTypewriterEnabled,\n mergedRenderSegments,\n sourceInlineCodeRanges,\n sourceSegments,\n sourceAnalysis.metadata,\n sourceSegmentOffsets,\n ]\n );\n const richRenderRuns = useMemo(() => {\n const runs: Array<{\n indices: number[];\n sandbox: boolean;\n plan?: ReturnType<typeof createVideoMarkdownRunPlan>;\n }> = [];\n sourceSegments.forEach((segment, index) => {\n const previous = runs.at(-1);\n if (segment.type !== \"sandbox\" && previous && !previous.sandbox) {\n previous.indices.push(index);\n } else {\n runs.push({ indices: [index], sandbox: segment.type === \"sandbox\" });\n }\n });\n for (const run of runs) {\n if (\n !run.sandbox &&\n run.indices.some((index) => isImmediateSegment(sourceSegments[index]))\n ) {\n const segments = run.indices.map((index) => sourceSegments[index]);\n const fullSource = segments.map((segment) => segment.value).join(\"\");\n run.plan = createVideoMarkdownRunPlan(\n segments,\n fullSource === sourceContent ? sourceAnalysis : undefined\n );\n }\n }\n return runs;\n }, [sourceSegments, sourceContent, sourceAnalysis]);\n const renderContent = hasRichSegments\n ? mergedRenderSegments.map((segment) => segment.value).join(\"\")\n : isTypewriterEnabled\n ? displayContent\n : sourceContent;\n const normalizedContent = useMemo(\n () => (customRenderBar ? normalizeInlineHtml(renderContent) : \"\"),\n [customRenderBar, renderContent]\n );\n\n const safeMarkdownContent = useMemo(\n () =>\n hasRichSegments\n ? \"\"\n : normalizeInlineHtml(\n isTypewriterEnabled\n ? protectTypedMarkdownPrefix(\n renderContent,\n sourceContent,\n sourceInlineCodeRanges[0] ?? [],\n sourceAnalysis.metadata\n )\n : escapeTypedMarkdownMetadata(\n renderContent,\n sourceAnalysis.metadata\n )\n ),\n [\n sourceContent,\n hasRichSegments,\n isTypewriterEnabled,\n renderContent,\n sourceInlineCodeRanges,\n sourceAnalysis.metadata,\n ]\n );\n\n const interactionDefaults = useMemo(\n () =>\n getInteractionDefaultValues(\n renderContent,\n userInput,\n interactionDefaultValueOptions\n ),\n [interactionDefaultValueOptions, renderContent, userInput]\n );\n\n const resolvedDefaultButtonText =\n defaultButtonText?.trim() || interactionDefaults.buttonText;\n const resolvedDefaultInputText =\n defaultInputText?.trim() || interactionDefaults.inputText;\n const fallbackSelectedValues = useMemo(\n () =>\n userInput\n ? userInput\n .split(\",\")\n .map((value) => value.trim())\n .filter(Boolean)\n : undefined,\n [userInput]\n );\n const resolvedDefaultSelectedValues = defaultSelectedValues?.length\n ? defaultSelectedValues\n : interactionDefaults.selectedValues || fallbackSelectedValues;\n const stableDefaultSelectedValues = useStableStringArray(\n resolvedDefaultSelectedValues\n );\n const componentRuntimeValuesRef = useRef<MarkdownComponentRuntimeValues>({\n direction,\n language,\n mermaidMessages,\n beforeSend,\n locale,\n onClickCustomButtonAfterContent,\n onSend,\n readonly,\n renderContent,\n resolvedConfirmButtonText,\n resolvedCopiedButtonText,\n resolvedCopyButtonText,\n resolvedDefaultButtonText,\n resolvedDefaultInputText,\n resolvedDefaultSelectedValues: stableDefaultSelectedValues,\n });\n\n componentRuntimeValuesRef.current = {\n direction,\n language,\n mermaidMessages,\n beforeSend,\n locale,\n onClickCustomButtonAfterContent,\n onSend,\n readonly,\n renderContent,\n resolvedConfirmButtonText,\n resolvedCopiedButtonText,\n resolvedCopyButtonText,\n resolvedDefaultButtonText,\n resolvedDefaultInputText,\n resolvedDefaultSelectedValues: stableDefaultSelectedValues,\n };\n\n const components = useMemo<CustomComponents>(\n () => ({\n \"custom-button-after-content\": ({\n children,\n }: {\n children: React.ReactNode;\n }) => {\n return (\n <button\n className=\"content-render-custom-button-after-content\"\n onClick={\n componentRuntimeValuesRef.current.onClickCustomButtonAfterContent\n }\n >\n <span className=\"content-render-custom-button-after-content-inner\">\n {children}\n </span>\n </button>\n );\n },\n \"custom-variable\": (props) => (\n <CustomButtonInputVariable\n {...props}\n readonly={componentRuntimeValuesRef.current.readonly}\n defaultButtonText={\n componentRuntimeValuesRef.current.resolvedDefaultButtonText\n }\n defaultInputText={\n componentRuntimeValuesRef.current.resolvedDefaultInputText\n }\n defaultSelectedValues={\n componentRuntimeValuesRef.current.resolvedDefaultSelectedValues\n }\n onSend={componentRuntimeValuesRef.current.onSend}\n beforeSend={componentRuntimeValuesRef.current.beforeSend}\n locale={componentRuntimeValuesRef.current.locale}\n dir={componentRuntimeValuesRef.current.direction}\n lang={componentRuntimeValuesRef.current.language}\n confirmButtonText={\n componentRuntimeValuesRef.current.resolvedConfirmButtonText\n }\n // tooltipMinLength={tooltipMinLength}\n />\n ),\n code: MarkdownCode,\n table: ({ ...props }) => (\n <div className=\"content-render-table-container\">\n <table className=\"content-render-table\" {...props} />\n </div>\n ),\n th: ({ ...props }) => <th className=\"content-render-th\" {...props} />,\n td: ({ ...props }) => <td className=\"content-render-td\" {...props} />,\n tr: ({ ...props }) => <tr className=\"content-render-tr\" {...props} />,\n li: ({ node, ...props }) => {\n const className = node?.properties?.className;\n const hasTaskListItem =\n (typeof className === \"string\" &&\n className.includes(\"task-list-item\")) ||\n (Array.isArray(className) && className.includes(\"task-list-item\"));\n if (hasTaskListItem) {\n return <li className=\"content-render-task-list-item\" {...props} />;\n }\n return <li {...props} />;\n },\n ol: ({ ...props }) => <ol className=\"content-render-ol\" {...props} />,\n ul: ({ ...props }) => <ul className=\"content-render-ul\" {...props} />,\n input: ({ ...props }) => {\n if (props.type === \"checkbox\") {\n return (\n <input\n type=\"checkbox\"\n className=\"content-render-checkbox\"\n disabled\n {...props}\n />\n );\n }\n return <input {...props} />;\n },\n a: ({ children, ...props }) => (\n <a target=\"_blank\" rel=\"noopener noreferrer\" {...props}>\n {children}\n </a>\n ),\n pre: (props) => (\n <CodeBlock\n {...props}\n copyButtonText={\n componentRuntimeValuesRef.current.resolvedCopyButtonText\n }\n copiedButtonText={\n componentRuntimeValuesRef.current.resolvedCopiedButtonText\n }\n />\n ),\n }),\n []\n );\n\n const segments = useMemo(\n () => parseMarkdownSegments(safeMarkdownContent),\n [safeMarkdownContent]\n );\n\n const renderMarkdownSegments = (raw: string, keyPrefix: string) => {\n const normalized = normalizeInlineHtml(raw);\n const parsed = parseMarkdownSegments(normalized);\n\n return parsed.map((seg, index) => {\n const key = `${keyPrefix}-${seg.type}-${index}`;\n\n if (seg.type === \"text\") {\n return (\n <MarkdownComponentRuntimeContext.Provider\n key={key}\n value={componentRuntimeValuesRef}\n >\n <MarkdownRenderer\n locale={locale}\n components={components}\n content={seg.value}\n />\n </MarkdownComponentRuntimeContext.Provider>\n );\n }\n\n if (seg.type === \"mermaid\") {\n return (\n <MermaidChart\n key={key}\n chart={seg.value}\n frozen={!seg.complete}\n messages={mermaidMessages}\n />\n );\n }\n\n if (seg.type === \"svg\") {\n return <SvgBlockInShadow key={key} svg={seg.value} />;\n }\n\n return null;\n });\n };\n\n const customBar = customRenderBar ? (\n <div className=\"content-render-custom-bar\">\n {React.createElement(customRenderBar, {\n content,\n displayContent: normalizedContent,\n onSend,\n })}\n </div>\n ) : null;\n\n if (hasRichSegments) {\n return (\n <div\n className=\"content-render markdown-body\"\n dir={direction}\n lang={language}\n >\n {richRenderRuns.map((run) => {\n const idx = run.indices[0];\n const segment = mergedRenderSegments[idx];\n if (run.sandbox)\n return segment.value ? (\n <IframeSandbox\n key={`sandbox-${idx}`}\n hideFullScreen\n type=\"sandbox\"\n content={segment.value}\n className=\"content-render-iframe\"\n locale={locale}\n dir={direction}\n lang={language}\n loadingText={sandboxLoadingText}\n styleLoadingText={sandboxStyleLoadingText}\n scriptLoadingText={sandboxScriptLoadingText}\n disableLoadingOverlay={disableSandboxLoadingOverlay}\n fullScreenButtonText={resolvedSandboxFullscreenButtonText}\n exitFullScreenButtonText={\n resolvedSandboxExitFullscreenButtonText\n }\n mode={sandboxMode}\n />\n ) : null;\n if (run.plan)\n return (\n <MarkdownComponentRuntimeContext.Provider\n key={`md-${idx}`}\n value={componentRuntimeValuesRef}\n >\n <StableVideoMarkdownRenderer\n locale={locale}\n components={components}\n plan={run.plan}\n renderedSegments={run.indices.map(\n (index) => mergedRenderSegments[index]\n )}\n />\n </MarkdownComponentRuntimeContext.Provider>\n );\n return run.indices.map((index) => (\n <React.Fragment key={`md-${index}`}>\n {mergedRenderSegments[index].type === \"markdown\" &&\n mergedRenderSegments[index].pending\n ? null\n : renderMarkdownSegments(\n safeRichMarkdownContent[index],\n `md-${index}`\n )}\n </React.Fragment>\n ));\n })}\n {customBar}\n </div>\n );\n }\n\n return (\n <div\n className=\"content-render markdown-body\"\n dir={direction}\n lang={language}\n >\n {segments.map((seg, index) => {\n if (seg.type === \"text\") {\n return (\n <MarkdownComponentRuntimeContext.Provider\n key={index}\n value={componentRuntimeValuesRef}\n >\n <MarkdownRenderer\n locale={locale}\n components={components}\n content={seg.value}\n />\n </MarkdownComponentRuntimeContext.Provider>\n );\n }\n\n if (seg.type === \"mermaid\") {\n return (\n <MermaidChart\n key={index}\n chart={seg.value}\n frozen={!seg.complete}\n messages={mermaidMessages}\n />\n );\n }\n\n if (seg.type === \"svg\") {\n return <SvgBlockInShadow key={index} svg={seg.value} />;\n }\n })}\n\n {customBar}\n </div>\n );\n};\n\nexport default ContentRender;\n"],"names":["FIXED_TYPEWRITER_CHUNK_SIZE","SvgBlockInShadow","svg","inline","hostRef","useRef","Wrapper","useEffect","host","shadowRoot","styleId","styleEl","node","template","cleanedSvg","stripSvgTextLineBreaks","hasResponsiveSvg","hasFixedSvg","svgEl","viewBox","dimensions","value","viewBoxWidth","viewBoxHeight","widthAttr","heightAttr","isRelativeLength","normalized","toNumericLength","parsed","isWidthRelative","isHeightRelative","widthMissing","heightMissing","numericWidth","numericHeight","hostResponsive","jsx","MarkdownComponentRuntimeContext","React","MarkdownCode","props","receivedTree","codeProps","runtimeValuesRef","isInCodeBlock","CodeBlockContext","className","children","rest","chartContent","complete","mermaidBlockIsComplete","frozen","MermaidChart","sourceRehypePlugins","preserveCustomVariableProperties","rehypeRaw","sanitizeInvalidTagName","restoreCustomVariableProperties","formattingRehypePlugins","rehypeHighlight","highlightLanguages","subsetLanguages","rehypeKatex","rehypePlugins","MarkdownRenderer","markdownContent","components","locale","texts","getContentRenderLocaleTexts","ReactMarkdown","remarkPlugins","referenceIndex","rereferenceIndex","reference","usePreparedTree","StableVideoMarkdownRenderer","plan","renderedSegments","prepared","useMemo","sourceProcessor","unified","remarkRehype","formattingProcessor","tree","cloneVideoMarkdownSourceTree","prepareVideoMarkdownRun","projected","projectVideoMarkdownRun","originalComponents","wrappers","stableComponents","tags","collect","result","tag","Component","state","getVideoMarkdownNodeState","Fragment","Original","visibleProps","preparedPlugins","isImmediateSegment","segment","mergeNonSandboxSegments","segments","merged","last","closeTypedInlineCode","visible","source","ranges","range","start","end","delimiter","closingStart","protectTypedMarkdownPrefix","inlineCodeRanges","metadataRanges","sourceOffset","closed","escapeTypedMarkdownMetadata","splitTextByCharacterChunk","chunkSize","safeChunkSize","characters","areStringArraysEqual","left","right","index","useStableStringArray","values","valuesRef","ContentRender","content","contentType","lang","dir","customRenderBar","onSend","typingSpeed","enableTypewriter","typewriterPacing","onTypeFinished","onTypewriterStateChange","userInput","interactionDefaultValueOptions","defaultButtonText","defaultInputText","defaultSelectedValues","readonly","confirmButtonText","copyButtonText","copiedButtonText","sandboxLoadingText","sandboxStyleLoadingText","sandboxScriptLoadingText","disableSandboxLoadingOverlay","sandboxFullscreenButtonText","sandboxExitFullscreenButtonText","sandboxMode","onClickCustomButtonAfterContent","beforeSend","localeTexts","mermaidMessages","direction","getMarkdownFlowDirection","language","getMarkdownFlowLanguage","resolvedConfirmButtonText","resolvedCopyButtonText","resolvedCopiedButtonText","resolvedSandboxFullscreenButtonText","resolvedSandboxExitFullscreenButtonText","isTypewriterEnabled","sourceContent","normalizeWrappedSandboxContent","sourceAnalysis","getMarkdownSourceAnalysis","sourceSegments","splitContentSegments","hasRichSegments","typewriterContent","typewriterTickMs","fixedTypewriterContentVersion","displayContent","setDisplayContent","useState","displayContentRef","pendingContentRef","contentAwareQueueRef","contentAwareBudgetRef","previousTypewriterEnabledRef","previousTypewriterPacingRef","previousSourceContentRef","previousReceivedContentRef","hasReportedTypeFinishedRef","typewriterWakeVersion","setTypewriterWakeVersion","wasTypewriterEnabled","previousTypewriterPacing","previousSourceContent","wasPending","receivedContentChanged","receivedContentAppended","clearPendingContent","updateDisplayContent","nextContent","visibleContent","getTrailingTypewriterGrapheme","sharedLength","nextPendingContent","previousPendingContent","appended","appendContentAwareTypewriterQueue","version","typewriterTimer","chunk","consumeContentAwareTypewriterQueue","CONTENT_AWARE_TYPEWRITER_TICK_BUDGET","isContentAwareTypewriterQueueEmpty","nextDisplayContent","mergedRenderSegments","textOffset","typewriterState","remaining","sourceSegmentOffsets","offset","sourceInlineCodeRanges","getInlineCodeRanges","safeRichMarkdownContent","richRenderRuns","runs","previous","run","fullSource","createVideoMarkdownRunPlan","renderContent","normalizedContent","normalizeInlineHtml","safeMarkdownContent","interactionDefaults","getInteractionDefaultValues","resolvedDefaultButtonText","resolvedDefaultInputText","fallbackSelectedValues","resolvedDefaultSelectedValues","stableDefaultSelectedValues","componentRuntimeValuesRef","CustomButtonInputVariable","CodeBlock","parseMarkdownSegments","renderMarkdownSegments","raw","keyPrefix","seg","key","customBar","jsxs","idx","IframeSandbox"],"mappings":"ihDA4EMA,GAA8B,EA6E9BC,GAAgE,CAAC,CACrE,IAAAC,EACA,OAAAC,EAAS,EACX,IAAM,CACJ,MAAMC,EAAUC,EAAAA,OAA2B,IAAI,EACzCC,EAAUH,EAAS,OAAS,MAElCI,OAAAA,EAAAA,UAAU,IAAM,CACd,MAAMC,EAAOJ,EAAQ,QACrB,GAAI,CAACI,EAAM,OACX,MAAMC,EAAaD,EAAK,YAAcA,EAAK,aAAa,CAAE,KAAM,OAAQ,EAClEE,EAAU,2BAChB,IAAIC,EAAUF,EAAW,eAAeC,CAAO,EAE1CC,IACHA,EAAU,SAAS,cAAc,OAAO,EACxCA,E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EAAI,SACb,SAAU3F,CAAA,EAHLnC,CAAA,EAQX,GAAI8H,EAAI,OAAS,MACf,OAAO/N,EAAAA,IAACpC,GAAA,CAA6B,IAAKmQ,EAAI,OAAhB9H,CAAuB,CAEzD,CAAC,EAEAgI,EAAA,CAAA,CAAA,CAGP"}
1
+ {"version":3,"file":"ContentRender.cjs","sources":["../../../src/components/ContentRender/ContentRender.tsx"],"sourcesContent":["import { trimVariablePadding } from \"remark-flow\";\nimport React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport ReactMarkdown from \"react-markdown\";\nimport rehypeHighlight from \"rehype-highlight\";\nimport rehypeKatex from \"rehype-katex\";\nimport rehypeRaw from \"rehype-raw\";\nimport { unified, type PluggableList, type Plugin } from \"unified\";\nimport remarkRehype from \"remark-rehype\";\nimport type { Element, Root } from \"hast\";\nimport { CustomRenderBarProps, OnSendContentParams } from \"../types\";\nimport { sanitizeInvalidTagName } from \"./utils/sanitize-invalid-tag-name\";\nimport { stripSvgTextLineBreaks } from \"./utils/strip-svg-text-line-breaks\";\nimport \"./contentRender.css\";\nimport \"./github-markdown-light.css\";\nimport \"highlight.js/styles/github.css\";\nimport \"katex/dist/katex.min.css\";\nimport CodeBlock, { CodeBlockContext } from \"./CodeBlock\";\nimport CustomButtonInputVariable, {\n ComponentsWithCustomVariable,\n} from \"./plugins/CustomVariable\";\nimport MermaidChart, { type MermaidChartProps } from \"./plugins/MermaidChart\";\nimport {\n preserveCustomVariableProperties,\n restoreCustomVariableProperties,\n} from \"./utils/custom-variable-props\";\nimport {\n highlightLanguages,\n subsetLanguages,\n} from \"./utils/highlight-languages\";\n// import { processMarkdownText } from \"./utils/process-markdown\";\nimport {\n parseMarkdownSegments,\n mermaidBlockIsComplete,\n} from \"./utils/mermaid-parse\";\nimport {\n getInlineCodeRanges,\n getMarkdownSourceAnalysis,\n} from \"./utils/inline-code-ranges\";\nimport { remarkPlugins } from \"./utils/markdown-plugins\";\nimport { normalizeInlineHtml } from \"./utils/normalize-inline-html\";\nimport {\n escapeTypedMarkdownMetadata,\n type MarkdownMetadataRange,\n} from \"./utils/escape-typed-metadata\";\nimport IframeSandbox from \"./IframeSandbox\";\nimport {\n appendContentAwareTypewriterQueue,\n CONTENT_AWARE_TYPEWRITER_TICK_BUDGET,\n consumeContentAwareTypewriterQueue,\n getTrailingTypewriterGrapheme,\n isContentAwareTypewriterQueueEmpty,\n type ContentAwareTypewriterQueue,\n} from \"./utils/typewriter-pacing\";\nimport {\n normalizeWrappedSandboxContent,\n splitContentSegments,\n type RenderSegment,\n} from \"./utils/split-content\";\nimport {\n getInteractionDefaultValues,\n type InteractionDefaultValueOptions,\n} from \"../../lib/interaction-defaults\";\nimport {\n getMarkdownFlowDirection,\n getMarkdownFlowLanguage,\n type MarkdownFlowLocale,\n} from \"../../lib/locale\";\nimport { getContentRenderLocaleTexts } from \"./contentRenderI18n\";\nimport {\n createVideoMarkdownRunPlan,\n cloneVideoMarkdownSourceTree,\n projectVideoMarkdownRun,\n prepareVideoMarkdownRun,\n getVideoMarkdownNodeState,\n type VideoMarkdownRunPlan,\n} from \"./utils/video-markdown-run\";\n\nconst FIXED_TYPEWRITER_CHUNK_SIZE = 2;\n\nexport type ContentRenderTypewriterPacing = \"fixed\" | \"content-aware\";\n\n// Define component Props type\nexport interface ContentRenderProps {\n content: string;\n contentType?: string;\n /** Locale used for built-in UI text when a more specific text prop is not provided. */\n locale?: MarkdownFlowLocale;\n /** Overrides the locale-derived language; omitted values inherit from the host. */\n lang?: string;\n /** Overrides locale-derived direction; omitted values inherit when no locale is set. */\n dir?: React.HTMLAttributes<HTMLDivElement>[\"dir\"];\n /**\n * Callback invoked when the custom button after content is clicked.\n * This button is rendered via the `<custom-button-after-content>` tag in markdown content.\n * @example\n * ```tsx\n * <ContentRender\n * content=\"Hello <custom-button-after-content>Ask</custom-button-after-content>\"\n * onClickCustomButtonAfterContent={() => console.log('Button clicked')}\n * />\n * ```\n */\n customRenderBar?: CustomRenderBarProps;\n onClickCustomButtonAfterContent?: () => void;\n onSend?: (content: OnSendContentParams) => void;\n typingSpeed?: number;\n /** Types prose only; following HTML renders progressively once preceding prose is displayed. */\n enableTypewriter?: boolean;\n /** Controls how much text is revealed per tick. Defaults to the legacy fixed pacing. */\n typewriterPacing?: ContentRenderTypewriterPacing;\n onTypeFinished?: () => void;\n onTypewriterStateChange?: (state: ContentRenderTypewriterState) => void;\n userInput?: string;\n interactionDefaultValueOptions?: InteractionDefaultValueOptions;\n defaultButtonText?: string;\n defaultInputText?: string; // Text input by user\n defaultSelectedValues?: string[]; // Default selected values for multi-select\n readonly?: boolean;\n // Multi-select confirm button text (i18n support)\n confirmButtonText?: string;\n // Copy button text (i18n support)\n copyButtonText?: string;\n // Copied state text (i18n support)\n copiedButtonText?: string;\n // Dynamic interaction format for multi-select support\n dynamicInteractionFormat?: string;\n // Loading text before first HTML block renders inside iframe (i18n support)\n sandboxLoadingText?: string;\n // Loading text while styles are being generated inside iframe\n sandboxStyleLoadingText?: string;\n // Loading text while scripts are being cached/executed inside iframe\n sandboxScriptLoadingText?: string;\n // Disable sandbox loading overlays when upper layers have already entered an error state\n disableSandboxLoadingOverlay?: boolean;\n // Fullscreen button text for iframe sandbox\n sandboxFullscreenButtonText?: string;\n // Exit fullscreen button text for iframe sandbox\n sandboxExitFullscreenButtonText?: string;\n // Sandbox render mode\n sandboxMode?: \"content\" | \"blackboard\";\n beforeSend?: (param: OnSendContentParams) => boolean;\n // tooltipMinLength?: number; // Control minimum character length for tooltip display, default 10\n}\n\nexport interface ContentRenderTypewriterState {\n isTypewriterEnabled: boolean;\n isTyping: boolean;\n isComplete: boolean;\n /** Received source units already displayed, including unpaced HTML. */\n renderedLength: number;\n totalLength: number;\n}\n\n// Render svg string via Shadow DOM to avoid markdown wrapping\nconst SvgBlockInShadow: React.FC<{ svg: string; inline?: boolean }> = ({\n svg,\n inline = false,\n}) => {\n const hostRef = useRef<HTMLElement | null>(null);\n const Wrapper = inline ? \"span\" : \"div\";\n\n useEffect(() => {\n const host = hostRef.current;\n if (!host) return;\n const shadowRoot = host.shadowRoot ?? host.attachShadow({ mode: \"open\" });\n const styleId = \"content-render-svg-style\";\n let styleEl = shadowRoot.getElementById(styleId) as HTMLStyleElement | null;\n\n if (!styleEl) {\n styleEl = document.createElement(\"style\");\n styleEl.id = styleId;\n // Keep intrinsic SVG width so the wrapper can scroll horizontally when needed\n styleEl.textContent = `\n svg { height: auto; display: inline-block; }\n svg.content-render-svg-el--responsive { width: 100%; max-width: 100%; }\n svg.content-render-svg-el--fixed { max-width: none; }\n `;\n shadowRoot.appendChild(styleEl);\n }\n\n const nodesToRemove = Array.from(shadowRoot.childNodes).filter(\n (node) => node !== styleEl\n );\n nodesToRemove.forEach((node) => shadowRoot.removeChild(node));\n\n const template = document.createElement(\"template\");\n const cleanedSvg = stripSvgTextLineBreaks(svg);\n template.innerHTML = cleanedSvg;\n shadowRoot.append(template.content.cloneNode(true));\n\n let hasResponsiveSvg = false;\n let hasFixedSvg = false;\n\n shadowRoot.querySelectorAll(\"svg\").forEach((svgEl) => {\n // Derive responsive sizing from viewBox so pure viewBox SVGs stay visible and fluid\n const viewBox = svgEl.getAttribute(\"viewBox\");\n if (!viewBox) return;\n\n const dimensions = viewBox\n .trim()\n .split(/[\\s,]+/)\n .map((value) => Number(value));\n\n if (dimensions.length !== 4 || dimensions.some(Number.isNaN)) return;\n\n const [, , viewBoxWidth, viewBoxHeight] = dimensions;\n const widthAttr = svgEl.getAttribute(\"width\");\n const heightAttr = svgEl.getAttribute(\"height\");\n const isRelativeLength = (value?: string | null) => {\n if (!value) return false;\n const normalized = value.trim().toLowerCase();\n return normalized === \"auto\" || normalized.endsWith(\"%\");\n };\n const toNumericLength = (value?: string | null) => {\n if (!value) return null;\n const normalized = value.trim().toLowerCase();\n if (normalized === \"auto\" || normalized.endsWith(\"%\")) {\n return null;\n }\n const parsed = Number.parseFloat(normalized);\n return Number.isNaN(parsed) ? null : parsed;\n };\n // Treat percentage/auto sizing as responsive so viewBox drives the layout\n const isWidthRelative = isRelativeLength(widthAttr);\n const isHeightRelative = isRelativeLength(heightAttr);\n const widthMissing = !widthAttr || widthAttr === \"0\";\n const heightMissing = !heightAttr || heightAttr === \"0\";\n const numericWidth = toNumericLength(widthAttr);\n const numericHeight = toNumericLength(heightAttr);\n const matchesViewBox =\n numericWidth === viewBoxWidth && numericHeight === viewBoxHeight;\n\n // Prefer responsive layout when sizing is relative or matches the viewBox\n const shouldUseResponsiveSize =\n isWidthRelative ||\n isHeightRelative ||\n (widthMissing && heightMissing) ||\n matchesViewBox;\n\n if (shouldUseResponsiveSize) {\n hasResponsiveSvg = true;\n svgEl.classList.add(\"content-render-svg-el--responsive\");\n svgEl.classList.remove(\"content-render-svg-el--fixed\");\n svgEl.style.width = \"100%\";\n svgEl.style.height = \"auto\";\n if (!svgEl.style.aspectRatio && viewBoxHeight > 0) {\n svgEl.style.aspectRatio = `${viewBoxWidth} / ${viewBoxHeight}`;\n }\n return;\n }\n\n hasFixedSvg = true;\n svgEl.classList.add(\"content-render-svg-el--fixed\");\n svgEl.classList.remove(\"content-render-svg-el--responsive\");\n if (widthMissing && viewBoxWidth > 0) {\n svgEl.setAttribute(\"width\", `${viewBoxWidth}`);\n }\n if (heightMissing && viewBoxHeight > 0) {\n svgEl.setAttribute(\"height\", `${viewBoxHeight}`);\n }\n });\n\n const hostResponsive = hasResponsiveSvg && !hasFixedSvg;\n host.classList.toggle(\"content-render-svg--responsive\", hostResponsive);\n host.classList.toggle(\"content-render-svg--fixed\", !hostResponsive);\n }, [svg]);\n\n return (\n <Wrapper className=\"content-render-svg-scroll\">\n <Wrapper\n className=\"content-render-svg\"\n ref={(node) => {\n hostRef.current = node;\n }}\n />\n </Wrapper>\n );\n};\n\n// Extended component interface\ntype CustomComponents = ComponentsWithCustomVariable & {\n \"custom-button-after-content\"?: React.ComponentType<{\n children: React.ReactNode;\n }>;\n};\n\ntype MarkdownComponentRuntimeValues = {\n direction?: ContentRenderProps[\"dir\"];\n language?: string;\n mermaidMessages: MermaidChartProps[\"messages\"];\n beforeSend?: (param: OnSendContentParams) => boolean;\n locale?: MarkdownFlowLocale;\n onClickCustomButtonAfterContent?: () => void;\n onSend?: (content: OnSendContentParams) => void;\n readonly: boolean;\n renderContent: string;\n resolvedConfirmButtonText: string;\n resolvedCopiedButtonText: string;\n resolvedCopyButtonText: string;\n resolvedDefaultButtonText?: string;\n resolvedDefaultInputText?: string;\n resolvedDefaultSelectedValues?: string[];\n};\n\nconst MarkdownComponentRuntimeContext =\n React.createContext<React.RefObject<MarkdownComponentRuntimeValues> | null>(\n null\n );\n\nconst MarkdownCode = (\n props: React.ComponentProps<\"code\"> & { receivedTree?: boolean }\n) => {\n const { receivedTree, ...codeProps } = props;\n const runtimeValuesRef = React.useContext(MarkdownComponentRuntimeContext);\n const isInCodeBlock = React.useContext(CodeBlockContext);\n if (!runtimeValuesRef) {\n throw new Error(\"Markdown code renderer requires ContentRender context.\");\n }\n const { className, children, ...rest } = codeProps as {\n className?: string;\n children?: React.ReactNode;\n dir?: string;\n };\n const match = /language-(\\w+)/.exec(className || \"\");\n const language = match?.[1];\n if (language === \"mermaid\") {\n const chartContent = children?.toString().replace(/\\n$/, \"\") || \"\";\n const complete = mermaidBlockIsComplete(\n runtimeValuesRef.current.renderContent,\n chartContent\n );\n // The received-tree path replaces standalone Mermaid segments, whose\n // unfinished charts freeze until the closing fence reaches the prose budget.\n const frozen = receivedTree ? !complete : complete;\n return (\n <MermaidChart\n chart={chartContent}\n frozen={frozen}\n messages={runtimeValuesRef.current.mermaidMessages}\n />\n );\n }\n\n return (\n <code\n className={className}\n {...rest}\n dir={rest.dir ?? (isInCodeBlock ? undefined : \"ltr\")}\n >\n {children}\n </code>\n );\n};\n\nconst sourceRehypePlugins: PluggableList = [\n preserveCustomVariableProperties,\n rehypeRaw,\n sanitizeInvalidTagName,\n restoreCustomVariableProperties,\n];\nconst formattingRehypePlugins: PluggableList = [\n [rehypeHighlight, { languages: highlightLanguages, subset: subsetLanguages }],\n rehypeKatex,\n];\nconst rehypePlugins: PluggableList = [\n ...sourceRehypePlugins,\n ...formattingRehypePlugins,\n];\n\nexport const MarkdownRenderer: React.FC<{\n content: string;\n components: CustomComponents;\n locale?: MarkdownFlowLocale;\n}> = ({ content: markdownContent, components, locale }) => {\n const texts = getContentRenderLocaleTexts(locale);\n return (\n <div className=\"markdown-renderer\">\n <ReactMarkdown\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n remarkRehypeOptions={{\n footnoteLabel: texts.footnoteLabel,\n footnoteBackLabel: (referenceIndex, rereferenceIndex) => {\n const reference =\n String(referenceIndex + 1) +\n (rereferenceIndex > 1 ? `-${rereferenceIndex}` : \"\");\n return texts.footnoteBackLabel.replace(\"{reference}\", reference);\n },\n }}\n components={components}\n >\n {markdownContent}\n </ReactMarkdown>\n </div>\n );\n};\n\n// ReactMarkdown still owns URL handling and JSX conversion. Its parser is\n// bypassed because the received source was already parsed and transformed.\nconst usePreparedTree: Plugin = function () {\n this.parser = () => ({ type: \"root\", children: [] });\n};\n\nconst StableVideoMarkdownRenderer: React.FC<{\n plan: VideoMarkdownRunPlan;\n renderedSegments: readonly RenderSegment[];\n components: CustomComponents;\n locale?: MarkdownFlowLocale;\n}> = ({ plan, renderedSegments, components, locale }) => {\n const prepared = useMemo(() => {\n const texts = getContentRenderLocaleTexts(locale);\n const sourceProcessor = unified()\n .use(remarkPlugins)\n .use(remarkRehype, {\n allowDangerousHtml: true,\n footnoteLabel: texts.footnoteLabel,\n footnoteBackLabel: (referenceIndex, rereferenceIndex) =>\n texts.footnoteBackLabel.replace(\n \"{reference}\",\n String(referenceIndex + 1) +\n (rereferenceIndex > 1 ? `-${rereferenceIndex}` : \"\")\n ),\n })\n .use(sourceRehypePlugins);\n const formattingProcessor = unified().use(formattingRehypePlugins);\n const tree = sourceProcessor.runSync(\n cloneVideoMarkdownSourceTree(plan),\n plan.markdownSource\n ) as Root;\n return prepareVideoMarkdownRun(\n plan,\n tree,\n (value) => formattingProcessor.runSync(value, plan.fullSource) as Root\n );\n }, [plan, locale]);\n const projected = useMemo(\n () => projectVideoMarkdownRun(prepared, renderedSegments),\n [prepared, renderedSegments]\n );\n const originalComponents = useRef(components);\n originalComponents.current = components;\n const wrappers = useRef(\n new Map<\n string,\n React.ComponentType<{\n node: Element;\n children?: React.ReactNode;\n }>\n >()\n );\n const stableComponents = useMemo(() => {\n const tags = new Set<string>();\n const collect = (node: Root | Root[\"children\"][number]) => {\n if (node.type === \"element\") tags.add(node.tagName);\n if (\"children\" in node) node.children.forEach(collect);\n };\n collect(prepared.tree!);\n const result: Record<\n string,\n React.ComponentType<{\n node: Element;\n children?: React.ReactNode;\n }>\n > = {};\n for (const tag of tags) {\n if (!wrappers.current.has(tag)) {\n const Component = ({\n node,\n children,\n ...props\n }: {\n node: Element;\n children?: React.ReactNode;\n }) => {\n const state = getVideoMarkdownNodeState(node);\n if (state?.svg) {\n return state.svgSource ? (\n <SvgBlockInShadow svg={state.svgSource} inline />\n ) : null;\n }\n if (state?.atomic) {\n return state.active ? <>{children}</> : null;\n }\n if (state?.active === false && tag !== \"a\") return null;\n const current = originalComponents.current as Record<\n string,\n React.ElementType\n >;\n const Original = current[tag];\n const visibleProps =\n state?.active === false\n ? { ...props, href: undefined, tabIndex: -1 }\n : props;\n return Original\n ? React.createElement(\n Original,\n {\n ...visibleProps,\n node,\n ...(Original === MarkdownCode ? { receivedTree: true } : {}),\n },\n children\n )\n : React.createElement(tag, visibleProps, children);\n };\n Component.displayName = `StableMarkdown(${tag})`;\n wrappers.current.set(tag, Component);\n }\n result[tag] = wrappers.current.get(tag)!;\n }\n return result as CustomComponents;\n }, [prepared]);\n const preparedPlugins = useMemo<PluggableList>(\n () => [() => () => projected],\n [projected]\n );\n return (\n <div className=\"markdown-renderer\">\n <ReactMarkdown\n remarkPlugins={[usePreparedTree]}\n rehypePlugins={preparedPlugins}\n components={stableComponents}\n >\n {\"\"}\n </ReactMarkdown>\n </div>\n );\n};\n\nconst isImmediateSegment = (segment: RenderSegment) =>\n segment.type === \"markdown\" && segment.immediate === true;\n\nconst mergeNonSandboxSegments = (segments: RenderSegment[]) => {\n if (segments.length <= 1) return segments;\n const merged: RenderSegment[] = [];\n\n segments.forEach((segment) => {\n if (segment.type === \"sandbox\" || isImmediateSegment(segment)) {\n merged.push(segment);\n return;\n }\n\n const last = merged[merged.length - 1];\n if (last && last.type !== \"sandbox\" && !isImmediateSegment(last)) {\n merged[merged.length - 1] = {\n type: \"markdown\",\n value: `${last.value}${segment.value}`,\n };\n return;\n }\n\n merged.push({ type: \"markdown\", value: segment.value });\n });\n\n return merged;\n};\n\nconst closeTypedInlineCode = (\n visible: string,\n source: string,\n ranges: ReturnType<typeof getInlineCodeRanges>\n) => {\n if (visible.length >= source.length) return visible;\n const range = ranges.find(\n ({ start, end }) => start < visible.length && visible.length < end\n );\n if (!range) return visible;\n const delimiter = /^`+/.exec(source.slice(range.start))?.[0];\n if (!delimiter || visible.length < range.start + delimiter.length) {\n return visible;\n }\n const closingStart = range.end - delimiter.length;\n if (visible.length > closingStart) {\n return visible + delimiter.slice(visible.length - closingStart);\n }\n // Close only the render copy so a typed prefix cannot activate code as HTML.\n return visible + (visible.endsWith(\"`\") ? \" \" : \"\") + delimiter;\n};\n\nconst protectTypedMarkdownPrefix = (\n visible: string,\n source: string,\n inlineCodeRanges: ReturnType<typeof getInlineCodeRanges>,\n metadataRanges: readonly MarkdownMetadataRange[],\n sourceOffset = 0\n) => {\n // Both protections use raw coordinates. Append any synthetic code delimiter\n // after escaping so encoded '<' characters cannot shift the typing budget.\n const closed = closeTypedInlineCode(visible, source, inlineCodeRanges);\n return (\n escapeTypedMarkdownMetadata(visible, metadataRanges, sourceOffset) +\n closed.slice(visible.length)\n );\n};\n\nconst splitTextByCharacterChunk = (value: string, chunkSize: number) => {\n const safeChunkSize = Math.max(1, chunkSize);\n const characters = Array.from(value);\n\n return {\n chunk: characters.slice(0, safeChunkSize).join(\"\"),\n rest: characters.slice(safeChunkSize).join(\"\"),\n };\n};\n\nconst areStringArraysEqual = (left?: string[], right?: string[]) => {\n if (left === right) {\n return true;\n }\n if (!left || !right || left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => value === right[index]);\n};\n\nconst useStableStringArray = (values?: string[]) => {\n const valuesRef = useRef<string[] | undefined>(values);\n\n if (!areStringArraysEqual(valuesRef.current, values)) {\n valuesRef.current = values;\n }\n\n return valuesRef.current;\n};\n\nconst ContentRender: React.FC<ContentRenderProps> = ({\n content,\n contentType,\n locale,\n lang,\n dir,\n customRenderBar,\n onSend,\n typingSpeed = 30,\n enableTypewriter = false,\n typewriterPacing = \"fixed\",\n onTypeFinished,\n onTypewriterStateChange,\n userInput,\n interactionDefaultValueOptions,\n defaultButtonText,\n defaultInputText,\n defaultSelectedValues,\n readonly = false,\n confirmButtonText,\n copyButtonText,\n copiedButtonText,\n sandboxLoadingText,\n sandboxStyleLoadingText,\n sandboxScriptLoadingText,\n disableSandboxLoadingOverlay = false,\n sandboxFullscreenButtonText,\n sandboxExitFullscreenButtonText,\n sandboxMode = \"content\",\n onClickCustomButtonAfterContent,\n beforeSend,\n // tooltipMinLength,\n}) => {\n const localeTexts = getContentRenderLocaleTexts(locale);\n const mermaidMessages = useMemo(\n () => ({\n loading: localeTexts.mermaidLoadingText,\n emptyChart: localeTexts.mermaidEmptyChartText,\n error: localeTexts.mermaidErrorText,\n }),\n [localeTexts]\n );\n const direction = dir ?? getMarkdownFlowDirection(locale);\n const language = lang ?? getMarkdownFlowLanguage(locale);\n const resolvedConfirmButtonText =\n confirmButtonText || localeTexts.confirmButtonText;\n const resolvedCopyButtonText = copyButtonText || localeTexts.copyButtonText;\n const resolvedCopiedButtonText =\n copiedButtonText || localeTexts.copiedButtonText;\n const resolvedSandboxFullscreenButtonText =\n sandboxFullscreenButtonText || localeTexts.sandboxFullscreenButtonText;\n const resolvedSandboxExitFullscreenButtonText =\n sandboxExitFullscreenButtonText ||\n localeTexts.sandboxExitFullscreenButtonText;\n const shouldApplyTypewriterByContentType =\n !contentType || contentType === \"text\";\n const isTypewriterEnabled =\n Boolean(enableTypewriter) && shouldApplyTypewriterByContentType;\n const sourceContent = useMemo(\n () => normalizeWrappedSandboxContent(content),\n [content]\n );\n const sourceAnalysis = useMemo(\n () => getMarkdownSourceAnalysis(sourceContent),\n [sourceContent]\n );\n // Parse the received source, never a typewriter-truncated HTML string.\n const sourceSegments = useMemo(() => {\n const segments = mergeNonSandboxSegments(\n splitContentSegments(sourceContent, true, true, sourceAnalysis)\n );\n if (\n sourceContent !== content &&\n segments.length &&\n (segments[0].type === \"sandbox\" || isImmediateSegment(segments[0]))\n ) {\n // The removed opening quote occupied a prose slot before the wrapper\n // completed. Retain its empty slot so the existing iframe keeps its key.\n return [{ type: \"text\" as const, value: \"\" }, ...segments];\n }\n return segments;\n }, [content, sourceContent, sourceAnalysis]);\n const hasRichSegments = sourceSegments.some(\n (segment) => segment.type === \"sandbox\" || isImmediateSegment(segment)\n );\n const typewriterContent = hasRichSegments\n ? sourceSegments\n .filter(\n (segment) =>\n segment.type !== \"sandbox\" && !isImmediateSegment(segment)\n )\n .map((segment) => segment.value)\n .join(\"\")\n : sourceContent;\n const typewriterTickMs = Math.max(0, typingSpeed);\n const fixedTypewriterContentVersion =\n typewriterPacing === \"fixed\" ? typewriterContent : undefined;\n const [displayContent, setDisplayContent] = useState(() =>\n isTypewriterEnabled ? \"\" : typewriterContent\n );\n const displayContentRef = useRef(displayContent);\n const pendingContentRef = useRef(\"\");\n const contentAwareQueueRef = useRef<ContentAwareTypewriterQueue>({\n tokens: [],\n head: 0,\n trailingGrapheme: \"\",\n });\n const contentAwareBudgetRef = useRef(0);\n const previousTypewriterEnabledRef = useRef(isTypewriterEnabled);\n const previousTypewriterPacingRef = useRef(typewriterPacing);\n const previousSourceContentRef = useRef(typewriterContent);\n const previousReceivedContentRef = useRef(content);\n const hasReportedTypeFinishedRef = useRef(false);\n const [typewriterWakeVersion, setTypewriterWakeVersion] = useState(0);\n\n useEffect(() => {\n const wasTypewriterEnabled = previousTypewriterEnabledRef.current;\n const previousTypewriterPacing = previousTypewriterPacingRef.current;\n const previousSourceContent = previousSourceContentRef.current;\n const wasPending = Boolean(pendingContentRef.current);\n const receivedContentChanged =\n previousReceivedContentRef.current !== content;\n const receivedContentAppended =\n receivedContentChanged &&\n content.startsWith(previousReceivedContentRef.current);\n previousReceivedContentRef.current = content;\n\n previousTypewriterEnabledRef.current = isTypewriterEnabled;\n previousTypewriterPacingRef.current = typewriterPacing;\n previousSourceContentRef.current = typewriterContent;\n\n if (\n receivedContentChanged ||\n isTypewriterEnabled !== wasTypewriterEnabled\n ) {\n hasReportedTypeFinishedRef.current = false;\n }\n\n const clearPendingContent = () => {\n pendingContentRef.current = \"\";\n contentAwareQueueRef.current = {\n tokens: [],\n head: 0,\n trailingGrapheme: \"\",\n };\n contentAwareBudgetRef.current = 0;\n };\n\n const updateDisplayContent = (nextContent: string) => {\n displayContentRef.current = nextContent;\n setDisplayContent(nextContent);\n };\n\n if (!isTypewriterEnabled) {\n clearPendingContent();\n updateDisplayContent(typewriterContent);\n return;\n }\n\n if (!wasTypewriterEnabled) {\n clearPendingContent();\n updateDisplayContent(\"\");\n }\n\n let visibleContent = !wasTypewriterEnabled ? \"\" : displayContentRef.current;\n\n if (!typewriterContent.startsWith(visibleContent)) {\n clearPendingContent();\n if (!receivedContentAppended) {\n updateDisplayContent(typewriterContent);\n if (typewriterPacing === \"content-aware\") {\n contentAwareQueueRef.current = {\n tokens: [],\n head: 0,\n trailingGrapheme: getTrailingTypewriterGrapheme(typewriterContent),\n };\n }\n return;\n }\n // A newly recognized HTML tag can replace a previously literal prefix.\n // Keep the shared prose visible and pace only the newly received prose.\n let sharedLength = 0;\n while (\n sharedLength < visibleContent.length &&\n sharedLength < typewriterContent.length &&\n visibleContent[sharedLength] === typewriterContent[sharedLength]\n ) {\n sharedLength += 1;\n }\n visibleContent = visibleContent.slice(0, sharedLength);\n updateDisplayContent(visibleContent);\n }\n\n let nextPendingContent = typewriterContent.slice(visibleContent.length);\n if (!nextPendingContent) {\n pendingContentRef.current = \"\";\n contentAwareBudgetRef.current = 0;\n contentAwareQueueRef.current =\n typewriterPacing === \"content-aware\"\n ? {\n tokens: [],\n head: 0,\n trailingGrapheme: getTrailingTypewriterGrapheme(visibleContent),\n }\n : { tokens: [], head: 0, trailingGrapheme: \"\" };\n return;\n }\n\n if (typewriterPacing === \"content-aware\") {\n const previousPendingContent = previousSourceContent.slice(\n visibleContent.length\n );\n const canAppendToCachedQueue =\n wasTypewriterEnabled &&\n previousTypewriterPacing === \"content-aware\" &&\n typewriterContent.startsWith(previousSourceContent) &&\n pendingContentRef.current === previousPendingContent;\n\n if (canAppendToCachedQueue) {\n const appended = appendContentAwareTypewriterQueue(\n contentAwareQueueRef.current,\n typewriterContent.slice(previousSourceContent.length)\n );\n contentAwareQueueRef.current = appended.queue;\n\n if (appended.immediateChunk) {\n nextPendingContent = nextPendingContent.slice(\n appended.immediateChunk.length\n );\n updateDisplayContent(`${visibleContent}${appended.immediateChunk}`);\n }\n } else {\n const appended = appendContentAwareTypewriterQueue(\n {\n tokens: [],\n head: 0,\n trailingGrapheme: getTrailingTypewriterGrapheme(visibleContent),\n },\n nextPendingContent\n );\n contentAwareQueueRef.current = appended.queue;\n\n if (appended.immediateChunk) {\n nextPendingContent = nextPendingContent.slice(\n appended.immediateChunk.length\n );\n updateDisplayContent(`${visibleContent}${appended.immediateChunk}`);\n }\n\n contentAwareBudgetRef.current = 0;\n }\n } else {\n contentAwareQueueRef.current = {\n tokens: [],\n head: 0,\n trailingGrapheme: \"\",\n };\n contentAwareBudgetRef.current = 0;\n }\n\n pendingContentRef.current = nextPendingContent;\n\n if (!wasPending && nextPendingContent) {\n setTypewriterWakeVersion((version) => version + 1);\n }\n }, [content, typewriterContent, isTypewriterEnabled, typewriterPacing]);\n\n useEffect(() => {\n if (!isTypewriterEnabled) {\n return;\n }\n\n if (\n hasReportedTypeFinishedRef.current ||\n pendingContentRef.current ||\n displayContent !== typewriterContent\n ) {\n return;\n }\n\n hasReportedTypeFinishedRef.current = true;\n onTypeFinished?.();\n }, [\n content,\n typewriterContent,\n displayContent,\n isTypewriterEnabled,\n onTypeFinished,\n ]);\n\n useEffect(() => {\n if (!isTypewriterEnabled || !pendingContentRef.current) {\n return undefined;\n }\n\n const typewriterTimer = window.setTimeout(() => {\n if (!pendingContentRef.current) {\n return;\n }\n\n let chunk = \"\";\n\n if (typewriterPacing === \"content-aware\") {\n const result = consumeContentAwareTypewriterQueue(\n contentAwareQueueRef.current,\n contentAwareBudgetRef.current + CONTENT_AWARE_TYPEWRITER_TICK_BUDGET\n );\n\n chunk = result.chunk;\n contentAwareQueueRef.current = result.queue;\n\n if (isContentAwareTypewriterQueueEmpty(result.queue)) {\n contentAwareBudgetRef.current = 0;\n } else {\n contentAwareBudgetRef.current = result.remainingBudget;\n }\n } else {\n const fixedChunk = splitTextByCharacterChunk(\n pendingContentRef.current,\n FIXED_TYPEWRITER_CHUNK_SIZE\n );\n chunk = fixedChunk.chunk;\n }\n\n if (!chunk) {\n return;\n }\n\n pendingContentRef.current = pendingContentRef.current.slice(chunk.length);\n if (!pendingContentRef.current) {\n contentAwareQueueRef.current =\n typewriterPacing === \"content-aware\"\n ? {\n tokens: [],\n head: 0,\n trailingGrapheme: contentAwareQueueRef.current.trailingGrapheme,\n }\n : { tokens: [], head: 0, trailingGrapheme: \"\" };\n contentAwareBudgetRef.current = 0;\n }\n\n const nextDisplayContent = `${displayContentRef.current}${chunk}`;\n displayContentRef.current = nextDisplayContent;\n setDisplayContent(nextDisplayContent);\n }, typewriterTickMs);\n\n return () => window.clearTimeout(typewriterTimer);\n }, [\n displayContent,\n fixedTypewriterContentVersion,\n isTypewriterEnabled,\n typewriterPacing,\n typewriterTickMs,\n typewriterWakeVersion,\n ]);\n\n const mergedRenderSegments = useMemo(() => {\n let textOffset = 0;\n return sourceSegments.map((segment) => {\n if (!isTypewriterEnabled) return segment;\n if (segment.type === \"sandbox\" || isImmediateSegment(segment)) {\n // HTML skips the prose budget only after earlier prose has caught up.\n // Retain its source slot so later updates keep the same render key.\n return displayContent.length >= textOffset\n ? segment\n : { ...segment, value: \"\" };\n }\n const value = displayContent.slice(\n textOffset,\n textOffset + segment.value.length\n );\n textOffset += segment.value.length;\n // Keep empty prose slots so an existing sandbox never changes its key.\n return { ...segment, value };\n });\n }, [sourceSegments, displayContent, isTypewriterEnabled]);\n const typewriterState = useMemo<ContentRenderTypewriterState>(\n () => ({\n isTypewriterEnabled,\n isTyping: isTypewriterEnabled && displayContent !== typewriterContent,\n isComplete: displayContent === typewriterContent,\n renderedLength:\n content.length -\n sourceSegments.reduce(\n (remaining, segment, index) =>\n remaining +\n segment.value.length -\n mergedRenderSegments[index].value.length,\n 0\n ),\n totalLength: content.length,\n }),\n [\n content,\n typewriterContent,\n displayContent,\n isTypewriterEnabled,\n sourceSegments,\n mergedRenderSegments,\n ]\n );\n\n useEffect(() => {\n onTypewriterStateChange?.(typewriterState);\n }, [onTypewriterStateChange, typewriterState]);\n const sourceSegmentOffsets = useMemo(() => {\n let offset = 0;\n return sourceSegments.map((segment) => {\n const start = offset;\n offset += segment.value.length;\n return start;\n });\n }, [sourceSegments]);\n const sourceInlineCodeRanges = useMemo(\n () =>\n isTypewriterEnabled\n ? sourceSegments.map((segment) =>\n segment.type === \"sandbox\" || isImmediateSegment(segment)\n ? []\n : segment.value === sourceContent\n ? sourceAnalysis.inline\n : getInlineCodeRanges(segment.value)\n )\n : [],\n [isTypewriterEnabled, sourceSegments, sourceContent, sourceAnalysis]\n );\n const safeRichMarkdownContent = useMemo(\n () =>\n hasRichSegments\n ? mergedRenderSegments.map((segment, index) =>\n segment.type === \"sandbox\" || isImmediateSegment(segment)\n ? segment.value\n : isTypewriterEnabled\n ? protectTypedMarkdownPrefix(\n segment.value,\n sourceSegments[index].value,\n sourceInlineCodeRanges[index] ?? [],\n sourceAnalysis.metadata,\n sourceSegmentOffsets[index]\n )\n : escapeTypedMarkdownMetadata(\n segment.value,\n sourceAnalysis.metadata,\n sourceSegmentOffsets[index]\n )\n )\n : [],\n [\n hasRichSegments,\n isTypewriterEnabled,\n mergedRenderSegments,\n sourceInlineCodeRanges,\n sourceSegments,\n sourceAnalysis.metadata,\n sourceSegmentOffsets,\n ]\n );\n const richRenderRuns = useMemo(() => {\n const runs: Array<{\n indices: number[];\n sandbox: boolean;\n plan?: ReturnType<typeof createVideoMarkdownRunPlan>;\n }> = [];\n sourceSegments.forEach((segment, index) => {\n const previous = runs.at(-1);\n if (segment.type !== \"sandbox\" && previous && !previous.sandbox) {\n previous.indices.push(index);\n } else {\n runs.push({ indices: [index], sandbox: segment.type === \"sandbox\" });\n }\n });\n for (const run of runs) {\n if (\n !run.sandbox &&\n run.indices.some((index) => isImmediateSegment(sourceSegments[index]))\n ) {\n const segments = run.indices.map((index) => sourceSegments[index]);\n const fullSource = segments.map((segment) => segment.value).join(\"\");\n run.plan = createVideoMarkdownRunPlan(\n segments,\n fullSource === sourceContent ? sourceAnalysis : undefined\n );\n }\n }\n return runs;\n }, [sourceSegments, sourceContent, sourceAnalysis]);\n const renderContent = hasRichSegments\n ? mergedRenderSegments.map((segment) => segment.value).join(\"\")\n : isTypewriterEnabled\n ? displayContent\n : sourceContent;\n const normalizedContent = useMemo(\n () => (customRenderBar ? normalizeInlineHtml(renderContent) : \"\"),\n [customRenderBar, renderContent]\n );\n\n const safeMarkdownContent = useMemo(\n () =>\n hasRichSegments\n ? \"\"\n : normalizeInlineHtml(\n isTypewriterEnabled\n ? protectTypedMarkdownPrefix(\n renderContent,\n sourceContent,\n sourceInlineCodeRanges[0] ?? [],\n sourceAnalysis.metadata\n )\n : escapeTypedMarkdownMetadata(\n renderContent,\n sourceAnalysis.metadata\n )\n ),\n [\n sourceContent,\n hasRichSegments,\n isTypewriterEnabled,\n renderContent,\n sourceInlineCodeRanges,\n sourceAnalysis.metadata,\n ]\n );\n\n const interactionDefaults = useMemo(\n () =>\n getInteractionDefaultValues(\n renderContent,\n userInput,\n interactionDefaultValueOptions\n ),\n [interactionDefaultValueOptions, renderContent, userInput]\n );\n\n const resolvedDefaultButtonText =\n (defaultButtonText ? trimVariablePadding(defaultButtonText) : undefined) ||\n interactionDefaults.buttonText;\n const resolvedDefaultInputText =\n defaultInputText?.trim() || interactionDefaults.inputText;\n const fallbackSelectedValues = useMemo(\n () =>\n userInput\n ? userInput\n .split(\",\")\n .map((value) => trimVariablePadding(value))\n .filter(Boolean)\n : undefined,\n [userInput]\n );\n const resolvedDefaultSelectedValues = defaultSelectedValues?.length\n ? defaultSelectedValues\n : interactionDefaults.selectedValues || fallbackSelectedValues;\n const stableDefaultSelectedValues = useStableStringArray(\n resolvedDefaultSelectedValues\n );\n const componentRuntimeValuesRef = useRef<MarkdownComponentRuntimeValues>({\n direction,\n language,\n mermaidMessages,\n beforeSend,\n locale,\n onClickCustomButtonAfterContent,\n onSend,\n readonly,\n renderContent,\n resolvedConfirmButtonText,\n resolvedCopiedButtonText,\n resolvedCopyButtonText,\n resolvedDefaultButtonText,\n resolvedDefaultInputText,\n resolvedDefaultSelectedValues: stableDefaultSelectedValues,\n });\n\n componentRuntimeValuesRef.current = {\n direction,\n language,\n mermaidMessages,\n beforeSend,\n locale,\n onClickCustomButtonAfterContent,\n onSend,\n readonly,\n renderContent,\n resolvedConfirmButtonText,\n resolvedCopiedButtonText,\n resolvedCopyButtonText,\n resolvedDefaultButtonText,\n resolvedDefaultInputText,\n resolvedDefaultSelectedValues: stableDefaultSelectedValues,\n };\n\n const components = useMemo<CustomComponents>(\n () => ({\n \"custom-button-after-content\": ({\n children,\n }: {\n children: React.ReactNode;\n }) => {\n return (\n <button\n className=\"content-render-custom-button-after-content\"\n onClick={\n componentRuntimeValuesRef.current.onClickCustomButtonAfterContent\n }\n >\n <span className=\"content-render-custom-button-after-content-inner\">\n {children}\n </span>\n </button>\n );\n },\n \"custom-variable\": (props) => (\n <CustomButtonInputVariable\n {...props}\n readonly={componentRuntimeValuesRef.current.readonly}\n defaultButtonText={\n componentRuntimeValuesRef.current.resolvedDefaultButtonText\n }\n defaultInputText={\n componentRuntimeValuesRef.current.resolvedDefaultInputText\n }\n defaultSelectedValues={\n componentRuntimeValuesRef.current.resolvedDefaultSelectedValues\n }\n onSend={componentRuntimeValuesRef.current.onSend}\n beforeSend={componentRuntimeValuesRef.current.beforeSend}\n locale={componentRuntimeValuesRef.current.locale}\n dir={componentRuntimeValuesRef.current.direction}\n lang={componentRuntimeValuesRef.current.language}\n confirmButtonText={\n componentRuntimeValuesRef.current.resolvedConfirmButtonText\n }\n // tooltipMinLength={tooltipMinLength}\n />\n ),\n code: MarkdownCode,\n table: ({ ...props }) => (\n <div className=\"content-render-table-container\">\n <table className=\"content-render-table\" {...props} />\n </div>\n ),\n th: ({ ...props }) => <th className=\"content-render-th\" {...props} />,\n td: ({ ...props }) => <td className=\"content-render-td\" {...props} />,\n tr: ({ ...props }) => <tr className=\"content-render-tr\" {...props} />,\n li: ({ node, ...props }) => {\n const className = node?.properties?.className;\n const hasTaskListItem =\n (typeof className === \"string\" &&\n className.includes(\"task-list-item\")) ||\n (Array.isArray(className) && className.includes(\"task-list-item\"));\n if (hasTaskListItem) {\n return <li className=\"content-render-task-list-item\" {...props} />;\n }\n return <li {...props} />;\n },\n ol: ({ ...props }) => <ol className=\"content-render-ol\" {...props} />,\n ul: ({ ...props }) => <ul className=\"content-render-ul\" {...props} />,\n input: ({ ...props }) => {\n if (props.type === \"checkbox\") {\n return (\n <input\n type=\"checkbox\"\n className=\"content-render-checkbox\"\n disabled\n {...props}\n />\n );\n }\n return <input {...props} />;\n },\n a: ({ children, ...props }) => (\n <a target=\"_blank\" rel=\"noopener noreferrer\" {...props}>\n {children}\n </a>\n ),\n pre: (props) => (\n <CodeBlock\n {...props}\n copyButtonText={\n componentRuntimeValuesRef.current.resolvedCopyButtonText\n }\n copiedButtonText={\n componentRuntimeValuesRef.current.resolvedCopiedButtonText\n }\n />\n ),\n }),\n []\n );\n\n const segments = useMemo(\n () => parseMarkdownSegments(safeMarkdownContent),\n [safeMarkdownContent]\n );\n\n const renderMarkdownSegments = (raw: string, keyPrefix: string) => {\n const normalized = normalizeInlineHtml(raw);\n const parsed = parseMarkdownSegments(normalized);\n\n return parsed.map((seg, index) => {\n const key = `${keyPrefix}-${seg.type}-${index}`;\n\n if (seg.type === \"text\") {\n return (\n <MarkdownComponentRuntimeContext.Provider\n key={key}\n value={componentRuntimeValuesRef}\n >\n <MarkdownRenderer\n locale={locale}\n components={components}\n content={seg.value}\n />\n </MarkdownComponentRuntimeContext.Provider>\n );\n }\n\n if (seg.type === \"mermaid\") {\n return (\n <MermaidChart\n key={key}\n chart={seg.value}\n frozen={!seg.complete}\n messages={mermaidMessages}\n />\n );\n }\n\n if (seg.type === \"svg\") {\n return <SvgBlockInShadow key={key} svg={seg.value} />;\n }\n\n return null;\n });\n };\n\n const customBar = customRenderBar ? (\n <div className=\"content-render-custom-bar\">\n {React.createElement(customRenderBar, {\n content,\n displayContent: normalizedContent,\n onSend,\n })}\n </div>\n ) : null;\n\n if (hasRichSegments) {\n return (\n <div\n className=\"content-render markdown-body\"\n dir={direction}\n lang={language}\n >\n {richRenderRuns.map((run) => {\n const idx = run.indices[0];\n const segment = mergedRenderSegments[idx];\n if (run.sandbox)\n return segment.type === \"sandbox\" &&\n segment.value &&\n !segment.pending ? (\n <IframeSandbox\n key={`sandbox-${idx}`}\n hideFullScreen\n type=\"sandbox\"\n content={segment.value}\n className=\"content-render-iframe\"\n locale={locale}\n dir={direction}\n lang={language}\n loadingText={sandboxLoadingText}\n styleLoadingText={sandboxStyleLoadingText}\n scriptLoadingText={sandboxScriptLoadingText}\n disableLoadingOverlay={disableSandboxLoadingOverlay}\n fullScreenButtonText={resolvedSandboxFullscreenButtonText}\n exitFullScreenButtonText={\n resolvedSandboxExitFullscreenButtonText\n }\n mode={sandboxMode}\n />\n ) : null;\n if (run.plan)\n return (\n <MarkdownComponentRuntimeContext.Provider\n key={`md-${idx}`}\n value={componentRuntimeValuesRef}\n >\n <StableVideoMarkdownRenderer\n locale={locale}\n components={components}\n plan={run.plan}\n renderedSegments={run.indices.map(\n (index) => mergedRenderSegments[index]\n )}\n />\n </MarkdownComponentRuntimeContext.Provider>\n );\n return run.indices.map((index) => (\n <React.Fragment key={`md-${index}`}>\n {mergedRenderSegments[index].type === \"markdown\" &&\n mergedRenderSegments[index].pending\n ? null\n : renderMarkdownSegments(\n safeRichMarkdownContent[index],\n `md-${index}`\n )}\n </React.Fragment>\n ));\n })}\n {customBar}\n </div>\n );\n }\n\n return (\n <div\n className=\"content-render markdown-body\"\n dir={direction}\n lang={language}\n >\n {segments.map((seg, index) => {\n if (seg.type === \"text\") {\n return (\n <MarkdownComponentRuntimeContext.Provider\n key={index}\n value={componentRuntimeValuesRef}\n >\n <MarkdownRenderer\n locale={locale}\n components={components}\n content={seg.value}\n />\n </MarkdownComponentRuntimeContext.Provider>\n );\n }\n\n if (seg.type === \"mermaid\") {\n return (\n <MermaidChart\n key={index}\n chart={seg.value}\n frozen={!seg.complete}\n messages={mermaidMessages}\n />\n );\n }\n\n if (seg.type === \"svg\") {\n return <SvgBlockInShadow key={index} svg={seg.value} />;\n }\n })}\n\n {customBar}\n </div>\n );\n};\n\nexport default ContentRender;\n"],"names":["FIXED_TYPEWRITER_CHUNK_SIZE","SvgBlockInShadow","svg","inline","hostRef","useRef","Wrapper","useEffect","host","shadowRoot","styleId","styleEl","node","template","cleanedSvg","stripSvgTextLineBreaks","hasResponsiveSvg","hasFixedSvg","svgEl","viewBox","dimensions","value","viewBoxWidth","viewBoxHeight","widthAttr","heightAttr","isRelativeLength","normalized","toNumericLength","parsed","isWidthRelative","isHeightRelative","widthMissing","heightMissing","numericWidth","numericHeight","hostResponsive","jsx","MarkdownComponentRuntimeContext","React","MarkdownCode","props","receivedTree","codeProps","runtimeValuesRef","isInCodeBlock","CodeBlockContext","className","children","rest","chartContent","complete","mermaidBlockIsComplete","frozen","MermaidChart","sourceRehypePlugins","preserveCustomVariableProperties","rehypeRaw","sanitizeInvalidTagName","restoreCustomVariableProperties","formattingRehypePlugins","rehypeHighlight","highlightLanguages","subsetLanguages","rehypeKatex","rehypePlugins","MarkdownRenderer","markdownContent","components","locale","texts","getContentRenderLocaleTexts","ReactMarkdown","remarkPlugins","referenceIndex","rereferenceIndex","reference","usePreparedTree","StableVideoMarkdownRenderer","plan","renderedSegments","prepared","useMemo","sourceProcessor","unified","remarkRehype","formattingProcessor","tree","cloneVideoMarkdownSourceTree","prepareVideoMarkdownRun","projected","projectVideoMarkdownRun","originalComponents","wrappers","stableComponents","tags","collect","result","tag","Component","state","getVideoMarkdownNodeState","Fragment","Original","visibleProps","preparedPlugins","isImmediateSegment","segment","mergeNonSandboxSegments","segments","merged","last","closeTypedInlineCode","visible","source","ranges","range","start","end","delimiter","closingStart","protectTypedMarkdownPrefix","inlineCodeRanges","metadataRanges","sourceOffset","closed","escapeTypedMarkdownMetadata","splitTextByCharacterChunk","chunkSize","safeChunkSize","characters","areStringArraysEqual","left","right","index","useStableStringArray","values","valuesRef","ContentRender","content","contentType","lang","dir","customRenderBar","onSend","typingSpeed","enableTypewriter","typewriterPacing","onTypeFinished","onTypewriterStateChange","userInput","interactionDefaultValueOptions","defaultButtonText","defaultInputText","defaultSelectedValues","readonly","confirmButtonText","copyButtonText","copiedButtonText","sandboxLoadingText","sandboxStyleLoadingText","sandboxScriptLoadingText","disableSandboxLoadingOverlay","sandboxFullscreenButtonText","sandboxExitFullscreenButtonText","sandboxMode","onClickCustomButtonAfterContent","beforeSend","localeTexts","mermaidMessages","direction","getMarkdownFlowDirection","language","getMarkdownFlowLanguage","resolvedConfirmButtonText","resolvedCopyButtonText","resolvedCopiedButtonText","resolvedSandboxFullscreenButtonText","resolvedSandboxExitFullscreenButtonText","isTypewriterEnabled","sourceContent","normalizeWrappedSandboxContent","sourceAnalysis","getMarkdownSourceAnalysis","sourceSegments","splitContentSegments","hasRichSegments","typewriterContent","typewriterTickMs","fixedTypewriterContentVersion","displayContent","setDisplayContent","useState","displayContentRef","pendingContentRef","contentAwareQueueRef","contentAwareBudgetRef","previousTypewriterEnabledRef","previousTypewriterPacingRef","previousSourceContentRef","previousReceivedContentRef","hasReportedTypeFinishedRef","typewriterWakeVersion","setTypewriterWakeVersion","wasTypewriterEnabled","previousTypewriterPacing","previousSourceContent","wasPending","receivedContentChanged","receivedContentAppended","clearPendingContent","updateDisplayContent","nextContent","visibleContent","getTrailingTypewriterGrapheme","sharedLength","nextPendingContent","previousPendingContent","appended","appendContentAwareTypewriterQueue","version","typewriterTimer","chunk","consumeContentAwareTypewriterQueue","CONTENT_AWARE_TYPEWRITER_TICK_BUDGET","isContentAwareTypewriterQueueEmpty","nextDisplayContent","mergedRenderSegments","textOffset","typewriterState","remaining","sourceSegmentOffsets","offset","sourceInlineCodeRanges","getInlineCodeRanges","safeRichMarkdownContent","richRenderRuns","runs","previous","run","fullSource","createVideoMarkdownRunPlan","renderContent","normalizedContent","normalizeInlineHtml","safeMarkdownContent","interactionDefaults","getInteractionDefaultValues","resolvedDefaultButtonText","trimVariablePadding","resolvedDefaultInputText","fallbackSelectedValues","resolvedDefaultSelectedValues","stableDefaultSelectedValues","componentRuntimeValuesRef","CustomButtonInputVariable","CodeBlock","parseMarkdownSegments","renderMarkdownSegments","raw","keyPrefix","seg","key","customBar","jsxs","idx","IframeSandbox"],"mappings":"wjDA6EMA,GAA8B,EA6E9BC,GAAgE,CAAC,CACrE,IAAAC,EACA,OAAAC,EAAS,EACX,IAAM,CACJ,MAAMC,EAAUC,EAAAA,OAA2B,IAAI,EACzCC,EAAUH,EAAS,OAAS,MAElCI,OAAAA,EAAAA,UAAU,IAAM,CACd,MAAMC,EAAOJ,EAAQ,QACrB,GAAI,CAACI,EAAM,OACX,MAAMC,EAAaD,EAAK,YAAcA,EAAK,aAAa,CAAE,KAAM,OAAQ,EAClEE,EAAU,2BAChB,IAAIC,EAAUF,EAAW,eAAeC,CAAO,EAE1CC,IACHA,EAAU,SAAS,cAAc,OAAO,EACxCA,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