UNPKG

@mui/internal-docs-infra

Version:

MUI Infra - internal documentation creation tools.

69 lines (67 loc) 2.52 kB
'use client'; import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray"; import * as React from 'react'; import { createStarryNight } from '@wooorm/starry-night'; import { CodeContext } from "./CodeContext.js"; import { extensionMap, grammars } from "../pipeline/parseSource/grammars.js"; import { starryNightGutter } from "../pipeline/parseSource/addLineGutters.js"; import { jsx as _jsx } from "react/jsx-runtime"; export function CodeProvider(_ref) { var children = _ref.children, loadCodeMeta = _ref.loadCodeMeta, loadVariantMeta = _ref.loadVariantMeta, loadSource = _ref.loadSource; var _React$useState = React.useState(undefined), _React$useState2 = _slicedToArray(_React$useState, 2), parseSource = _React$useState2[0], setParseSource = _React$useState2[1]; var sourceParser = React.useMemo(function () { // Only initialize Starry Night in the browser, not during SSR if (typeof window === 'undefined') { return Promise.resolve(function () { throw new Error('parseSource not available during SSR'); }); } return createStarryNight(grammars).then(function (starryNight) { var parseSourceFn = function parseSourceFn(source, fileName) { var fileType = fileName.slice(fileName.lastIndexOf('.')); if (!extensionMap[fileType]) { // Return a basic HAST root node with the source text for unsupported file types return { type: 'root', children: [{ type: 'text', value: source }] }; } var highlighted = starryNight.highlight(source, extensionMap[fileType]); starryNightGutter(highlighted); // mutates the tree to add line gutters return highlighted; }; return parseSourceFn; }); }, []); React.useEffect(function () { // Update the sync version when available sourceParser.then(function (parseSourceFn) { return setParseSource(function () { return parseSourceFn; }); }); }, [sourceParser]); var context = React.useMemo(function () { return { sourceParser: sourceParser, parseSource: parseSource, // Sync version when available loadSource: loadSource, loadVariantMeta: loadVariantMeta, loadCodeMeta: loadCodeMeta }; }, [sourceParser, parseSource, loadSource, loadVariantMeta, loadCodeMeta]); return /*#__PURE__*/_jsx(CodeContext.Provider, { value: context, children: children }); }