@mui/internal-docs-infra
Version:
MUI Infra - internal documentation creation tools.
58 lines (55 loc) • 2.61 kB
JavaScript
'use client';
import * as React from 'react';
import { useCodeContext } from "../CodeProvider/CodeContext.mjs";
import { preloadCodeEmphasis } from "../pipeline/enhanceCodeEmphasis/enhanceCodeEmphasisLazy.mjs";
import { ensureGrammars } from "../pipeline/parseSource/grammarCache.mjs";
/**
* Warms ALL the live-editing dependencies a block needs — the editing engine
* (contentEditable + source-editing), the per-language grammars, the emphasis
* enhancer, and the off-main-thread worker — so they are in flight before the
* user edits. Mirrors {@link useSpeculativeCodePreload}: detection is cheap and
* synchronous, the work runs in a mount/activation effect (never blocking first
* paint), and each fetch is deduped page-wide with the eventual consumer.
*
* Timing follows `editActivation`:
* - `'eager'` (default): warms on mount once the block is `enabled` (editable).
* - `'interaction'`: warms only once the block is `activated` — `useEditable`
* fires `onActivate` on first engagement (hover / focus / click), and
* `CodeHighlighter` flips `activated`. This is the single moment that kicks off
* every editing dependency, rather than each loading on its own trigger.
*
* A read-only block sets `enabled = false` and warms nothing.
*/
export function useSpeculativeEditingPreload({
enabled,
editActivation,
activated = false,
scopes
}) {
const {
editingEngineLoader,
ensureParseSourceWorker
} = useCodeContext();
// In `'interaction'` mode, wait for engagement; otherwise warm on mount.
const shouldWarm = enabled && ((editActivation ?? 'eager') !== 'interaction' || activated);
React.useEffect(() => {
// Best-effort head start; swallow rejections (the real consumers surface any
// load error). `?.()?.catch` no-ops cleanly when no provider supplies the
// accessor.
if (!shouldWarm) {
return;
}
editingEngineLoader?.()?.catch(() => {});
// Warm the emphasis enhancer too, so the first live-edit re-enhancement
// (a synchronous render-path) runs without a flash under `CodeProviderLazy`.
preloadCodeEmphasis().catch(() => {});
if (scopes && scopes.length > 0) {
// Main-thread grammars for the edited file...
ensureGrammars(scopes).catch(() => {});
// ...and the (lazily-created) worker with the same grammars, so
// off-main-thread highlighting is ready before the first keystroke. No-op
// without a worker (no provider, SSR, or no `Worker`).
ensureParseSourceWorker?.(scopes);
}
}, [shouldWarm, editingEngineLoader, ensureParseSourceWorker, scopes]);
}