fumadocs-core
Version:
The React.js library for building a documentation website
39 lines (38 loc) • 1.42 kB
JavaScript
"use client";
import { toJsx } from "../../utils/hast-to-jsx.js";
import { r as highlightHast } from "../../shiki-DL5DIaX-.js";
import { use, useEffect, useMemo, useRef, useState } from "react";
// src/highlight/shiki/react.ts
const promises = {};
async function render(highlighter, code, options) {
const instance = typeof highlighter === "function" ? await highlighter() : highlighter;
return toJsx(await highlightHast(instance, code, options), { components: options.components });
}
/**
* get highlighted results (uncached), use `useEffect` instead of React 19 APIs.
*/
function useShikiDynamic(highlighter, code, options, deps) {
const [node, setNode] = useState(options.defaultValue);
const lastTask = useRef(null);
useEffect(() => {
const promise = render(highlighter, code, options);
lastTask.current = promise;
promise.then((res) => {
if (lastTask.current === promise) setNode(res);
});
return () => {
lastTask.current = null;
};
}, deps);
return node;
}
/**
* get highlighted results, should be used with React Suspense API.
*
* note: results are cached with (lang, code) as keys, if this is not the desired behaviour, pass a `deps` instead.
*/
function useShiki(highlighter, code, options, deps = [options.lang, code]) {
const key = useMemo(() => JSON.stringify(deps), [deps]);
return use(promises[key] ??= render(highlighter, code, options));
}
export { useShiki, useShikiDynamic };