UNPKG

ds-markdown

Version:

> 🚀 高性能 React Markdown 打字动画组件,完美复刻 DeepSeek 聊天界面效果

1,020 lines (994 loc) 45.4 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var jsxRuntime = require('react/jsx-runtime'); var react = require('react'); var Markdown$2 = require('react-markdown'); var gfmPlugin = require('remark-gfm'); var classNames = require('classnames'); var reactSyntaxHighlighter = require('react-syntax-highlighter'); /** * 将括号格式的数学公式转换为美元符号格式 * 支持以下转换: * - \(...\) → $...$ (行内公式) * - \[...\] → $$...$$ (块级公式) * * 特殊处理: * - 如果文本包含 Markdown 超链接,则跳过转换以避免误处理 * - 使用占位符机制保护块级公式内的括号不被误转换 * * @param value 要转换的字符串 * @returns 转换后的字符串 */ const replaceMathBracket = (value) => { // 1. 提取所有块级公式内容,临时替换为占位符, [...] const blockMatches = []; let replaced = value.replace(/\\+\[([\s\S]+?)\\+\]/g, (_m, p1) => { blockMatches.push(p1); return `__BLOCK_MATH_${blockMatches.length - 1}__`; }); // 也需要兼容 $$ xxxx $$ 这种写法 replaced = replaced.replace(/\$\$([\s\S]+?)\$\$/g, (_m, p1) => { blockMatches.push(p1); return `__BLOCK_MATH_${blockMatches.length - 1}__`; }); // 2. 替换块级公式外部的 ( ... ) 为 $...$ replaced = replaced.replace(/\\+\(([^)]+?)\\+\)/g, (_m, p1) => { return '$' + p1 + '$'; }); // 3. 还原块级公式内容,保持其内部小括号原样 replaced = replaced.replace(/__BLOCK_MATH_(\d+)__/g, (_m, idx) => { return '$$' + blockMatches[Number(idx)] + '$$'; }); return replaced; }; const DEFAULT_THEME = 'light'; const DEFAULT_ANSWER_TYPE = 'answer'; const DEFAULT_PLUGINS = []; const MarkdownThemeContext = react.createContext({ state: { theme: DEFAULT_THEME, answerType: DEFAULT_ANSWER_TYPE, }, methods: {}, }); const MarkdownThemeProvider = ({ value = {}, children }) => { const contextValue = react.useMemo(() => ({ state: { theme: DEFAULT_THEME, answerType: DEFAULT_ANSWER_TYPE, ...value, }, methods: { // 这里可以添加主题相关的方法实现 }, }), [value]); return jsxRuntime.jsx(MarkdownThemeContext.Provider, { value: contextValue, children: children }); }; const useMarkdownThemeContext = () => react.useContext(MarkdownThemeContext); const useThemeState = () => { return react.useContext(MarkdownThemeContext).state; }; const CodeBlockWrap = ({ children, title }) => { const { theme } = useThemeState(); return (jsxRuntime.jsxs("div", { className: `md-code-block md-code-block-${theme}`, children: [jsxRuntime.jsx("div", { className: "md-code-block-banner-wrap", children: jsxRuntime.jsx("div", { className: "md-code-block-banner md-code-block-banner-lite", children: title }) }), jsxRuntime.jsx("div", { className: "md-code-block-content", children: children })] })); }; const CheckMarkIcon = ({ size }) => { return (jsxRuntime.jsx("svg", { width: size, height: size, viewBox: `0 0 ${size} ${size}`, fill: "none", xmlns: "http://www.w3.org/2000/svg", children: jsxRuntime.jsx("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M9.338 21.575a1.058 1.058 0 0 1-.53-.363L2.275 13.17a1.063 1.063 0 0 1 1.65-1.341l5.63 6.928L19.33 3.86a1.064 1.064 0 0 1 1.778 1.167L10.551 21.115a1.065 1.065 0 0 1-1.213.46z", fill: "currentColor" }) })); }; const CopyIcon = ({ size }) => { return (jsxRuntime.jsxs("svg", { width: size, height: size, viewBox: `0 0 ${size} ${size}`, fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [jsxRuntime.jsx("path", { d: "M3.65169 12.9243C3.68173 13.1045 3.74181 13.2748 3.80189 13.445C3.87198 13.6052 3.96211 13.7654 4.06225 13.9156C4.16238 14.0658 4.27253 14.206 4.4027 14.3362C4.52286 14.4663 4.66306 14.5765 4.81326 14.6766C4.96346 14.7768 5.11366 14.8569 5.28389 14.927C5.44411 14.9971 5.61434 15.0571 5.79459 15.0872C5.97483 15.1272 6.14506 15.1373 6.3253 15.1373V16.9196C6.30739 16.9196 6.28949 16.9195 6.27159 16.9193C5.9991 16.9158 5.72659 16.8859 5.4541 16.8295C5.16371 16.7694 4.88334 16.6893 4.61298 16.5692C4.3326 16.459 4.08226 16.3188 3.83193 16.1586C3.59161 15.9884 3.3613 15.7981 3.15102 15.5878C2.94074 15.3776 2.7605 15.1473 2.59027 14.9069C2.43006 14.6566 2.28986 14.3962 2.17972 14.1259C2.06957 13.8455 1.97944 13.5651 1.91936 13.2747C1.86929 12.9843 1.83926 12.684 1.83926 12.3936V6.26532C1.83926 5.96492 1.86929 5.67456 1.91936 5.38417C1.97944 5.09378 2.06957 4.80338 2.17972 4.53302C2.28986 4.26265 2.43006 4.0023 2.59027 3.75197C2.7605 3.50163 2.94074 3.27132 3.15102 3.06104C3.3613 2.85076 3.59161 2.67052 3.83193 2.50029C4.08226 2.33006 4.3326 2.19987 4.61298 2.07971C4.88334 1.96956 5.16371 1.87943 5.4541 1.81935C5.74449 1.75927 6.03491 1.73926 6.3253 1.73926H12.3934C12.6838 1.73926 12.9842 1.75927 13.2746 1.81935C13.555 1.87943 13.8354 1.96956 14.1158 2.07971C14.3861 2.19987 14.6465 2.33006 14.8868 2.50029C15.1371 2.67052 15.3574 2.85076 15.5677 3.06104C15.778 3.27132 15.9582 3.50163 16.1284 3.75197C16.2887 4.0023 16.4288 4.26265 16.539 4.53302C16.6592 4.80338 16.7393 5.09378 16.7994 5.38417C16.8558 5.65722 16.8858 5.93024 16.8892 6.21161C16.8894 6.22948 16.8895 6.24739 16.8895 6.26532H15.1271C15.1271 6.08508 15.1071 5.90486 15.067 5.72462C15.037 5.55439 14.9869 5.38415 14.9168 5.21392C14.8467 5.04369 14.7566 4.88347 14.6665 4.73327C14.5664 4.58307 14.4462 4.45289 14.326 4.32271C14.1959 4.19254 14.0557 4.08239 13.9055 3.98226C13.7553 3.88212 13.6051 3.79202 13.4348 3.72193C13.2746 3.65184 13.1044 3.60174 12.9242 3.5717C12.7539 3.53165 12.5737 3.51163 12.3934 3.51163H6.3253C6.14506 3.51163 5.97483 3.53165 5.79459 3.5717C5.61434 3.60174 5.44411 3.65184 5.28389 3.72193C5.11366 3.79202 4.96346 3.88212 4.81326 3.98226C4.66306 4.08239 4.52286 4.19254 4.4027 4.32271C4.27253 4.45289 4.16238 4.58307 4.06225 4.73327C3.96211 4.88347 3.87198 5.04369 3.80189 5.21392C3.74181 5.38415 3.68173 5.55439 3.65169 5.72462C3.61164 5.90486 3.60164 6.08508 3.60164 6.26532V12.3936C3.60164 12.5638 3.61164 12.744 3.65169 12.9243Z", fill: "currentColor" }), jsxRuntime.jsx("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M9.66972 21.6772C9.39936 21.567 9.13902 21.4268 8.8987 21.2566C8.64836 21.0964 8.42804 20.9061 8.21776 20.6959C8.00748 20.4856 7.81723 20.2553 7.65701 20.015C7.4968 19.7646 7.3566 19.5043 7.24646 19.2239C7.12629 18.9535 7.04621 18.6731 6.98613 18.3727C6.92605 18.0823 6.89601 17.792 6.89601 17.4915V11.3733C6.89601 11.0729 6.92605 10.7825 6.98613 10.4922C7.04621 10.1918 7.12629 9.91137 7.24646 9.64101C7.3566 9.36063 7.4968 9.10028 7.65701 8.85996C7.81723 8.60962 8.00748 8.37931 8.21776 8.16903C8.42804 7.95875 8.64836 7.76849 8.8987 7.60828C9.13902 7.43805 9.39936 7.29785 9.66972 7.1877C9.94009 7.07755 10.2205 6.98745 10.5108 6.92737C10.8012 6.86729 11.0916 6.83725 11.392 6.83725H17.4602C17.7506 6.83725 18.041 6.86729 18.3313 6.92737C18.6217 6.98745 18.9021 7.07755 19.1725 7.1877C19.4529 7.29785 19.7032 7.43805 19.9535 7.60828C20.1938 7.76849 20.4242 7.95875 20.6345 8.16903C20.8447 8.37931 21.025 8.60962 21.1952 8.85996C21.3554 9.10028 21.4956 9.36063 21.6058 9.64101C21.7159 9.91137 21.806 10.1918 21.8661 10.4922C21.9162 10.7825 21.9462 11.0729 21.9462 11.3733V17.4915C21.9462 17.792 21.9162 18.0823 21.8661 18.3727C21.806 18.6731 21.7159 18.9535 21.6058 19.2239C21.4956 19.5043 21.3554 19.7646 21.1952 20.015C21.025 20.2553 20.8447 20.4856 20.6345 20.6959C20.4242 20.9061 20.1938 21.0964 19.9535 21.2566C19.7032 21.4268 19.4529 21.567 19.1725 21.6772C18.9021 21.7973 18.6217 21.8774 18.3313 21.9375C18.041 21.9976 17.7506 22.0276 17.4602 22.0276H11.392C11.0916 22.0276 10.8012 21.9976 10.5108 21.9375C10.2205 21.8774 9.94009 21.7973 9.66972 21.6772ZM10.8613 8.6697C11.0316 8.63966 11.2118 8.61965 11.392 8.61965H17.4602C17.6404 8.61965 17.8107 8.63966 17.9909 8.6697C18.1611 8.70975 18.3314 8.75983 18.5016 8.82992C18.6618 8.90001 18.822 8.98012 18.9722 9.08026C19.1224 9.18039 19.2626 9.30055 19.3828 9.42071C19.513 9.55088 19.6231 9.69109 19.7232 9.84129C19.8234 9.99149 19.9035 10.1517 19.9736 10.3219C20.0437 10.4821 20.0937 10.6624 20.1338 10.8326C20.1638 11.0129 20.1838 11.1931 20.1838 11.3733V17.4915C20.1838 17.6718 20.1638 17.852 20.1338 18.0323C20.0937 18.2125 20.0437 18.3828 19.9736 18.543C19.9035 18.7132 19.8234 18.8734 19.7232 19.0236C19.6231 19.1738 19.513 19.314 19.3828 19.4342C19.2626 19.5643 19.1224 19.6845 18.9722 19.7846C18.822 19.8848 18.6618 19.9649 18.5016 20.035C18.3314 20.1051 18.1611 20.1551 17.9909 20.1952C17.8107 20.2252 17.6404 20.2452 17.4602 20.2452H11.392C11.2118 20.2452 11.0316 20.2252 10.8613 20.1952C10.6811 20.1551 10.5108 20.1051 10.3506 20.035C10.1804 19.9649 10.0202 19.8848 9.87 19.7846C9.72982 19.6845 9.58962 19.5643 9.45945 19.4342C9.33929 19.314 9.21913 19.1738 9.119 19.0236C9.01886 18.8734 8.93875 18.7132 8.86866 18.543C8.79857 18.3828 8.74847 18.2125 8.71843 18.0323C8.67838 17.852 8.65836 17.6718 8.65836 17.4915V11.3733C8.65836 11.1931 8.67838 11.0129 8.71843 10.8326C8.74847 10.6624 8.79857 10.4821 8.86866 10.3219C8.93875 10.1517 9.01886 9.99149 9.119 9.84129C9.21913 9.69109 9.33929 9.55088 9.45945 9.42071C9.58962 9.30055 9.72982 9.18039 9.87 9.08026C10.0202 8.98012 10.1804 8.90001 10.3506 8.82992C10.5108 8.75983 10.6811 8.70975 10.8613 8.6697Z", fill: "currentColor" })] })); }; const DownloadIcon = ({ size }) => { return (jsxRuntime.jsxs("svg", { width: size, height: size, viewBox: `0 0 ${size} ${size}`, fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [jsxRuntime.jsx("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M12 2.55a.97.97 0 0 1 .982.956v13.04a.97.97 0 0 1-.982.957.97.97 0 0 1-.982-.956V3.507A.97.97 0 0 1 12 2.55z", fill: "currentColor" }), jsxRuntime.jsx("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M19.418 9.808c.382.375.37.971-.027 1.332l-6.7 6.085a1.04 1.04 0 0 1-1.41-.025.905.905 0 0 1 .027-1.332l6.7-6.085a1.04 1.04 0 0 1 1.41.025z", fill: "currentColor" }), jsxRuntime.jsx("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M4.582 9.808a1.04 1.04 0 0 1 1.41-.025l6.7 6.085c.397.361.409.957.027 1.332a1.04 1.04 0 0 1-1.41.025l-6.7-6.085a.905.905 0 0 1-.027-1.332z", fill: "currentColor" }), jsxRuntime.jsx("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M3.068 16.46a.97.97 0 0 1 .983.956v1.739c0 .432.36.782.803.782h14.291c.445 0 .804-.35.804-.782v-1.739a.97.97 0 0 1 .983-.956.97.97 0 0 1 .982.956v1.739c0 1.488-1.24 2.695-2.769 2.695H4.855c-1.53 0-2.77-1.207-2.77-2.695v-1.739a.97.97 0 0 1 .983-.956z", fill: "currentColor" })] })); }; const zhCN = { codeBlock: { copy: '复制', copied: '已复制', download: '下载', downloaded: '已下载', }, mermaid: { diagram: '图表', code: '代码', zoomOut: '缩小', zoomIn: '放大', download: '下载', fullScreen: '全屏', exitFullScreen: '退出全屏', downloadImage: '下载图片', downloadedImage: '已下载', copyImage: '复制图片', copiedImage: '已复制', fitInView: '适应页面', }, }; const ConfigContext = react.createContext({ locale: zhCN, }); const ConfigProvider = ({ locale, children, mermaidConfig }) => { const contextValue = react.useMemo(() => { const contextValue = { locale: locale || zhCN, }; if (mermaidConfig) { contextValue.mermaidConfig = mermaidConfig; } return contextValue; }, [locale, mermaidConfig]); return jsxRuntime.jsx(ConfigContext.Provider, { value: contextValue, children: children }); }; // Hook 用于在组件中使用配置 const useConfig = () => { const context = react.useContext(ConfigContext); return context; }; // Hook 用于获取当前语言包 const useLocale = () => { const { locale } = useConfig(); return locale; }; const Button = ({ className = '', children, icon, onClick, style, disabled = false, ...restProps }) => { const handleClick = (e) => { if (disabled) { e.preventDefault(); return; } onClick?.(); }; return (jsxRuntime.jsxs("div", { role: "button", className: classNames({ 'ds-button': true, 'ds-button__disabled': disabled, }, className), onClick: handleClick, style: style, "aria-disabled": disabled, ...restProps, children: [icon && jsxRuntime.jsx("div", { className: "ds-button__icon", children: icon }), children] })); }; const SuccessButton = (props) => { const { onClick, icon, executeText, children, ...rest } = props; const [isLoading, setIsLoading] = react.useState(false); const [isSuccess, setIsSuccess] = react.useState(false); const isUnmounted = react.useRef(false); const handleClick = async () => { if (isLoading || isSuccess) { return; } try { // 如果onClick不是异步函数,则直接调用 const returnValue = onClick(); if (returnValue instanceof Promise) { setIsLoading(true); const result = await returnValue; if (result) { setIsSuccess(true); setTimeout(() => { if (!isUnmounted.current) { setIsSuccess(false); } }, 1000); } } } catch (error) { setIsSuccess(false); } finally { setIsLoading(false); } }; react.useEffect(() => { isUnmounted.current = false; return () => { isUnmounted.current = true; }; }, []); return (jsxRuntime.jsx(Button, { ...rest, onClick: handleClick, icon: isSuccess ? jsxRuntime.jsx(CheckMarkIcon, { size: 24 }) : icon, children: isSuccess ? executeText || children : children })); }; const CopyButton = ({ codeContent, style, className }) => { const { locale } = useConfig(); const handleCopy = async () => { try { await navigator.clipboard.writeText(codeContent || ''); return true; } catch (err) { // 降级方案:使用传统方法 const textArea = document.createElement('textarea'); textArea.value = codeContent || ''; textArea.select(); document.execCommand('copy'); return true; } }; return (jsxRuntime.jsx(SuccessButton, { onClick: handleCopy, icon: jsxRuntime.jsx(CopyIcon, { size: 24 }), executeText: locale.codeBlock.copied || 'copied', style: style, className: className, children: locale.codeBlock.copy || 'copy' })); }; const DownloadButton = ({ codeContent, language, style, className }) => { const { locale } = useConfig(); // 下载文件 const handleDownload = async () => { if (!codeContent) return false; const blob = new Blob([codeContent], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); // 根据语言设置文件扩展名 const getFileExtension = (lang) => { const extensions = { javascript: 'js', typescript: 'ts', jsx: 'jsx', tsx: 'tsx', python: 'py', java: 'java', cpp: 'cpp', c: 'c', csharp: 'cs', php: 'php', ruby: 'rb', go: 'go', rust: 'rs', swift: 'swift', kotlin: 'kt', scala: 'scala', shell: 'sh', bash: 'sh', powershell: 'ps1', sql: 'sql', html: 'html', css: 'css', scss: 'scss', less: 'less', json: 'json', xml: 'xml', yaml: 'yml', markdown: 'md', dockerfile: 'dockerfile', }; return extensions[lang.toLowerCase()] || 'txt'; }; const fileName = `code.${getFileExtension(language)}`; link.href = url; link.download = fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); return true; }; return (jsxRuntime.jsx(SuccessButton, { onClick: handleDownload, icon: jsxRuntime.jsx(DownloadIcon, { size: 24 }), executeText: locale.codeBlock.downloaded || 'Downloaded', style: style, className: className, children: locale.codeBlock.download || 'Download' })); }; const CodeBlockActions = ({ codeContent, language }) => { return (jsxRuntime.jsxs("div", { className: "md-code-block-header-actions", children: [jsxRuntime.jsx(CopyButton, { codeContent: codeContent, style: { fontSize: 13, padding: '0 4px' } }), jsxRuntime.jsx(DownloadButton, { codeContent: codeContent, language: language, style: { fontSize: 13, padding: '0 4px' } })] })); }; const BlockWrap = ({ children, language, codeContent }) => { const { state: themeState } = useMarkdownThemeContext(); // 从 context 中获取主题配置 const currentCodeBlock = themeState.codeBlock; const { headerActions = true } = currentCodeBlock || {}; const renderHeaderActions = () => { if (headerActions === true) { return jsxRuntime.jsx(CodeBlockActions, { codeContent: codeContent, language: language }); } return headerActions; }; return (jsxRuntime.jsx(CodeBlockWrap, { title: jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: "md-code-block-language", children: language }), renderHeaderActions()] }), children: children })); }; const __DEV__ = process.env.NODE_ENV === 'development'; const ID_PREFIX__ = '__ds-markdown__'; /** 数学公式插件id */ const katexId = `${ID_PREFIX__}katex`; const HighlightCode = ({ code, language }) => { return (jsxRuntime.jsx(reactSyntaxHighlighter.Prism, { useInlineStyles: false, language: language, style: {}, children: code })); }; const CodeComponent = ({ className, children = '' }) => { const match = /language-(\w+)/.exec(className || ''); const codeContent = String(children).replace(/\n$/, ''); return match ? (jsxRuntime.jsx(BlockWrap, { language: match[1], codeContent: codeContent, children: jsxRuntime.jsx(HighlightCode, { code: codeContent, language: match[1] }) })) : (jsxRuntime.jsx("code", { className: className, children: children })); }; const HighReactMarkdown = ({ children: _children, ...props }) => { const { state: themeState } = useMarkdownThemeContext(); // 从 context 中获取主题配置 const currentMath = themeState.math; const currentPlugins = themeState.plugins; const mathSplitSymbol = currentMath?.splitSymbol ?? 'dollar'; const finalReplaceMathBracket = currentMath?.replaceMathBracket ?? replaceMathBracket; const { remarkPlugins, rehypePlugins, hasKatexPlugin, components } = react.useMemo(() => { let hasKatexPlugin = false; const components = {}; const remarkPlugins = [gfmPlugin]; const rehypePlugins = []; if (!currentPlugins) { return { remarkPlugins, rehypePlugins, }; } currentPlugins.forEach((plugin) => { if (plugin.id === katexId) { hasKatexPlugin = true; remarkPlugins.push(plugin.remarkPlugin); rehypePlugins.push(plugin.rehypePlugin); } else { if (plugin.rehypePlugin) { rehypePlugins.push(plugin.rehypePlugin); } if (plugin.remarkPlugin) { remarkPlugins.push(plugin.remarkPlugin); } } if (plugin.components) { Object.assign(components, plugin.components); } }); return { remarkPlugins, rehypePlugins, hasKatexPlugin, components, }; }, [currentPlugins]); const children = react.useMemo(() => { /** 如果存在数学公式插件,并且数学公式分隔符为括号,则替换成 $ 符号 */ if (hasKatexPlugin && mathSplitSymbol === 'bracket') { return finalReplaceMathBracket(_children); } return _children; }, [hasKatexPlugin, mathSplitSymbol, finalReplaceMathBracket, _children]); return (jsxRuntime.jsx(Markdown$2, { remarkPlugins: remarkPlugins, rehypePlugins: rehypePlugins, components: { code: CodeComponent, table: ({ children, ...props }) => { return (jsxRuntime.jsx("div", { className: "markdown-table-wrapper", children: jsxRuntime.jsx("table", { className: "ds-markdown-table", children: children }) })); }, ...components, }, ...props, children: children })); }; var HighReactMarkdown$1 = react.memo(HighReactMarkdown); const useTypingTask = (options) => { const { timerType = 'setTimeout', interval, charsRef, onEnd, onStart, onBeforeTypedChar, onTypedChar, processCharDisplay, wholeContentRef, disableTyping, triggerUpdate, resetWholeContent, } = options; /** 是否卸载 */ const isUnmountRef = react.useRef(false); /** 是否正在打字 */ const isTypingRef = react.useRef(false); /** 动画帧ID */ const animationFrameRef = react.useRef(null); /** 传统定时器(兼容模式) */ const timerRef = react.useRef(null); // 已经打过的字记录 const typedCharsRef = react.useRef(undefined); // 是否主动调用 stop 方法 const typedIsManualStopRef = react.useRef(false); const disableTypingRef = react.useRef(disableTyping); disableTypingRef.current = disableTyping; const intervalRef = react.useRef(interval); intervalRef.current = interval; const getChars = () => { return charsRef.current; }; react.useEffect(() => { isUnmountRef.current = false; return () => { isUnmountRef.current = true; clearTimer(); }; }, []); /** * 触发打字开始回调 * @param char 当前字符 */ const triggerOnStart = (char) => { if (!onStart) { return; } const prevStr = wholeContentRef.current[char.answerType].content; onStart({ currentIndex: prevStr.length, currentChar: char.content, answerType: char.answerType, prevStr, }); }; /** * 触发打字结束回调 */ const triggerOnEnd = (data) => { if (!onEnd) { return; } onEnd({ str: wholeContentRef.current.answer.content, answerStr: wholeContentRef.current.answer.content, thinkingStr: wholeContentRef.current.thinking.content, manual: data?.manual ?? false, }); }; /** * 触发打字过程中回调 * @param char 当前字符 */ const triggerOnBeforeTypedChar = async (char) => { if (!onBeforeTypedChar) { return; } const { answerType, content, index } = char; const allLength = wholeContentRef.current.allLength; // 计算之前字符的百分比 const percent = (char.index / allLength) * 100; await onBeforeTypedChar({ currentIndex: index, currentChar: content, answerType: answerType, prevStr: wholeContentRef.current[answerType].content, percent, }); }; /** 打字完成回调 */ const triggerOnTypedChar = async (char) => { if (!onTypedChar) { return; } const { answerType, content, index } = char; const allLength = wholeContentRef.current.allLength; const percent = ((char.index + 1) / allLength) * 100; onTypedChar({ currentIndex: index, currentChar: content, answerType: answerType, prevStr: wholeContentRef.current[answerType].content.slice(0, index), currentStr: wholeContentRef.current[answerType].content, percent, }); }; /** 清除定时器 */ const clearTimer = () => { // 清理 requestAnimationFrame if (animationFrameRef.current) { cancelAnimationFrame(animationFrameRef.current); animationFrameRef.current = null; } // 清理 setTimeout (可能被 timestamp 模式使用) if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; } isTypingRef.current = false; typedCharsRef.current = undefined; }; /** 开始打字任务 */ const startTypedTask = () => { /** 如果手动调用 stop 方法,则不重新开始打字 */ if (typedIsManualStopRef.current) { return; } if (isTypingRef.current) { return; } if (timerType === 'requestAnimationFrame') { startAnimationFrameMode(); } else { startTimeoutMode(); } }; /** 打字机打完所有字符 */ async function typingRemainAll() { const chars = getChars(); const thinkingCharsStr = chars .filter((char) => char.answerType === 'thinking') .map((char) => char.content) .join(''); const answerCharsStr = chars .filter((char) => char.answerType === 'answer') .map((char) => char.content) .join(''); if (thinkingCharsStr) { await onBeforeTypedChar?.({ currentIndex: wholeContentRef.current.thinking.length, currentChar: thinkingCharsStr, answerType: 'thinking', prevStr: wholeContentRef.current.thinking.content, percent: 100, }); } if (answerCharsStr) { await onBeforeTypedChar?.({ currentIndex: wholeContentRef.current.answer.length, currentChar: answerCharsStr, answerType: 'answer', prevStr: wholeContentRef.current.answer.content, percent: 100, }); } wholeContentRef.current.thinking.content += thinkingCharsStr; wholeContentRef.current.thinking.length += thinkingCharsStr.length; wholeContentRef.current.answer.content += answerCharsStr; wholeContentRef.current.answer.length += answerCharsStr.length; wholeContentRef.current.allLength += thinkingCharsStr.length + answerCharsStr.length; charsRef.current = []; isTypingRef.current = false; triggerOnEnd(); triggerUpdate(); } /** requestAnimationFrame 模式 */ const startAnimationFrameMode = () => { let lastFrameTime = performance.now(); const frameLoop = async (currentTime) => { // 如果关闭打字机效果,则打完所有字符 if (disableTypingRef.current) { await typingRemainAll(); return; } const chars = getChars(); if (isUnmountRef.current) return; if (chars.length === 0) { stopAnimationFrame(); return; } const deltaTime = currentTime - lastFrameTime; let needToTypingCharsLength = Math.max(0, Math.floor(deltaTime / intervalRef.current)); needToTypingCharsLength = Math.min(needToTypingCharsLength, chars.length); if (needToTypingCharsLength > 0) { // 处理字符 for (let i = 0; i < needToTypingCharsLength; i++) { const char = chars.shift(); if (char === undefined) break; if (!isTypingRef.current) { isTypingRef.current = true; triggerOnStart(char); } /** 打字前回调 */ await triggerOnBeforeTypedChar(char); processCharDisplay(char); /** 打字完成回调 */ triggerOnTypedChar(char); } lastFrameTime = performance.now(); // 继续下一帧 if (chars.length > 0) { animationFrameRef.current = requestAnimationFrame(frameLoop); } else { isTypingRef.current = false; triggerOnEnd(); } } else { // 本次你不需要打字,继续下一帧 animationFrameRef.current = requestAnimationFrame(frameLoop); } }; animationFrameRef.current = requestAnimationFrame(frameLoop); }; /** 停止动画帧模式 */ const stopAnimationFrame = (manual = false) => { isTypingRef.current = false; if (animationFrameRef.current) { cancelAnimationFrame(animationFrameRef.current); animationFrameRef.current = null; } if (!manual) { triggerOnEnd({ manual }); } }; /** setTimeout 模式 */ const startTimeoutMode = () => { const nextTyped = () => { const chars = getChars(); if (chars.length === 0) { stopTimeout(); return; } timerRef.current = setTimeout(startTyped, intervalRef.current); }; const startTyped = async (isStartPoint = false) => { // 如果关闭打字机效果,则打完所有字符 if (disableTypingRef.current) { typingRemainAll(); return; } const chars = getChars(); if (isUnmountRef.current) return; isTypingRef.current = true; const char = chars.shift(); if (char === undefined) { stopTimeout(); return; } if (isStartPoint) { triggerOnStart(char); } /** 打字前回调 */ await triggerOnBeforeTypedChar(char); processCharDisplay(char); /** 打字完成回调 */ triggerOnTypedChar(char); nextTyped(); }; startTyped(true); }; /** 停止超时模式 */ const stopTimeout = () => { isTypingRef.current = false; if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; } triggerOnEnd(); }; const cancelTask = () => { if (timerType === 'requestAnimationFrame') { stopAnimationFrame(); } else { stopTimeout(); } }; /** 暂时停止 */ const stopTask = () => { typedIsManualStopRef.current = true; cancelTask(); }; /** 停止打字任务 */ const endTask = () => { cancelTask(); }; function restartTypedTask() { endTask(); // 将wholeContentRef的内容放到charsRef中 charsRef.current.unshift(...wholeContentRef.current.thinking.content.split('').map((charUnit) => { const char = { content: charUnit, answerType: 'thinking', tokenId: 0, index: 0, }; return char; })); charsRef.current.unshift(...wholeContentRef.current.answer.content.split('').map((charUnit) => { const char = { content: charUnit, answerType: 'answer', tokenId: 0, index: 0, }; return char; })); resetWholeContent(); triggerUpdate(); startTypedTask(); } function clear() { clearTimer(); } function resume() { typedIsManualStopRef.current = false; startTypedTask(); } return { start: startTypedTask, restart: restartTypedTask, stop: stopTask, resume: resume, clear: clear, isTyping: () => isTypingRef.current, typedIsManualStopRef, }; }; const MarkdownContext = react.createContext({}); const MarkdownProvider = ({ value, children }) => { const contextValue = react.useMemo(() => value, [value]); return jsxRuntime.jsx(MarkdownContext.Provider, { value: contextValue, children: children }); }; const MarkdownCMDInner = react.forwardRef(({ interval = 30, onEnd, onStart, onTypedChar, onBeforeTypedChar, timerType = 'setTimeout', disableTyping = false, autoStartTyping = true }, ref) => { const { state: themeState } = useMarkdownThemeContext(); // 从 context 中获取主题配置 const currentTheme = themeState.theme; /** 是否自动开启打字动画, 后面发生变化将不会生效 */ const autoStartTypingRef = react.useRef(autoStartTyping); /** 是否打过字 */ const isStartedTypingRef = react.useRef(false); /** 当前需要打字的内容 */ const charsRef = react.useRef([]); /** * 打字是否已经完全结束 * 如果打字已经完全结束,则不会再触发打字效果 */ const isWholeTypedEndRef = react.useRef(false); const charIndexRef = react.useRef(0); /** 整个内容引用 */ const wholeContentRef = react.useRef({ thinking: { content: '', length: 0, prevLength: 0, }, answer: { content: '', length: 0, prevLength: 0, }, allLength: 0, }); const [, setUpdate] = react.useState(0); const triggerUpdate = () => { setUpdate((prev) => prev + 1); }; /** * 处理字符显示逻辑 */ const processCharDisplay = (char) => { if (!isStartedTypingRef.current) { isStartedTypingRef.current = true; } if (char.answerType === 'thinking') { wholeContentRef.current.thinking.content += char.content; wholeContentRef.current.thinking.length += 1; } else { wholeContentRef.current.answer.content += char.content; wholeContentRef.current.answer.length += 1; } triggerUpdate(); }; const resetWholeContent = () => { wholeContentRef.current.thinking.content = ''; wholeContentRef.current.thinking.length = 0; wholeContentRef.current.thinking.prevLength = 0; wholeContentRef.current.answer.content = ''; wholeContentRef.current.answer.length = 0; wholeContentRef.current.answer.prevLength = 0; wholeContentRef.current.allLength = 0; }; // 使用新的打字任务 hook const typingTask = useTypingTask({ timerType, interval, charsRef, onEnd, onStart, onTypedChar, onBeforeTypedChar, processCharDisplay, wholeContentRef, disableTyping, triggerUpdate, resetWholeContent, }); /** * 内部推送处理逻辑 */ const processHasTypingPush = (content, answerType) => { if (content.length === 0) { return; } charsRef.current.push(...content.split('').map((chatStr) => { const index = charIndexRef.current++; const charObj = { content: chatStr, answerType, tokenId: 0, index, }; return charObj; })); wholeContentRef.current.allLength += content.length; // 如果关闭了自动打字, 并且没有打过字, 则不开启打字动画 if (!autoStartTypingRef.current && !isStartedTypingRef.current) { return; } if (!typingTask.isTyping()) { typingTask.start(); } }; const processNoTypingPush = (content, answerType) => { wholeContentRef.current[answerType].content += content; // 记录打字前的长度 wholeContentRef.current[answerType].prevLength = wholeContentRef.current[answerType].length; wholeContentRef.current[answerType].length += content.length; triggerUpdate(); onEnd?.({ str: content, answerStr: wholeContentRef.current.answer.content, thinkingStr: wholeContentRef.current.thinking.content, manual: false, }); }; react.useImperativeHandle(ref, () => ({ /** * 添加内容 * @param content 内容 {string} * @param answerType 回答类型 {AnswerType} */ push: (content, answerType = 'answer') => { if (disableTyping) { processNoTypingPush(content, answerType); return; } processHasTypingPush(content, answerType); }, /** * 清除打字任务 */ clear: () => { typingTask.stop(); typingTask.typedIsManualStopRef.current = false; charsRef.current = []; resetWholeContent(); isWholeTypedEndRef.current = false; charIndexRef.current = 0; isStartedTypingRef.current = false; triggerUpdate(); }, /** 开启打字,只有在关闭了自动打字才生效 */ start: () => { if (!autoStartTypingRef.current) { typingTask.start(); } }, /** 停止打字任务 */ stop: () => { typingTask.stop(); }, /** 重新开始打字任务 */ resume: () => { typingTask.resume(); }, /** * 主动触发打字结束 */ triggerWholeEnd: () => { isWholeTypedEndRef.current = true; if (!typingTask.isTyping()) { // 这里需要手动触发结束回调,因为 hook 中的 triggerOnEnd 不能直接调用 onEnd?.({ str: wholeContentRef.current.answer.content, answerStr: wholeContentRef.current.answer.content, thinkingStr: wholeContentRef.current.thinking.content, manual: true, }); } }, /** 重新开始打字任务 */ restart: () => { typingTask.restart(); }, })); const getParagraphs = (answerType) => { const content = wholeContentRef.current[answerType].content || ''; return (jsxRuntime.jsx("div", { className: `ds-markdown-paragraph ds-typed-${answerType}`, children: jsxRuntime.jsx(HighReactMarkdown$1, { children: content }) })); }; return (jsxRuntime.jsxs("div", { className: classNames({ 'ds-markdown': true, apple: true, 'ds-markdown-dark': currentTheme === 'dark', }), children: [jsxRuntime.jsx("div", { className: "ds-markdown-thinking", children: getParagraphs('thinking') }), jsxRuntime.jsx("div", { className: "ds-markdown-answer", children: getParagraphs('answer') })] })); }); if (__DEV__) { MarkdownCMDInner.displayName = 'MarkdownCMD'; } const MarkdownCMD = react.forwardRef((props, ref) => { const { children = '', answerType = 'answer', isInnerRender, ...reset } = props; if (__DEV__) { if (!['thinking', 'answer'].includes(answerType)) { throw new Error('Markdown组件的answerType必须是thinking或answer'); } if (typeof children !== 'string') { throw new Error('Markdown组件的子元素必须是一个字符串'); } } const contextValue = react.useMemo(() => ({ ...reset, answerType }), [reset, answerType]); // 分离主题相关的 props const themeProps = react.useMemo(() => ({ theme: props.theme || DEFAULT_THEME, math: props.math, codeBlock: props.codeBlock, plugins: props.plugins || DEFAULT_PLUGINS, answerType: props.answerType || DEFAULT_ANSWER_TYPE, }), [props.theme, props.math, props.codeBlock, props.plugins, props.answerType]); if (isInnerRender) { // 内部渲染,外层已经 context 传递了 props,这里不再重复传递 return jsxRuntime.jsx(MarkdownCMDInner, { ...props, ref: ref }); } return (jsxRuntime.jsx(MarkdownProvider, { value: contextValue, children: jsxRuntime.jsx(MarkdownThemeProvider, { value: themeProps, children: jsxRuntime.jsx(MarkdownCMDInner, { ...props, ref: ref }) }) })); }); const MarkdownInner = ({ children: _children = '', answerType, markdownRef, ...rest }) => { const cmdRef = react.useRef(null); const prefixRef = react.useRef(''); const content = react.useMemo(() => { if (typeof _children === 'string') { return _children; } if (__DEV__) { console.error('Markdown组件的子元素必须是一个字符串'); } return ''; }, [_children]); react.useEffect(() => { if (prefixRef.current !== content) { let newContent = ''; if (prefixRef.current === '') { newContent = content; } else { if (content.startsWith(prefixRef.current)) { newContent = content.slice(prefixRef.current.length); } else { newContent = content; cmdRef.current.clear(); } } cmdRef.current.push(newContent, answerType); prefixRef.current = content; } }, [answerType, content]); react.useImperativeHandle(markdownRef, () => ({ stop: () => { cmdRef.current.stop(); }, resume: () => { cmdRef.current.resume(); }, start: () => { cmdRef.current.start(); }, restart: () => { cmdRef.current.restart(); }, })); // 只传递 MarkdownBaseProps 相关的属性 const { theme, math, plugins, codeBlock, ...baseProps } = rest; return jsxRuntime.jsx(MarkdownCMD, { ref: cmdRef, ...baseProps, isInnerRender: true }); }; const Markdown = react.forwardRef((props, ref) => { const { children = '', answerType = 'answer', ...reset } = props; if (__DEV__) { if (!['thinking', 'answer'].includes(answerType)) { throw new Error('Markdown组件的answerType必须是thinking或answer'); } if (typeof children !== 'string') { throw new Error('Markdown组件的子元素必须是一个字符串'); } } const contextValue = react.useMemo(() => ({ ...reset, answerType }), [reset, answerType]); // 分离主题相关的 props const themeProps = react.useMemo(() => ({ theme: props.theme || DEFAULT_THEME, math: props.math, codeBlock: props.codeBlock, plugins: props.plugins || DEFAULT_PLUGINS, answerType: props.answerType || DEFAULT_ANSWER_TYPE, }), [props.theme, props.math, props.codeBlock, props.plugins, props.answerType]); return (jsxRuntime.jsx(MarkdownProvider, { value: contextValue, children: jsxRuntime.jsx(MarkdownThemeProvider, { value: themeProps, children: jsxRuntime.jsx(MarkdownInner, { ...props, answerType: answerType, markdownRef: ref }) }) })); }); var Markdown$1 = react.memo(Markdown); const IconButton = ({ icon, className = '', ...restProps }) => { return jsxRuntime.jsx(Button, { icon: icon, className: `ds-icon-button ${className}`, ...restProps }); }; const Segmented = ({ Segmented: segments, value, onChange }) => { const handleClick = (itemValue) => { onChange?.(itemValue); }; return (jsxRuntime.jsx("div", { className: "ds-segmented-container", children: segments.map((item) => (jsxRuntime.jsx("div", { className: `ds-segmented-item ${value === item.value ? 'active' : ''}`, onClick: () => handleClick(item.value), children: item.label }, item.value))) })); }; /* eslint-disable react-refresh/only-export-components */ exports.Button = Button; exports.CheckMarkIcon = CheckMarkIcon; exports.CodeBlockActions = CodeBlockActions; exports.CodeBlockWrap = CodeBlockWrap; exports.ConfigProvider = ConfigProvider; exports.CopyButton = CopyButton; exports.CopyIcon = CopyIcon; exports.DownloadButton = DownloadButton; exports.DownloadIcon = DownloadIcon; exports.HighlightCode = HighlightCode; exports.IconButton = IconButton; exports.Markdown = Markdown$1; exports.MarkdownCMD = MarkdownCMD; exports.Segmented = Segmented; exports.SuccessButton = SuccessButton; exports.default = Markdown$1; exports.useConfig = useConfig; exports.useLocale = useLocale; exports.useThemeState = useThemeState; //# sourceMappingURL=index.js.map