@lobehub/ui 5.10.3 → 5.10.5
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.
- package/es/Highlighter/style.mjs +1 -1
- package/es/HtmlPreview/HtmlPreview.d.mts +8 -0
- package/es/HtmlPreview/HtmlPreview.mjs +377 -0
- package/es/HtmlPreview/HtmlPreview.mjs.map +1 -0
- package/es/HtmlPreview/Iframe.d.mts +8 -0
- package/es/HtmlPreview/Iframe.mjs +159 -0
- package/es/HtmlPreview/Iframe.mjs.map +1 -0
- package/es/HtmlPreview/buildShellSrcDoc.mjs +235 -0
- package/es/HtmlPreview/buildShellSrcDoc.mjs.map +1 -0
- package/es/HtmlPreview/buildStaticSrcDoc.mjs +44 -0
- package/es/HtmlPreview/buildStaticSrcDoc.mjs.map +1 -0
- package/es/HtmlPreview/const.d.mts +42 -0
- package/es/HtmlPreview/const.mjs +63 -0
- package/es/HtmlPreview/const.mjs.map +1 -0
- package/es/HtmlPreview/index.d.mts +6 -0
- package/es/HtmlPreview/index.d.ts +1 -0
- package/es/HtmlPreview/index.js +1 -0
- package/es/HtmlPreview/index.mjs +5 -0
- package/es/HtmlPreview/injectAutoHeightScript.d.mts +5 -0
- package/es/HtmlPreview/injectAutoHeightScript.mjs +37 -0
- package/es/HtmlPreview/injectAutoHeightScript.mjs.map +1 -0
- package/es/HtmlPreview/injectStorageShim.mjs +62 -0
- package/es/HtmlPreview/injectStorageShim.mjs.map +1 -0
- package/es/HtmlPreview/type.d.mts +114 -0
- package/es/Markdown/Markdown.mjs +7 -3
- package/es/Markdown/Markdown.mjs.map +1 -1
- package/es/Markdown/SyntaxMarkdown/StreamdownRender.mjs +2 -17
- package/es/Markdown/SyntaxMarkdown/StreamdownRender.mjs.map +1 -1
- package/es/Markdown/SyntaxMarkdown/fenceState.mjs +40 -0
- package/es/Markdown/SyntaxMarkdown/fenceState.mjs.map +1 -0
- package/es/Markdown/SyntaxMarkdown/useSmoothStreamContent.mjs +13 -0
- package/es/Markdown/SyntaxMarkdown/useSmoothStreamContent.mjs.map +1 -1
- package/es/Markdown/components/CodeBlock.mjs +10 -2
- package/es/Markdown/components/CodeBlock.mjs.map +1 -1
- package/es/Markdown/type.d.mts +3 -0
- package/es/NeuralNetworkLoading/NeuralNetworkLoading.d.mts +8 -0
- package/es/NeuralNetworkLoading/NeuralNetworkLoading.mjs +142 -0
- package/es/NeuralNetworkLoading/NeuralNetworkLoading.mjs.map +1 -0
- package/es/NeuralNetworkLoading/index.d.mts +3 -0
- package/es/NeuralNetworkLoading/index.d.ts +1 -0
- package/es/NeuralNetworkLoading/index.js +1 -0
- package/es/NeuralNetworkLoading/index.mjs +2 -0
- package/es/NeuralNetworkLoading/type.d.mts +12 -0
- package/es/hooks/useMarkdown/useMarkdownComponents.mjs +9 -2
- package/es/hooks/useMarkdown/useMarkdownComponents.mjs.map +1 -1
- package/es/hooks/useStableValue.mjs +30 -0
- package/es/hooks/useStableValue.mjs.map +1 -0
- package/es/index.d.mts +8 -1
- package/es/index.mjs +7 -2
- package/es/mdx/mdxComponents/Pre.mjs +14 -1
- package/es/mdx/mdxComponents/Pre.mjs.map +1 -1
- package/es/utils/isDeepEqual.mjs +21 -0
- package/es/utils/isDeepEqual.mjs.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { DivProps } from "../types/index.mjs";
|
|
2
|
+
import { ActionIconProps } from "../ActionIcon/type.mjs";
|
|
3
|
+
import { CSSProperties, ReactNode, Ref } from "react";
|
|
4
|
+
|
|
5
|
+
//#region src/HtmlPreview/type.d.ts
|
|
6
|
+
type HtmlPreviewMode = 'preview' | 'source';
|
|
7
|
+
/**
|
|
8
|
+
* How to handle the preview while content is still streaming (`animated`):
|
|
9
|
+
*
|
|
10
|
+
* - `'defer'` — keep the iframe unmounted until the content stabilizes
|
|
11
|
+
* (`</html>` arrives or `animated` flips to false). Safest for
|
|
12
|
+
* script-heavy demos (p5.js, three.js) where `setup()` must run exactly
|
|
13
|
+
* once.
|
|
14
|
+
* - `'live'` — mount the iframe immediately and update `srcDoc` as tokens
|
|
15
|
+
* arrive. Feels responsive for pure-markup content but reboots scripts
|
|
16
|
+
* on every chunk.
|
|
17
|
+
* - `'auto'` (default) — `defer` if a `<script>` tag is present, otherwise
|
|
18
|
+
* `live`.
|
|
19
|
+
*/
|
|
20
|
+
type HtmlPreviewStreamingMode = 'defer' | 'live' | 'auto';
|
|
21
|
+
interface HtmlPreviewIframeProps {
|
|
22
|
+
/**
|
|
23
|
+
* When `true` the iframe stays mounted as a "shell" and content arrives
|
|
24
|
+
* via postMessage + DOM morph — used during streaming so we can fade
|
|
25
|
+
* new nodes in without reloading. When `false` the iframe loads the
|
|
26
|
+
* user's HTML directly as `srcDoc`, which lets the browser's native
|
|
27
|
+
* HTML pipeline handle `<script src>` tags (Tailwind / Chart.js /
|
|
28
|
+
* p5.js style CDN integrations work the way they would on a normal
|
|
29
|
+
* page).
|
|
30
|
+
*/
|
|
31
|
+
animated?: boolean;
|
|
32
|
+
background?: string;
|
|
33
|
+
className?: string;
|
|
34
|
+
content: string;
|
|
35
|
+
defaultHeight?: number;
|
|
36
|
+
ref?: Ref<HTMLIFrameElement>;
|
|
37
|
+
sandbox?: string;
|
|
38
|
+
style?: CSSProperties;
|
|
39
|
+
title?: string;
|
|
40
|
+
}
|
|
41
|
+
interface HtmlPreviewProps extends Omit<DivProps, 'onCopy'> {
|
|
42
|
+
actionIconSize?: ActionIconProps['size'];
|
|
43
|
+
actionsRender?: (props: {
|
|
44
|
+
actionIconSize: ActionIconProps['size'];
|
|
45
|
+
content: string;
|
|
46
|
+
getContent: () => string;
|
|
47
|
+
mode: HtmlPreviewMode;
|
|
48
|
+
originalNode: ReactNode;
|
|
49
|
+
setMode: (mode: HtmlPreviewMode) => void;
|
|
50
|
+
}) => ReactNode;
|
|
51
|
+
/**
|
|
52
|
+
* When `true`, the component treats the content as a still-streaming document
|
|
53
|
+
* and only renders the source view. The iframe mounts once streaming ends
|
|
54
|
+
* (either `animated` flips to `false` or `</html>` appears in the content).
|
|
55
|
+
*
|
|
56
|
+
* This avoids re-booting iframes (and the scripts inside them) on every
|
|
57
|
+
* token.
|
|
58
|
+
*/
|
|
59
|
+
animated?: boolean;
|
|
60
|
+
bodyRender?: (props: {
|
|
61
|
+
content: string;
|
|
62
|
+
mode: HtmlPreviewMode;
|
|
63
|
+
originalNode: ReactNode;
|
|
64
|
+
}) => ReactNode;
|
|
65
|
+
children: string;
|
|
66
|
+
classNames?: {
|
|
67
|
+
content?: string;
|
|
68
|
+
header?: string;
|
|
69
|
+
iframe?: string;
|
|
70
|
+
};
|
|
71
|
+
copyable?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Accepted for API compatibility with the rest of the Pre family. Has no
|
|
74
|
+
* effect — the body is always rendered.
|
|
75
|
+
*/
|
|
76
|
+
defaultExpand?: boolean;
|
|
77
|
+
defaultHeight?: number;
|
|
78
|
+
defaultMode?: HtmlPreviewMode;
|
|
79
|
+
downloadable?: boolean;
|
|
80
|
+
fileName?: string;
|
|
81
|
+
/**
|
|
82
|
+
* Accepted for API compatibility with the rest of the Pre family. The
|
|
83
|
+
* toolbar is always inline, so this flag is a no-op.
|
|
84
|
+
*/
|
|
85
|
+
fullFeatured?: boolean;
|
|
86
|
+
language?: string;
|
|
87
|
+
/**
|
|
88
|
+
* Fires when the user clicks the expand button. Receives the full HTML.
|
|
89
|
+
* Hosts typically open a portal/drawer/modal here.
|
|
90
|
+
*/
|
|
91
|
+
onExpand?: (content: string) => void;
|
|
92
|
+
/**
|
|
93
|
+
* Override the iframe's `sandbox` attribute. **Strongly discouraged** —
|
|
94
|
+
* the default omits `allow-same-origin` and other privileges on purpose
|
|
95
|
+
* (see `const.ts` for rationale). If you override it, you take
|
|
96
|
+
* responsibility for the security boundary.
|
|
97
|
+
*/
|
|
98
|
+
sandbox?: string;
|
|
99
|
+
shadow?: boolean;
|
|
100
|
+
/** Accepted for API compatibility — the inline toolbar has no language tag. */
|
|
101
|
+
showLanguage?: boolean;
|
|
102
|
+
/** @see {@link HtmlPreviewStreamingMode} */
|
|
103
|
+
streamingMode?: HtmlPreviewStreamingMode;
|
|
104
|
+
styles?: {
|
|
105
|
+
content?: CSSProperties;
|
|
106
|
+
header?: CSSProperties;
|
|
107
|
+
iframe?: CSSProperties;
|
|
108
|
+
};
|
|
109
|
+
theme?: 'light' | 'dark';
|
|
110
|
+
variant?: 'filled' | 'outlined' | 'borderless';
|
|
111
|
+
}
|
|
112
|
+
//#endregion
|
|
113
|
+
export { HtmlPreviewIframeProps, HtmlPreviewMode, HtmlPreviewProps, HtmlPreviewStreamingMode };
|
|
114
|
+
//# sourceMappingURL=type.d.mts.map
|
package/es/Markdown/Markdown.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import PreviewGroup from "../Image/PreviewGroup.mjs";
|
|
3
|
+
import { useStableValue } from "../hooks/useStableValue.mjs";
|
|
3
4
|
import { MarkdownProvider } from "./components/MarkdownProvider.mjs";
|
|
4
5
|
import { useDelayedAnimated } from "./components/useDelayedAnimated.mjs";
|
|
5
6
|
import { variants } from "./style.mjs";
|
|
@@ -11,8 +12,10 @@ import { jsx } from "react/jsx-runtime";
|
|
|
11
12
|
import { cx } from "antd-style";
|
|
12
13
|
//#region src/Markdown/Markdown.tsx
|
|
13
14
|
const Markdown = memo((props) => {
|
|
14
|
-
const { ref, children = "", className, style, fullFeaturedCodeBlock, onDoubleClick, animated, enableLatex = true, enableMermaid = true, enableImageGallery, enableCustomFootnotes, enableGithubAlert, enableStream = true, componentProps, rehypePluginsAhead, allowHtml, borderRadius, fontSize = props.variant === "chat" ? 14 : void 0, headerMultiple = props.variant === "chat" ? .25 : void 0, marginMultiple = props.variant === "chat" ? 1 : void 0, variant = "default", reactMarkdownProps, lineHeight = props.variant === "chat" ? 1.6 : void 0, rehypePlugins, remarkPlugins, remarkPluginsAhead, components = {}, customRender, showFootnotes = true, streamSmoothingPreset, citations, ...rest } = props;
|
|
15
|
+
const { ref, children = "", className, style, fullFeaturedCodeBlock, onDoubleClick, animated, enableHtmlPreview = false, enableLatex = true, enableMermaid = true, enableImageGallery, enableCustomFootnotes, enableGithubAlert, enableStream = true, componentProps, rehypePluginsAhead, allowHtml, borderRadius, fontSize = props.variant === "chat" ? 14 : void 0, headerMultiple = props.variant === "chat" ? .25 : void 0, marginMultiple = props.variant === "chat" ? 1 : void 0, variant = "default", reactMarkdownProps, lineHeight = props.variant === "chat" ? 1.6 : void 0, rehypePlugins, remarkPlugins, remarkPluginsAhead, components = {}, customRender, showFootnotes = true, streamSmoothingPreset, citations, ...rest } = props;
|
|
15
16
|
const delayedAnimated = useDelayedAnimated(animated);
|
|
17
|
+
const stableComponentProps = useStableValue(componentProps);
|
|
18
|
+
const stableComponents = useStableValue(components);
|
|
16
19
|
const Render = useCallback(({ enableStream, children, reactMarkdownProps }) => {
|
|
17
20
|
const defaultDOM = /* @__PURE__ */ jsx(enableStream ? StreamdownRender : MarkdownRenderer, {
|
|
18
21
|
...reactMarkdownProps,
|
|
@@ -41,10 +44,11 @@ const Markdown = memo((props) => {
|
|
|
41
44
|
allowHtml,
|
|
42
45
|
animated: delayedAnimated,
|
|
43
46
|
citations,
|
|
44
|
-
componentProps,
|
|
45
|
-
components,
|
|
47
|
+
componentProps: stableComponentProps,
|
|
48
|
+
components: stableComponents,
|
|
46
49
|
enableCustomFootnotes,
|
|
47
50
|
enableGithubAlert,
|
|
51
|
+
enableHtmlPreview,
|
|
48
52
|
enableLatex,
|
|
49
53
|
enableMermaid,
|
|
50
54
|
fullFeaturedCodeBlock,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Markdown.mjs","names":["MarkdownRender"],"sources":["../../src/Markdown/Markdown.tsx"],"sourcesContent":["'use client';\n\nimport { cx } from 'antd-style';\nimport { memo, useCallback } from 'react';\n\nimport { PreviewGroup } from '@/Image';\n\nimport { MarkdownProvider } from './components/MarkdownProvider';\nimport { useDelayedAnimated } from './components/useDelayedAnimated';\nimport { variants } from './style';\nimport { MarkdownRender, StreamdownRender } from './SyntaxMarkdown';\nimport { type MarkdownProps } from './type';\nimport Typography from './Typography';\n\nconst Markdown = memo<MarkdownProps>((props) => {\n const {\n ref,\n children = '',\n className,\n style,\n fullFeaturedCodeBlock,\n onDoubleClick,\n animated,\n enableLatex = true,\n enableMermaid = true,\n enableImageGallery,\n enableCustomFootnotes,\n enableGithubAlert,\n enableStream = true,\n componentProps,\n rehypePluginsAhead,\n allowHtml,\n borderRadius,\n fontSize = props.variant === 'chat' ? 14 : undefined,\n headerMultiple = props.variant === 'chat' ? 0.25 : undefined,\n marginMultiple = props.variant === 'chat' ? 1 : undefined,\n variant = 'default',\n reactMarkdownProps,\n lineHeight = props.variant === 'chat' ? 1.6 : undefined,\n rehypePlugins,\n remarkPlugins,\n remarkPluginsAhead,\n components = {},\n customRender,\n showFootnotes = true,\n streamSmoothingPreset,\n citations,\n ...rest\n } = props;\n\n const delayedAnimated = useDelayedAnimated(animated);\n\n const Render = useCallback(\n ({\n enableStream,\n children,\n reactMarkdownProps,\n }: Pick<MarkdownProps, 'children' | 'enableStream' | 'reactMarkdownProps'>) => {\n const DefaultRender = enableStream ? StreamdownRender : MarkdownRender;\n const defaultDOM = <DefaultRender {...reactMarkdownProps}>{children}</DefaultRender>;\n return customRender ? customRender(defaultDOM, { text: children }) : defaultDOM;\n },\n [customRender],\n );\n\n return (\n <PreviewGroup enable={enableImageGallery}>\n <Typography\n borderRadius={borderRadius}\n className={cx(variants({ enableLatex, variant }), className)}\n data-code-type=\"markdown\"\n fontSize={fontSize}\n headerMultiple={headerMultiple}\n lineHeight={lineHeight}\n marginMultiple={marginMultiple}\n ref={ref}\n style={style}\n onDoubleClick={onDoubleClick}\n {...rest}\n >\n <MarkdownProvider\n allowHtml={allowHtml}\n animated={delayedAnimated}\n citations={citations}\n componentProps={
|
|
1
|
+
{"version":3,"file":"Markdown.mjs","names":["MarkdownRender"],"sources":["../../src/Markdown/Markdown.tsx"],"sourcesContent":["'use client';\n\nimport { cx } from 'antd-style';\nimport { memo, useCallback } from 'react';\n\nimport { useStableValue } from '@/hooks/useStableValue';\nimport { PreviewGroup } from '@/Image';\n\nimport { MarkdownProvider } from './components/MarkdownProvider';\nimport { useDelayedAnimated } from './components/useDelayedAnimated';\nimport { variants } from './style';\nimport { MarkdownRender, StreamdownRender } from './SyntaxMarkdown';\nimport { type MarkdownProps } from './type';\nimport Typography from './Typography';\n\nconst Markdown = memo<MarkdownProps>((props) => {\n const {\n ref,\n children = '',\n className,\n style,\n fullFeaturedCodeBlock,\n onDoubleClick,\n animated,\n enableHtmlPreview = false,\n enableLatex = true,\n enableMermaid = true,\n enableImageGallery,\n enableCustomFootnotes,\n enableGithubAlert,\n enableStream = true,\n componentProps,\n rehypePluginsAhead,\n allowHtml,\n borderRadius,\n fontSize = props.variant === 'chat' ? 14 : undefined,\n headerMultiple = props.variant === 'chat' ? 0.25 : undefined,\n marginMultiple = props.variant === 'chat' ? 1 : undefined,\n variant = 'default',\n reactMarkdownProps,\n lineHeight = props.variant === 'chat' ? 1.6 : undefined,\n rehypePlugins,\n remarkPlugins,\n remarkPluginsAhead,\n components = {},\n customRender,\n showFootnotes = true,\n streamSmoothingPreset,\n citations,\n ...rest\n } = props;\n\n const delayedAnimated = useDelayedAnimated(animated);\n\n // Stabilise structural props so an inline `componentProps={{ html:\n // {...} }}` from the caller doesn't cascade through MarkdownProvider →\n // useMarkdownComponents → react-markdown's `components` and remount the\n // entire code-block subtree (including the HtmlPreview iframe) on\n // every parent render. The deep-equal compare treats inline literals\n // as the same object as long as their structure matches. Inline\n // callbacks (`actionsRender`, custom `components`) still need\n // `useCallback` at the call site — function bodies aren't compared.\n const stableComponentProps = useStableValue(componentProps);\n const stableComponents = useStableValue(components);\n\n const Render = useCallback(\n ({\n enableStream,\n children,\n reactMarkdownProps,\n }: Pick<MarkdownProps, 'children' | 'enableStream' | 'reactMarkdownProps'>) => {\n const DefaultRender = enableStream ? StreamdownRender : MarkdownRender;\n const defaultDOM = <DefaultRender {...reactMarkdownProps}>{children}</DefaultRender>;\n return customRender ? customRender(defaultDOM, { text: children }) : defaultDOM;\n },\n [customRender],\n );\n\n return (\n <PreviewGroup enable={enableImageGallery}>\n <Typography\n borderRadius={borderRadius}\n className={cx(variants({ enableLatex, variant }), className)}\n data-code-type=\"markdown\"\n fontSize={fontSize}\n headerMultiple={headerMultiple}\n lineHeight={lineHeight}\n marginMultiple={marginMultiple}\n ref={ref}\n style={style}\n onDoubleClick={onDoubleClick}\n {...rest}\n >\n <MarkdownProvider\n allowHtml={allowHtml}\n animated={delayedAnimated}\n citations={citations}\n componentProps={stableComponentProps}\n components={stableComponents}\n enableCustomFootnotes={enableCustomFootnotes}\n enableGithubAlert={enableGithubAlert}\n enableHtmlPreview={enableHtmlPreview}\n enableLatex={enableLatex}\n enableMermaid={enableMermaid}\n fullFeaturedCodeBlock={fullFeaturedCodeBlock}\n rehypePlugins={rehypePlugins}\n rehypePluginsAhead={rehypePluginsAhead}\n remarkPlugins={remarkPlugins}\n remarkPluginsAhead={remarkPluginsAhead}\n showFootnotes={showFootnotes}\n streamSmoothingPreset={streamSmoothingPreset}\n variant={variant}\n >\n <Render\n enableStream={enableStream && delayedAnimated}\n reactMarkdownProps={reactMarkdownProps}\n >\n {children}\n </Render>\n </MarkdownProvider>\n </Typography>\n </PreviewGroup>\n );\n});\n\nMarkdown.displayName = 'Markdown';\n\nexport default Markdown;\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAM,WAAW,MAAqB,UAAU;CAC9C,MAAM,EACJ,KACA,WAAW,IACX,WACA,OACA,uBACA,eACA,UACA,oBAAoB,OACpB,cAAc,MACd,gBAAgB,MAChB,oBACA,uBACA,mBACA,eAAe,MACf,gBACA,oBACA,WACA,cACA,WAAW,MAAM,YAAY,SAAS,KAAK,KAAA,GAC3C,iBAAiB,MAAM,YAAY,SAAS,MAAO,KAAA,GACnD,iBAAiB,MAAM,YAAY,SAAS,IAAI,KAAA,GAChD,UAAU,WACV,oBACA,aAAa,MAAM,YAAY,SAAS,MAAM,KAAA,GAC9C,eACA,eACA,oBACA,aAAa,EAAE,EACf,cACA,gBAAgB,MAChB,uBACA,WACA,GAAG,SACD;CAEJ,MAAM,kBAAkB,mBAAmB,SAAS;CAUpD,MAAM,uBAAuB,eAAe,eAAe;CAC3D,MAAM,mBAAmB,eAAe,WAAW;CAEnD,MAAM,SAAS,aACZ,EACC,cACA,UACA,yBAC6E;EAE7E,MAAM,aAAa,oBADG,eAAe,mBAAmBA,kBACrC;GAAe,GAAI;GAAqB;GAAyB,CAAA;AACpF,SAAO,eAAe,aAAa,YAAY,EAAE,MAAM,UAAU,CAAC,GAAG;IAEvE,CAAC,aAAa,CACf;AAED,QACE,oBAAC,cAAD;EAAc,QAAQ;YACpB,oBAAC,YAAD;GACgB;GACd,WAAW,GAAG,SAAS;IAAE;IAAa;IAAS,CAAC,EAAE,UAAU;GAC5D,kBAAe;GACL;GACM;GACJ;GACI;GACX;GACE;GACQ;GACf,GAAI;aAEJ,oBAAC,kBAAD;IACa;IACX,UAAU;IACC;IACX,gBAAgB;IAChB,YAAY;IACW;IACJ;IACA;IACN;IACE;IACQ;IACR;IACK;IACL;IACK;IACL;IACQ;IACd;cAET,oBAAC,QAAD;KACE,cAAc,gBAAgB;KACV;KAEnB;KACM,CAAA;IACQ,CAAA;GACR,CAAA;EACA,CAAA;EAEjB;AAEF,SAAS,cAAc"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
+
import { isDeepEqual } from "../../utils/isDeepEqual.mjs";
|
|
2
3
|
import { useMarkdownContext } from "../components/MarkdownProvider.mjs";
|
|
3
4
|
import { useMarkdownComponents } from "../../hooks/useMarkdown/useMarkdownComponents.mjs";
|
|
4
5
|
import { useMarkdownContent } from "../../hooks/useMarkdown/useMarkdownContent.mjs";
|
|
@@ -24,28 +25,12 @@ function countChars(text) {
|
|
|
24
25
|
function getNow() {
|
|
25
26
|
return typeof performance === "undefined" ? Date.now() : performance.now();
|
|
26
27
|
}
|
|
27
|
-
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
28
|
-
const isDeepEqualValue = (a, b) => {
|
|
29
|
-
if (a === b) return true;
|
|
30
|
-
if (Array.isArray(a) || Array.isArray(b)) {
|
|
31
|
-
if (!Array.isArray(a) || !Array.isArray(b)) return false;
|
|
32
|
-
if (a.length !== b.length) return false;
|
|
33
|
-
for (let i = 0; i < a.length; i++) if (!isDeepEqualValue(a[i], b[i])) return false;
|
|
34
|
-
return true;
|
|
35
|
-
}
|
|
36
|
-
if (!isRecord(a) || !isRecord(b)) return false;
|
|
37
|
-
const keysA = Object.keys(a);
|
|
38
|
-
const keysB = Object.keys(b);
|
|
39
|
-
if (keysA.length !== keysB.length) return false;
|
|
40
|
-
for (const key of keysA) if (!isDeepEqualValue(a[key], b[key])) return false;
|
|
41
|
-
return true;
|
|
42
|
-
};
|
|
43
28
|
const isSamePlugin = (prevPlugin, nextPlugin) => {
|
|
44
29
|
const prevTuple = Array.isArray(prevPlugin) ? prevPlugin : [prevPlugin];
|
|
45
30
|
const nextTuple = Array.isArray(nextPlugin) ? nextPlugin : [nextPlugin];
|
|
46
31
|
if (prevTuple.length !== nextTuple.length) return false;
|
|
47
32
|
if (prevTuple[0] !== nextTuple[0]) return false;
|
|
48
|
-
return
|
|
33
|
+
return isDeepEqual(prevTuple.slice(1), nextTuple.slice(1));
|
|
49
34
|
};
|
|
50
35
|
const isSamePlugins = (prevPlugins, nextPlugins) => {
|
|
51
36
|
if (prevPlugins === nextPlugins) return true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StreamdownRender.mjs","names":[],"sources":["../../../src/Markdown/SyntaxMarkdown/StreamdownRender.tsx"],"sourcesContent":["'use client';\n\nimport { marked } from 'marked';\nimport {\n memo,\n Profiler,\n type ProfilerOnRenderCallback,\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n} from 'react';\nimport Markdown, { type Options } from 'react-markdown';\nimport remend from 'remend';\nimport type { Pluggable, PluggableList } from 'unified';\n\nimport {\n useMarkdownComponents,\n useMarkdownContent,\n useMarkdownRehypePlugins,\n useMarkdownRemarkPlugins,\n} from '@/hooks/useMarkdown';\nimport { useMarkdownContext } from '@/Markdown/components/MarkdownProvider';\nimport { rehypeStreamAnimated } from '@/Markdown/plugins/rehypeStreamAnimated';\nimport { useStreamdownProfiler } from '@/Markdown/streamProfiler';\n\nimport { resolveBlockAnimationMeta } from './streamAnimationMeta';\nimport { styles } from './style';\nimport { useSmoothStreamContent } from './useSmoothStreamContent';\nimport { type BlockInfo, useStreamQueue } from './useStreamQueue';\n\nconst STREAM_FADE_DURATION = 280;\nconst REVEALED_STREAM_PLUGIN: Pluggable = [rehypeStreamAnimated, { revealed: true }];\n\nfunction countChars(text: string): number {\n return [...text].length;\n}\n\nfunction getNow(): number {\n return typeof performance === 'undefined' ? Date.now() : performance.now();\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst isDeepEqualValue = (a: unknown, b: unknown): boolean => {\n if (a === b) return true;\n\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b)) return false;\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!isDeepEqualValue(a[i], b[i])) return false;\n }\n return true;\n }\n\n if (!isRecord(a) || !isRecord(b)) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (!isDeepEqualValue(a[key], b[key])) return false;\n }\n\n return true;\n};\n\nconst isSamePlugin = (prevPlugin: Pluggable, nextPlugin: Pluggable): boolean => {\n const prevTuple = Array.isArray(prevPlugin) ? prevPlugin : [prevPlugin];\n const nextTuple = Array.isArray(nextPlugin) ? nextPlugin : [nextPlugin];\n\n if (prevTuple.length !== nextTuple.length) return false;\n if (prevTuple[0] !== nextTuple[0]) return false;\n\n return isDeepEqualValue(prevTuple.slice(1), nextTuple.slice(1));\n};\n\nconst isSamePlugins = (\n prevPlugins?: PluggableList | null,\n nextPlugins?: PluggableList | null,\n): boolean => {\n if (prevPlugins === nextPlugins) return true;\n if (!prevPlugins || !nextPlugins) return !prevPlugins && !nextPlugins;\n if (prevPlugins.length !== nextPlugins.length) return false;\n\n for (let i = 0; i < prevPlugins.length; i++) {\n if (!isSamePlugin(prevPlugins[i], nextPlugins[i])) return false;\n }\n\n return true;\n};\n\nconst useStablePlugins = (plugins: PluggableList): PluggableList => {\n const stableRef = useRef<PluggableList>(plugins);\n\n if (!isSamePlugins(stableRef.current, plugins)) {\n stableRef.current = plugins;\n }\n\n return stableRef.current;\n};\n\nconst StreamdownBlock = memo<Options>(\n ({ children, ...rest }) => {\n return <Markdown {...rest}>{children}</Markdown>;\n },\n (prevProps, nextProps) =>\n prevProps.children === nextProps.children &&\n prevProps.components === nextProps.components &&\n isSamePlugins(prevProps.rehypePlugins, nextProps.rehypePlugins) &&\n isSamePlugins(prevProps.remarkPlugins, nextProps.remarkPlugins),\n);\n\nStreamdownBlock.displayName = 'StreamdownBlock';\n\nexport const StreamdownRender = memo<Options>(({ children, ...rest }) => {\n const { streamSmoothingPreset = 'balanced' } = useMarkdownContext();\n const profiler = useStreamdownProfiler();\n const escapedContent = useMarkdownContent(children || '');\n const components = useMarkdownComponents();\n const baseRehypePlugins = useStablePlugins(useMarkdownRehypePlugins());\n const remarkPlugins = useStablePlugins(useMarkdownRemarkPlugins());\n const generatedId = useId();\n const smoothedContent = useSmoothStreamContent(\n typeof escapedContent === 'string' ? escapedContent : '',\n { preset: streamSmoothingPreset },\n );\n\n const processedContentResult = useMemo(() => {\n const start = profiler ? getNow() : 0;\n const value = remend(smoothedContent);\n\n return {\n durationMs: profiler ? getNow() - start : 0,\n value,\n };\n }, [profiler, smoothedContent]);\n const processedContent = processedContentResult.value;\n\n const blocksResult = useMemo(() => {\n const start = profiler ? getNow() : 0;\n const tokens = marked.lexer(processedContent);\n let offset = 0;\n\n const value = tokens.map((token) => {\n const block = { content: token.raw, startOffset: offset };\n offset += token.raw.length;\n return block;\n });\n\n return {\n durationMs: profiler ? getNow() - start : 0,\n value,\n };\n }, [processedContent, profiler]);\n const blocks: BlockInfo[] = blocksResult.value;\n\n const { getBlockState, charDelay } = useStreamQueue(blocks);\n const blockCharDelayRef = useRef<Map<number, number>>(new Map());\n const blockBirthsRef = useRef<Map<number, number[]>>(new Map());\n\n const renderNow = getNow();\n\n const birthsResult = useMemo(() => {\n const start = profiler ? getNow() : 0;\n const nextBirths = new Map<number, number[]>();\n const prevBirths = blockBirthsRef.current;\n\n for (const [index, block] of blocks.entries()) {\n const state = getBlockState(index);\n // Queued blocks are not rendered. Defer birth assignment so that\n // when the block later transitions to animating/streaming, its\n // chars start fading from that moment instead of having already\n // \"aged out\" of the fade window.\n if (state === 'queued') continue;\n\n const blockCharCount = countChars(block.content);\n const prev = prevBirths.get(block.startOffset);\n let arr: number[];\n\n if (prev && prev.length === blockCharCount) {\n arr = prev;\n } else if (prev && prev.length > blockCharCount) {\n // Block content shrunk (stream restart or upstream rewrite).\n arr = prev.slice(0, blockCharCount);\n } else {\n arr = prev ? prev.slice() : [];\n const startIdx = arr.length;\n // Chain each new char monotonically after the previous one so fades\n // never race out of order. Cap how far the fade queue can run ahead\n // of renderNow to prevent stream-faster-than-fade producing seconds\n // of invisible backlog at the tail.\n const cap = renderNow + STREAM_FADE_DURATION;\n for (let i = startIdx; i < blockCharCount; i++) {\n const prevBirth = i > 0 ? (arr[i - 1] as number) : renderNow - charDelay;\n const chained = prevBirth + charDelay;\n arr.push(Math.min(cap, Math.max(chained, renderNow)));\n }\n }\n\n nextBirths.set(block.startOffset, arr);\n }\n\n return {\n durationMs: profiler ? getNow() - start : 0,\n value: nextBirths,\n };\n }, [blocks, charDelay, getBlockState, profiler, renderNow]);\n const birthsForRender = birthsResult.value;\n\n useEffect(() => {\n if (!profiler) return;\n\n profiler.recordCalculation({\n durationMs: processedContentResult.durationMs,\n name: 'content-normalize',\n textLength: processedContent.length,\n });\n }, [processedContent.length, processedContentResult.durationMs, profiler]);\n\n useEffect(() => {\n if (!profiler) return;\n\n profiler.recordCalculation({\n durationMs: blocksResult.durationMs,\n itemCount: blocks.length,\n name: 'block-lex',\n textLength: processedContent.length,\n });\n }, [blocks.length, blocksResult.durationMs, processedContent.length, profiler]);\n\n useEffect(() => {\n if (!profiler) return;\n\n profiler.recordCalculation({\n durationMs: birthsResult.durationMs,\n itemCount: blocks.length,\n name: 'block-births',\n textLength: processedContent.length,\n });\n }, [birthsResult.durationMs, blocks.length, processedContent.length, profiler]);\n\n const blockAnimationMetaResult = useMemo(() => {\n const nextBlockCharDelay = new Map<number, number>();\n const blockAnimationMeta = new Map<number, ReturnType<typeof resolveBlockAnimationMeta>>();\n\n for (const [index, block] of blocks.entries()) {\n const state = getBlockState(index);\n const births = birthsForRender.get(block.startOffset);\n const lastBirthTs = births && births.length > 0 ? (births.at(-1) ?? renderNow) : renderNow;\n const lastElapsedMs = renderNow - lastBirthTs;\n const animationMeta = resolveBlockAnimationMeta({\n currentCharDelay: charDelay,\n fadeDuration: STREAM_FADE_DURATION,\n lastElapsedMs,\n previousCharDelay: blockCharDelayRef.current.get(block.startOffset),\n state,\n });\n\n nextBlockCharDelay.set(block.startOffset, animationMeta.charDelay);\n blockAnimationMeta.set(block.startOffset, animationMeta);\n }\n\n return {\n blockAnimationMeta,\n blockCharDelay: nextBlockCharDelay,\n };\n }, [birthsForRender, blocks, charDelay, getBlockState, renderNow]);\n\n useEffect(() => {\n blockCharDelayRef.current = blockAnimationMetaResult.blockCharDelay;\n blockBirthsRef.current = birthsForRender;\n }, [birthsForRender, blockAnimationMetaResult.blockCharDelay]);\n\n const handleRootRender = useCallback<ProfilerOnRenderCallback>(\n (_, phase, actualDuration, baseDuration) => {\n profiler?.recordRootCommit({\n actualDuration,\n baseDuration,\n blockCount: blocks.length,\n phase,\n textLength: processedContent.length,\n });\n },\n [blocks.length, processedContent.length, profiler],\n );\n\n const handleBlockRender = useCallback<ProfilerOnRenderCallback>(\n (id, phase, actualDuration, baseDuration) => {\n if (!profiler) return;\n\n const [, indexText, offsetText] = id.split(':');\n const blockIndex = Number(indexText);\n\n if (!Number.isFinite(blockIndex)) return;\n\n const block = blocks[blockIndex];\n if (!block) return;\n\n profiler.recordBlockCommit({\n actualDuration,\n baseDuration,\n blockChars: countChars(block.content),\n blockIndex,\n blockKey: offsetText ?? String(block.startOffset),\n phase,\n state: getBlockState(blockIndex),\n });\n },\n [blocks, getBlockState, profiler],\n );\n\n const content = (\n <div className={styles.animated}>\n {blocks.map((block, index) => {\n const state = getBlockState(index);\n if (state === 'queued') return null;\n const animationMeta = blockAnimationMetaResult.blockAnimationMeta.get(block.startOffset);\n if (!animationMeta) return null;\n\n const births = birthsForRender.get(block.startOffset);\n const plugins: Pluggable[] = animationMeta.settled\n ? [...baseRehypePlugins, REVEALED_STREAM_PLUGIN]\n : [\n ...baseRehypePlugins,\n [\n rehypeStreamAnimated,\n {\n births,\n fadeDuration: STREAM_FADE_DURATION,\n nowMs: renderNow,\n },\n ],\n ];\n\n const key = `${generatedId}-${block.startOffset}`;\n const blockNode = (\n <StreamdownBlock\n {...rest}\n components={components}\n rehypePlugins={plugins}\n remarkPlugins={remarkPlugins}\n >\n {block.content}\n </StreamdownBlock>\n );\n\n if (!profiler) {\n return (\n <StreamdownBlock\n {...rest}\n components={components}\n key={key}\n rehypePlugins={plugins}\n remarkPlugins={remarkPlugins}\n >\n {block.content}\n </StreamdownBlock>\n );\n }\n\n return (\n <Profiler\n id={`streamdown-block:${index}:${block.startOffset}`}\n key={key}\n onRender={handleBlockRender}\n >\n {blockNode}\n </Profiler>\n );\n })}\n </div>\n );\n\n if (!profiler) return content;\n\n return (\n <Profiler id={'streamdown-root'} onRender={handleRootRender}>\n {content}\n </Profiler>\n );\n});\n\nStreamdownRender.displayName = 'StreamdownRender';\n\nexport default StreamdownRender;\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3B,MAAM,SAAS,gBAAgB,IAAI,MAAM,YAAY;GACrD,MAAM,UAAuB,cAAc,UACvC,CAAC,GAAG,mBAAmB,uBAAuB,GAC9C,CACE,GAAG,mBACH,CACE,sBACA;IACE;IACA,cAAc;IACd,OAAO;IACR,CACF,CACF;GAEL,MAAM,MAAM,GAAG,YAAY,GAAG,MAAM;GACpC,MAAM,YACJ,oBAAC,iBAAD;IACE,GAAI;IACQ;IACZ,eAAe;IACA;cAEd,MAAM;IACS,CAAA;AAGpB,OAAI,CAAC,SACH,QACE,8BAAC,iBAAD;IACE,GAAI;IACQ;IACP;IACL,eAAe;IACA;IAGC,EADf,MAAM,QACS;AAItB,UACE,oBAAC,UAAD;IACE,IAAI,oBAAoB,MAAM,GAAG,MAAM;IAEvC,UAAU;cAET;IACQ,EAJJ,IAII;IAEb;EACE,CAAA;AAGR,KAAI,CAAC,SAAU,QAAO;AAEtB,QACE,oBAAC,UAAD;EAAU,IAAI;EAAmB,UAAU;YACxC;EACQ,CAAA;EAEb;AAEF,iBAAiB,cAAc"}
|
|
1
|
+
{"version":3,"file":"StreamdownRender.mjs","names":[],"sources":["../../../src/Markdown/SyntaxMarkdown/StreamdownRender.tsx"],"sourcesContent":["'use client';\n\nimport { marked } from 'marked';\nimport {\n memo,\n Profiler,\n type ProfilerOnRenderCallback,\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n} from 'react';\nimport Markdown, { type Options } from 'react-markdown';\nimport remend from 'remend';\nimport type { Pluggable, PluggableList } from 'unified';\n\nimport {\n useMarkdownComponents,\n useMarkdownContent,\n useMarkdownRehypePlugins,\n useMarkdownRemarkPlugins,\n} from '@/hooks/useMarkdown';\nimport { useMarkdownContext } from '@/Markdown/components/MarkdownProvider';\nimport { rehypeStreamAnimated } from '@/Markdown/plugins/rehypeStreamAnimated';\nimport { useStreamdownProfiler } from '@/Markdown/streamProfiler';\nimport { isDeepEqual } from '@/utils/isDeepEqual';\n\nimport { resolveBlockAnimationMeta } from './streamAnimationMeta';\nimport { styles } from './style';\nimport { useSmoothStreamContent } from './useSmoothStreamContent';\nimport { type BlockInfo, useStreamQueue } from './useStreamQueue';\n\nconst STREAM_FADE_DURATION = 280;\nconst REVEALED_STREAM_PLUGIN: Pluggable = [rehypeStreamAnimated, { revealed: true }];\n\nfunction countChars(text: string): number {\n return [...text].length;\n}\n\nfunction getNow(): number {\n return typeof performance === 'undefined' ? Date.now() : performance.now();\n}\n\nconst isSamePlugin = (prevPlugin: Pluggable, nextPlugin: Pluggable): boolean => {\n const prevTuple = Array.isArray(prevPlugin) ? prevPlugin : [prevPlugin];\n const nextTuple = Array.isArray(nextPlugin) ? nextPlugin : [nextPlugin];\n\n if (prevTuple.length !== nextTuple.length) return false;\n if (prevTuple[0] !== nextTuple[0]) return false;\n\n return isDeepEqual(prevTuple.slice(1), nextTuple.slice(1));\n};\n\nconst isSamePlugins = (\n prevPlugins?: PluggableList | null,\n nextPlugins?: PluggableList | null,\n): boolean => {\n if (prevPlugins === nextPlugins) return true;\n if (!prevPlugins || !nextPlugins) return !prevPlugins && !nextPlugins;\n if (prevPlugins.length !== nextPlugins.length) return false;\n\n for (let i = 0; i < prevPlugins.length; i++) {\n if (!isSamePlugin(prevPlugins[i], nextPlugins[i])) return false;\n }\n\n return true;\n};\n\nconst useStablePlugins = (plugins: PluggableList): PluggableList => {\n const stableRef = useRef<PluggableList>(plugins);\n\n if (!isSamePlugins(stableRef.current, plugins)) {\n stableRef.current = plugins;\n }\n\n return stableRef.current;\n};\n\nconst StreamdownBlock = memo<Options>(\n ({ children, ...rest }) => {\n return <Markdown {...rest}>{children}</Markdown>;\n },\n (prevProps, nextProps) =>\n prevProps.children === nextProps.children &&\n prevProps.components === nextProps.components &&\n isSamePlugins(prevProps.rehypePlugins, nextProps.rehypePlugins) &&\n isSamePlugins(prevProps.remarkPlugins, nextProps.remarkPlugins),\n);\n\nStreamdownBlock.displayName = 'StreamdownBlock';\n\nexport const StreamdownRender = memo<Options>(({ children, ...rest }) => {\n const { streamSmoothingPreset = 'balanced' } = useMarkdownContext();\n const profiler = useStreamdownProfiler();\n const escapedContent = useMarkdownContent(children || '');\n const components = useMarkdownComponents();\n const baseRehypePlugins = useStablePlugins(useMarkdownRehypePlugins());\n const remarkPlugins = useStablePlugins(useMarkdownRemarkPlugins());\n const generatedId = useId();\n const smoothedContent = useSmoothStreamContent(\n typeof escapedContent === 'string' ? escapedContent : '',\n { preset: streamSmoothingPreset },\n );\n\n const processedContentResult = useMemo(() => {\n const start = profiler ? getNow() : 0;\n const value = remend(smoothedContent);\n\n return {\n durationMs: profiler ? getNow() - start : 0,\n value,\n };\n }, [profiler, smoothedContent]);\n const processedContent = processedContentResult.value;\n\n const blocksResult = useMemo(() => {\n const start = profiler ? getNow() : 0;\n const tokens = marked.lexer(processedContent);\n let offset = 0;\n\n const value = tokens.map((token) => {\n const block = { content: token.raw, startOffset: offset };\n offset += token.raw.length;\n return block;\n });\n\n return {\n durationMs: profiler ? getNow() - start : 0,\n value,\n };\n }, [processedContent, profiler]);\n const blocks: BlockInfo[] = blocksResult.value;\n\n const { getBlockState, charDelay } = useStreamQueue(blocks);\n const blockCharDelayRef = useRef<Map<number, number>>(new Map());\n const blockBirthsRef = useRef<Map<number, number[]>>(new Map());\n\n const renderNow = getNow();\n\n const birthsResult = useMemo(() => {\n const start = profiler ? getNow() : 0;\n const nextBirths = new Map<number, number[]>();\n const prevBirths = blockBirthsRef.current;\n\n for (const [index, block] of blocks.entries()) {\n const state = getBlockState(index);\n // Queued blocks are not rendered. Defer birth assignment so that\n // when the block later transitions to animating/streaming, its\n // chars start fading from that moment instead of having already\n // \"aged out\" of the fade window.\n if (state === 'queued') continue;\n\n const blockCharCount = countChars(block.content);\n const prev = prevBirths.get(block.startOffset);\n let arr: number[];\n\n if (prev && prev.length === blockCharCount) {\n arr = prev;\n } else if (prev && prev.length > blockCharCount) {\n // Block content shrunk (stream restart or upstream rewrite).\n arr = prev.slice(0, blockCharCount);\n } else {\n arr = prev ? prev.slice() : [];\n const startIdx = arr.length;\n // Chain each new char monotonically after the previous one so fades\n // never race out of order. Cap how far the fade queue can run ahead\n // of renderNow to prevent stream-faster-than-fade producing seconds\n // of invisible backlog at the tail.\n const cap = renderNow + STREAM_FADE_DURATION;\n for (let i = startIdx; i < blockCharCount; i++) {\n const prevBirth = i > 0 ? (arr[i - 1] as number) : renderNow - charDelay;\n const chained = prevBirth + charDelay;\n arr.push(Math.min(cap, Math.max(chained, renderNow)));\n }\n }\n\n nextBirths.set(block.startOffset, arr);\n }\n\n return {\n durationMs: profiler ? getNow() - start : 0,\n value: nextBirths,\n };\n }, [blocks, charDelay, getBlockState, profiler, renderNow]);\n const birthsForRender = birthsResult.value;\n\n useEffect(() => {\n if (!profiler) return;\n\n profiler.recordCalculation({\n durationMs: processedContentResult.durationMs,\n name: 'content-normalize',\n textLength: processedContent.length,\n });\n }, [processedContent.length, processedContentResult.durationMs, profiler]);\n\n useEffect(() => {\n if (!profiler) return;\n\n profiler.recordCalculation({\n durationMs: blocksResult.durationMs,\n itemCount: blocks.length,\n name: 'block-lex',\n textLength: processedContent.length,\n });\n }, [blocks.length, blocksResult.durationMs, processedContent.length, profiler]);\n\n useEffect(() => {\n if (!profiler) return;\n\n profiler.recordCalculation({\n durationMs: birthsResult.durationMs,\n itemCount: blocks.length,\n name: 'block-births',\n textLength: processedContent.length,\n });\n }, [birthsResult.durationMs, blocks.length, processedContent.length, profiler]);\n\n const blockAnimationMetaResult = useMemo(() => {\n const nextBlockCharDelay = new Map<number, number>();\n const blockAnimationMeta = new Map<number, ReturnType<typeof resolveBlockAnimationMeta>>();\n\n for (const [index, block] of blocks.entries()) {\n const state = getBlockState(index);\n const births = birthsForRender.get(block.startOffset);\n const lastBirthTs = births && births.length > 0 ? (births.at(-1) ?? renderNow) : renderNow;\n const lastElapsedMs = renderNow - lastBirthTs;\n const animationMeta = resolveBlockAnimationMeta({\n currentCharDelay: charDelay,\n fadeDuration: STREAM_FADE_DURATION,\n lastElapsedMs,\n previousCharDelay: blockCharDelayRef.current.get(block.startOffset),\n state,\n });\n\n nextBlockCharDelay.set(block.startOffset, animationMeta.charDelay);\n blockAnimationMeta.set(block.startOffset, animationMeta);\n }\n\n return {\n blockAnimationMeta,\n blockCharDelay: nextBlockCharDelay,\n };\n }, [birthsForRender, blocks, charDelay, getBlockState, renderNow]);\n\n useEffect(() => {\n blockCharDelayRef.current = blockAnimationMetaResult.blockCharDelay;\n blockBirthsRef.current = birthsForRender;\n }, [birthsForRender, blockAnimationMetaResult.blockCharDelay]);\n\n const handleRootRender = useCallback<ProfilerOnRenderCallback>(\n (_, phase, actualDuration, baseDuration) => {\n profiler?.recordRootCommit({\n actualDuration,\n baseDuration,\n blockCount: blocks.length,\n phase,\n textLength: processedContent.length,\n });\n },\n [blocks.length, processedContent.length, profiler],\n );\n\n const handleBlockRender = useCallback<ProfilerOnRenderCallback>(\n (id, phase, actualDuration, baseDuration) => {\n if (!profiler) return;\n\n const [, indexText, offsetText] = id.split(':');\n const blockIndex = Number(indexText);\n\n if (!Number.isFinite(blockIndex)) return;\n\n const block = blocks[blockIndex];\n if (!block) return;\n\n profiler.recordBlockCommit({\n actualDuration,\n baseDuration,\n blockChars: countChars(block.content),\n blockIndex,\n blockKey: offsetText ?? String(block.startOffset),\n phase,\n state: getBlockState(blockIndex),\n });\n },\n [blocks, getBlockState, profiler],\n );\n\n const content = (\n <div className={styles.animated}>\n {blocks.map((block, index) => {\n const state = getBlockState(index);\n if (state === 'queued') return null;\n const animationMeta = blockAnimationMetaResult.blockAnimationMeta.get(block.startOffset);\n if (!animationMeta) return null;\n\n const births = birthsForRender.get(block.startOffset);\n const plugins: Pluggable[] = animationMeta.settled\n ? [...baseRehypePlugins, REVEALED_STREAM_PLUGIN]\n : [\n ...baseRehypePlugins,\n [\n rehypeStreamAnimated,\n {\n births,\n fadeDuration: STREAM_FADE_DURATION,\n nowMs: renderNow,\n },\n ],\n ];\n\n const key = `${generatedId}-${block.startOffset}`;\n const blockNode = (\n <StreamdownBlock\n {...rest}\n components={components}\n rehypePlugins={plugins}\n remarkPlugins={remarkPlugins}\n >\n {block.content}\n </StreamdownBlock>\n );\n\n if (!profiler) {\n return (\n <StreamdownBlock\n {...rest}\n components={components}\n key={key}\n rehypePlugins={plugins}\n remarkPlugins={remarkPlugins}\n >\n {block.content}\n </StreamdownBlock>\n );\n }\n\n return (\n <Profiler\n id={`streamdown-block:${index}:${block.startOffset}`}\n key={key}\n onRender={handleBlockRender}\n >\n {blockNode}\n </Profiler>\n );\n })}\n </div>\n );\n\n if (!profiler) return content;\n\n return (\n <Profiler id={'streamdown-root'} onRender={handleRootRender}>\n {content}\n </Profiler>\n );\n});\n\nStreamdownRender.displayName = 'StreamdownRender';\n\nexport default StreamdownRender;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,MAAM,uBAAuB;AAC7B,MAAM,yBAAoC,CAAC,sBAAsB,EAAE,UAAU,MAAM,CAAC;AAEpF,SAAS,WAAW,MAAsB;AACxC,QAAO,CAAC,GAAG,KAAK,CAAC;;AAGnB,SAAS,SAAiB;AACxB,QAAO,OAAO,gBAAgB,cAAc,KAAK,KAAK,GAAG,YAAY,KAAK;;AAG5E,MAAM,gBAAgB,YAAuB,eAAmC;CAC9E,MAAM,YAAY,MAAM,QAAQ,WAAW,GAAG,aAAa,CAAC,WAAW;CACvE,MAAM,YAAY,MAAM,QAAQ,WAAW,GAAG,aAAa,CAAC,WAAW;AAEvE,KAAI,UAAU,WAAW,UAAU,OAAQ,QAAO;AAClD,KAAI,UAAU,OAAO,UAAU,GAAI,QAAO;AAE1C,QAAO,YAAY,UAAU,MAAM,EAAE,EAAE,UAAU,MAAM,EAAE,CAAC;;AAG5D,MAAM,iBACJ,aACA,gBACY;AACZ,KAAI,gBAAgB,YAAa,QAAO;AACxC,KAAI,CAAC,eAAe,CAAC,YAAa,QAAO,CAAC,eAAe,CAAC;AAC1D,KAAI,YAAY,WAAW,YAAY,OAAQ,QAAO;AAEtD,MAAK,IAAI,I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E,GAAI;IACQ;IACZ,eAAe;IACA;cAEd,MAAM;IACS,CAAA;AAGpB,OAAI,CAAC,SACH,QACE,8BAAC,iBAAD;IACE,GAAI;IACQ;IACP;IACL,eAAe;IACA;IAGC,EADf,MAAM,QACS;AAItB,UACE,oBAAC,UAAD;IACE,IAAI,oBAAoB,MAAM,GAAG,MAAM;IAEvC,UAAU;cAET;IACQ,EAJJ,IAII;IAEb;EACE,CAAA;AAGR,KAAI,CAAC,SAAU,QAAO;AAEtB,QACE,oBAAC,UAAD;EAAU,IAAI;EAAmB,UAAU;YACxC;EACQ,CAAA;EAEb;AAEF,iBAAiB,cAAc"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
//#region src/Markdown/SyntaxMarkdown/fenceState.ts
|
|
2
|
+
/**
|
|
3
|
+
* Walk `content` and return the language of the last *unclosed* fenced
|
|
4
|
+
* code block, or `null` if every fence is closed (or there are none).
|
|
5
|
+
*
|
|
6
|
+
* Used by the smoother to decide whether to bypass its buffer for the
|
|
7
|
+
* current input. CommonMark recognises an opening fence as a line whose
|
|
8
|
+
* first non-space chars are 3+ backticks; we deliberately stay simple:
|
|
9
|
+
* 3 literal backticks at line start, language word after. That covers
|
|
10
|
+
* the markdown LLMs actually emit; tildes and indented fences fall back
|
|
11
|
+
* to normal smoothing rather than getting clever.
|
|
12
|
+
*
|
|
13
|
+
* Linear scan over the input, ~10ns per char on V8. Called on every
|
|
14
|
+
* smoothing tick during streaming so the simplicity matters.
|
|
15
|
+
*/
|
|
16
|
+
const findOpenFenceLanguage = (content) => {
|
|
17
|
+
let inFence = false;
|
|
18
|
+
let lang = "";
|
|
19
|
+
let i = 0;
|
|
20
|
+
const len = content.length;
|
|
21
|
+
while (i < len) {
|
|
22
|
+
const nl = content.indexOf("\n", i);
|
|
23
|
+
const lineEnd = nl === -1 ? len : nl;
|
|
24
|
+
const line = content.slice(i, lineEnd);
|
|
25
|
+
if (line.startsWith("```")) if (inFence) {
|
|
26
|
+
inFence = false;
|
|
27
|
+
lang = "";
|
|
28
|
+
} else {
|
|
29
|
+
inFence = true;
|
|
30
|
+
lang = line.slice(3).trim().toLowerCase();
|
|
31
|
+
}
|
|
32
|
+
if (nl === -1) break;
|
|
33
|
+
i = nl + 1;
|
|
34
|
+
}
|
|
35
|
+
return inFence ? lang : null;
|
|
36
|
+
};
|
|
37
|
+
//#endregion
|
|
38
|
+
export { findOpenFenceLanguage };
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=fenceState.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fenceState.mjs","names":[],"sources":["../../../src/Markdown/SyntaxMarkdown/fenceState.ts"],"sourcesContent":["/**\n * Walk `content` and return the language of the last *unclosed* fenced\n * code block, or `null` if every fence is closed (or there are none).\n *\n * Used by the smoother to decide whether to bypass its buffer for the\n * current input. CommonMark recognises an opening fence as a line whose\n * first non-space chars are 3+ backticks; we deliberately stay simple:\n * 3 literal backticks at line start, language word after. That covers\n * the markdown LLMs actually emit; tildes and indented fences fall back\n * to normal smoothing rather than getting clever.\n *\n * Linear scan over the input, ~10ns per char on V8. Called on every\n * smoothing tick during streaming so the simplicity matters.\n */\nexport const findOpenFenceLanguage = (content: string): string | null => {\n let inFence = false;\n let lang = '';\n let i = 0;\n const len = content.length;\n while (i < len) {\n const nl = content.indexOf('\\n', i);\n const lineEnd = nl === -1 ? len : nl;\n const line = content.slice(i, lineEnd);\n if (line.startsWith('```')) {\n if (inFence) {\n inFence = false;\n lang = '';\n } else {\n inFence = true;\n lang = line.slice(3).trim().toLowerCase();\n }\n }\n if (nl === -1) break;\n i = nl + 1;\n }\n return inFence ? lang : null;\n};\n"],"mappings":";;;;;;;;;;;;;;;AAcA,MAAa,yBAAyB,YAAmC;CACvE,IAAI,UAAU;CACd,IAAI,OAAO;CACX,IAAI,IAAI;CACR,MAAM,MAAM,QAAQ;AACpB,QAAO,IAAI,KAAK;EACd,MAAM,KAAK,QAAQ,QAAQ,MAAM,EAAE;EACnC,MAAM,UAAU,OAAO,KAAK,MAAM;EAClC,MAAM,OAAO,QAAQ,MAAM,GAAG,QAAQ;AACtC,MAAI,KAAK,WAAW,MAAM,CACxB,KAAI,SAAS;AACX,aAAU;AACV,UAAO;SACF;AACL,aAAU;AACV,UAAO,KAAK,MAAM,EAAE,CAAC,MAAM,CAAC,aAAa;;AAG7C,MAAI,OAAO,GAAI;AACf,MAAI,KAAK;;AAEX,QAAO,UAAU,OAAO"}
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { useStreamdownProfiler } from "../streamProfiler/StreamdownProfilerProvider.mjs";
|
|
2
|
+
import { findOpenFenceLanguage } from "./fenceState.mjs";
|
|
2
3
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
3
4
|
//#region src/Markdown/SyntaxMarkdown/useSmoothStreamContent.ts
|
|
5
|
+
const DEFAULT_BYPASS_LANGUAGES = ["html"];
|
|
4
6
|
const PRESET_CONFIG = {
|
|
5
7
|
balanced: {
|
|
6
8
|
activeInputWindowMs: 220,
|
|
9
|
+
bypassFencedLanguages: DEFAULT_BYPASS_LANGUAGES,
|
|
7
10
|
defaultCps: 38,
|
|
8
11
|
emaAlpha: .2,
|
|
9
12
|
flushCps: 120,
|
|
@@ -19,6 +22,7 @@ const PRESET_CONFIG = {
|
|
|
19
22
|
},
|
|
20
23
|
realtime: {
|
|
21
24
|
activeInputWindowMs: 140,
|
|
25
|
+
bypassFencedLanguages: DEFAULT_BYPASS_LANGUAGES,
|
|
22
26
|
defaultCps: 50,
|
|
23
27
|
emaAlpha: .3,
|
|
24
28
|
flushCps: 170,
|
|
@@ -34,6 +38,7 @@ const PRESET_CONFIG = {
|
|
|
34
38
|
},
|
|
35
39
|
silky: {
|
|
36
40
|
activeInputWindowMs: 320,
|
|
41
|
+
bypassFencedLanguages: DEFAULT_BYPASS_LANGUAGES,
|
|
37
42
|
defaultCps: 28,
|
|
38
43
|
emaAlpha: .14,
|
|
39
44
|
flushCps: 96,
|
|
@@ -226,6 +231,13 @@ const useSmoothStreamContent = (content, { enabled = true, preset = "balanced" }
|
|
|
226
231
|
syncImmediate(content);
|
|
227
232
|
return;
|
|
228
233
|
}
|
|
234
|
+
if (config.bypassFencedLanguages.length > 0) {
|
|
235
|
+
const openLang = findOpenFenceLanguage(content);
|
|
236
|
+
if (openLang !== null && config.bypassFencedLanguages.includes(openLang)) {
|
|
237
|
+
syncImmediate(content);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
229
241
|
const appendedChars = [...content.slice(prevTargetContent.length)];
|
|
230
242
|
const appendedCount = appendedChars.length;
|
|
231
243
|
profiler?.recordInputAppend({
|
|
@@ -254,6 +266,7 @@ const useSmoothStreamContent = (content, { enabled = true, preset = "balanced" }
|
|
|
254
266
|
lastInputCountRef.current = targetCountRef.current;
|
|
255
267
|
startFrameLoop();
|
|
256
268
|
}, [
|
|
269
|
+
config.bypassFencedLanguages,
|
|
257
270
|
config.emaAlpha,
|
|
258
271
|
config.largeAppendChars,
|
|
259
272
|
config.maxActiveCps,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSmoothStreamContent.mjs","names":[],"sources":["../../../src/Markdown/SyntaxMarkdown/useSmoothStreamContent.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from 'react';\n\nimport { useStreamdownProfiler } from '@/Markdown/streamProfiler';\nimport { type StreamSmoothingPreset } from '@/Markdown/type';\n\ninterface StreamSmoothingPresetConfig {\n activeInputWindowMs: number;\n defaultCps: number;\n emaAlpha: number;\n flushCps: number;\n largeAppendChars: number;\n maxActiveCps: number;\n maxCps: number;\n maxFlushCps: number;\n minCps: number;\n settleAfterMs: number;\n settleDrainMaxMs: number;\n settleDrainMinMs: number;\n targetBufferMs: number;\n}\n\nconst PRESET_CONFIG: Record<StreamSmoothingPreset, StreamSmoothingPresetConfig> = {\n balanced: {\n activeInputWindowMs: 220,\n defaultCps: 38,\n emaAlpha: 0.2,\n flushCps: 120,\n largeAppendChars: 120,\n maxActiveCps: 132,\n maxCps: 72,\n maxFlushCps: 280,\n minCps: 18,\n settleAfterMs: 360,\n settleDrainMaxMs: 520,\n settleDrainMinMs: 180,\n targetBufferMs: 120,\n },\n realtime: {\n activeInputWindowMs: 140,\n defaultCps: 50,\n emaAlpha: 0.3,\n flushCps: 170,\n largeAppendChars: 180,\n maxActiveCps: 180,\n maxCps: 96,\n maxFlushCps: 360,\n minCps: 24,\n settleAfterMs: 260,\n settleDrainMaxMs: 360,\n settleDrainMinMs: 140,\n targetBufferMs: 40,\n },\n silky: {\n activeInputWindowMs: 320,\n defaultCps: 28,\n emaAlpha: 0.14,\n flushCps: 96,\n largeAppendChars: 100,\n maxActiveCps: 102,\n maxCps: 56,\n maxFlushCps: 220,\n minCps: 14,\n settleAfterMs: 460,\n settleDrainMaxMs: 680,\n settleDrainMinMs: 240,\n targetBufferMs: 170,\n },\n};\n\nconst clamp = (value: number, min: number, max: number): number => {\n return Math.min(max, Math.max(min, value));\n};\n\nconst getNow = () => {\n return typeof performance === 'undefined' ? Date.now() : performance.now();\n};\n\nexport const countChars = (text: string): number => {\n return [...text].length;\n};\n\ninterface UseSmoothStreamContentOptions {\n enabled?: boolean;\n preset?: StreamSmoothingPreset;\n}\n\nexport const useSmoothStreamContent = (\n content: string,\n { enabled = true, preset = 'balanced' }: UseSmoothStreamContentOptions = {},\n): string => {\n const config = PRESET_CONFIG[preset];\n const profiler = useStreamdownProfiler();\n const [displayedContent, setDisplayedContent] = useState(content);\n\n const displayedContentRef = useRef(content);\n const displayedCountRef = useRef(countChars(content));\n\n const targetContentRef = useRef(content);\n const targetCharsRef = useRef([...content]);\n const targetCountRef = useRef(targetCharsRef.current.length);\n\n const emaCpsRef = useRef(config.defaultCps);\n const lastInputTsRef = useRef(0);\n const lastInputCountRef = useRef(targetCountRef.current);\n const chunkSizeEmaRef = useRef(1);\n const arrivalCpsEmaRef = useRef(config.defaultCps);\n\n const rafRef = useRef<number | null>(null);\n const lastFrameTsRef = useRef<number | null>(null);\n const wakeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const clearWakeTimer = useCallback(() => {\n if (wakeTimerRef.current !== null) {\n clearTimeout(wakeTimerRef.current);\n wakeTimerRef.current = null;\n }\n }, []);\n\n const stopFrameLoop = useCallback(() => {\n if (rafRef.current !== null) {\n cancelAnimationFrame(rafRef.current);\n rafRef.current = null;\n }\n lastFrameTsRef.current = null;\n }, []);\n\n const stopScheduling = useCallback(() => {\n stopFrameLoop();\n clearWakeTimer();\n }, [clearWakeTimer, stopFrameLoop]);\n\n const startFrameLoopRef = useRef<() => void>(() => {});\n\n const scheduleFrameWake = useCallback(\n (delayMs: number) => {\n clearWakeTimer();\n\n wakeTimerRef.current = setTimeout(\n () => {\n wakeTimerRef.current = null;\n startFrameLoopRef.current();\n },\n Math.max(1, Math.ceil(delayMs)),\n );\n },\n [clearWakeTimer],\n );\n\n const syncImmediate = useCallback(\n (nextContent: string) => {\n stopScheduling();\n\n const chars = [...nextContent];\n const now = getNow();\n\n targetContentRef.current = nextContent;\n targetCharsRef.current = chars;\n targetCountRef.current = chars.length;\n\n displayedContentRef.current = nextContent;\n displayedCountRef.current = chars.length;\n setDisplayedContent(nextContent);\n\n emaCpsRef.current = config.defaultCps;\n chunkSizeEmaRef.current = 1;\n arrivalCpsEmaRef.current = config.defaultCps;\n lastInputTsRef.current = now;\n lastInputCountRef.current = chars.length;\n },\n [config.defaultCps, stopScheduling],\n );\n\n const startFrameLoop = useCallback(() => {\n clearWakeTimer();\n if (rafRef.current !== null) return;\n\n const tick = (ts: number) => {\n const frameStart = getNow();\n\n if (lastFrameTsRef.current === null) {\n lastFrameTsRef.current = ts;\n rafRef.current = requestAnimationFrame(tick);\n return;\n }\n\n const frameIntervalMs = Math.max(0, ts - lastFrameTsRef.current);\n const dtSeconds = Math.max(0.001, Math.min(frameIntervalMs / 1000, 0.05));\n lastFrameTsRef.current = ts;\n\n const targetCount = targetCountRef.current;\n const displayedCount = displayedCountRef.current;\n const backlog = targetCount - displayedCount;\n\n if (backlog <= 0) {\n stopFrameLoop();\n return;\n }\n\n const now = getNow();\n const idleMs = now - lastInputTsRef.current;\n const inputActive = idleMs <= config.activeInputWindowMs;\n const settling = !inputActive && idleMs >= config.settleAfterMs;\n\n const baseCps = clamp(emaCpsRef.current, config.minCps, config.maxCps);\n const baseLagChars = Math.max(1, Math.round((baseCps * config.targetBufferMs) / 1000));\n const lagUpperBound = Math.max(baseLagChars + 2, baseLagChars * 3);\n const targetLagChars = inputActive\n ? Math.round(\n clamp(baseLagChars + chunkSizeEmaRef.current * 0.35, baseLagChars, lagUpperBound),\n )\n : 0;\n const desiredDisplayed = Math.max(0, targetCount - targetLagChars);\n\n let currentCps: number;\n if (inputActive) {\n const backlogPressure = targetLagChars > 0 ? backlog / targetLagChars : 1;\n const chunkPressure = targetLagChars > 0 ? chunkSizeEmaRef.current / targetLagChars : 1;\n const arrivalPressure = arrivalCpsEmaRef.current / Math.max(baseCps, 1);\n const combinedPressure = clamp(\n backlogPressure * 0.6 + chunkPressure * 0.25 + arrivalPressure * 0.15,\n 1,\n 4.5,\n );\n const activeCap = clamp(\n config.maxActiveCps + chunkSizeEmaRef.current * 6,\n config.maxActiveCps,\n config.maxFlushCps,\n );\n currentCps = clamp(baseCps * combinedPressure, config.minCps, activeCap);\n } else if (settling) {\n // If upstream likely ended, cap the remaining tail duration so\n // we do not keep replaying old backlog for seconds.\n const drainTargetMs = clamp(backlog * 8, config.settleDrainMinMs, config.settleDrainMaxMs);\n const settleCps = (backlog * 1000) / drainTargetMs;\n currentCps = clamp(settleCps, config.flushCps, config.maxFlushCps);\n } else {\n const idleFlushCps = Math.max(\n config.flushCps,\n baseCps * 1.8,\n arrivalCpsEmaRef.current * 0.8,\n );\n currentCps = clamp(idleFlushCps, config.flushCps, config.maxFlushCps);\n }\n\n const urgentBacklog = inputActive && targetLagChars > 0 && backlog > targetLagChars * 2.2;\n const burstyInput = inputActive && chunkSizeEmaRef.current >= targetLagChars * 0.9;\n const minRevealChars = inputActive ? (urgentBacklog || burstyInput ? 2 : 1) : 2;\n let revealChars = Math.max(minRevealChars, Math.round(currentCps * dtSeconds));\n\n if (inputActive) {\n const shortfall = desiredDisplayed - displayedCount;\n if (shortfall <= 0) {\n stopFrameLoop();\n scheduleFrameWake(config.activeInputWindowMs - idleMs);\n\n profiler?.recordAnimationFrame({\n backlog,\n durationMs: getNow() - frameStart,\n frameIntervalMs,\n inputActive,\n revealChars: 0,\n settling,\n });\n return;\n }\n revealChars = Math.min(revealChars, shortfall, backlog);\n } else {\n revealChars = Math.min(revealChars, backlog);\n }\n\n const nextCount = displayedCount + revealChars;\n const segment = targetCharsRef.current.slice(displayedCount, nextCount).join('');\n\n if (segment) {\n const nextDisplayed = displayedContentRef.current + segment;\n displayedContentRef.current = nextDisplayed;\n displayedCountRef.current = nextCount;\n setDisplayedContent(nextDisplayed);\n } else {\n displayedContentRef.current = targetContentRef.current;\n displayedCountRef.current = targetCount;\n setDisplayedContent(targetContentRef.current);\n }\n\n profiler?.recordAnimationFrame({\n backlog,\n durationMs: getNow() - frameStart,\n frameIntervalMs,\n inputActive,\n revealChars: segment ? revealChars : backlog,\n settling,\n });\n\n rafRef.current = requestAnimationFrame(tick);\n };\n\n rafRef.current = requestAnimationFrame(tick);\n }, [\n clearWakeTimer,\n config.activeInputWindowMs,\n config.flushCps,\n config.maxActiveCps,\n config.maxCps,\n config.maxFlushCps,\n config.minCps,\n config.settleAfterMs,\n config.settleDrainMaxMs,\n config.settleDrainMinMs,\n config.targetBufferMs,\n scheduleFrameWake,\n stopFrameLoop,\n ]);\n startFrameLoopRef.current = startFrameLoop;\n\n useEffect(() => {\n if (!enabled) {\n syncImmediate(content);\n return;\n }\n\n const prevTargetContent = targetContentRef.current;\n if (content === prevTargetContent) return;\n\n const now = getNow();\n const appendOnly = content.startsWith(prevTargetContent);\n\n if (!appendOnly) {\n syncImmediate(content);\n return;\n }\n\n const appended = content.slice(prevTargetContent.length);\n const appendedChars = [...appended];\n const appendedCount = appendedChars.length;\n\n profiler?.recordInputAppend({\n appendedChars: appendedCount,\n contentLength: countChars(content),\n });\n\n if (appendedCount > config.largeAppendChars) {\n syncImmediate(content);\n return;\n }\n\n targetContentRef.current = content;\n targetCharsRef.current = [...targetCharsRef.current, ...appendedChars];\n targetCountRef.current += appendedCount;\n\n const deltaChars = targetCountRef.current - lastInputCountRef.current;\n const deltaMs = Math.max(1, now - lastInputTsRef.current);\n\n if (deltaChars > 0) {\n const instantCps = (deltaChars * 1000) / deltaMs;\n const normalizedInstantCps = clamp(instantCps, config.minCps, config.maxFlushCps * 2);\n const chunkEmaAlpha = 0.35;\n chunkSizeEmaRef.current =\n chunkSizeEmaRef.current * (1 - chunkEmaAlpha) + appendedCount * chunkEmaAlpha;\n arrivalCpsEmaRef.current =\n arrivalCpsEmaRef.current * (1 - chunkEmaAlpha) + normalizedInstantCps * chunkEmaAlpha;\n\n const clampedCps = clamp(instantCps, config.minCps, config.maxActiveCps);\n emaCpsRef.current = emaCpsRef.current * (1 - config.emaAlpha) + clampedCps * config.emaAlpha;\n }\n\n lastInputTsRef.current = now;\n lastInputCountRef.current = targetCountRef.current;\n\n startFrameLoop();\n }, [\n config.emaAlpha,\n config.largeAppendChars,\n config.maxActiveCps,\n config.maxCps,\n config.maxFlushCps,\n config.minCps,\n content,\n enabled,\n startFrameLoop,\n syncImmediate,\n profiler,\n ]);\n\n useEffect(() => {\n return () => {\n stopScheduling();\n };\n }, [stopScheduling]);\n\n return displayedContent;\n};\n"],"mappings":";;;AAqBA,MAAM,gBAA4E;CAChF,UAAU;EACR,qBAAqB;EACrB,YAAY;EACZ,UAAU;EACV,UAAU;EACV,kBAAkB;EAClB,cAAc;EACd,QAAQ;EACR,aAAa;EACb,QAAQ;EACR,eAAe;EACf,kBAAkB;EAClB,kBAAkB;EAClB,gBAAgB;EACjB;CACD,UAAU;EACR,qBAAqB;EACrB,YAAY;EACZ,UAAU;EACV,UAAU;EACV,kBAAkB;EAClB,cAA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
1
|
+
{"version":3,"file":"useSmoothStreamContent.mjs","names":[],"sources":["../../../src/Markdown/SyntaxMarkdown/useSmoothStreamContent.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from 'react';\n\nimport { useStreamdownProfiler } from '@/Markdown/streamProfiler';\nimport { type StreamSmoothingPreset } from '@/Markdown/type';\n\nimport { findOpenFenceLanguage } from './fenceState';\n\ninterface StreamSmoothingPresetConfig {\n activeInputWindowMs: number;\n /**\n * Code-fence languages whose contents bypass smoothing entirely. While\n * the input ends inside an open fence in this set, every chunk is\n * `syncImmediate`-d to the display so downstream consumers (the\n * HtmlPreview iframe in particular) see partial HTML at the demo's\n * actual production rate instead of waiting on the smoother's\n * ~maxFlushCps budget. As soon as the fence closes — or another\n * non-bypass fence opens — smoothing resumes for the rest of the\n * stream. Default `['html']` covers the artifact case that motivated\n * this; tune via preset if you need to bypass `mermaid`, `svg`, etc.\n */\n bypassFencedLanguages: readonly string[];\n defaultCps: number;\n emaAlpha: number;\n flushCps: number;\n largeAppendChars: number;\n maxActiveCps: number;\n maxCps: number;\n maxFlushCps: number;\n minCps: number;\n settleAfterMs: number;\n settleDrainMaxMs: number;\n settleDrainMinMs: number;\n targetBufferMs: number;\n}\n\nconst DEFAULT_BYPASS_LANGUAGES = ['html'] as const;\n\nconst PRESET_CONFIG: Record<StreamSmoothingPreset, StreamSmoothingPresetConfig> = {\n balanced: {\n activeInputWindowMs: 220,\n bypassFencedLanguages: DEFAULT_BYPASS_LANGUAGES,\n defaultCps: 38,\n emaAlpha: 0.2,\n flushCps: 120,\n largeAppendChars: 120,\n maxActiveCps: 132,\n maxCps: 72,\n maxFlushCps: 280,\n minCps: 18,\n settleAfterMs: 360,\n settleDrainMaxMs: 520,\n settleDrainMinMs: 180,\n targetBufferMs: 120,\n },\n realtime: {\n activeInputWindowMs: 140,\n bypassFencedLanguages: DEFAULT_BYPASS_LANGUAGES,\n defaultCps: 50,\n emaAlpha: 0.3,\n flushCps: 170,\n largeAppendChars: 180,\n maxActiveCps: 180,\n maxCps: 96,\n maxFlushCps: 360,\n minCps: 24,\n settleAfterMs: 260,\n settleDrainMaxMs: 360,\n settleDrainMinMs: 140,\n targetBufferMs: 40,\n },\n silky: {\n activeInputWindowMs: 320,\n bypassFencedLanguages: DEFAULT_BYPASS_LANGUAGES,\n defaultCps: 28,\n emaAlpha: 0.14,\n flushCps: 96,\n largeAppendChars: 100,\n maxActiveCps: 102,\n maxCps: 56,\n maxFlushCps: 220,\n minCps: 14,\n settleAfterMs: 460,\n settleDrainMaxMs: 680,\n settleDrainMinMs: 240,\n targetBufferMs: 170,\n },\n};\n\nconst clamp = (value: number, min: number, max: number): number => {\n return Math.min(max, Math.max(min, value));\n};\n\nconst getNow = () => {\n return typeof performance === 'undefined' ? Date.now() : performance.now();\n};\n\nexport const countChars = (text: string): number => {\n return [...text].length;\n};\n\ninterface UseSmoothStreamContentOptions {\n enabled?: boolean;\n preset?: StreamSmoothingPreset;\n}\n\nexport const useSmoothStreamContent = (\n content: string,\n { enabled = true, preset = 'balanced' }: UseSmoothStreamContentOptions = {},\n): string => {\n const config = PRESET_CONFIG[preset];\n const profiler = useStreamdownProfiler();\n const [displayedContent, setDisplayedContent] = useState(content);\n\n const displayedContentRef = useRef(content);\n const displayedCountRef = useRef(countChars(content));\n\n const targetContentRef = useRef(content);\n const targetCharsRef = useRef([...content]);\n const targetCountRef = useRef(targetCharsRef.current.length);\n\n const emaCpsRef = useRef(config.defaultCps);\n const lastInputTsRef = useRef(0);\n const lastInputCountRef = useRef(targetCountRef.current);\n const chunkSizeEmaRef = useRef(1);\n const arrivalCpsEmaRef = useRef(config.defaultCps);\n\n const rafRef = useRef<number | null>(null);\n const lastFrameTsRef = useRef<number | null>(null);\n const wakeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const clearWakeTimer = useCallback(() => {\n if (wakeTimerRef.current !== null) {\n clearTimeout(wakeTimerRef.current);\n wakeTimerRef.current = null;\n }\n }, []);\n\n const stopFrameLoop = useCallback(() => {\n if (rafRef.current !== null) {\n cancelAnimationFrame(rafRef.current);\n rafRef.current = null;\n }\n lastFrameTsRef.current = null;\n }, []);\n\n const stopScheduling = useCallback(() => {\n stopFrameLoop();\n clearWakeTimer();\n }, [clearWakeTimer, stopFrameLoop]);\n\n const startFrameLoopRef = useRef<() => void>(() => {});\n\n const scheduleFrameWake = useCallback(\n (delayMs: number) => {\n clearWakeTimer();\n\n wakeTimerRef.current = setTimeout(\n () => {\n wakeTimerRef.current = null;\n startFrameLoopRef.current();\n },\n Math.max(1, Math.ceil(delayMs)),\n );\n },\n [clearWakeTimer],\n );\n\n const syncImmediate = useCallback(\n (nextContent: string) => {\n stopScheduling();\n\n const chars = [...nextContent];\n const now = getNow();\n\n targetContentRef.current = nextContent;\n targetCharsRef.current = chars;\n targetCountRef.current = chars.length;\n\n displayedContentRef.current = nextContent;\n displayedCountRef.current = chars.length;\n setDisplayedContent(nextContent);\n\n emaCpsRef.current = config.defaultCps;\n chunkSizeEmaRef.current = 1;\n arrivalCpsEmaRef.current = config.defaultCps;\n lastInputTsRef.current = now;\n lastInputCountRef.current = chars.length;\n },\n [config.defaultCps, stopScheduling],\n );\n\n const startFrameLoop = useCallback(() => {\n clearWakeTimer();\n if (rafRef.current !== null) return;\n\n const tick = (ts: number) => {\n const frameStart = getNow();\n\n if (lastFrameTsRef.current === null) {\n lastFrameTsRef.current = ts;\n rafRef.current = requestAnimationFrame(tick);\n return;\n }\n\n const frameIntervalMs = Math.max(0, ts - lastFrameTsRef.current);\n const dtSeconds = Math.max(0.001, Math.min(frameIntervalMs / 1000, 0.05));\n lastFrameTsRef.current = ts;\n\n const targetCount = targetCountRef.current;\n const displayedCount = displayedCountRef.current;\n const backlog = targetCount - displayedCount;\n\n if (backlog <= 0) {\n stopFrameLoop();\n return;\n }\n\n const now = getNow();\n const idleMs = now - lastInputTsRef.current;\n const inputActive = idleMs <= config.activeInputWindowMs;\n const settling = !inputActive && idleMs >= config.settleAfterMs;\n\n const baseCps = clamp(emaCpsRef.current, config.minCps, config.maxCps);\n const baseLagChars = Math.max(1, Math.round((baseCps * config.targetBufferMs) / 1000));\n const lagUpperBound = Math.max(baseLagChars + 2, baseLagChars * 3);\n const targetLagChars = inputActive\n ? Math.round(\n clamp(baseLagChars + chunkSizeEmaRef.current * 0.35, baseLagChars, lagUpperBound),\n )\n : 0;\n const desiredDisplayed = Math.max(0, targetCount - targetLagChars);\n\n let currentCps: number;\n if (inputActive) {\n const backlogPressure = targetLagChars > 0 ? backlog / targetLagChars : 1;\n const chunkPressure = targetLagChars > 0 ? chunkSizeEmaRef.current / targetLagChars : 1;\n const arrivalPressure = arrivalCpsEmaRef.current / Math.max(baseCps, 1);\n const combinedPressure = clamp(\n backlogPressure * 0.6 + chunkPressure * 0.25 + arrivalPressure * 0.15,\n 1,\n 4.5,\n );\n const activeCap = clamp(\n config.maxActiveCps + chunkSizeEmaRef.current * 6,\n config.maxActiveCps,\n config.maxFlushCps,\n );\n currentCps = clamp(baseCps * combinedPressure, config.minCps, activeCap);\n } else if (settling) {\n // If upstream likely ended, cap the remaining tail duration so\n // we do not keep replaying old backlog for seconds.\n const drainTargetMs = clamp(backlog * 8, config.settleDrainMinMs, config.settleDrainMaxMs);\n const settleCps = (backlog * 1000) / drainTargetMs;\n currentCps = clamp(settleCps, config.flushCps, config.maxFlushCps);\n } else {\n const idleFlushCps = Math.max(\n config.flushCps,\n baseCps * 1.8,\n arrivalCpsEmaRef.current * 0.8,\n );\n currentCps = clamp(idleFlushCps, config.flushCps, config.maxFlushCps);\n }\n\n const urgentBacklog = inputActive && targetLagChars > 0 && backlog > targetLagChars * 2.2;\n const burstyInput = inputActive && chunkSizeEmaRef.current >= targetLagChars * 0.9;\n const minRevealChars = inputActive ? (urgentBacklog || burstyInput ? 2 : 1) : 2;\n let revealChars = Math.max(minRevealChars, Math.round(currentCps * dtSeconds));\n\n if (inputActive) {\n const shortfall = desiredDisplayed - displayedCount;\n if (shortfall <= 0) {\n stopFrameLoop();\n scheduleFrameWake(config.activeInputWindowMs - idleMs);\n\n profiler?.recordAnimationFrame({\n backlog,\n durationMs: getNow() - frameStart,\n frameIntervalMs,\n inputActive,\n revealChars: 0,\n settling,\n });\n return;\n }\n revealChars = Math.min(revealChars, shortfall, backlog);\n } else {\n revealChars = Math.min(revealChars, backlog);\n }\n\n const nextCount = displayedCount + revealChars;\n const segment = targetCharsRef.current.slice(displayedCount, nextCount).join('');\n\n if (segment) {\n const nextDisplayed = displayedContentRef.current + segment;\n displayedContentRef.current = nextDisplayed;\n displayedCountRef.current = nextCount;\n setDisplayedContent(nextDisplayed);\n } else {\n displayedContentRef.current = targetContentRef.current;\n displayedCountRef.current = targetCount;\n setDisplayedContent(targetContentRef.current);\n }\n\n profiler?.recordAnimationFrame({\n backlog,\n durationMs: getNow() - frameStart,\n frameIntervalMs,\n inputActive,\n revealChars: segment ? revealChars : backlog,\n settling,\n });\n\n rafRef.current = requestAnimationFrame(tick);\n };\n\n rafRef.current = requestAnimationFrame(tick);\n }, [\n clearWakeTimer,\n config.activeInputWindowMs,\n config.flushCps,\n config.maxActiveCps,\n config.maxCps,\n config.maxFlushCps,\n config.minCps,\n config.settleAfterMs,\n config.settleDrainMaxMs,\n config.settleDrainMinMs,\n config.targetBufferMs,\n scheduleFrameWake,\n stopFrameLoop,\n ]);\n startFrameLoopRef.current = startFrameLoop;\n\n useEffect(() => {\n if (!enabled) {\n syncImmediate(content);\n return;\n }\n\n const prevTargetContent = targetContentRef.current;\n if (content === prevTargetContent) return;\n\n const now = getNow();\n const appendOnly = content.startsWith(prevTargetContent);\n\n if (!appendOnly) {\n syncImmediate(content);\n return;\n }\n\n // Bypass smoothing entirely while the input ends inside an open\n // fence whose language is opted out — see the preset config.\n // Without this, a 5 KB inline `<style>` block can keep `</style>`\n // (and therefore the HtmlPreview head-close trigger) trapped in the\n // smoother's buffer for tens of seconds, leaving the iframe pinned\n // on the loading placeholder while the artifact \"looks stuck\".\n if (config.bypassFencedLanguages.length > 0) {\n const openLang = findOpenFenceLanguage(content);\n if (openLang !== null && config.bypassFencedLanguages.includes(openLang)) {\n syncImmediate(content);\n return;\n }\n }\n\n const appended = content.slice(prevTargetContent.length);\n const appendedChars = [...appended];\n const appendedCount = appendedChars.length;\n\n profiler?.recordInputAppend({\n appendedChars: appendedCount,\n contentLength: countChars(content),\n });\n\n if (appendedCount > config.largeAppendChars) {\n syncImmediate(content);\n return;\n }\n\n targetContentRef.current = content;\n targetCharsRef.current = [...targetCharsRef.current, ...appendedChars];\n targetCountRef.current += appendedCount;\n\n const deltaChars = targetCountRef.current - lastInputCountRef.current;\n const deltaMs = Math.max(1, now - lastInputTsRef.current);\n\n if (deltaChars > 0) {\n const instantCps = (deltaChars * 1000) / deltaMs;\n const normalizedInstantCps = clamp(instantCps, config.minCps, config.maxFlushCps * 2);\n const chunkEmaAlpha = 0.35;\n chunkSizeEmaRef.current =\n chunkSizeEmaRef.current * (1 - chunkEmaAlpha) + appendedCount * chunkEmaAlpha;\n arrivalCpsEmaRef.current =\n arrivalCpsEmaRef.current * (1 - chunkEmaAlpha) + normalizedInstantCps * chunkEmaAlpha;\n\n const clampedCps = clamp(instantCps, config.minCps, config.maxActiveCps);\n emaCpsRef.current = emaCpsRef.current * (1 - config.emaAlpha) + clampedCps * config.emaAlpha;\n }\n\n lastInputTsRef.current = now;\n lastInputCountRef.current = targetCountRef.current;\n\n startFrameLoop();\n }, [\n config.bypassFencedLanguages,\n config.emaAlpha,\n config.largeAppendChars,\n config.maxActiveCps,\n config.maxCps,\n config.maxFlushCps,\n config.minCps,\n content,\n enabled,\n startFrameLoop,\n syncImmediate,\n profiler,\n ]);\n\n useEffect(() => {\n return () => {\n stopScheduling();\n };\n }, [stopScheduling]);\n\n return displayedContent;\n};\n"],"mappings":";;;;AAmCA,MAAM,2BAA2B,CAAC,OAAO;AAEzC,MAAM,gBAA4E;CAChF,UAAU;EACR,qBAAqB;EACrB,uBAAuB;EACvB,YAAY;EACZ,UAAU;EACV,UAAU;E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AI,iBAAiB,uBAAuB;GAE1E,MAAM,aAAa,MAAM,YAAY,OAAO,QAAQ,OAAO,aAAa;AACxE,aAAU,UAAU,UAAU,WAAW,IAAI,OAAO,YAAY,aAAa,OAAO;;AAGtF,iBAAe,UAAU;AACzB,oBAAkB,UAAU,eAAe;AAE3C,kBAAgB;IACf;EACD,OAAO;EACP,OAAO;EACP,OAAO;EACP,OAAO;EACP,OAAO;EACP,OAAO;EACP,OAAO;EACP;EACA;EACA;EACA;EACA;EACD,CAAC;AAEF,iBAAgB;AACd,eAAa;AACX,mBAAgB;;IAEjB,CAAC,eAAe,CAAC;AAEpB,QAAO"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import "../../Highlighter/const.mjs";
|
|
2
|
-
import
|
|
2
|
+
import { isFullHtmlDocument } from "../../HtmlPreview/const.mjs";
|
|
3
|
+
import Pre, { PreHtmlPreview, PreMermaid, PreSingleLine } from "../../mdx/mdxComponents/Pre.mjs";
|
|
3
4
|
import { memo } from "react";
|
|
4
5
|
import { jsx } from "react/jsx-runtime";
|
|
5
6
|
//#region src/Markdown/components/CodeBlock.tsx
|
|
@@ -19,7 +20,7 @@ const useCode = (raw) => {
|
|
|
19
20
|
lang
|
|
20
21
|
};
|
|
21
22
|
};
|
|
22
|
-
const CodeBlock = memo(({ fullFeatured, enableMermaid, highlight, mermaid, children, animated, ...rest }) => {
|
|
23
|
+
const CodeBlock = memo(({ fullFeatured, enableHtmlPreview, enableMermaid, highlight, html, mermaid, children, animated, ...rest }) => {
|
|
23
24
|
const code = useCode(children);
|
|
24
25
|
if (!code) return;
|
|
25
26
|
if (enableMermaid && code.lang === "mermaid") return /* @__PURE__ */ jsx(PreMermaid, {
|
|
@@ -29,6 +30,13 @@ const CodeBlock = memo(({ fullFeatured, enableMermaid, highlight, mermaid, child
|
|
|
29
30
|
...rest,
|
|
30
31
|
children: code.content
|
|
31
32
|
});
|
|
33
|
+
if (enableHtmlPreview && code.lang === "html" && isFullHtmlDocument(code.content)) return /* @__PURE__ */ jsx(PreHtmlPreview, {
|
|
34
|
+
animated,
|
|
35
|
+
fullFeatured,
|
|
36
|
+
...html,
|
|
37
|
+
...rest,
|
|
38
|
+
children: code.content
|
|
39
|
+
});
|
|
32
40
|
if (!highlight && code.isSingleLine) return /* @__PURE__ */ jsx(PreSingleLine, {
|
|
33
41
|
language: code.lang,
|
|
34
42
|
children: code.content
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeBlock.mjs","names":[],"sources":["../../../src/Markdown/components/CodeBlock.tsx"],"sourcesContent":["import { memo } from 'react';\n\nimport type { HighlighterProps } from '@/Highlighter';\nimport { FALLBACK_LANG } from '@/Highlighter/const';\nimport Pre, { PreMermaid, PreSingleLine } from '@/mdx/mdxComponents/Pre';\nimport type { MermaidProps } from '@/Mermaid';\n\nconst countLines = (str: string): number => {\n const regex = /\\n/g;\n const matches = str.match(regex);\n return matches ? matches.length : 1;\n};\n\nexport const useCode = (raw: any) => {\n if (!raw) return;\n\n const { children = '', className } = raw?.props || { children: '' };\n\n if (!children) return;\n\n const content = Array.isArray(children) ? (children[0] as string) : children;\n\n const lang = className?.replace('language-', '') || FALLBACK_LANG;\n\n const isSingleLine = countLines(content) <= 1 && content.length <= 32;\n\n return {\n content,\n isSingleLine,\n lang,\n };\n};\n\ninterface CodeBlockProps {\n animated?: boolean;\n children: any;\n enableMermaid?: boolean;\n fullFeatured?: boolean;\n highlight?: HighlighterProps;\n mermaid?: MermaidProps;\n}\n\nexport const CodeBlock = memo<CodeBlockProps>(\n ({
|
|
1
|
+
{"version":3,"file":"CodeBlock.mjs","names":[],"sources":["../../../src/Markdown/components/CodeBlock.tsx"],"sourcesContent":["import { memo } from 'react';\n\nimport type { HighlighterProps } from '@/Highlighter';\nimport { FALLBACK_LANG } from '@/Highlighter/const';\nimport { isFullHtmlDocument } from '@/HtmlPreview/const';\nimport type { HtmlPreviewProps } from '@/HtmlPreview/type';\nimport Pre, { PreHtmlPreview, PreMermaid, PreSingleLine } from '@/mdx/mdxComponents/Pre';\nimport type { MermaidProps } from '@/Mermaid';\n\nconst countLines = (str: string): number => {\n const regex = /\\n/g;\n const matches = str.match(regex);\n return matches ? matches.length : 1;\n};\n\nexport const useCode = (raw: any) => {\n if (!raw) return;\n\n const { children = '', className } = raw?.props || { children: '' };\n\n if (!children) return;\n\n const content = Array.isArray(children) ? (children[0] as string) : children;\n\n const lang = className?.replace('language-', '') || FALLBACK_LANG;\n\n const isSingleLine = countLines(content) <= 1 && content.length <= 32;\n\n return {\n content,\n isSingleLine,\n lang,\n };\n};\n\ninterface CodeBlockProps {\n animated?: boolean;\n children: any;\n enableHtmlPreview?: boolean;\n enableMermaid?: boolean;\n fullFeatured?: boolean;\n highlight?: HighlighterProps;\n html?: HtmlPreviewProps;\n mermaid?: MermaidProps;\n}\n\nexport const CodeBlock = memo<CodeBlockProps>(\n ({\n fullFeatured,\n enableHtmlPreview,\n enableMermaid,\n highlight,\n html,\n mermaid,\n children,\n animated,\n ...rest\n }) => {\n const code = useCode(children);\n\n if (!code) return;\n\n if (enableMermaid && code.lang === 'mermaid')\n return (\n <PreMermaid animated={animated} fullFeatured={fullFeatured} {...mermaid} {...rest}>\n {code.content}\n </PreMermaid>\n );\n\n // Auto-route to HTML preview only for full HTML documents. Fragments fall\n // through to the normal highlighter — inline-rendering a `<div>` snippet\n // produces a degraded experience and risks hiding the actual code from\n // the reader.\n if (enableHtmlPreview && code.lang === 'html' && isFullHtmlDocument(code.content))\n return (\n <PreHtmlPreview animated={animated} fullFeatured={fullFeatured} {...html} {...rest}>\n {code.content}\n </PreHtmlPreview>\n );\n\n if (!highlight && code.isSingleLine)\n return <PreSingleLine language={code.lang}>{code.content}</PreSingleLine>;\n\n return (\n <Pre\n animated={animated}\n fullFeatured={fullFeatured}\n language={code.lang}\n {...highlight}\n {...rest}\n >\n {code.content}\n </Pre>\n );\n },\n (prevProps, nextProps) => prevProps.children === nextProps.children,\n);\n"],"mappings":";;;;;;AASA,MAAM,cAAc,QAAwB;CAE1C,MAAM,UAAU,IAAI,MAAM,MAAM;AAChC,QAAO,UAAU,QAAQ,SAAS;;AAGpC,MAAa,WAAW,QAAa;AACnC,KAAI,CAAC,IAAK;CAEV,MAAM,EAAE,WAAW,IAAI,cAAc,KAAK,SAAS,EAAE,UAAU,IAAI;AAEnE,KAAI,CAAC,SAAU;CAEf,MAAM,UAAU,MAAM,QAAQ,SAAS,GAAI,SAAS,KAAgB;CAEpE,MAAM,OAAO,WAAW,QAAQ,aAAa,GAAG,IAAA;AAIhD,QAAO;EACL;EACA,cAJmB,WAAW,QAAQ,IAAI,KAAK,QAAQ,UAAU;EAKjE;EACD;;AAcH,MAAa,YAAY,MACtB,EACC,cACA,mBACA,eACA,WACA,MACA,SACA,UACA,UACA,GAAG,WACC;CACJ,MAAM,OAAO,QAAQ,SAAS;AAE9B,KAAI,CAAC,KAAM;AAEX,KAAI,iBAAiB,KAAK,SAAS,UACjC,QACE,oBAAC,YAAD;EAAsB;EAAwB;EAAc,GAAI;EAAS,GAAI;YAC1E,KAAK;EACK,CAAA;AAOjB,KAAI,qBAAqB,KAAK,SAAS,UAAU,mBAAmB,KAAK,QAAQ,CAC/E,QACE,oBAAC,gBAAD;EAA0B;EAAwB;EAAc,GAAI;EAAM,GAAI;YAC3E,KAAK;EACS,CAAA;AAGrB,KAAI,CAAC,aAAa,KAAK,aACrB,QAAO,oBAAC,eAAD;EAAe,UAAU,KAAK;YAAO,KAAK;EAAwB,CAAA;AAE3E,QACE,oBAAC,KAAD;EACY;EACI;EACd,UAAU,KAAK;EACf,GAAI;EACJ,GAAI;YAEH,KAAK;EACF,CAAA;IAGT,WAAW,cAAc,UAAU,aAAa,UAAU,SAC5D"}
|
package/es/Markdown/type.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AProps, DivProps } from "../types/index.mjs";
|
|
2
2
|
import { HighlighterProps } from "../Highlighter/type.mjs";
|
|
3
|
+
import { HtmlPreviewProps } from "../HtmlPreview/type.mjs";
|
|
3
4
|
import { MermaidProps } from "../Mermaid/type.mjs";
|
|
4
5
|
import { ImageProps as ImageProps$1 } from "../mdx/mdxComponents/Image.mjs";
|
|
5
6
|
import { CitationItem } from "../types/citation.mjs";
|
|
@@ -29,6 +30,7 @@ interface SyntaxMarkdownProps {
|
|
|
29
30
|
componentProps?: {
|
|
30
31
|
a?: Partial<AProps & AnchorProps>;
|
|
31
32
|
highlight?: Partial<HighlighterProps>;
|
|
33
|
+
html?: Partial<HtmlPreviewProps>;
|
|
32
34
|
img?: Partial<ImageProps$1>;
|
|
33
35
|
mermaid?: Partial<MermaidProps>;
|
|
34
36
|
pre?: Partial<PreProps>;
|
|
@@ -37,6 +39,7 @@ interface SyntaxMarkdownProps {
|
|
|
37
39
|
components?: Components & Record<string, FC>;
|
|
38
40
|
enableCustomFootnotes?: boolean;
|
|
39
41
|
enableGithubAlert?: boolean;
|
|
42
|
+
enableHtmlPreview?: boolean;
|
|
40
43
|
enableLatex?: boolean;
|
|
41
44
|
enableMermaid?: boolean;
|
|
42
45
|
enableStream?: boolean;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { NeuralNetworkLoadingProps } from "./type.mjs";
|
|
2
|
+
import * as _$react from "react";
|
|
3
|
+
|
|
4
|
+
//#region src/NeuralNetworkLoading/NeuralNetworkLoading.d.ts
|
|
5
|
+
declare const NeuralNetworkLoading: _$react.NamedExoticComponent<NeuralNetworkLoadingProps>;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { NeuralNetworkLoading };
|
|
8
|
+
//# sourceMappingURL=NeuralNetworkLoading.d.mts.map
|