UNPKG

ds-markdown

Version:

> 🚀 React Markdown 打字动画组件,提供现代聊天界面效果

78 lines 3.37 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { forwardRef, memo, useEffect, useImperativeHandle, useMemo, useRef } from 'react'; import { __DEV__ } from '../constant.js'; import MarkdownCMD from '../MarkdownCMD/index.js'; import { MarkdownProvider } from '../context/MarkdownProvider.js'; import { DEFAULT_ANSWER_TYPE, DEFAULT_PLUGINS, DEFAULT_THEME, MarkdownThemeProvider } from '../context/MarkdownThemeProvider.js'; const MarkdownInner = ({ children: _children = '', answerType = 'answer', markdownRef, timerType = 'requestAnimationFrame', ...rest }) => { const cmdRef = useRef(null); const prefixRef = useRef(''); const content = useMemo(() => { if (typeof _children === 'string') { return _children; } if (__DEV__) { console.error('The children of Markdown component must be a string'); } return ''; }, [_children]); 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]); useImperativeHandle(markdownRef, () => ({ stop: () => { cmdRef.current.stop(); }, resume: () => { cmdRef.current.resume(); }, start: () => { cmdRef.current.start(); }, restart: () => { cmdRef.current.restart(); }, })); // 从 props 中获取 interval,如果没有则使用默认值 30 const interval = 'interval' in rest ? rest.interval : 30; return _jsx(MarkdownCMD, { ref: cmdRef, ...rest, interval: interval, answerType: answerType, timerType: timerType, isInnerRender: true }); }; const Markdown = forwardRef((props, ref) => { const { children = '', answerType = 'answer', ...reset } = props; if (__DEV__) { if (!['thinking', 'answer'].includes(answerType)) { throw new Error('The answerType of Markdown component must be thinking or answer'); } if (typeof children !== 'string') { throw new Error('The children of Markdown component must be a string'); } } const contextValue = useMemo(() => ({ ...reset, answerType }), [reset, answerType]); // 分离主题相关的 props const themeProps = 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 (_jsx(MarkdownProvider, { value: contextValue, children: _jsx(MarkdownThemeProvider, { value: themeProps, children: _jsx(MarkdownInner, { ...props, answerType: answerType, markdownRef: ref }) }) })); }); export default memo(Markdown); //# sourceMappingURL=index.js.map