import type { RendererRule } from 'markdown-it' import type { Markdown } from 'vuepress/markdown' import type { CodeTreeEnv } from './renderCodeTree.js' import { resolveAttrs } from './utils.js' /** * MarkdownIt instances the code block renderer is installed on * * 已安装代码块渲染器的 MarkdownIt 实例 */ const installed = new WeakSet() /** * Mark the code block of the active file of a code tree as active while the * Markdown is rendered * * The code tree only displays the code block of the active file, and the active * file is decided when the container or the embed syntax is rendered. Marking * it in the rendered HTML keeps the entry code block visible in the SSR output * and before the client takes over, instead of leaving the panel blank until * the client marks the block. * * Only the default markup of the code block title is supported. When the title * is rendered by a custom function, the rendered code block is kept as it is. * * 在渲染 Markdown 时将代码树中激活文件的代码块标记为激活 * * 代码树只显示激活文件的代码块,激活文件由容器语法或嵌入语法确定。在渲染时标记它,代码块在 SSR * 输出中、客户端接管之前就能显示,面板不会空白到客户端标记为止。 * * 仅支持默认的代码块标题结构。标题由自定义函数渲染时,渲染后的代码块会保持原样。 * * @param md - MarkdownIt instance / MarkdownIt 实例 */ export const installActiveCodeBlockRenderer = (md: Markdown): void => { if (installed.has(md)) return installed.add(md) const rawFence = md.renderer.rules.fence const activeCodeBlockRenderer: RendererRule = ( tokens, index, options, env: CodeTreeEnv | undefined, self, ): string => { const result = rawFence(tokens, index, options, env, self) const activeFile = env?.codeTreeActiveFile if (!activeFile) return result const token = tokens[index] // The info string is parsed the same way as the code block title plugin const info = token.info ? md.utils.unescapeAll(token.info).trim() : '' const title = resolveAttrs(info, 'title')?.trim() if (title !== activeFile) return result // The default title markup is required by the code tree, so a custom title // that does not use it is left untouched return result.replace( '
', '
', ) } md.renderer.rules.fence = activeCodeBlockRenderer }