UNPKG

webforai

Version:

A library that provides a web interface for AI

21 lines (20 loc) 900 B
// src/mdast-handlers/custom-code-handler.ts import { toText } from "hast-util-to-text"; import { trimTrailingLines } from "trim-trailing-lines"; import { detectLanguage } from "../utils/detect-code-lang.js"; var LANGUAGE_MATCH_REGEX = [/language-(\w+)/, /highlight-source-(\w+)/, /CodeBlock--language-(\w+)/]; var customCodeHandler = (state, node) => { const classNames = node.properties?.className || []; const codeValue = trimTrailingLines(toText(node)).trim(); const classLang = classNames.map((className) => { const match = LANGUAGE_MATCH_REGEX.map((regex) => className.match(regex)).find((match2) => match2); return match?.[1]; }).find((className) => className); const lang = classLang || detectLanguage(codeValue) || null; const result = { type: "code", lang, meta: null, value: codeValue }; state.patch(node, result); return result; }; export { customCodeHandler };