import React from 'react'; import { createRoot, Root } from 'react-dom/client'; import markdownItContainer from 'markdown-it-container'; import JSON5 from 'json5'; /** * 解析 markdown-it-container 的配置 JSON * 通用方法,抽取了容器标签解析配置的公共逻辑 * @param tokenInfo token.info 字符串 * @param tagName 容器标签名(如 'amap', 'copyPassword') * @returns 解析后的配置对象,解析失败返回空对象 */ export function parseContainerConfig(tokenInfo: string, tagName: string): Record { const text = tokenInfo.trim(); // 使用 [\s\S] 匹配多行内容,提取 tagName 之后的全部文本 const m = text.match(new RegExp(`^${tagName}\\s*([\\s\\S]*)$`)); if (m && m[1]) { try { // 兼容末尾带有 ::: 的情况,去除 ::: 及之后的内容 const configStr = m[1].trim().split(':::')[0].trim(); if (configStr) { return JSON5.parse(configStr); } } catch (e) { console.warn(`[${tagName}] Failed to parse config:`, e); } } return {}; } /** * 创建 markdown-it-container 插件 * 抽取了 validate 和 render 骨架的公共逻辑 * @param md markdown-it 实例 * @param tagName 容器标签名 * @param renderOpen 渲染开始标签的回调,接收 (config, md),返回 HTML 字符串 * @param renderClose 渲染结束标签的回调,返回 HTML 字符串,默认 `''` */ export function createContainerPlugin( md: any, tagName: string, renderOpen: (config: Record, md: any, isBlock?: boolean) => string, renderClose: () => string = () => '', ) { // 添加 inline rule 处理单行完整容器 :::tagName{...}::: md.inline.ruler.before('escape', `${tagName}_inline`, (state: any, silent: boolean) => { const src = state.src.slice(state.pos); // 匹配 :::tagName{...}::: const match = src.match(new RegExp(`^:::${tagName}\\s*(\\{[^}]*\\}):::`)); if (!match) return false; if (!silent) { const token = state.push(`${tagName}_inline`, '', 0); token.content = match[1]; } state.pos += match[0].length; return true; }); // 添加 inline render rule md.renderer.rules[`${tagName}_inline`] = (tokens: any[], idx: number) => { const token = tokens[idx]; try { const config = JSON5.parse(token.content); return renderOpen(config, md, false); } catch (e) { console.warn(`[${tagName}] Failed to parse inline config:`, e); return ''; } }; md.use(markdownItContainer, tagName, { validate: (params: string) => { const m = params.trim().match(new RegExp(`^${tagName}\\s*(.*)$`)); if (!m) return false; // 如果包含 :::,说明是单行完整容器,交给 inline rule 处理 if (m[1].includes(':::')) return false; return true; }, render: (tokens: any[], idx: number) => { const token = tokens[idx]; if (token.nesting === 1) { let config = parseContainerConfig(token.info, tagName); // 如果从 token.info 没解析到配置,尝试从容器内部 token 中读取多行 JSON if (Object.keys(config).length === 0) { for (let i = idx + 1; i < tokens.length; i++) { if (tokens[i].nesting === -1) { const innerContent = tokens .slice(idx + 1, i) .map(t => { // inline token 的内容在 children 中 if (t.children && t.children.length > 0) { return t.children.map((c: any) => c.content || c.markup || '').join(''); } return t.content || t.markup || ''; }) .join('') .trim(); if (innerContent) { config = parseContainerConfig(`${tagName} ${innerContent}`, tagName); } break; } } } return renderOpen(config, md, true); } else { return renderClose(); } }, }); } /** * 创建 markdown-it-container 容器组件 * 极致封装:只需提供 tagName 和 React 组件,自动处理解析、占位、挂载 * @param tagName 容器标签名 * @param Component React 组件,接收 config 中各字段作为 props * @returns render(md) 注册插件,自动通过 MutationObserver 挂载组件 */ /** 与 remons-render-markdown 约定的持久节点标记:增量 patch 时不丢弃该节点 */ const MD_PERSIST_ATTR = 'data-md-persist'; /** mount 时记录原始 className,供增量渲染按稳定 key 匹配(组件渲染后 class 可能被追加) */ const MD_KEY_ATTR = 'data-md-key'; export function createContainerComponent(tagName: string) { return (Component: React.FC): (md: any) => void => { const placeholderAttr = `data-${tagName}-placeholder`; // 跟踪已挂载的元素,避免重复创建 React 根节点 const mountedElements = new WeakSet(); // 挂载后的 React Root,用于节点真正从 DOM 移除时卸载,避免内存泄漏 const elementRoots = new WeakMap(); const unmountDetached = (el: HTMLElement) => { // 增量渲染会先摘除再恢复持久节点,恢复后 isConnected 为 true,不能卸载 if (el.isConnected) return; const root = elementRoots.get(el); if (!root) return; root.unmount(); elementRoots.delete(el); }; const cleanupRemovedTree = (node: Node) => { if (!(node instanceof HTMLElement)) return; if (node.hasAttribute(MD_PERSIST_ATTR)) unmountDetached(node); node.querySelectorAll(`[${MD_PERSIST_ATTR}]`).forEach(unmountDetached); }; const mount = (el: HTMLElement) => { // 如果已挂载则跳过,避免重复创建 React 根节点 if (mountedElements.has(el)) return; // 增量渲染 patch 期间被替换掉的孤立占位符不再挂载 if (!el.isConnected) return; const props: Record = {}; for (const attr of el.attributes) { if (attr.name.startsWith('data-') && !attr.name.endsWith('-placeholder')) { props[attr.name.slice(5)] = attr.value; } } if (Object.keys(props).length === 0) { const textContent = el.textContent?.trim(); if (textContent) { props.content = textContent; } } // mount 前记录原始 class,增量渲染恢复时按它匹配(组件渲染后可能追加自己的 class) el.setAttribute(MD_KEY_ATTR, Array.from(el.classList).join(' ')); // 标记为持久节点:增量 patch 时先摘除、patch 后按配置恢复,避免被占位符清空 el.setAttribute(MD_PERSIST_ATTR, ''); el.removeAttribute(placeholderAttr); mountedElements.add(el); const root = createRoot(el); elementRoots.set(el, root); root.render(React.createElement(Component, props)); }; // Auto-mount: 通过 MutationObserver 监听 DOM 中新增的占位符并自动挂载 if (typeof window !== 'undefined' && typeof MutationObserver !== 'undefined') { const startObserver = () => { // 先挂载已存在的占位符 document.querySelectorAll(`[${placeholderAttr}]`).forEach(mount); // 持续监听新加入的占位符 const observer = new MutationObserver((mutations) => { for (const mutation of mutations) { for (const node of mutation.addedNodes) { if (node instanceof HTMLElement) { if (node.matches(`[${placeholderAttr}]`)) mount(node); node.querySelectorAll(`[${placeholderAttr}]`).forEach(mount); } } // 节点被真正移除(而非增量渲染的摘除-恢复)时卸载 React Root for (const node of mutation.removedNodes) { cleanupRemovedTree(node); } } }); observer.observe(document.body, { childList: true, subtree: true }); }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', startObserver); } else { startObserver(); } } return (md: any) => { createContainerPlugin( md, tagName, (config, md, isBlock) => { const dataAttrs = Object.entries(config) .map(([key, val]) => `data-${key}="${md.utils.escapeHtml(val || '')}"`) .join(' '); const className = `render-md-plugin-${tagName}-container ${config.class || ''}`; if (isBlock) { // 块级容器将内部原始内容包进隐藏元素:MutationObserver 挂载 React 前, // 块内的原始配置文本不可见,避免「原始内容 -> 组件」的闪动; // mount() 中 el.textContent 兜底读取仍有效,createRoot 首次渲染会清掉容器内旧内容 return `
', ); }; }; }