import "@microflash/remark-callout-directives/theme/github" import "remark-gh-alerts/styles/github-colors-light.css" import "remark-gh-alerts/styles/github-colors-dark-media.css" import "remark-gh-alerts/styles/github-base.css" import remarkCalloutDirectives from "@microflash/remark-callout-directives" import type { Components } from "hast-util-to-jsx-runtime" import { toJsxRuntime } from "hast-util-to-jsx-runtime" import { createElement } from "react" import { Fragment, jsx, jsxs } from "react/jsx-runtime" import rehypeStringify from "rehype-stringify" import remarkDirective from "remark-directive" import remarkGfm from "remark-gfm" import remarkGithubAlerts from "remark-gh-alerts" import remarkParse from "remark-parse" import remarkRehype from "remark-rehype" import { unified } from "unified" import { VFile } from "vfile" import { MarkdownLink } from "~/components/ui/markdown/renderers/MarkdownLink" import { VideoPlayer } from "~/components/ui/media/VideoPlayer" export interface RemarkOptions { components: Partial } export const parseMarkdown = (content: string, options?: Partial) => { const file = new VFile(content) const { components } = options || {} const pipeline = unified() .use(remarkParse) .use(remarkGfm) .use(remarkGithubAlerts) .use(remarkDirective) .use(remarkCalloutDirectives, { aliases: { danger: "deter", tip: "note", }, callouts: { note: { title: "Note", hint: ``, }, commend: { title: "Success", hint: ``, }, warn: { title: "Warning", hint: ``, }, deter: { title: "Danger", hint: ``, }, assert: { title: "Info", hint: ``, }, }, }) .use(remarkRehype, { allowDangerousHtml: true }) .use(rehypeStringify, { allowDangerousHtml: true }) const tree = pipeline.parse(content) const hastTree = pipeline.runSync(tree, file) return { content: toJsxRuntime(hastTree, { Fragment, ignoreInvalidStyle: true, jsx: (type, props, key) => jsx(type as any, props, key), jsxs: (type, props, key) => jsxs(type as any, props, key), passNode: true, components: { a: ({ node, ...props }) => createElement(MarkdownLink, { ...props } as any), img: ({ node, ...props }) => { const { src } = props const isVideo = src?.endsWith(".mp4") if (isVideo) { return createElement(VideoPlayer, { src: src as string, }) } return createElement("img", { ...props } as any) }, ...components, }, }), } }