import * as React from "react"; import assign from "core-js/features/object/assign"; import Highlight, { Prism } from "prism-react-renderer"; import theme from "prism-react-renderer/themes/github"; import { useIsomorphicLayoutEffect as useLayoutEffect } from "@reach/utils/use-isomorphic-layout-effect"; /* * We need to transpile code extracted from mdx before we try to eval it. * babel/standalone is HUGE, buble is smaller and this buble fork is even * smaller. We can always switch if we run into issues in the future but this * works pretty well AFAICT. */ import { transform as bubleTransform } from "@philpl/buble"; /** @type {boolean} */ const __DEBUG__ = false; const CodeContext = React.createContext(); export function PreComponent({ children, scope, ...props }) { /* * We will look for a leading comment in a js or jsx markdown block to signify * we need to run a code demo. This is a little nicer than adding a new * language key because we can still get proper editor highlighting support * that works with existing markdown parsing tools (also Prettier!) */ const demoKey = "// jsx-demo"; const language = children?.props?.className.replace("language-", "") || null; const trimmed = children?.props?.children.trim(); const isDemo = trimmed && typeof trimmed === "string" && (language === "jsx" || language === "js") ? trimmed.startsWith(demoKey) : false; const [isSSR, setIsSSR] = React.useState(true); React.useEffect(() => { setIsSSR(false); }, []); const code = isDemo ? trimmed.replace(new RegExp(`^${demoKey}(\\n|\\s)*`), "") : trimmed; return code ? (
{children}
);
}
////////////////////////////////////////////////////////////////////////////////
const ERROR = "ERROR";
const READY = "READY";
const SET_ERROR = "SET_ERROR";
const SET_ELEMENT = "SET_ELEMENT";
function providerReducer(data, action = {}) {
const { type: actionType, context } = action;
switch (actionType) {
case SET_ERROR:
return {
state: ERROR,
context: context.toString(),
};
case SET_ELEMENT:
return {
state: READY,
context,
};
default:
return data;
}
}
export function CodeProvider({
children,
code = "",
language = "jsx",
scope,
theme,
}) {
let [{ state, context }, dispatch] = React.useReducer(providerReducer, {
state: null,
context: null,
});
const transpile = React.useCallback(function (code, scope) {
const input = { code, scope };
function handleError(error) {
dispatch({ type: SET_ERROR, context: error });
}
try {
const element = generateElement(input, handleError);
dispatch({
type: SET_ELEMENT,
context: element,
});
} catch (error) {
if (__DEBUG__) {
console.error(error);
}
handleError(error);
}
}, []);
useLayoutEffect(() => {
transpile(code, scope);
}, [code, scope, transpile]);
return (
{tokens.map((line, key) => {
const lineProps = getLineProps({ line, key });
return (
{line.map((token, key) => (
))}
);
})}
)}
{error}