2 * Rehype plugin to enhance code blocks with wrapper, header, and action buttons.
4 * Wraps <pre><code> elements with a container that includes:
7 * - Preview button (for HTML code blocks)
9 * This operates directly on the HAST tree for better performance,
10 * avoiding the need to stringify and re-parse HTML.
13 import type { Plugin } from 'unified';
14 import type { Root, Element, ElementContent } from 'hast';
15 import { visit } from 'unist-util-visit';
17 CODE_BLOCK_SCROLL_CONTAINER_CLASS,
18 CODE_BLOCK_WRAPPER_CLASS,
19 CODE_BLOCK_HEADER_CLASS,
20 CODE_BLOCK_ACTIONS_CLASS,
23 PREVIEW_CODE_BTN_CLASS,
25 } from '$lib/constants';
29 idxCodeBlock?: number;
33 const COPY_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-copy-icon lucide-copy"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>`;
35 const PREVIEW_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-eye lucide-eye-icon"><path d="M2.062 12.345a1 1 0 0 1 0-.69C3.5 7.73 7.36 5 12 5s8.5 2.73 9.938 6.655a1 1 0 0 1 0 .69C20.5 16.27 16.64 19 12 19s-8.5-2.73-9.938-6.655"/><circle cx="12" cy="12" r="3"/></svg>`;
37 function createIconElement(svg: string): Element {
42 children: [{ type: 'raw', value: svg } as unknown as ElementContent]
46 function createButton(className: string, title: string, iconSvg: string, codeId: string): Element {
51 className: [className],
52 'data-code-id': codeId,
56 children: [createIconElement(iconSvg)]
60 function createCopyButton(codeId: string): Element {
61 return createButton(COPY_CODE_BTN_CLASS, 'Copy code', COPY_ICON_SVG, codeId);
64 function createPreviewButton(codeId: string): Element {
65 return createButton(PREVIEW_CODE_BTN_CLASS, 'Preview code', PREVIEW_ICON_SVG, codeId);
68 function createHeader(language: string, codeId: string): Element {
69 const actions: Element[] = [createCopyButton(codeId)];
71 if (language.toLowerCase() === 'html') {
72 actions.push(createPreviewButton(codeId));
78 properties: { className: [CODE_BLOCK_HEADER_CLASS] },
83 properties: { className: [CODE_LANGUAGE_CLASS] },
84 children: [{ type: 'text', value: language }]
89 properties: { className: [CODE_BLOCK_ACTIONS_CLASS] },
96 function createScrollContainer(preElement: Element): Element {
100 properties: { className: [CODE_BLOCK_SCROLL_CONTAINER_CLASS] },
101 children: [preElement]
105 function createWrapper(header: Element, preElement: Element): Element {
109 properties: { className: [CODE_BLOCK_WRAPPER_CLASS, RELATIVE_CLASS] },
110 children: [header, createScrollContainer(preElement)]
114 function extractLanguage(codeElement: Element): string {
115 const className = codeElement.properties?.className;
116 if (!Array.isArray(className)) return 'text';
118 for (const cls of className) {
119 if (typeof cls === 'string' && cls.startsWith('language-')) {
120 return cls.replace('language-', '');
128 * Generates a unique code block ID using a global counter.
130 function generateCodeId(): string {
131 if (typeof window !== 'undefined') {
132 return `code-${(window.idxCodeBlock = (window.idxCodeBlock ?? 0) + 1)}`;
134 // Fallback for SSR - use timestamp + random
135 return `code-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
139 * Rehype plugin to enhance code blocks with wrapper, header, and action buttons.
140 * This plugin wraps <pre><code> elements with a container that includes:
143 * - Preview button (for HTML code blocks)
145 export const rehypeEnhanceCodeBlocks: Plugin<[], Root> = () => {
146 return (tree: Root) => {
147 visit(tree, 'element', (node: Element, index, parent) => {
148 if (node.tagName !== 'pre' || !parent || index === undefined) return;
150 const codeElement = node.children.find(
151 (child): child is Element => child.type === 'element' && child.tagName === 'code'
154 if (!codeElement) return;
156 const language = extractLanguage(codeElement);
157 const codeId = generateCodeId();
159 codeElement.properties = {
160 ...codeElement.properties,
161 'data-code-id': codeId
164 const header = createHeader(language, codeId);
165 const wrapper = createWrapper(header, node);
167 // Replace pre with wrapper in parent
168 (parent.children as ElementContent[])[index] = wrapper;