From 4b471ce52fb59d28c7de9c76db7adf38a9919d2c Mon Sep 17 00:00:00 2001 From: Brijesh Bittu <717550+brijeshb42@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:19:08 +0530 Subject: [PATCH 1/5] Initialize visible demo editors during idle --- .../components/code-highlighter/page.mdx | 12 ++ .../components/code-highlighter/types.md | 134 ++++++++++-------- docs/app/docs-infra/components/page.mdx | 1 + .../CodeHighlighter/CodeHighlighterClient.tsx | 2 +- .../CodeHighlighterContext.tsx | 6 +- .../docs-infra/src/CodeHighlighter/types.ts | 13 +- .../useSpeculativeEditingPreload.test.tsx | 10 +- .../useSpeculativeEditingPreload.ts | 10 +- .../docs-infra/src/useCode/Pre.browser.tsx | 118 +++++++++++++++ packages/docs-infra/src/useCode/Pre.tsx | 21 ++- .../src/useCode/useFileNavigation.tsx | 4 +- .../docs-infra/src/useCode/useIdleEditor.ts | 107 ++++++++++++++ .../useCode/useSourceEditing.lazyLoad.test.ts | 37 ++--- .../src/useCode/useSourceEditing.ts | 2 +- .../test/CodeHighlighterEditing.browser.tsx | 23 ++- 15 files changed, 402 insertions(+), 98 deletions(-) create mode 100644 packages/docs-infra/src/useCode/useIdleEditor.ts diff --git a/docs/app/docs-infra/components/code-highlighter/page.mdx b/docs/app/docs-infra/components/code-highlighter/page.mdx index cc5718bee5..14dc7420f1 100644 --- a/docs/app/docs-infra/components/code-highlighter/page.mdx +++ b/docs/app/docs-infra/components/code-highlighter/page.mdx @@ -531,3 +531,15 @@ export const metadata = /** @type {import('@mui/internal-docs-infra/createSitemap/types').NextMetadata} */ ({ keywords: ['syntax highlighting', 'code block', 'demo', 'precompute', 'variants', 'fallback'], }); + +## Preparing editors during idle + +Set `editActivation="idle"` on an editable code block to initialize its editor before the reader clicks it. +Visible blocks wait until the page has loaded and input has stopped for 1.5 seconds, then initialize during browser idle time. +If idle callbacks are starved, initialization runs after another five seconds without input. +Initialization does not focus the editor. +Hidden and offscreen blocks stay deferred. + +Clicking before initialization still loads the editor on demand. +Without `IntersectionObserver`, this mode falls back to interaction activation. +Use `editActivation="interaction"` to keep all editing work deferred until interaction. diff --git a/docs/app/docs-infra/components/code-highlighter/types.md b/docs/app/docs-infra/components/code-highlighter/types.md index c08c75de14..1f4bf0f3ea 100644 --- a/docs/app/docs-infra/components/code-highlighter/types.md +++ b/docs/app/docs-infra/components/code-highlighter/types.md @@ -20,47 +20,47 @@ never reaches the path that renders precomputed content. **CodeHighlighter Props:** -| Prop | Type | Default | Description | -| :---------------------- | :--------------------------------------------- | :-------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| name | `string` | - | Display name for the code example, used for identification and titles | -| collapseToEmpty | `boolean` | - | Render-time "collapse to empty": collapse the code block to an empty window so the whole block is hidden until expanded. Threaded into `contentProps` and consumed by `useCode`/`
`. Runtime-only — the precomputed HAST is
unchanged.                                                                                                                                                                                                                                                                  |
-| initialExpanded         | `boolean`                                      | -         | Whether the (collapsible) code block starts expanded. Threaded into
`contentProps` so both `useCode` and the loading fallback honor it.                                                                                                                                                                                                                                                                                                                                                                             |
-| Content\*               | `React.ComponentType>`        | -         | Component to render the code content and preview                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
-| ContentFrame            | `React.ComponentType>`   | -         | Client Component that keeps the preview shell mounted while loading and
interactive chrome change. Requires `ContentLoading`.                                                                                                                                                                                                                                                                                                                                                                                       |
-| ContentLoading          | `React.ComponentType>` | -         | Component to show while code is being loaded or processed                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
-| code                    | `Code`                                         | -         | Static code content with variants and metadata                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
-| components              | `Components`                                   | -         | React components for live preview alongside code                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
-| contentProps            | `{}`                                           | -         | Additional props passed to the Content component                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
-| controlled              | `boolean`                                      | -         | Enable controlled mode for external code state management                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
-| defaultVariant          | `string`                                       | -         | Fallback variant when the requested variant is not available                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
-| deferParsing            | `'none' \| 'json' \| 'gzip'`                   | `'gzip'`  | Defer parsing and populating the AST into memory until the code is enhanced
Applies only in production when RSC loading                                                                                                                                                                                                                                                                                                                                                                                             |
-| editActivation          | `'eager' \| 'interaction'`                     | `'eager'` | When the textarea editor loads for an editable block: `'eager'` (default): load it as soon as the block is editable, and let
`CodeHighlighter` speculatively preload it on first render.`'interaction'`: defer the load until the reader hovers, focuses, or
clicks the code, and suppress the speculative preload — so a block the
reader never engages does not fetch the editor chunk at all. Only meaningful for editable blocks (a `CodeControllerContext` exposing
`setCode`); ignored otherwise. |
-| enhanceAfter            | `'init' \| 'stream' \| 'hydration' \| 'idle'`  | `'idle'`  | When to enhance the code display with interactivity                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
-| fallbackCollapsed       | `boolean`                                      | `false`   | Paint only the collapsed window in the `ContentLoading` fallback and defer
each file's full fallback into the compressed payload. Shrinks the initial
HTML of a collapsed block to its on-screen lines, but removes the hidden
lines from the server-rendered markup — so it is **only** appropriate for
content that will not be crawled (authenticated or internal pages). See the
prop-compression pattern's "Splitting the Fallback by Visibility".                                             |
-| fallbackUsesAllVariants | `boolean`                                      | -         | Whether fallback content should include all variants                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
-| fallbackUsesExtraFiles  | `boolean`                                      | -         | Whether fallback content should include extra files                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
-| fileName                | `string`                                       | -         | Currently selected file name                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
-| forceClient             | `boolean`                                      | -         | Force client-side rendering even when server rendering is available                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
-| globalsCode             | `(string \| Code)[]`                           | -         | Global static code snippets to inject, typically for styling or tooling                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
-| highlightAfter          | `'init' \| 'stream' \| 'hydration' \| 'idle'`  | `'idle'`  | When to perform syntax highlighting and code processing                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
-| initialDisabled         | `boolean`                                      | -         | Start the editable code read-only. Threaded into `contentProps`; `useCode` seeds its
`editable` toggle from it (a reader flips it back with `setEditable`). Runtime-only.                                                                                                                                                                                                                                                                                                                                           |
-| initialVariant          | `string`                                       | -         | Default variant to show on first load                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
-| language                | `string`                                       | -         | Language for syntax highlighting (for example, 'tsx', 'css'). When provided, fileName is not required for parsing.                                                                                                                                                                                                                                                                                                                                                                                                      |
-| loadCodeMeta            | `LoadCodeMeta`                                 | -         | Function to load code metadata from a URL                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
-| loadPrecompute          | `(() => Promise)`                        | -         | Loads the complete precomputed source after the fallback approaches the viewport.                                                                                                                                                                                                                                                                                                                                                                                                                                       |
-| loadSource              | `LoadSource`                                   | -         | Function to load raw source code and dependencies                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
-| loadVariantMeta         | `LoadVariantMeta`                              | -         | Function to load specific variant metadata                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
-| precompute              | `Code`                                         | -         | Pre-computed code data from build-time optimization                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
-| slug                    | `string`                                       | -         | URL-friendly identifier for deep linking and navigation                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
-| sourceEnhancers         | `SourceEnhancers`                              | -         | Array of source enhancers that run after parsing to enhance the HAST tree                                                                                                                                                                                                                                                                                                                                                                                                                                               |
-| sourceParser            | `Promise`                         | -         | Promise resolving to a source parser for syntax highlighting                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
-| sourceTransformers      | `SourceTransformers`                           | -         | Array of source transformers for code processing (for example, TypeScript to JavaScript)                                                                                                                                                                                                                                                                                                                                                                                                                                |
-| url                     | `string`                                       | -         | Source URL where the code content originates from                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
-| urlPrefix               | `{ from: string; to: string }`                 | -         | Optional URL-prefix rewrite forwarded to .
Lets the demo factory translate local `file://` URLs returned by
`loadSource` into hosted URLs before they reach the client.                                                                                                                                                                                                                                                                                                                                         |
-| variant                 | `string`                                       | -         | Currently selected variant name                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
-| variantType             | `string`                                       | -         | What type of variants are available (for example, a type `packageManager` when variants `npm` and `yarn` are available)                                                                                                                                                                                                                                                                                                                                                                                                 |
-| variants                | `string[]`                                     | -         | Static variant names that should be fetched at runtime                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
-| children                | `string`                                       | -         | Raw code string for simple use cases                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
+| Prop                    | Type                                           | Default   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
+| :---------------------- | :--------------------------------------------- | :-------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| name                    | `string`                                       | -         | Display name for the code example, used for identification and titles                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
+| collapseToEmpty         | `boolean`                                      | -         | Render-time "collapse to empty": collapse the code block to an empty window so
the whole block is hidden until expanded. Threaded into `contentProps` and
consumed by `useCode`/`
`. Runtime-only — the precomputed HAST is
unchanged.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
+| initialExpanded         | `boolean`                                      | -         | Whether the (collapsible) code block starts expanded. Threaded into
`contentProps` so both `useCode` and the loading fallback honor it.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
+| Content\*               | `React.ComponentType>`        | -         | Component to render the code content and preview                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
+| ContentFrame            | `React.ComponentType>`   | -         | Client Component that keeps the preview shell mounted while loading and
interactive chrome change. Requires `ContentLoading`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
+| ContentLoading          | `React.ComponentType>` | -         | Component to show while code is being loaded or processed                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
+| code                    | `Code`                                         | -         | Static code content with variants and metadata                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
+| components              | `Components`                                   | -         | React components for live preview alongside code                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
+| contentProps            | `{}`                                           | -         | Additional props passed to the Content component                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
+| controlled              | `boolean`                                      | -         | Enable controlled mode for external code state management                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
+| defaultVariant          | `string`                                       | -         | Fallback variant when the requested variant is not available                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
+| deferParsing            | `'none' \| 'json' \| 'gzip'`                   | `'gzip'`  | Defer parsing and populating the AST into memory until the code is enhanced
Applies only in production when RSC loading                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
+| editActivation          | `'eager' \| 'interaction' \| 'idle'`           | `'eager'` | When the textarea editor loads for an editable block: `'eager'` (default): load it as soon as the block is editable, and let
`CodeHighlighter` speculatively preload it on first render.`'interaction'`: defer the load until the reader clicks the code or
presses Enter on its wrapper. Blocks the reader never engages do not
fetch the editor chunk.`'idle'`: initialize visible editors after page load and 1.5 seconds
without input, during browser idle time. Interaction still activates
the editor immediately. Hidden and offscreen blocks stay deferred.
Starved idle callbacks run after another five seconds without input. Only meaningful for editable blocks (a `CodeControllerContext` exposing
`setCode`); ignored otherwise. |
+| enhanceAfter            | `'init' \| 'stream' \| 'hydration' \| 'idle'`  | `'idle'`  | When to enhance the code display with interactivity                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+| fallbackCollapsed       | `boolean`                                      | `false`   | Paint only the collapsed window in the `ContentLoading` fallback and defer
each file's full fallback into the compressed payload. Shrinks the initial
HTML of a collapsed block to its on-screen lines, but removes the hidden
lines from the server-rendered markup — so it is **only** appropriate for
content that will not be crawled (authenticated or internal pages). See the
prop-compression pattern's "Splitting the Fallback by Visibility".                                                                                                                                                                                                                                                                                                  |
+| fallbackUsesAllVariants | `boolean`                                      | -         | Whether fallback content should include all variants                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
+| fallbackUsesExtraFiles  | `boolean`                                      | -         | Whether fallback content should include extra files                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+| fileName                | `string`                                       | -         | Currently selected file name                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
+| forceClient             | `boolean`                                      | -         | Force client-side rendering even when server rendering is available                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+| globalsCode             | `(string \| Code)[]`                           | -         | Global static code snippets to inject, typically for styling or tooling                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
+| highlightAfter          | `'init' \| 'stream' \| 'hydration' \| 'idle'`  | `'idle'`  | When to perform syntax highlighting and code processing                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
+| initialDisabled         | `boolean`                                      | -         | Start the editable code read-only. Threaded into `contentProps`; `useCode` seeds its
`editable` toggle from it (a reader flips it back with `setEditable`). Runtime-only.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
+| initialVariant          | `string`                                       | -         | Default variant to show on first load                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
+| language                | `string`                                       | -         | Language for syntax highlighting (for example, 'tsx', 'css'). When provided, fileName is not required for parsing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
+| loadCodeMeta            | `LoadCodeMeta`                                 | -         | Function to load code metadata from a URL                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
+| loadPrecompute          | `(() => Promise)`                        | -         | Loads the complete precomputed source after the fallback approaches the viewport.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
+| loadSource              | `LoadSource`                                   | -         | Function to load raw source code and dependencies                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
+| loadVariantMeta         | `LoadVariantMeta`                              | -         | Function to load specific variant metadata                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
+| precompute              | `Code`                                         | -         | Pre-computed code data from build-time optimization                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+| slug                    | `string`                                       | -         | URL-friendly identifier for deep linking and navigation                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
+| sourceEnhancers         | `SourceEnhancers`                              | -         | Array of source enhancers that run after parsing to enhance the HAST tree                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
+| sourceParser            | `Promise`                         | -         | Promise resolving to a source parser for syntax highlighting                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
+| sourceTransformers      | `SourceTransformers`                           | -         | Array of source transformers for code processing (for example, TypeScript to JavaScript)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
+| url                     | `string`                                       | -         | Source URL where the code content originates from                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
+| urlPrefix               | `{ from: string; to: string }`                 | -         | Optional URL-prefix rewrite forwarded to .
Lets the demo factory translate local `file://` URLs returned by
`loadSource` into hosted URLs before they reach the client.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
+| variant                 | `string`                                       | -         | Currently selected variant name                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
+| variantType             | `string`                                       | -         | What type of variants are available (for example, a type `packageManager` when variants `npm` and `yarn` are available)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
+| variants                | `string[]`                                     | -         | Static variant names that should be fetched at runtime                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
+| children                | `string`                                       | -         | Raw code string for simple use cases                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
 
 ### LoadCodeMeta
 
@@ -500,15 +500,20 @@ type CodeHighlighterBaseProps = {
    * When the textarea editor loads for an editable block:
    *   - `'eager'` (default): load it as soon as the block is editable, and let
    *     `CodeHighlighter` speculatively preload it on first render.
-   *   - `'interaction'`: defer the load until the reader hovers, focuses, or
-   *     clicks the code, and suppress the speculative preload — so a block the
-   *     reader never engages does not fetch the editor chunk at all.
+   *   - `'interaction'`: defer the load until the reader clicks the code or
+   *     presses Enter on its wrapper. Blocks the reader never engages do not
+   *     fetch the editor chunk.
+   *
+   *   - `'idle'`: initialize visible editors after page load and 1.5 seconds
+   *     without input, during browser idle time. Interaction still activates
+   *     the editor immediately. Hidden and offscreen blocks stay deferred.
+   *     Starved idle callbacks run after another five seconds without input.
    *
    * Only meaningful for editable blocks (a `CodeControllerContext` exposing
    * `setCode`); ignored otherwise.
    * @default 'eager'
    */
-  editActivation?: 'eager' | 'interaction';
+  editActivation?: 'eager' | 'interaction' | 'idle';
   /** Raw code string for simple use cases */
   children?: string;
   /**
@@ -632,15 +637,20 @@ type CodeHighlighterClientProps = {
    * When the textarea editor loads for an editable block:
    *   - `'eager'` (default): load it as soon as the block is editable, and let
    *     `CodeHighlighter` speculatively preload it on first render.
-   *   - `'interaction'`: defer the load until the reader hovers, focuses, or
-   *     clicks the code, and suppress the speculative preload — so a block the
-   *     reader never engages does not fetch the editor chunk at all.
+   *   - `'interaction'`: defer the load until the reader clicks the code or
+   *     presses Enter on its wrapper. Blocks the reader never engages do not
+   *     fetch the editor chunk.
+   *
+   *   - `'idle'`: initialize visible editors after page load and 1.5 seconds
+   *     without input, during browser idle time. Interaction still activates
+   *     the editor immediately. Hidden and offscreen blocks stay deferred.
+   *     Starved idle callbacks run after another five seconds without input.
    *
    * Only meaningful for editable blocks (a `CodeControllerContext` exposing
    * `setCode`); ignored otherwise.
    * @default 'eager'
    */
-  editActivation?: 'eager' | 'interaction';
+  editActivation?: 'eager' | 'interaction' | 'idle';
   /** Force client-side rendering even when server rendering is available */
   forceClient?: boolean;
   /**
@@ -737,15 +747,20 @@ type CodeHighlighterProps = {
    * When the textarea editor loads for an editable block:
    *   - `'eager'` (default): load it as soon as the block is editable, and let
    *     `CodeHighlighter` speculatively preload it on first render.
-   *   - `'interaction'`: defer the load until the reader hovers, focuses, or
-   *     clicks the code, and suppress the speculative preload — so a block the
-   *     reader never engages does not fetch the editor chunk at all.
+   *   - `'interaction'`: defer the load until the reader clicks the code or
+   *     presses Enter on its wrapper. Blocks the reader never engages do not
+   *     fetch the editor chunk.
+   *
+   *   - `'idle'`: initialize visible editors after page load and 1.5 seconds
+   *     without input, during browser idle time. Interaction still activates
+   *     the editor immediately. Hidden and offscreen blocks stay deferred.
+   *     Starved idle callbacks run after another five seconds without input.
    *
    * Only meaningful for editable blocks (a `CodeControllerContext` exposing
    * `setCode`); ignored otherwise.
    * @default 'eager'
    */
-  editActivation?: 'eager' | 'interaction';
+  editActivation?: 'eager' | 'interaction' | 'idle';
   /** Raw code string for simple use cases */
   children?: string;
   /**
@@ -841,15 +856,20 @@ type CodeLoadingProps = {
    * When the textarea editor loads for an editable block:
    *   - `'eager'` (default): load it as soon as the block is editable, and let
    *     `CodeHighlighter` speculatively preload it on first render.
-   *   - `'interaction'`: defer the load until the reader hovers, focuses, or
-   *     clicks the code, and suppress the speculative preload — so a block the
-   *     reader never engages does not fetch the editor chunk at all.
+   *   - `'interaction'`: defer the load until the reader clicks the code or
+   *     presses Enter on its wrapper. Blocks the reader never engages do not
+   *     fetch the editor chunk.
+   *
+   *   - `'idle'`: initialize visible editors after page load and 1.5 seconds
+   *     without input, during browser idle time. Interaction still activates
+   *     the editor immediately. Hidden and offscreen blocks stay deferred.
+   *     Starved idle callbacks run after another five seconds without input.
    *
    * Only meaningful for editable blocks (a `CodeControllerContext` exposing
    * `setCode`); ignored otherwise.
    * @default 'eager'
    */
-  editActivation?: 'eager' | 'interaction';
+  editActivation?: 'eager' | 'interaction' | 'idle';
   /** Raw code string for simple use cases */
   children?: string;
   /**
diff --git a/docs/app/docs-infra/components/page.mdx b/docs/app/docs-infra/components/page.mdx
index 45b9788a01..179eae90c5 100644
--- a/docs/app/docs-infra/components/page.mdx
+++ b/docs/app/docs-infra/components/page.mdx
@@ -52,6 +52,7 @@ It supports both static code blocks and interactive demos with component preview
   - Types
     - CodeHighlighter
     - CodeHighlighter Types
+  - Preparing editors during idle
 - Exports:
   - CodeHighlighter
     - Props: Content, ContentFrame, ContentLoading, children, code, collapseToEmpty, components, contentProps, controlled, defaultVariant, deferParsing, editActivation, enhanceAfter, fallbackCollapsed, fallbackUsesAllVariants, fallbackUsesExtraFiles, fileName, forceClient, globalsCode, highlightAfter, initialDisabled, initialExpanded, initialVariant, language, loadCodeMeta, loadPrecompute, loadSource, loadVariantMeta, name, precompute, slug, sourceEnhancers, sourceParser, sourceTransformers, url, urlPrefix, variant, variantType, variants
diff --git a/packages/docs-infra/src/CodeHighlighter/CodeHighlighterClient.tsx b/packages/docs-infra/src/CodeHighlighter/CodeHighlighterClient.tsx
index b3201b3060..1735d988bf 100644
--- a/packages/docs-infra/src/CodeHighlighter/CodeHighlighterClient.tsx
+++ b/packages/docs-infra/src/CodeHighlighter/CodeHighlighterClient.tsx
@@ -1301,7 +1301,7 @@ export function CodeHighlighterClient(props: CodeHighlighterClientProps) {
     !!speculativeCode &&
     (Boolean(props.forceClient) ||
       !hasAllVariants(variants, speculativeCode, true) ||
-      ((editActivation ?? 'eager') !== 'interaction' && Boolean(controlled?.setCode)));
+      ((editActivation ?? 'eager') === 'eager' && Boolean(controlled?.setCode)));
   useSpeculativeGrammarPreload({ scopes: speculativeGrammarScopes, enabled: willClientHighlight });
 
   // ── Fallback hoisting ──
diff --git a/packages/docs-infra/src/CodeHighlighter/CodeHighlighterContext.tsx b/packages/docs-infra/src/CodeHighlighter/CodeHighlighterContext.tsx
index 6400f4a917..f6e6cbf4ad 100644
--- a/packages/docs-infra/src/CodeHighlighter/CodeHighlighterContext.tsx
+++ b/packages/docs-infra/src/CodeHighlighter/CodeHighlighterContext.tsx
@@ -71,10 +71,10 @@ export interface CodeHighlighterContextType {
   /**
    * Echo of the `editActivation` prop on the surrounding `CodeHighlighter` /
    * `CodeHighlighterClient`. `useCode` reads it from here and threads it down to
-   * `Pre` (which defers the textarea load when `'interaction'`), so the strategy can be configured at
-   * the `CodeHighlighter` / demo level rather than inside the content subtree.
+   * `Pre`, which handles interaction and visible-idle activation. Configure the
+   * strategy at the `CodeHighlighter` / demo level.
    */
-  editActivation?: 'eager' | 'interaction';
+  editActivation?: 'eager' | 'interaction' | 'idle';
   /**
    * Callback `useCode` threads down to the editor's `onActivate`, fired once
    * when the block first engages for editing. `CodeHighlighterClient` supplies it
diff --git a/packages/docs-infra/src/CodeHighlighter/types.ts b/packages/docs-infra/src/CodeHighlighter/types.ts
index 1e4af2360a..32388f0d74 100644
--- a/packages/docs-infra/src/CodeHighlighter/types.ts
+++ b/packages/docs-infra/src/CodeHighlighter/types.ts
@@ -593,15 +593,20 @@ export interface CodeLoadingProps {
    * When the textarea editor loads for an editable block:
    *   - `'eager'` (default): load it as soon as the block is editable, and let
    *     `CodeHighlighter` speculatively preload it on first render.
-   *   - `'interaction'`: defer the load until the reader hovers, focuses, or
-   *     clicks the code, and suppress the speculative preload — so a block the
-   *     reader never engages does not fetch the editor chunk at all.
+   *   - `'interaction'`: defer the load until the reader clicks the code or
+   *     presses Enter on its wrapper. Blocks the reader never engages do not
+   *     fetch the editor chunk.
+   *
+   *   - `'idle'`: initialize visible editors after page load and 1.5 seconds
+   *     without input, during browser idle time. Interaction still activates
+   *     the editor immediately. Hidden and offscreen blocks stay deferred.
+   *     Starved idle callbacks run after another five seconds without input.
    *
    * Only meaningful for editable blocks (a `CodeControllerContext` exposing
    * `setCode`); ignored otherwise.
    * @default 'eager'
    */
-  editActivation?: 'eager' | 'interaction';
+  editActivation?: 'eager' | 'interaction' | 'idle';
   /** Raw code string for simple use cases */
   children?: string;
   /**
diff --git a/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.test.tsx b/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.test.tsx
index a7ab936101..b315a10ce7 100644
--- a/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.test.tsx
+++ b/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.test.tsx
@@ -16,7 +16,11 @@ import type { CodeContext as CodeContextValue } from '../CodeProvider/CodeContex
 import { useSpeculativeEditingPreload } from './useSpeculativeEditingPreload';
 
 function setup(
-  props: { enabled: boolean; editActivation?: 'eager' | 'interaction'; activated?: boolean },
+  props: {
+    enabled: boolean;
+    editActivation?: 'eager' | 'interaction' | 'idle';
+    activated?: boolean;
+  },
   loaders: Partial,
 ) {
   function Speculative() {
@@ -43,9 +47,9 @@ describe('useSpeculativeEditingPreload', () => {
     expect(codeEditorLoader).not.toHaveBeenCalled();
   });
 
-  it("waits for activation when editActivation is 'interaction'", () => {
+  it.each(['interaction', 'idle'] as const)('waits for activation in %s mode', (editActivation) => {
     const codeEditorLoader = vi.fn(async () => ({}) as never);
-    setup({ enabled: true, editActivation: 'interaction', activated: false }, { codeEditorLoader });
+    setup({ enabled: true, editActivation, activated: false }, { codeEditorLoader });
     expect(codeEditorLoader).not.toHaveBeenCalled();
   });
 
diff --git a/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.ts b/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.ts
index 4dfd971f0f..6b58e57f39 100644
--- a/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.ts
+++ b/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.ts
@@ -21,6 +21,8 @@ import { preloadCodeEditor } from '../useCode/codeEditorCache';
  *   `CodeHighlighter` flips `activated`. This is the single moment that kicks off
  *   every editing dependency, rather than each loading on its own trigger.
  *
+ * - `'idle'`: waits for a visible `Pre` to activate during idle time or input.
+ *
  * A read-only block sets `enabled = false` and warms nothing.
  */
 export function useSpeculativeEditingPreload({
@@ -30,8 +32,8 @@ export function useSpeculativeEditingPreload({
   scopes,
 }: {
   enabled: boolean;
-  editActivation?: 'eager' | 'interaction';
-  /** Whether an `'interaction'` block has engaged yet (ignored when `'eager'`). */
+  editActivation?: 'eager' | 'interaction' | 'idle';
+  /** Whether a deferred block has activated (ignored when `'eager'`). */
   activated?: boolean;
   /**
    * Grammar scopes the editable block uses, so its grammars (main thread) and the
@@ -41,8 +43,8 @@ export function useSpeculativeEditingPreload({
 }): void {
   const { codeEditorLoader, ensureParseSourceWorker } = useCodeContext();
 
-  // In `'interaction'` mode, wait for engagement; otherwise warm on mount.
-  const shouldWarm = enabled && ((editActivation ?? 'eager') !== 'interaction' || activated);
+  // Deferred modes warm only after activation.
+  const shouldWarm = enabled && ((editActivation ?? 'eager') === 'eager' || activated);
 
   React.useEffect(() => {
     // Best-effort head start; swallow rejections (the real consumers surface any
diff --git a/packages/docs-infra/src/useCode/Pre.browser.tsx b/packages/docs-infra/src/useCode/Pre.browser.tsx
index bd355691f9..d448844fca 100644
--- a/packages/docs-infra/src/useCode/Pre.browser.tsx
+++ b/packages/docs-infra/src/useCode/Pre.browser.tsx
@@ -88,6 +88,124 @@ describe('Pre editor - browser', () => {
     cleanup();
   });
 
+  it('initializes a visible idle editor without moving focus and preserves the first clicked caret', async () => {
+    const source = Array.from(
+      { length: 40 },
+      (_, index) => `const value_${index} = ${index};`,
+    ).join('\n');
+
+    const { container } = render(
+      
+ +
+
 {}} editActivation="idle">
+            {source}
+          
+
+
+
 {}} editActivation="idle">
+            {source}
+          
+
+
+          {source}
+        
+ +
, + ); + + const focusTarget = screen.getByRole('button', { name: 'Keep focus' }); + + await userEvent.click(focusTarget); + expect(container.querySelector('textarea')).toBeNull(); + + const textarea = await screen.findByRole( + 'textbox', + { name: 'Edit App.ts' }, + { timeout: 10000 }, + ); + + expect(document.activeElement).toBe(focusTarget); + expect(container.querySelectorAll('textarea')).toHaveLength(1); + + const scroller = screen.getByTestId('scroller'); + scroller.scrollTop = LINE_HEIGHT * 20; + const scrollTop = scroller.scrollTop; + const pageScroll = window.scrollY; + + await userEvent.click(textarea, { position: { x: 60, y: scrollTop + LINE_HEIGHT } }); + + expect(document.activeElement).toBe(textarea); + expect((textarea as HTMLTextAreaElement).selectionStart).toBeGreaterThan( + source.indexOf('value_19'), + ); + expect(scroller.scrollTop).toBe(scrollTop); + expect(window.scrollY).toBe(pageScroll); + }); + + it('cancels initialization when the source is hidden and resumes on reopening', async () => { + function ToggleSource() { + const [visible, setVisible] = React.useState(true); + const [activations, setActivations] = React.useState(0); + + return ( + + + Activations: {activations} + + + ); + } + + const { container } = render(); + + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + + try { + await userEvent.click(screen.getByRole('button', { name: 'Toggle code' })); + await vi.advanceTimersByTimeAsync(2000); + + expect(container.querySelector('textarea')).toBeNull(); + expect(screen.getByText('Activations: 0')).not.toBeNull(); + } finally { + vi.useRealTimers(); + } + + await userEvent.click(screen.getByRole('button', { name: 'Toggle code' })); + await screen.findByRole('textbox', {}, { timeout: 10000 }); + + expect(screen.getByText('Activations: 1')).not.toBeNull(); + }); + + it('keeps interaction activation available before idle initialization', async () => { + render( +
 {}} editActivation="idle">
+        {'const value = 1;'}
+      
, + ); + + await userEvent.click(screen.getByRole('group', { name: 'Editable code' })); + + const textarea = await screen.findByRole('textbox'); + + await waitFor(() => expect(document.activeElement).toBe(textarea)); + }); + it('uses the wrapper as one Tab stop, Enter to engage, and Escape to exit', async () => { render(
 {}}>
diff --git a/packages/docs-infra/src/useCode/Pre.tsx b/packages/docs-infra/src/useCode/Pre.tsx
index 4979c7171d..f5bc2addfc 100644
--- a/packages/docs-infra/src/useCode/Pre.tsx
+++ b/packages/docs-infra/src/useCode/Pre.tsx
@@ -20,6 +20,7 @@ import { getSourceLineCounts } from './sourceLineCounts';
 import type { SourceLineCounts } from './sourceLineCounts';
 import { subscribeToggleNudge } from './subscribeToggleNudge';
 import { CodeEditorLazy } from './CodeEditorLazy';
+import { useIdleEditor } from './useIdleEditor';
 
 const hastChildrenCache = new WeakMap();
 const fallbackHastCache = new WeakMap();
@@ -125,10 +126,11 @@ export function Pre({
   /**
    * Controls when the textarea editor loads for an editable block: `'eager'`
    * (default) loads it as soon as the block is editable; `'interaction'` defers
-   * the load until the user hovers/focuses/clicks the `
`. Ignored when the
-   * block is not editable.
+   * the load until the reader clicks the code or presses Enter on its wrapper. Ignored when the
+   * block is not editable. `'idle'` initializes visible blocks during idle
+   * time after page load and a quiet input interval, or on interaction.
    */
-  editActivation?: 'eager' | 'interaction';
+  editActivation?: 'eager' | 'interaction' | 'idle';
   /**
    * Fired once when the block first engages for editing. `CodeHighlighter` uses
    * it to warm the live-editing runtime, grammars, and worker.
@@ -569,7 +571,7 @@ export function Pre({
 
   const isEditable = Boolean(setSource) && editable;
   const [editorRequested, setEditorRequested] = React.useState(
-    () => editActivation !== 'interaction',
+    () => (editActivation ?? 'eager') === 'eager',
   );
   const fullSource = React.useMemo(
     () =>
@@ -646,6 +648,17 @@ export function Pre({
     }
   }, [onActivate]);
 
+  const initializeEditor = React.useCallback(() => {
+    handleEditorActivate();
+    React.startTransition(() => setEditorRequested(true));
+  }, [handleEditorActivate]);
+
+  useIdleEditor(
+    wrapperRef,
+    initializeEditor,
+    isEditable && !editorRequested && editActivation === 'idle' ? 'idle' : 'disabled',
+  );
+
   const requestEditorFocus = React.useCallback(() => {
     setPromptVisible(false);
     const textarea = wrapperRef.current?.querySelector('textarea');
diff --git a/packages/docs-infra/src/useCode/useFileNavigation.tsx b/packages/docs-infra/src/useCode/useFileNavigation.tsx
index 21cb9c5cff..9b06727a95 100644
--- a/packages/docs-infra/src/useCode/useFileNavigation.tsx
+++ b/packages/docs-infra/src/useCode/useFileNavigation.tsx
@@ -79,10 +79,10 @@ interface UseFileNavigationProps {
   /**
    * Forwarded to `
`: when the textarea editor loads for an
    * editable block. `'eager'` (default) loads on mount; `'interaction'` defers
-   * until the user hovers/focuses/clicks. Sourced from the `editActivation`
+   * until interaction or visible idle time. Sourced from the `editActivation`
    * prop on `CodeHighlighter` (via `CodeHighlighterContext`).
    */
-  editActivation?: 'eager' | 'interaction';
+  editActivation?: 'eager' | 'interaction' | 'idle';
   /** Forwarded to `
`: fired once when the block engages for editing. */
   onActivate?: () => void;
   /** Forwarded to `
`: expands focused source from textarea boundary navigation. */
diff --git a/packages/docs-infra/src/useCode/useIdleEditor.ts b/packages/docs-infra/src/useCode/useIdleEditor.ts
new file mode 100644
index 0000000000..a9b66d5f11
--- /dev/null
+++ b/packages/docs-infra/src/useCode/useIdleEditor.ts
@@ -0,0 +1,107 @@
+'use client';
+
+import * as React from 'react';
+import { requestIdle } from '../useCoordinated/scheduleTasks';
+
+const EDITOR_IDLE_DELAY_MS = 1500;
+const EDITOR_IDLE_TIMEOUT_MS = 5000;
+
+const INPUT_EVENTS = [
+  'pointerdown',
+  'pointermove',
+  'keydown',
+  'scroll',
+  'wheel',
+  'touchstart',
+] as const;
+
+/** Initializes visible editors after page loading and a quiet input interval. */
+export function useIdleEditor(
+  target: React.RefObject,
+  onIdle: () => void,
+  mode: 'idle' | 'disabled',
+) {
+  React.useEffect(() => {
+    const element = target.current;
+
+    if (mode !== 'idle' || !element || typeof IntersectionObserver === 'undefined') {
+      return undefined;
+    }
+
+    let visible = false;
+    let requested = false;
+    let timer: ReturnType | undefined;
+    let cancelIdle: (() => void) | undefined;
+
+    const cancel = () => {
+      clearTimeout(timer);
+      cancelIdle?.();
+    };
+
+    const canInitialize = () =>
+      visible &&
+      !requested &&
+      document.readyState === 'complete' &&
+      document.visibilityState === 'visible';
+
+    const schedule = () => {
+      cancel();
+
+      if (!canInitialize()) {
+        return;
+      }
+
+      timer = setTimeout(() => {
+        // Continuous rendering can starve idle callbacks even after input stops.
+        cancelIdle = requestIdle(
+          () => {
+            if (!canInitialize()) {
+              return;
+            }
+
+            const bounds = element.getBoundingClientRect();
+
+            if (
+              bounds.width === 0 ||
+              bounds.height === 0 ||
+              getComputedStyle(element).visibility === 'hidden'
+            ) {
+              return;
+            }
+
+            requested = true;
+            onIdle();
+          },
+          { timeout: EDITOR_IDLE_TIMEOUT_MS },
+        );
+      }, EDITOR_IDLE_DELAY_MS);
+    };
+
+    const observer = new IntersectionObserver(([entry]) => {
+      visible =
+        entry.isIntersecting &&
+        entry.intersectionRect.width > 0 &&
+        entry.intersectionRect.height > 0;
+      schedule();
+    });
+
+    observer.observe(element);
+    window.addEventListener('load', schedule);
+    document.addEventListener('visibilitychange', schedule);
+
+    for (const event of INPUT_EVENTS) {
+      window.addEventListener(event, schedule, { capture: true, passive: true });
+    }
+
+    return () => {
+      cancel();
+      observer.disconnect();
+      window.removeEventListener('load', schedule);
+      document.removeEventListener('visibilitychange', schedule);
+
+      for (const event of INPUT_EVENTS) {
+        window.removeEventListener(event, schedule, { capture: true });
+      }
+    };
+  }, [target, onIdle, mode]);
+}
diff --git a/packages/docs-infra/src/useCode/useSourceEditing.lazyLoad.test.ts b/packages/docs-infra/src/useCode/useSourceEditing.lazyLoad.test.ts
index d8f5dec655..c73d0d1a29 100644
--- a/packages/docs-infra/src/useCode/useSourceEditing.lazyLoad.test.ts
+++ b/packages/docs-infra/src/useCode/useSourceEditing.lazyLoad.test.ts
@@ -44,7 +44,7 @@ function renderCold() {
 }
 
 describe('useSourceEditing lazy engine (cold cache)', () => {
-  function renderEditable(editActivation?: 'eager' | 'interaction') {
+  function renderEditable(editActivation?: 'eager' | 'interaction' | 'idle') {
     const setCode = vi.fn();
     const context: CodeHighlighterContextType = { code: {}, setCode, editActivation };
     const view = renderHook(() =>
@@ -58,22 +58,25 @@ describe('useSourceEditing lazy engine (cold cache)', () => {
     return { ...view, setCode };
   }
 
-  it('loads the interaction engine only when editing activates', async () => {
-    const { result, setCode } = renderEditable('interaction');
-    await vi.dynamicImportSettled();
-    expect(peekSourceEditingEngine()).toBeUndefined();
-    expect(setCode).not.toHaveBeenCalled();
-
-    act(() => result.current.activate?.());
-    await waitFor(() => expect(setCode).toHaveBeenCalledTimes(1));
-    expect(peekSourceEditingEngine()).toBeDefined();
-
-    act(() => result.current.setSource?.('new'));
-    expect(setCode).toHaveBeenCalledTimes(2);
-    const seeded = setCode.mock.calls[0][0](null);
-    const edited = setCode.mock.calls[1][0](seeded);
-    expect(edited.Default.source).toBe('new');
-  });
+  it.each(['interaction', 'idle'] as const)(
+    'loads the %s engine only when editing activates',
+    async (mode) => {
+      const { result, setCode } = renderEditable(mode);
+      await vi.dynamicImportSettled();
+      expect(peekSourceEditingEngine()).toBeUndefined();
+      expect(setCode).not.toHaveBeenCalled();
+
+      act(() => result.current.activate?.());
+      await waitFor(() => expect(setCode).toHaveBeenCalledTimes(1));
+      expect(peekSourceEditingEngine()).toBeDefined();
+
+      act(() => result.current.setSource?.('new'));
+      expect(setCode).toHaveBeenCalledTimes(2);
+      const seeded = setCode.mock.calls[0][0](null);
+      const edited = setCode.mock.calls[1][0](seeded);
+      expect(edited.Default.source).toBe('new');
+    },
+  );
 
   it('warms the engine on mount by default', async () => {
     renderEditable();
diff --git a/packages/docs-infra/src/useCode/useSourceEditing.ts b/packages/docs-infra/src/useCode/useSourceEditing.ts
index 5dc77c55b1..c15ceb0758 100644
--- a/packages/docs-infra/src/useCode/useSourceEditing.ts
+++ b/packages/docs-infra/src/useCode/useSourceEditing.ts
@@ -356,7 +356,7 @@ export function useSourceEditing({
       peekSourceEditingEngine() ||
       !contextSetCode ||
       disabled ||
-      context?.editActivation === 'interaction'
+      (context?.editActivation ?? 'eager') !== 'eager'
     ) {
       return;
     }
diff --git a/packages/docs-infra/test/CodeHighlighterEditing.browser.tsx b/packages/docs-infra/test/CodeHighlighterEditing.browser.tsx
index b44ed5836a..65995c68fa 100644
--- a/packages/docs-infra/test/CodeHighlighterEditing.browser.tsx
+++ b/packages/docs-infra/test/CodeHighlighterEditing.browser.tsx
@@ -59,7 +59,7 @@ function LiveSource(props: ContentProps<{}>) {
   );
 }
 
-function LiveDemo() {
+function LiveDemo({ activation = 'interaction' }: { activation?: 'interaction' | 'idle' }) {
   const controller = useDemoController();
 
   return (
@@ -73,7 +73,7 @@ function LiveDemo() {
           highlightAfter="init"
           enhanceAfter="init"
           initialExpanded
-          editActivation="interaction"
+          editActivation={activation}
           Content={LiveSource}
         />
       
@@ -208,6 +208,25 @@ describe('CodeHighlighter editing source switches', () => {
     expect(bundledMounts).toBe(mountsBeforeUndo);
   });
 
+  it('initializes an idle editor and runner without remounting or focusing the demo', async () => {
+    render();
+
+    const preview = screen.getByRole('button', { name: 'Count 0' });
+
+    await userEvent.click(preview);
+    expect(screen.queryByRole('textbox')).toBeNull();
+
+    const editor = await screen.findByRole('textbox', {}, { timeout: 10000 });
+
+    await screen.findByText('Live build ready');
+    expect(screen.getByRole('button', { name: 'Count 1' })).toBe(preview);
+    expect(bundledMounts).toBe(1);
+    expect(document.activeElement).not.toBe(editor);
+
+    await userEvent.fill(editor, COUNTER_SOURCE.replace('Count ', 'Edited '));
+    await screen.findByRole('button', { name: 'Edited 0' });
+  });
+
   it.each(['Helper', 'JavaScript'])(
     'keeps %s highlighted after activating another editor',
     async (label) => {

From 3f4cda621beeae9d0b52db4eecf49e03f34fd60b Mon Sep 17 00:00:00 2001
From: Brijesh Bittu <717550+brijeshb42@users.noreply.github.com>
Date: Thu, 26 Nov 2026 09:36:11 +0530
Subject: [PATCH 2/5] Expose editor preparation without scheduling

---
 .../components/code-highlighter/page.mdx      |  12 --
 .../components/code-highlighter/types.md      | 134 ++++++++----------
 docs/app/docs-infra/components/page.mdx       |   1 -
 docs/app/docs-infra/hooks/page.mdx            |   1 +
 docs/app/docs-infra/hooks/use-code/page.mdx   |  15 ++
 docs/app/docs-infra/hooks/use-code/types.md   |   6 +
 docs/app/docs-infra/hooks/use-demo/types.md   |   1 +
 .../CodeHighlighter/CodeHighlighterClient.tsx |   2 +-
 .../CodeHighlighterContext.tsx                |   6 +-
 .../docs-infra/src/CodeHighlighter/types.ts   |  13 +-
 .../useSpeculativeEditingPreload.test.tsx     |  10 +-
 .../useSpeculativeEditingPreload.ts           |  10 +-
 .../docs-infra/src/useCode/Pre.browser.tsx    | 118 ---------------
 packages/docs-infra/src/useCode/Pre.tsx       |  31 ++--
 packages/docs-infra/src/useCode/useCode.ts    |  17 +++
 .../src/useCode/useFileNavigation.tsx         |  12 +-
 .../docs-infra/src/useCode/useIdleEditor.ts   | 107 --------------
 .../useCode/useSourceEditing.lazyLoad.test.ts |  37 +++--
 .../src/useCode/useSourceEditing.ts           |   2 +-
 .../test/CodeHighlighterEditing.browser.tsx   |  16 ++-
 20 files changed, 167 insertions(+), 384 deletions(-)
 delete mode 100644 packages/docs-infra/src/useCode/useIdleEditor.ts

diff --git a/docs/app/docs-infra/components/code-highlighter/page.mdx b/docs/app/docs-infra/components/code-highlighter/page.mdx
index 14dc7420f1..cc5718bee5 100644
--- a/docs/app/docs-infra/components/code-highlighter/page.mdx
+++ b/docs/app/docs-infra/components/code-highlighter/page.mdx
@@ -531,15 +531,3 @@ export const metadata =
   /** @type {import('@mui/internal-docs-infra/createSitemap/types').NextMetadata} */ ({
     keywords: ['syntax highlighting', 'code block', 'demo', 'precompute', 'variants', 'fallback'],
   });
-
-## Preparing editors during idle
-
-Set `editActivation="idle"` on an editable code block to initialize its editor before the reader clicks it.
-Visible blocks wait until the page has loaded and input has stopped for 1.5 seconds, then initialize during browser idle time.
-If idle callbacks are starved, initialization runs after another five seconds without input.
-Initialization does not focus the editor.
-Hidden and offscreen blocks stay deferred.
-
-Clicking before initialization still loads the editor on demand.
-Without `IntersectionObserver`, this mode falls back to interaction activation.
-Use `editActivation="interaction"` to keep all editing work deferred until interaction.
diff --git a/docs/app/docs-infra/components/code-highlighter/types.md b/docs/app/docs-infra/components/code-highlighter/types.md
index 1f4bf0f3ea..c08c75de14 100644
--- a/docs/app/docs-infra/components/code-highlighter/types.md
+++ b/docs/app/docs-infra/components/code-highlighter/types.md
@@ -20,47 +20,47 @@ never reaches the path that renders precomputed content.
 
 **CodeHighlighter Props:**
 
-| Prop                    | Type                                           | Default   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
-| :---------------------- | :--------------------------------------------- | :-------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| name                    | `string`                                       | -         | Display name for the code example, used for identification and titles                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
-| collapseToEmpty         | `boolean`                                      | -         | Render-time "collapse to empty": collapse the code block to an empty window so
the whole block is hidden until expanded. Threaded into `contentProps` and
consumed by `useCode`/`
`. Runtime-only — the precomputed HAST is
unchanged.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
-| initialExpanded         | `boolean`                                      | -         | Whether the (collapsible) code block starts expanded. Threaded into
`contentProps` so both `useCode` and the loading fallback honor it.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
-| Content\*               | `React.ComponentType>`        | -         | Component to render the code content and preview                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
-| ContentFrame            | `React.ComponentType>`   | -         | Client Component that keeps the preview shell mounted while loading and
interactive chrome change. Requires `ContentLoading`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
-| ContentLoading          | `React.ComponentType>` | -         | Component to show while code is being loaded or processed                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
-| code                    | `Code`                                         | -         | Static code content with variants and metadata                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
-| components              | `Components`                                   | -         | React components for live preview alongside code                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
-| contentProps            | `{}`                                           | -         | Additional props passed to the Content component                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
-| controlled              | `boolean`                                      | -         | Enable controlled mode for external code state management                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
-| defaultVariant          | `string`                                       | -         | Fallback variant when the requested variant is not available                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
-| deferParsing            | `'none' \| 'json' \| 'gzip'`                   | `'gzip'`  | Defer parsing and populating the AST into memory until the code is enhanced
Applies only in production when RSC loading                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
-| editActivation          | `'eager' \| 'interaction' \| 'idle'`           | `'eager'` | When the textarea editor loads for an editable block: `'eager'` (default): load it as soon as the block is editable, and let
`CodeHighlighter` speculatively preload it on first render.`'interaction'`: defer the load until the reader clicks the code or
presses Enter on its wrapper. Blocks the reader never engages do not
fetch the editor chunk.`'idle'`: initialize visible editors after page load and 1.5 seconds
without input, during browser idle time. Interaction still activates
the editor immediately. Hidden and offscreen blocks stay deferred.
Starved idle callbacks run after another five seconds without input. Only meaningful for editable blocks (a `CodeControllerContext` exposing
`setCode`); ignored otherwise. |
-| enhanceAfter            | `'init' \| 'stream' \| 'hydration' \| 'idle'`  | `'idle'`  | When to enhance the code display with interactivity                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
-| fallbackCollapsed       | `boolean`                                      | `false`   | Paint only the collapsed window in the `ContentLoading` fallback and defer
each file's full fallback into the compressed payload. Shrinks the initial
HTML of a collapsed block to its on-screen lines, but removes the hidden
lines from the server-rendered markup — so it is **only** appropriate for
content that will not be crawled (authenticated or internal pages). See the
prop-compression pattern's "Splitting the Fallback by Visibility".                                                                                                                                                                                                                                                                                                  |
-| fallbackUsesAllVariants | `boolean`                                      | -         | Whether fallback content should include all variants                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
-| fallbackUsesExtraFiles  | `boolean`                                      | -         | Whether fallback content should include extra files                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
-| fileName                | `string`                                       | -         | Currently selected file name                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
-| forceClient             | `boolean`                                      | -         | Force client-side rendering even when server rendering is available                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
-| globalsCode             | `(string \| Code)[]`                           | -         | Global static code snippets to inject, typically for styling or tooling                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
-| highlightAfter          | `'init' \| 'stream' \| 'hydration' \| 'idle'`  | `'idle'`  | When to perform syntax highlighting and code processing                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
-| initialDisabled         | `boolean`                                      | -         | Start the editable code read-only. Threaded into `contentProps`; `useCode` seeds its
`editable` toggle from it (a reader flips it back with `setEditable`). Runtime-only.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
-| initialVariant          | `string`                                       | -         | Default variant to show on first load                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
-| language                | `string`                                       | -         | Language for syntax highlighting (for example, 'tsx', 'css'). When provided, fileName is not required for parsing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
-| loadCodeMeta            | `LoadCodeMeta`                                 | -         | Function to load code metadata from a URL                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
-| loadPrecompute          | `(() => Promise)`                        | -         | Loads the complete precomputed source after the fallback approaches the viewport.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
-| loadSource              | `LoadSource`                                   | -         | Function to load raw source code and dependencies                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
-| loadVariantMeta         | `LoadVariantMeta`                              | -         | Function to load specific variant metadata                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
-| precompute              | `Code`                                         | -         | Pre-computed code data from build-time optimization                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
-| slug                    | `string`                                       | -         | URL-friendly identifier for deep linking and navigation                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
-| sourceEnhancers         | `SourceEnhancers`                              | -         | Array of source enhancers that run after parsing to enhance the HAST tree                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
-| sourceParser            | `Promise`                         | -         | Promise resolving to a source parser for syntax highlighting                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
-| sourceTransformers      | `SourceTransformers`                           | -         | Array of source transformers for code processing (for example, TypeScript to JavaScript)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
-| url                     | `string`                                       | -         | Source URL where the code content originates from                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
-| urlPrefix               | `{ from: string; to: string }`                 | -         | Optional URL-prefix rewrite forwarded to .
Lets the demo factory translate local `file://` URLs returned by
`loadSource` into hosted URLs before they reach the client.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
-| variant                 | `string`                                       | -         | Currently selected variant name                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
-| variantType             | `string`                                       | -         | What type of variants are available (for example, a type `packageManager` when variants `npm` and `yarn` are available)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
-| variants                | `string[]`                                     | -         | Static variant names that should be fetched at runtime                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
-| children                | `string`                                       | -         | Raw code string for simple use cases                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
+| Prop                    | Type                                           | Default   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
+| :---------------------- | :--------------------------------------------- | :-------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| name                    | `string`                                       | -         | Display name for the code example, used for identification and titles                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
+| collapseToEmpty         | `boolean`                                      | -         | Render-time "collapse to empty": collapse the code block to an empty window so
the whole block is hidden until expanded. Threaded into `contentProps` and
consumed by `useCode`/`
`. Runtime-only — the precomputed HAST is
unchanged.                                                                                                                                                                                                                                                                  |
+| initialExpanded         | `boolean`                                      | -         | Whether the (collapsible) code block starts expanded. Threaded into
`contentProps` so both `useCode` and the loading fallback honor it.                                                                                                                                                                                                                                                                                                                                                                             |
+| Content\*               | `React.ComponentType>`        | -         | Component to render the code content and preview                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
+| ContentFrame            | `React.ComponentType>`   | -         | Client Component that keeps the preview shell mounted while loading and
interactive chrome change. Requires `ContentLoading`.                                                                                                                                                                                                                                                                                                                                                                                       |
+| ContentLoading          | `React.ComponentType>` | -         | Component to show while code is being loaded or processed                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
+| code                    | `Code`                                         | -         | Static code content with variants and metadata                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+| components              | `Components`                                   | -         | React components for live preview alongside code                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
+| contentProps            | `{}`                                           | -         | Additional props passed to the Content component                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
+| controlled              | `boolean`                                      | -         | Enable controlled mode for external code state management                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
+| defaultVariant          | `string`                                       | -         | Fallback variant when the requested variant is not available                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
+| deferParsing            | `'none' \| 'json' \| 'gzip'`                   | `'gzip'`  | Defer parsing and populating the AST into memory until the code is enhanced
Applies only in production when RSC loading                                                                                                                                                                                                                                                                                                                                                                                             |
+| editActivation          | `'eager' \| 'interaction'`                     | `'eager'` | When the textarea editor loads for an editable block: `'eager'` (default): load it as soon as the block is editable, and let
`CodeHighlighter` speculatively preload it on first render.`'interaction'`: defer the load until the reader hovers, focuses, or
clicks the code, and suppress the speculative preload — so a block the
reader never engages does not fetch the editor chunk at all. Only meaningful for editable blocks (a `CodeControllerContext` exposing
`setCode`); ignored otherwise. |
+| enhanceAfter            | `'init' \| 'stream' \| 'hydration' \| 'idle'`  | `'idle'`  | When to enhance the code display with interactivity                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
+| fallbackCollapsed       | `boolean`                                      | `false`   | Paint only the collapsed window in the `ContentLoading` fallback and defer
each file's full fallback into the compressed payload. Shrinks the initial
HTML of a collapsed block to its on-screen lines, but removes the hidden
lines from the server-rendered markup — so it is **only** appropriate for
content that will not be crawled (authenticated or internal pages). See the
prop-compression pattern's "Splitting the Fallback by Visibility".                                             |
+| fallbackUsesAllVariants | `boolean`                                      | -         | Whether fallback content should include all variants                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
+| fallbackUsesExtraFiles  | `boolean`                                      | -         | Whether fallback content should include extra files                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
+| fileName                | `string`                                       | -         | Currently selected file name                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
+| forceClient             | `boolean`                                      | -         | Force client-side rendering even when server rendering is available                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
+| globalsCode             | `(string \| Code)[]`                           | -         | Global static code snippets to inject, typically for styling or tooling                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
+| highlightAfter          | `'init' \| 'stream' \| 'hydration' \| 'idle'`  | `'idle'`  | When to perform syntax highlighting and code processing                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
+| initialDisabled         | `boolean`                                      | -         | Start the editable code read-only. Threaded into `contentProps`; `useCode` seeds its
`editable` toggle from it (a reader flips it back with `setEditable`). Runtime-only.                                                                                                                                                                                                                                                                                                                                           |
+| initialVariant          | `string`                                       | -         | Default variant to show on first load                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
+| language                | `string`                                       | -         | Language for syntax highlighting (for example, 'tsx', 'css'). When provided, fileName is not required for parsing.                                                                                                                                                                                                                                                                                                                                                                                                      |
+| loadCodeMeta            | `LoadCodeMeta`                                 | -         | Function to load code metadata from a URL                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
+| loadPrecompute          | `(() => Promise)`                        | -         | Loads the complete precomputed source after the fallback approaches the viewport.                                                                                                                                                                                                                                                                                                                                                                                                                                       |
+| loadSource              | `LoadSource`                                   | -         | Function to load raw source code and dependencies                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
+| loadVariantMeta         | `LoadVariantMeta`                              | -         | Function to load specific variant metadata                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
+| precompute              | `Code`                                         | -         | Pre-computed code data from build-time optimization                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
+| slug                    | `string`                                       | -         | URL-friendly identifier for deep linking and navigation                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
+| sourceEnhancers         | `SourceEnhancers`                              | -         | Array of source enhancers that run after parsing to enhance the HAST tree                                                                                                                                                                                                                                                                                                                                                                                                                                               |
+| sourceParser            | `Promise`                         | -         | Promise resolving to a source parser for syntax highlighting                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
+| sourceTransformers      | `SourceTransformers`                           | -         | Array of source transformers for code processing (for example, TypeScript to JavaScript)                                                                                                                                                                                                                                                                                                                                                                                                                                |
+| url                     | `string`                                       | -         | Source URL where the code content originates from                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
+| urlPrefix               | `{ from: string; to: string }`                 | -         | Optional URL-prefix rewrite forwarded to .
Lets the demo factory translate local `file://` URLs returned by
`loadSource` into hosted URLs before they reach the client.                                                                                                                                                                                                                                                                                                                                         |
+| variant                 | `string`                                       | -         | Currently selected variant name                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
+| variantType             | `string`                                       | -         | What type of variants are available (for example, a type `packageManager` when variants `npm` and `yarn` are available)                                                                                                                                                                                                                                                                                                                                                                                                 |
+| variants                | `string[]`                                     | -         | Static variant names that should be fetched at runtime                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
+| children                | `string`                                       | -         | Raw code string for simple use cases                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
 
 ### LoadCodeMeta
 
@@ -500,20 +500,15 @@ type CodeHighlighterBaseProps = {
    * When the textarea editor loads for an editable block:
    *   - `'eager'` (default): load it as soon as the block is editable, and let
    *     `CodeHighlighter` speculatively preload it on first render.
-   *   - `'interaction'`: defer the load until the reader clicks the code or
-   *     presses Enter on its wrapper. Blocks the reader never engages do not
-   *     fetch the editor chunk.
-   *
-   *   - `'idle'`: initialize visible editors after page load and 1.5 seconds
-   *     without input, during browser idle time. Interaction still activates
-   *     the editor immediately. Hidden and offscreen blocks stay deferred.
-   *     Starved idle callbacks run after another five seconds without input.
+   *   - `'interaction'`: defer the load until the reader hovers, focuses, or
+   *     clicks the code, and suppress the speculative preload — so a block the
+   *     reader never engages does not fetch the editor chunk at all.
    *
    * Only meaningful for editable blocks (a `CodeControllerContext` exposing
    * `setCode`); ignored otherwise.
    * @default 'eager'
    */
-  editActivation?: 'eager' | 'interaction' | 'idle';
+  editActivation?: 'eager' | 'interaction';
   /** Raw code string for simple use cases */
   children?: string;
   /**
@@ -637,20 +632,15 @@ type CodeHighlighterClientProps = {
    * When the textarea editor loads for an editable block:
    *   - `'eager'` (default): load it as soon as the block is editable, and let
    *     `CodeHighlighter` speculatively preload it on first render.
-   *   - `'interaction'`: defer the load until the reader clicks the code or
-   *     presses Enter on its wrapper. Blocks the reader never engages do not
-   *     fetch the editor chunk.
-   *
-   *   - `'idle'`: initialize visible editors after page load and 1.5 seconds
-   *     without input, during browser idle time. Interaction still activates
-   *     the editor immediately. Hidden and offscreen blocks stay deferred.
-   *     Starved idle callbacks run after another five seconds without input.
+   *   - `'interaction'`: defer the load until the reader hovers, focuses, or
+   *     clicks the code, and suppress the speculative preload — so a block the
+   *     reader never engages does not fetch the editor chunk at all.
    *
    * Only meaningful for editable blocks (a `CodeControllerContext` exposing
    * `setCode`); ignored otherwise.
    * @default 'eager'
    */
-  editActivation?: 'eager' | 'interaction' | 'idle';
+  editActivation?: 'eager' | 'interaction';
   /** Force client-side rendering even when server rendering is available */
   forceClient?: boolean;
   /**
@@ -747,20 +737,15 @@ type CodeHighlighterProps = {
    * When the textarea editor loads for an editable block:
    *   - `'eager'` (default): load it as soon as the block is editable, and let
    *     `CodeHighlighter` speculatively preload it on first render.
-   *   - `'interaction'`: defer the load until the reader clicks the code or
-   *     presses Enter on its wrapper. Blocks the reader never engages do not
-   *     fetch the editor chunk.
-   *
-   *   - `'idle'`: initialize visible editors after page load and 1.5 seconds
-   *     without input, during browser idle time. Interaction still activates
-   *     the editor immediately. Hidden and offscreen blocks stay deferred.
-   *     Starved idle callbacks run after another five seconds without input.
+   *   - `'interaction'`: defer the load until the reader hovers, focuses, or
+   *     clicks the code, and suppress the speculative preload — so a block the
+   *     reader never engages does not fetch the editor chunk at all.
    *
    * Only meaningful for editable blocks (a `CodeControllerContext` exposing
    * `setCode`); ignored otherwise.
    * @default 'eager'
    */
-  editActivation?: 'eager' | 'interaction' | 'idle';
+  editActivation?: 'eager' | 'interaction';
   /** Raw code string for simple use cases */
   children?: string;
   /**
@@ -856,20 +841,15 @@ type CodeLoadingProps = {
    * When the textarea editor loads for an editable block:
    *   - `'eager'` (default): load it as soon as the block is editable, and let
    *     `CodeHighlighter` speculatively preload it on first render.
-   *   - `'interaction'`: defer the load until the reader clicks the code or
-   *     presses Enter on its wrapper. Blocks the reader never engages do not
-   *     fetch the editor chunk.
-   *
-   *   - `'idle'`: initialize visible editors after page load and 1.5 seconds
-   *     without input, during browser idle time. Interaction still activates
-   *     the editor immediately. Hidden and offscreen blocks stay deferred.
-   *     Starved idle callbacks run after another five seconds without input.
+   *   - `'interaction'`: defer the load until the reader hovers, focuses, or
+   *     clicks the code, and suppress the speculative preload — so a block the
+   *     reader never engages does not fetch the editor chunk at all.
    *
    * Only meaningful for editable blocks (a `CodeControllerContext` exposing
    * `setCode`); ignored otherwise.
    * @default 'eager'
    */
-  editActivation?: 'eager' | 'interaction' | 'idle';
+  editActivation?: 'eager' | 'interaction';
   /** Raw code string for simple use cases */
   children?: string;
   /**
diff --git a/docs/app/docs-infra/components/page.mdx b/docs/app/docs-infra/components/page.mdx
index 179eae90c5..45b9788a01 100644
--- a/docs/app/docs-infra/components/page.mdx
+++ b/docs/app/docs-infra/components/page.mdx
@@ -52,7 +52,6 @@ It supports both static code blocks and interactive demos with component preview
   - Types
     - CodeHighlighter
     - CodeHighlighter Types
-  - Preparing editors during idle
 - Exports:
   - CodeHighlighter
     - Props: Content, ContentFrame, ContentLoading, children, code, collapseToEmpty, components, contentProps, controlled, defaultVariant, deferParsing, editActivation, enhanceAfter, fallbackCollapsed, fallbackUsesAllVariants, fallbackUsesExtraFiles, fileName, forceClient, globalsCode, highlightAfter, initialDisabled, initialExpanded, initialVariant, language, loadCodeMeta, loadPrecompute, loadSource, loadVariantMeta, name, precompute, slug, sourceEnhancers, sourceParser, sourceTransformers, url, urlPrefix, variant, variantType, variants
diff --git a/docs/app/docs-infra/hooks/page.mdx b/docs/app/docs-infra/hooks/page.mdx
index 6216fcc7d9..d52188fc95 100644
--- a/docs/app/docs-infra/hooks/page.mdx
+++ b/docs/app/docs-infra/hooks/page.mdx
@@ -36,6 +36,7 @@ The `useCode` hook provides programmatic access to code display, editing, and tr
   - Editing behavior
     - Collapsed and expanded editing
     - Editor interaction
+    - Preparing an editor
     - Selected file metadata
     - Source actions
     - Controlled transforms
diff --git a/docs/app/docs-infra/hooks/use-code/page.mdx b/docs/app/docs-infra/hooks/use-code/page.mdx
index 994f560902..a23be83cc3 100644
--- a/docs/app/docs-infra/hooks/use-code/page.mdx
+++ b/docs/app/docs-infra/hooks/use-code/page.mdx
@@ -45,6 +45,21 @@ Starting to edit a live demo switches it to the live preview immediately, even b
 first change. It stays on the live preview until the demo unmounts; resetting the source
 does not switch back to the bundled component.
 
+### Preparing an editor
+
+With `editActivation="interaction"`, call `prepareEditor()` from `useCode` or `useDemo`
+to initialize the selected editor and its editing runtime before a click:
+
+```tsx
+const code = useCode(props);
+return ;
+```
+
+Preparation loads asynchronously without moving focus or changing source.
+Repeated calls are safe. Calls while editing is disabled do nothing.
+The host owns visibility checks, idle timing, and cancellation.
+`preloadCodeEditor()` only fetches the editor module; it does not initialize an editor.
+
 ### Selected file metadata
 
 The hook exposes details about the selected file so controls do not need to inspect the
diff --git a/docs/app/docs-infra/hooks/use-code/types.md b/docs/app/docs-infra/hooks/use-code/types.md
index 976d6940dd..0ea0285690 100644
--- a/docs/app/docs-infra/hooks/use-code/types.md
+++ b/docs/app/docs-infra/hooks/use-code/types.md
@@ -180,6 +180,12 @@ type UseCodeResult = {
    * reader's edits (use `reset` to discard them).
    */
   setEditable?: (editable: boolean) => void;
+  /**
+   * Initialize the selected editor and editing runtime without moving focus.
+   * Loading is asynchronous. Does nothing while editing is disabled.
+   * The host decides when to call this, for example after visible source is idle.
+   */
+  prepareEditor: () => void;
   /**
    * Replace the source of the currently selected file (or `fileName` when
    * provided) in the controlled code. Internal hooks may pass additional
diff --git a/docs/app/docs-infra/hooks/use-demo/types.md b/docs/app/docs-infra/hooks/use-demo/types.md
index ae2c527658..78f594e341 100644
--- a/docs/app/docs-infra/hooks/use-demo/types.md
+++ b/docs/app/docs-infra/hooks/use-demo/types.md
@@ -254,6 +254,7 @@ type ReturnValue = void;
 | hasControlledEdits             | `boolean`                                                                                                                        | Whether the surrounding controller currently owns edited source.                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
 | editable                       | `boolean`                                                                                                                        | Whether edit mode is currently on. `true` by default; starts `false` when the block
opts in via `initialDisabled` — per demo through the `createDemo` `meta`, or across a
factory's demos through `createDemoFactory`. While `false` the block renders
read-only and the live-editing engine is not even warmed; flip it with
`setEditable`. Independent of `editActivation`, which governs _when_ the engine
loads once editing is on, and of `disabled`, which turns editing off permanently. |
 | setEditable                    | `((editable: boolean) => void) \| undefined`                                                                                     | Turns edit mode on or off. `undefined` when the block can't be edited at all — no
`CodeControllerContext` with `setCode` in scope, or editing is hard-`disabled` — so
a toggle button can render only when this is defined. Toggling off keeps the
reader's edits (use `reset` to discard them).                                                                                                                                                                                                        |
+| prepareEditor                  | `(() => void)`                                                                                                                   | Initialize the selected editor and editing runtime without moving focus.
Loading is asynchronous. Does nothing while editing is disabled.
The host decides when to call this, for example after visible source is idle.                                                                                                                                                                                                                                                                                     |
 | setSource                      | `((source: string, fileName?: string) => void) \| undefined`                                                                     | Replace the source of the currently selected file (or `fileName` when
provided) in the controlled code. Internal hooks may pass additional
arguments (caret position, pre-parsed HAST) that are not part of the
public contract.                                                                                                                                                                                                                                                                        |
 | reset                          | `(() => void) \| undefined`                                                                                                      | Clears the entire controlled code state back to `undefined`, discarding
user edits across **all variants and files** owned by the surrounding
`CodeControllerContext` (not just the currently selected file or
variant). Only available when a `CodeControllerContext` with `setCode`
is in scope and editing is not disabled.                                                                                                                                                                      |
 | refresh                        | `(() => void) \| undefined`                                                                                                      | Re-fetches the block's data on the client by re-running the full variant
loader, then swaps in the fresh result while keeping the current highlighted
output visible until the new tree lands (stale-while-revalidate). Invalidates
the pre-parsed HAST cache. `undefined` (or a no-op) for a block with no `url`
to re-fetch from, or with no `CodeProvider` in scope.                                                                                                                             |
diff --git a/packages/docs-infra/src/CodeHighlighter/CodeHighlighterClient.tsx b/packages/docs-infra/src/CodeHighlighter/CodeHighlighterClient.tsx
index 1735d988bf..b3201b3060 100644
--- a/packages/docs-infra/src/CodeHighlighter/CodeHighlighterClient.tsx
+++ b/packages/docs-infra/src/CodeHighlighter/CodeHighlighterClient.tsx
@@ -1301,7 +1301,7 @@ export function CodeHighlighterClient(props: CodeHighlighterClientProps) {
     !!speculativeCode &&
     (Boolean(props.forceClient) ||
       !hasAllVariants(variants, speculativeCode, true) ||
-      ((editActivation ?? 'eager') === 'eager' && Boolean(controlled?.setCode)));
+      ((editActivation ?? 'eager') !== 'interaction' && Boolean(controlled?.setCode)));
   useSpeculativeGrammarPreload({ scopes: speculativeGrammarScopes, enabled: willClientHighlight });
 
   // ── Fallback hoisting ──
diff --git a/packages/docs-infra/src/CodeHighlighter/CodeHighlighterContext.tsx b/packages/docs-infra/src/CodeHighlighter/CodeHighlighterContext.tsx
index f6e6cbf4ad..6400f4a917 100644
--- a/packages/docs-infra/src/CodeHighlighter/CodeHighlighterContext.tsx
+++ b/packages/docs-infra/src/CodeHighlighter/CodeHighlighterContext.tsx
@@ -71,10 +71,10 @@ export interface CodeHighlighterContextType {
   /**
    * Echo of the `editActivation` prop on the surrounding `CodeHighlighter` /
    * `CodeHighlighterClient`. `useCode` reads it from here and threads it down to
-   * `Pre`, which handles interaction and visible-idle activation. Configure the
-   * strategy at the `CodeHighlighter` / demo level.
+   * `Pre` (which defers the textarea load when `'interaction'`), so the strategy can be configured at
+   * the `CodeHighlighter` / demo level rather than inside the content subtree.
    */
-  editActivation?: 'eager' | 'interaction' | 'idle';
+  editActivation?: 'eager' | 'interaction';
   /**
    * Callback `useCode` threads down to the editor's `onActivate`, fired once
    * when the block first engages for editing. `CodeHighlighterClient` supplies it
diff --git a/packages/docs-infra/src/CodeHighlighter/types.ts b/packages/docs-infra/src/CodeHighlighter/types.ts
index 32388f0d74..1e4af2360a 100644
--- a/packages/docs-infra/src/CodeHighlighter/types.ts
+++ b/packages/docs-infra/src/CodeHighlighter/types.ts
@@ -593,20 +593,15 @@ export interface CodeLoadingProps {
    * When the textarea editor loads for an editable block:
    *   - `'eager'` (default): load it as soon as the block is editable, and let
    *     `CodeHighlighter` speculatively preload it on first render.
-   *   - `'interaction'`: defer the load until the reader clicks the code or
-   *     presses Enter on its wrapper. Blocks the reader never engages do not
-   *     fetch the editor chunk.
-   *
-   *   - `'idle'`: initialize visible editors after page load and 1.5 seconds
-   *     without input, during browser idle time. Interaction still activates
-   *     the editor immediately. Hidden and offscreen blocks stay deferred.
-   *     Starved idle callbacks run after another five seconds without input.
+   *   - `'interaction'`: defer the load until the reader hovers, focuses, or
+   *     clicks the code, and suppress the speculative preload — so a block the
+   *     reader never engages does not fetch the editor chunk at all.
    *
    * Only meaningful for editable blocks (a `CodeControllerContext` exposing
    * `setCode`); ignored otherwise.
    * @default 'eager'
    */
-  editActivation?: 'eager' | 'interaction' | 'idle';
+  editActivation?: 'eager' | 'interaction';
   /** Raw code string for simple use cases */
   children?: string;
   /**
diff --git a/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.test.tsx b/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.test.tsx
index b315a10ce7..a7ab936101 100644
--- a/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.test.tsx
+++ b/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.test.tsx
@@ -16,11 +16,7 @@ import type { CodeContext as CodeContextValue } from '../CodeProvider/CodeContex
 import { useSpeculativeEditingPreload } from './useSpeculativeEditingPreload';
 
 function setup(
-  props: {
-    enabled: boolean;
-    editActivation?: 'eager' | 'interaction' | 'idle';
-    activated?: boolean;
-  },
+  props: { enabled: boolean; editActivation?: 'eager' | 'interaction'; activated?: boolean },
   loaders: Partial,
 ) {
   function Speculative() {
@@ -47,9 +43,9 @@ describe('useSpeculativeEditingPreload', () => {
     expect(codeEditorLoader).not.toHaveBeenCalled();
   });
 
-  it.each(['interaction', 'idle'] as const)('waits for activation in %s mode', (editActivation) => {
+  it("waits for activation when editActivation is 'interaction'", () => {
     const codeEditorLoader = vi.fn(async () => ({}) as never);
-    setup({ enabled: true, editActivation, activated: false }, { codeEditorLoader });
+    setup({ enabled: true, editActivation: 'interaction', activated: false }, { codeEditorLoader });
     expect(codeEditorLoader).not.toHaveBeenCalled();
   });
 
diff --git a/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.ts b/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.ts
index 6b58e57f39..4dfd971f0f 100644
--- a/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.ts
+++ b/packages/docs-infra/src/CodeHighlighter/useSpeculativeEditingPreload.ts
@@ -21,8 +21,6 @@ import { preloadCodeEditor } from '../useCode/codeEditorCache';
  *   `CodeHighlighter` flips `activated`. This is the single moment that kicks off
  *   every editing dependency, rather than each loading on its own trigger.
  *
- * - `'idle'`: waits for a visible `Pre` to activate during idle time or input.
- *
  * A read-only block sets `enabled = false` and warms nothing.
  */
 export function useSpeculativeEditingPreload({
@@ -32,8 +30,8 @@ export function useSpeculativeEditingPreload({
   scopes,
 }: {
   enabled: boolean;
-  editActivation?: 'eager' | 'interaction' | 'idle';
-  /** Whether a deferred block has activated (ignored when `'eager'`). */
+  editActivation?: 'eager' | 'interaction';
+  /** Whether an `'interaction'` block has engaged yet (ignored when `'eager'`). */
   activated?: boolean;
   /**
    * Grammar scopes the editable block uses, so its grammars (main thread) and the
@@ -43,8 +41,8 @@ export function useSpeculativeEditingPreload({
 }): void {
   const { codeEditorLoader, ensureParseSourceWorker } = useCodeContext();
 
-  // Deferred modes warm only after activation.
-  const shouldWarm = enabled && ((editActivation ?? 'eager') === 'eager' || activated);
+  // 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
diff --git a/packages/docs-infra/src/useCode/Pre.browser.tsx b/packages/docs-infra/src/useCode/Pre.browser.tsx
index d448844fca..bd355691f9 100644
--- a/packages/docs-infra/src/useCode/Pre.browser.tsx
+++ b/packages/docs-infra/src/useCode/Pre.browser.tsx
@@ -88,124 +88,6 @@ describe('Pre editor - browser', () => {
     cleanup();
   });
 
-  it('initializes a visible idle editor without moving focus and preserves the first clicked caret', async () => {
-    const source = Array.from(
-      { length: 40 },
-      (_, index) => `const value_${index} = ${index};`,
-    ).join('\n');
-
-    const { container } = render(
-      
- -
-
 {}} editActivation="idle">
-            {source}
-          
-
-
-
 {}} editActivation="idle">
-            {source}
-          
-
-
-          {source}
-        
- -
, - ); - - const focusTarget = screen.getByRole('button', { name: 'Keep focus' }); - - await userEvent.click(focusTarget); - expect(container.querySelector('textarea')).toBeNull(); - - const textarea = await screen.findByRole( - 'textbox', - { name: 'Edit App.ts' }, - { timeout: 10000 }, - ); - - expect(document.activeElement).toBe(focusTarget); - expect(container.querySelectorAll('textarea')).toHaveLength(1); - - const scroller = screen.getByTestId('scroller'); - scroller.scrollTop = LINE_HEIGHT * 20; - const scrollTop = scroller.scrollTop; - const pageScroll = window.scrollY; - - await userEvent.click(textarea, { position: { x: 60, y: scrollTop + LINE_HEIGHT } }); - - expect(document.activeElement).toBe(textarea); - expect((textarea as HTMLTextAreaElement).selectionStart).toBeGreaterThan( - source.indexOf('value_19'), - ); - expect(scroller.scrollTop).toBe(scrollTop); - expect(window.scrollY).toBe(pageScroll); - }); - - it('cancels initialization when the source is hidden and resumes on reopening', async () => { - function ToggleSource() { - const [visible, setVisible] = React.useState(true); - const [activations, setActivations] = React.useState(0); - - return ( - - - Activations: {activations} - - - ); - } - - const { container } = render(); - - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); - - try { - await userEvent.click(screen.getByRole('button', { name: 'Toggle code' })); - await vi.advanceTimersByTimeAsync(2000); - - expect(container.querySelector('textarea')).toBeNull(); - expect(screen.getByText('Activations: 0')).not.toBeNull(); - } finally { - vi.useRealTimers(); - } - - await userEvent.click(screen.getByRole('button', { name: 'Toggle code' })); - await screen.findByRole('textbox', {}, { timeout: 10000 }); - - expect(screen.getByText('Activations: 1')).not.toBeNull(); - }); - - it('keeps interaction activation available before idle initialization', async () => { - render( -
 {}} editActivation="idle">
-        {'const value = 1;'}
-      
, - ); - - await userEvent.click(screen.getByRole('group', { name: 'Editable code' })); - - const textarea = await screen.findByRole('textbox'); - - await waitFor(() => expect(document.activeElement).toBe(textarea)); - }); - it('uses the wrapper as one Tab stop, Enter to engage, and Escape to exit', async () => { render(
 {}}>
diff --git a/packages/docs-infra/src/useCode/Pre.tsx b/packages/docs-infra/src/useCode/Pre.tsx
index f5bc2addfc..ca53d695b1 100644
--- a/packages/docs-infra/src/useCode/Pre.tsx
+++ b/packages/docs-infra/src/useCode/Pre.tsx
@@ -20,7 +20,6 @@ import { getSourceLineCounts } from './sourceLineCounts';
 import type { SourceLineCounts } from './sourceLineCounts';
 import { subscribeToggleNudge } from './subscribeToggleNudge';
 import { CodeEditorLazy } from './CodeEditorLazy';
-import { useIdleEditor } from './useIdleEditor';
 
 const hastChildrenCache = new WeakMap();
 const fallbackHastCache = new WeakMap();
@@ -86,6 +85,7 @@ export function Pre({
   expanded = false,
   collapseToEmpty = false,
   editActivation,
+  prepareRequested = false,
   onActivate,
   onBoundary,
   editable = true,
@@ -127,10 +127,10 @@ export function Pre({
    * Controls when the textarea editor loads for an editable block: `'eager'`
    * (default) loads it as soon as the block is editable; `'interaction'` defers
    * the load until the reader clicks the code or presses Enter on its wrapper. Ignored when the
-   * block is not editable. `'idle'` initializes visible blocks during idle
-   * time after page load and a quiet input interval, or on interaction.
+   * block is not editable.
    */
-  editActivation?: 'eager' | 'interaction' | 'idle';
+  editActivation?: 'eager' | 'interaction';
+  prepareRequested?: boolean;
   /**
    * Fired once when the block first engages for editing. `CodeHighlighter` uses
    * it to warm the live-editing runtime, grammars, and worker.
@@ -570,9 +570,13 @@ export function Pre({
   const sourceFocusedLines = collapseToEmpty ? 0 : rawFocusedLines;
 
   const isEditable = Boolean(setSource) && editable;
-  const [editorRequested, setEditorRequested] = React.useState(
-    () => (editActivation ?? 'eager') === 'eager',
+
+  const [interactionRequested, setEditorRequested] = React.useState(
+    () => editActivation !== 'interaction',
   );
+
+  const editorRequested = interactionRequested || prepareRequested;
+
   const fullSource = React.useMemo(
     () =>
       isEditable && editorRequested
@@ -648,16 +652,11 @@ export function Pre({
     }
   }, [onActivate]);
 
-  const initializeEditor = React.useCallback(() => {
-    handleEditorActivate();
-    React.startTransition(() => setEditorRequested(true));
-  }, [handleEditorActivate]);
-
-  useIdleEditor(
-    wrapperRef,
-    initializeEditor,
-    isEditable && !editorRequested && editActivation === 'idle' ? 'idle' : 'disabled',
-  );
+  React.useEffect(() => {
+    if (prepareRequested && isEditable) {
+      handleEditorActivate();
+    }
+  }, [prepareRequested, isEditable, handleEditorActivate]);
 
   const requestEditorFocus = React.useCallback(() => {
     setPromptVisible(false);
diff --git a/packages/docs-infra/src/useCode/useCode.ts b/packages/docs-infra/src/useCode/useCode.ts
index 5a898f8ebc..22b5a0e76b 100644
--- a/packages/docs-infra/src/useCode/useCode.ts
+++ b/packages/docs-infra/src/useCode/useCode.ts
@@ -142,6 +142,12 @@ export interface UseCodeResult {
    * reader's edits (use {@link reset} to discard them).
    */
   setEditable?: (editable: boolean) => void;
+  /**
+   * Initialize the selected editor and editing runtime without moving focus.
+   * Loading is asynchronous. Does nothing while editing is disabled.
+   * The host decides when to call this, for example after visible source is idle.
+   */
+  prepareEditor: () => void;
   /**
    * Replace the source of the currently selected file (or `fileName` when
    * provided) in the controlled code. Internal hooks may pass additional
@@ -387,6 +393,15 @@ export function useCode(
     [expand, rawSetExpanded],
   );
 
+  const [prepareRequested, setPrepareRequested] = React.useState(false);
+  const canPrepare = uiState.editable && Boolean(sourceEditing.setSource);
+
+  const prepareEditor = React.useCallback(() => {
+    if (canPrepare) {
+      React.startTransition(() => setPrepareRequested(true));
+    }
+  }, [canPrepare]);
+
   const sourceEditingActivate = sourceEditing.activate;
   const onEditingActivated = context?.onEditingActivated;
   const activateEditing = React.useCallback(() => {
@@ -422,6 +437,7 @@ export function useCode(
     preClassName,
     setSource: sourceEditing.setSource,
     editActivation: context?.editActivation,
+    prepareRequested,
     onActivate: activateEditing,
     onBoundary: expand,
     editable: uiState.editable,
@@ -503,6 +519,7 @@ export function useCode(
     hasControlledEdits,
     editable: uiState.editable,
     setEditable: canToggleEditing ? uiState.setEditable : undefined,
+    prepareEditor,
     setSource: sourceEditing.setSource,
     reset: sourceEditing.reset,
     refresh: context?.refresh,
diff --git a/packages/docs-infra/src/useCode/useFileNavigation.tsx b/packages/docs-infra/src/useCode/useFileNavigation.tsx
index 9b06727a95..30f4a798fc 100644
--- a/packages/docs-infra/src/useCode/useFileNavigation.tsx
+++ b/packages/docs-infra/src/useCode/useFileNavigation.tsx
@@ -79,10 +79,11 @@ interface UseFileNavigationProps {
   /**
    * Forwarded to `
`: when the textarea editor loads for an
    * editable block. `'eager'` (default) loads on mount; `'interaction'` defers
-   * until interaction or visible idle time. Sourced from the `editActivation`
+   * until interaction. Sourced from the `editActivation`
    * prop on `CodeHighlighter` (via `CodeHighlighterContext`).
    */
-  editActivation?: 'eager' | 'interaction' | 'idle';
+  editActivation?: 'eager' | 'interaction';
+  prepareRequested?: boolean;
   /** Forwarded to `
`: fired once when the block engages for editing. */
   onActivate?: () => void;
   /** Forwarded to `
`: expands focused source from textarea boundary navigation. */
@@ -180,6 +181,7 @@ export function useFileNavigation({
   preClassName,
   setSource,
   editActivation,
+  prepareRequested,
   onActivate,
   onBoundary,
   editable,
@@ -740,6 +742,7 @@ export function useFileNavigation({
           language={language}
           setSource={setSource}
           editActivation={editActivation}
+          prepareRequested={prepareRequested}
           onActivate={onActivate}
           onBoundary={onBoundary}
           editable={editable}
@@ -762,6 +765,7 @@ export function useFileNavigation({
     preClassName,
     setSource,
     editActivation,
+    prepareRequested,
     onActivate,
     onBoundary,
     editable,
@@ -850,6 +854,7 @@ export function useFileNavigation({
             language={getLanguageFromFileName(f.name)}
             setSource={setSource}
             editActivation={editActivation}
+            prepareRequested={prepareRequested}
             onActivate={onActivate}
             onBoundary={onBoundary}
             editable={editable}
@@ -881,6 +886,7 @@ export function useFileNavigation({
             language={selectedVariant.language}
             setSource={setSource}
             editActivation={editActivation}
+            prepareRequested={prepareRequested}
             onActivate={onActivate}
             onBoundary={onBoundary}
             editable={editable}
@@ -927,6 +933,7 @@ export function useFileNavigation({
               language={language ?? getLanguageFromFileName(fileName)}
               setSource={setSource}
               editActivation={editActivation}
+              prepareRequested={prepareRequested}
               onActivate={onActivate}
               onBoundary={onBoundary}
               editable={editable}
@@ -958,6 +965,7 @@ export function useFileNavigation({
     resolvedFallbacks,
     setSource,
     editActivation,
+    prepareRequested,
     onActivate,
     onBoundary,
     editable,
diff --git a/packages/docs-infra/src/useCode/useIdleEditor.ts b/packages/docs-infra/src/useCode/useIdleEditor.ts
deleted file mode 100644
index a9b66d5f11..0000000000
--- a/packages/docs-infra/src/useCode/useIdleEditor.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-'use client';
-
-import * as React from 'react';
-import { requestIdle } from '../useCoordinated/scheduleTasks';
-
-const EDITOR_IDLE_DELAY_MS = 1500;
-const EDITOR_IDLE_TIMEOUT_MS = 5000;
-
-const INPUT_EVENTS = [
-  'pointerdown',
-  'pointermove',
-  'keydown',
-  'scroll',
-  'wheel',
-  'touchstart',
-] as const;
-
-/** Initializes visible editors after page loading and a quiet input interval. */
-export function useIdleEditor(
-  target: React.RefObject,
-  onIdle: () => void,
-  mode: 'idle' | 'disabled',
-) {
-  React.useEffect(() => {
-    const element = target.current;
-
-    if (mode !== 'idle' || !element || typeof IntersectionObserver === 'undefined') {
-      return undefined;
-    }
-
-    let visible = false;
-    let requested = false;
-    let timer: ReturnType | undefined;
-    let cancelIdle: (() => void) | undefined;
-
-    const cancel = () => {
-      clearTimeout(timer);
-      cancelIdle?.();
-    };
-
-    const canInitialize = () =>
-      visible &&
-      !requested &&
-      document.readyState === 'complete' &&
-      document.visibilityState === 'visible';
-
-    const schedule = () => {
-      cancel();
-
-      if (!canInitialize()) {
-        return;
-      }
-
-      timer = setTimeout(() => {
-        // Continuous rendering can starve idle callbacks even after input stops.
-        cancelIdle = requestIdle(
-          () => {
-            if (!canInitialize()) {
-              return;
-            }
-
-            const bounds = element.getBoundingClientRect();
-
-            if (
-              bounds.width === 0 ||
-              bounds.height === 0 ||
-              getComputedStyle(element).visibility === 'hidden'
-            ) {
-              return;
-            }
-
-            requested = true;
-            onIdle();
-          },
-          { timeout: EDITOR_IDLE_TIMEOUT_MS },
-        );
-      }, EDITOR_IDLE_DELAY_MS);
-    };
-
-    const observer = new IntersectionObserver(([entry]) => {
-      visible =
-        entry.isIntersecting &&
-        entry.intersectionRect.width > 0 &&
-        entry.intersectionRect.height > 0;
-      schedule();
-    });
-
-    observer.observe(element);
-    window.addEventListener('load', schedule);
-    document.addEventListener('visibilitychange', schedule);
-
-    for (const event of INPUT_EVENTS) {
-      window.addEventListener(event, schedule, { capture: true, passive: true });
-    }
-
-    return () => {
-      cancel();
-      observer.disconnect();
-      window.removeEventListener('load', schedule);
-      document.removeEventListener('visibilitychange', schedule);
-
-      for (const event of INPUT_EVENTS) {
-        window.removeEventListener(event, schedule, { capture: true });
-      }
-    };
-  }, [target, onIdle, mode]);
-}
diff --git a/packages/docs-infra/src/useCode/useSourceEditing.lazyLoad.test.ts b/packages/docs-infra/src/useCode/useSourceEditing.lazyLoad.test.ts
index c73d0d1a29..d8f5dec655 100644
--- a/packages/docs-infra/src/useCode/useSourceEditing.lazyLoad.test.ts
+++ b/packages/docs-infra/src/useCode/useSourceEditing.lazyLoad.test.ts
@@ -44,7 +44,7 @@ function renderCold() {
 }
 
 describe('useSourceEditing lazy engine (cold cache)', () => {
-  function renderEditable(editActivation?: 'eager' | 'interaction' | 'idle') {
+  function renderEditable(editActivation?: 'eager' | 'interaction') {
     const setCode = vi.fn();
     const context: CodeHighlighterContextType = { code: {}, setCode, editActivation };
     const view = renderHook(() =>
@@ -58,25 +58,22 @@ describe('useSourceEditing lazy engine (cold cache)', () => {
     return { ...view, setCode };
   }
 
-  it.each(['interaction', 'idle'] as const)(
-    'loads the %s engine only when editing activates',
-    async (mode) => {
-      const { result, setCode } = renderEditable(mode);
-      await vi.dynamicImportSettled();
-      expect(peekSourceEditingEngine()).toBeUndefined();
-      expect(setCode).not.toHaveBeenCalled();
-
-      act(() => result.current.activate?.());
-      await waitFor(() => expect(setCode).toHaveBeenCalledTimes(1));
-      expect(peekSourceEditingEngine()).toBeDefined();
-
-      act(() => result.current.setSource?.('new'));
-      expect(setCode).toHaveBeenCalledTimes(2);
-      const seeded = setCode.mock.calls[0][0](null);
-      const edited = setCode.mock.calls[1][0](seeded);
-      expect(edited.Default.source).toBe('new');
-    },
-  );
+  it('loads the interaction engine only when editing activates', async () => {
+    const { result, setCode } = renderEditable('interaction');
+    await vi.dynamicImportSettled();
+    expect(peekSourceEditingEngine()).toBeUndefined();
+    expect(setCode).not.toHaveBeenCalled();
+
+    act(() => result.current.activate?.());
+    await waitFor(() => expect(setCode).toHaveBeenCalledTimes(1));
+    expect(peekSourceEditingEngine()).toBeDefined();
+
+    act(() => result.current.setSource?.('new'));
+    expect(setCode).toHaveBeenCalledTimes(2);
+    const seeded = setCode.mock.calls[0][0](null);
+    const edited = setCode.mock.calls[1][0](seeded);
+    expect(edited.Default.source).toBe('new');
+  });
 
   it('warms the engine on mount by default', async () => {
     renderEditable();
diff --git a/packages/docs-infra/src/useCode/useSourceEditing.ts b/packages/docs-infra/src/useCode/useSourceEditing.ts
index c15ceb0758..5dc77c55b1 100644
--- a/packages/docs-infra/src/useCode/useSourceEditing.ts
+++ b/packages/docs-infra/src/useCode/useSourceEditing.ts
@@ -356,7 +356,7 @@ export function useSourceEditing({
       peekSourceEditingEngine() ||
       !contextSetCode ||
       disabled ||
-      (context?.editActivation ?? 'eager') !== 'eager'
+      context?.editActivation === 'interaction'
     ) {
       return;
     }
diff --git a/packages/docs-infra/test/CodeHighlighterEditing.browser.tsx b/packages/docs-infra/test/CodeHighlighterEditing.browser.tsx
index 65995c68fa..330f8f6465 100644
--- a/packages/docs-infra/test/CodeHighlighterEditing.browser.tsx
+++ b/packages/docs-infra/test/CodeHighlighterEditing.browser.tsx
@@ -54,12 +54,15 @@ function LiveSource(props: ContentProps<{}>) {
   return (
     
       {context.components?.[demo.selectedVariant]}
+      
       
{demo.selectedFile}
); } -function LiveDemo({ activation = 'interaction' }: { activation?: 'interaction' | 'idle' }) { +function LiveDemo() { const controller = useDemoController(); return ( @@ -73,7 +76,7 @@ function LiveDemo({ activation = 'interaction' }: { activation?: 'interaction' | highlightAfter="init" enhanceAfter="init" initialExpanded - editActivation={activation} + editActivation="interaction" Content={LiveSource} /> @@ -195,6 +198,8 @@ describe('CodeHighlighter editing source switches', () => { await userEvent.click(editor); await screen.findByText('Live build ready'); + await userEvent.click(screen.getByRole('button', { name: 'Prepare editor' })); + expect(screen.getByRole('textbox')).toBe(editor); expect(screen.getByRole('button', { name: 'Count 1' })).toBe(preview); await userEvent.fill(editor, COUNTER_SOURCE.replace('Count ', 'Edited ')); @@ -208,17 +213,20 @@ describe('CodeHighlighter editing source switches', () => { expect(bundledMounts).toBe(mountsBeforeUndo); }); - it('initializes an idle editor and runner without remounting or focusing the demo', async () => { - render(); + it('prepares the editor and runner without remounting or focusing the demo', async () => { + render(); const preview = screen.getByRole('button', { name: 'Count 0' }); await userEvent.click(preview); expect(screen.queryByRole('textbox')).toBeNull(); + await userEvent.click(screen.getByRole('button', { name: 'Prepare editor' })); const editor = await screen.findByRole('textbox', {}, { timeout: 10000 }); await screen.findByText('Live build ready'); + await userEvent.click(screen.getByRole('button', { name: 'Prepare editor' })); + expect(screen.getByRole('textbox')).toBe(editor); expect(screen.getByRole('button', { name: 'Count 1' })).toBe(preview); expect(bundledMounts).toBe(1); expect(document.activeElement).not.toBe(editor); From d81315be647a1b29811bf4d6bdb4d9e9abf8208d Mon Sep 17 00:00:00 2001 From: Brijesh Bittu <717550+brijeshb42@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:42:57 +0530 Subject: [PATCH 3/5] [docs-infra] Keep source inputs stable --- .../components/code-highlighter/types.md | 17 +- docs/app/docs-infra/components/page.mdx | 2 +- docs/app/docs-infra/hooks/page.mdx | 2 +- docs/app/docs-infra/hooks/use-code/page.mdx | 24 +- docs/app/docs-infra/hooks/use-code/types.md | 8 +- docs/app/docs-infra/hooks/use-demo/types.md | 3 +- packages/docs-infra/package.json | 1 + .../CodeHighlighter/prepareInitialSource.tsx | 33 ++- .../docs-infra/src/CodeHighlighter/types.ts | 10 + .../src/CodeHighlighter/useCodeFallback.tsx | 57 ++++- .../src/CodeProvider/CodeContext.tsx | 2 +- .../src/CodeProvider/useCodeProviderValue.ts | 5 +- .../NativeCodeSource.browser.tsx | 216 +++++++++++++++++ .../src/NativeCodeSource/NativeCodeSource.tsx | 11 + .../NativeCodeSource/deferredSource.test.tsx | 73 ++++++ .../docs-infra/src/NativeCodeSource/index.ts | 5 + .../loadPrecomputedCodeHighlighter.ts | 20 +- .../docs-infra/src/useCode/CodeEditor.tsx | 223 ++++++++++++++---- packages/docs-infra/src/useCode/Pre.tsx | 173 ++++++++------ packages/docs-infra/src/useCode/useCode.ts | 21 +- .../src/useCode/useFileNavigation.tsx | 53 +++-- .../test/CodeHighlighterEditing.browser.tsx | 27 --- 22 files changed, 781 insertions(+), 205 deletions(-) create mode 100644 packages/docs-infra/src/NativeCodeSource/NativeCodeSource.browser.tsx create mode 100644 packages/docs-infra/src/NativeCodeSource/NativeCodeSource.tsx create mode 100644 packages/docs-infra/src/NativeCodeSource/deferredSource.test.tsx create mode 100644 packages/docs-infra/src/NativeCodeSource/index.ts diff --git a/docs/app/docs-infra/components/code-highlighter/types.md b/docs/app/docs-infra/components/code-highlighter/types.md index c08c75de14..edaeffa1cf 100644 --- a/docs/app/docs-infra/components/code-highlighter/types.md +++ b/docs/app/docs-infra/components/code-highlighter/types.md @@ -241,9 +241,10 @@ so this hook simply passes props through. **useCodeFallback Parameters:** -| Parameter | Type | Default | Description | -| :-------- | :--------------------- | :------ | :---------- | -| props | `UseCodeFallbackProps` | - | - | +| Parameter | Type | Default | Description | +| :-------- | :------------------------------------------------------------------------------- | :------ | :---------- | +| props | `UseCodeFallbackProps` | - | - | +| options | `{ SourceComponent?: React.ComponentType; expanded?: boolean }` | - | - | **useCodeFallback Return Value:** @@ -269,6 +270,8 @@ type ReturnValue = UseContentFrameResult; ```typescript type UseCodeFallbackResult = { + /** Selected source using the same renderer and key as the live view. */ + selectedFile?: ReactElement; source?: HastRoot; fileNames?: string[]; extraSource?: Record; @@ -322,6 +325,8 @@ type UseContentFrameResult = { ```typescript type BaseContentLoadingProps = { + /** Contiguous editable text of the initially displayed collapsed file. */ + sourceWindow?: SourceWindow; fileNames?: string[]; source?: FallbackNode[]; /** Loading metadata for the main `source` file. See [`ContentLoadingFile`](#contentloadingfile). */ @@ -923,6 +928,7 @@ type ContentFrameProps = ContentLoadingVariant & fallbackCollapsed?: boolean; collapseToEmpty?: boolean; initialExpanded?: boolean; + initialDisabled?: boolean; } & { children: React.ReactNode }; ``` @@ -957,6 +963,7 @@ type ContentLoadingProps = ContentLoadingVariant & fallbackCollapsed?: boolean; collapseToEmpty?: boolean; initialExpanded?: boolean; + initialDisabled?: boolean; }; ``` @@ -964,6 +971,8 @@ type ContentLoadingProps = ContentLoadingVariant & ```typescript type ContentLoadingVariant = { + /** Contiguous editable text of the initially displayed collapsed file. */ + sourceWindow?: SourceWindow; fileNames?: string[]; source?: FallbackNode[]; /** Loading metadata for the main `source` file. See [`ContentLoadingFile`](#contentloadingfile). */ @@ -1328,6 +1337,8 @@ type VariantCode = { source?: VariantSource; /** Contiguous source shown by the collapsed editor. */ sourceProjection?: EditableSourceProjection; + /** Editable window supplied by a deferred precompute shell. */ + sourceWindow?: SourceWindow; /** * Compact fallback (highlighting spans removed) for the main source. * Converted from HAST via `hastToFallback` for smaller RSC payloads. diff --git a/docs/app/docs-infra/components/page.mdx b/docs/app/docs-infra/components/page.mdx index 45b9788a01..5e7854d723 100644 --- a/docs/app/docs-infra/components/page.mdx +++ b/docs/app/docs-infra/components/page.mdx @@ -70,7 +70,7 @@ It supports both static code blocks and interactive demos with component preview - TransformSource - Parameters: source, fileName, comments - useCodeFallback - - Parameters: props + - Parameters: props, options - useContentFrame - Types: UseCodeFallbackResult, UseContentFrameResult diff --git a/docs/app/docs-infra/hooks/page.mdx b/docs/app/docs-infra/hooks/page.mdx index d52188fc95..0cabba5712 100644 --- a/docs/app/docs-infra/hooks/page.mdx +++ b/docs/app/docs-infra/hooks/page.mdx @@ -36,7 +36,7 @@ The `useCode` hook provides programmatic access to code display, editing, and tr - Editing behavior - Collapsed and expanded editing - Editor interaction - - Preparing an editor + - Render a native input on the server - Selected file metadata - Source actions - Controlled transforms diff --git a/docs/app/docs-infra/hooks/use-code/page.mdx b/docs/app/docs-infra/hooks/use-code/page.mdx index a23be83cc3..9e1d999065 100644 --- a/docs/app/docs-infra/hooks/use-code/page.mdx +++ b/docs/app/docs-infra/hooks/use-code/page.mdx @@ -45,20 +45,26 @@ Starting to edit a live demo switches it to the live preview immediately, even b first change. It stays on the live preview until the demo unmounts; resetting the source does not switch back to the bundled component. -### Preparing an editor +### Render a native input on the server -With `editActivation="interaction"`, call `prepareEditor()` from `useCode` or `useDemo` -to initialize the selected editor and its editing runtime before a click: +Pass `{ SourceComponent: NativeCodeSource }` to both `useCodeFallback` and +`useCode` or `useDemo`. Render the returned element in the same slot of a +persistent content frame. ```tsx -const code = useCode(props); -return ; +import { useCodeFallback } from '@mui/internal-docs-infra/CodeHighlighter'; +import { NativeCodeSource } from '@mui/internal-docs-infra/NativeCodeSource'; + +function SourceSlot({ loadingProps, live }) { + const loading = useCodeFallback(loadingProps, { SourceComponent: NativeCodeSource }); + return
{live?.selectedFile ?? loading.selectedFile}
; +} ``` -Preparation loads asynchronously without moving focus or changing source. -Repeated calls are safe. Calls while editing is disabled do nothing. -The host owns visibility checks, idle timing, and cancellation. -`preloadCodeEditor()` only fetches the editor module; it does not initialize an editor. +The loading view provides a read-only textarea with the displayed source. When live +bindings arrive, the same textarea accepts input. Precomputed colors remain visible +until the reader edits the text. Only import the native renderer for hosts that need +an input on first paint. ### Selected file metadata diff --git a/docs/app/docs-infra/hooks/use-code/types.md b/docs/app/docs-infra/hooks/use-code/types.md index 0ea0285690..88c36aaa1e 100644 --- a/docs/app/docs-infra/hooks/use-code/types.md +++ b/docs/app/docs-infra/hooks/use-code/types.md @@ -59,6 +59,8 @@ type CodeComponentsContext = React.Context | undefined>; ```typescript type UseCodeOpts = { + /** Renderer shared with the loading view to preserve the selected source element. */ + SourceComponent?: React.ComponentType; preClassName?: string; copy?: UseCopierOpts; githubUrlPrefix?: string; @@ -180,12 +182,6 @@ type UseCodeResult = { * reader's edits (use `reset` to discard them). */ setEditable?: (editable: boolean) => void; - /** - * Initialize the selected editor and editing runtime without moving focus. - * Loading is asynchronous. Does nothing while editing is disabled. - * The host decides when to call this, for example after visible source is idle. - */ - prepareEditor: () => void; /** * Replace the source of the currently selected file (or `fileName` when * provided) in the controlled code. Internal hooks may pass additional diff --git a/docs/app/docs-infra/hooks/use-demo/types.md b/docs/app/docs-infra/hooks/use-demo/types.md index 78f594e341..d0ae77ac7c 100644 --- a/docs/app/docs-infra/hooks/use-demo/types.md +++ b/docs/app/docs-infra/hooks/use-demo/types.md @@ -254,7 +254,6 @@ type ReturnValue = void; | hasControlledEdits | `boolean` | Whether the surrounding controller currently owns edited source. | | editable | `boolean` | Whether edit mode is currently on. `true` by default; starts `false` when the block opts in via `initialDisabled` — per demo through the `createDemo` `meta`, or across a factory's demos through `createDemoFactory`. While `false` the block renders read-only and the live-editing engine is not even warmed; flip it with `setEditable`. Independent of `editActivation`, which governs _when_ the engine loads once editing is on, and of `disabled`, which turns editing off permanently. | | setEditable | `((editable: boolean) => void) \| undefined` | Turns edit mode on or off. `undefined` when the block can't be edited at all — no `CodeControllerContext` with `setCode` in scope, or editing is hard-`disabled` — so a toggle button can render only when this is defined. Toggling off keeps the reader's edits (use `reset` to discard them). | -| prepareEditor | `(() => void)` | Initialize the selected editor and editing runtime without moving focus. Loading is asynchronous. Does nothing while editing is disabled. The host decides when to call this, for example after visible source is idle. | | setSource | `((source: string, fileName?: string) => void) \| undefined` | Replace the source of the currently selected file (or `fileName` when provided) in the controlled code. Internal hooks may pass additional arguments (caret position, pre-parsed HAST) that are not part of the public contract. | | reset | `(() => void) \| undefined` | Clears the entire controlled code state back to `undefined`, discarding user edits across **all variants and files** owned by the surrounding `CodeControllerContext` (not just the currently selected file or variant). Only available when a `CodeControllerContext` with `setCode` is in scope and editing is not disabled. | | refresh | `(() => void) \| undefined` | Re-fetches the block's data on the client by re-running the full variant loader, then swaps in the fresh result while keeping the current highlighted output visible until the new tree lands (stale-while-revalidate). Invalidates the pre-parsed HAST cache. `undefined` (or a no-op) for a block with no `url` to re-fetch from, or with no `CodeProvider` in scope. | @@ -435,6 +434,8 @@ createCodeSandboxDemo({ title, description, flattenedFiles, useTypescript }) ```typescript type UseDemoOpts = { + /** Renderer shared with the loading view to preserve the selected source element. */ + SourceComponent?: React.ComponentType; preClassName?: string; copy?: UseCopierOpts; githubUrlPrefix?: string; diff --git a/packages/docs-infra/package.json b/packages/docs-infra/package.json index 0c948e54d0..41eca9247a 100644 --- a/packages/docs-infra/package.json +++ b/packages/docs-infra/package.json @@ -21,6 +21,7 @@ "./CodeHighlighter/types": "./src/CodeHighlighter/types.ts", "./CodeHighlighter/errors": "./src/CodeHighlighter/errors.ts", "./CodeProvider": "./src/CodeProvider/index.ts", + "./NativeCodeSource": "./src/NativeCodeSource/index.ts", "./CoordinatedLazy": "./src/CoordinatedLazy/index.ts", "./CoordinatedLazy/types": "./src/CoordinatedLazy/types.ts", "./createDemoData": "./src/createDemoData/index.ts", diff --git a/packages/docs-infra/src/CodeHighlighter/prepareInitialSource.tsx b/packages/docs-infra/src/CodeHighlighter/prepareInitialSource.tsx index 8d5692450e..491b7c90aa 100644 --- a/packages/docs-infra/src/CodeHighlighter/prepareInitialSource.tsx +++ b/packages/docs-infra/src/CodeHighlighter/prepareInitialSource.tsx @@ -78,7 +78,7 @@ export function prepareInitialSource( } = props; const contentPropsFlags = props.contentProps as - { collapseToEmpty?: boolean; initialExpanded?: boolean } | undefined; + { collapseToEmpty?: boolean; initialExpanded?: boolean; initialDisabled?: boolean } | undefined; const collapseToEmpty = props.collapseToEmpty !== undefined ? props.collapseToEmpty @@ -87,6 +87,8 @@ export function prepareInitialSource( props.initialExpanded !== undefined ? props.initialExpanded : contentPropsFlags?.initialExpanded; + + const initialDisabled = props.initialDisabled ?? contentPropsFlags?.initialDisabled; const collapseToEmptyEnabled = collapseToEmpty === true; const initialExpandedEnabled = initialExpanded === true; @@ -331,6 +333,24 @@ export function prepareInitialSource( // Only include components (plural) if we're also including extraVariants const components = fallbackProps.extraVariants ? props.components : undefined; + const selected = code?.[initialVariant]; + + const file = + selected && + typeof selected === 'object' && + (!initialFilename || selected.fileName === initialFilename) + ? selected + : undefined; + + const projection = file?.sourceProjection; + + const sourceWindow = + file?.sourceWindow ?? + (projection && { + source: projection.source, + indentation: projection.indentation, + }); + const contentProps = { ...props.contentProps, ...fallbackProps, @@ -351,8 +371,19 @@ export function prepareInitialSource( // Render-time default-expanded: the loading placeholder can render expanded // so it doesn't flash collapsed before hydration. ...(initialExpanded !== undefined ? { initialExpanded } : undefined), + ...(initialDisabled !== undefined ? { initialDisabled } : undefined), } as ContentLoadingProps; + if ( + sourceWindow && + !initialDisabled && + fallbackProps.focusedLines !== 0 && + !collapseToEmptyEnabled && + !initialExpandedEnabled + ) { + contentProps.sourceWindow = sourceWindow; + } + const fallback = ; return { fallback, residualFallbacks, codeForClient }; diff --git a/packages/docs-infra/src/CodeHighlighter/types.ts b/packages/docs-infra/src/CodeHighlighter/types.ts index 1e4af2360a..59bff61b57 100644 --- a/packages/docs-infra/src/CodeHighlighter/types.ts +++ b/packages/docs-infra/src/CodeHighlighter/types.ts @@ -54,6 +54,10 @@ export interface EditableSourceProjection { indentation?: string; } +type SourceWindow = + | Pick + | { length: number; indentation?: string }; + export type Transforms = Record< string, { @@ -160,6 +164,8 @@ export type VariantCode = CodeMeta & { source?: VariantSource; /** Contiguous source shown by the collapsed editor. */ sourceProjection?: EditableSourceProjection; + /** Editable window supplied by a deferred precompute shell. */ + sourceWindow?: SourceWindow; /** * Compact fallback (highlighting spans removed) for the main source. * Converted from HAST via `hastToFallback` for smaller RSC payloads. @@ -313,6 +319,8 @@ export type ContentLoadingFile = { }; export type ContentLoadingVariant = { + /** Contiguous editable text of the initially displayed collapsed file. */ + sourceWindow?: SourceWindow; fileNames?: string[]; source?: FallbackNode[]; /** Loading metadata for the main `source` file. See {@link ContentLoadingFile}. */ @@ -366,6 +374,8 @@ export type ContentLoadingProps = BaseContentLoadingProps & * block will start expanded. */ initialExpanded?: boolean; + /** Whether editing starts disabled in the live view. */ + initialDisabled?: boolean; // `totalLines` / `focusedLines` for the displayed (main) file are inherited from // `ContentLoadingVariant`; extra files carry theirs in `extraSource[file]`, and // each `extraVariants` entry carries its own set. A `ContentLoading` mirrors them diff --git a/packages/docs-infra/src/CodeHighlighter/useCodeFallback.tsx b/packages/docs-infra/src/CodeHighlighter/useCodeFallback.tsx index af1551d6ef..f4dc226bce 100644 --- a/packages/docs-infra/src/CodeHighlighter/useCodeFallback.tsx +++ b/packages/docs-infra/src/CodeHighlighter/useCodeFallback.tsx @@ -1,8 +1,9 @@ 'use client'; import * as React from 'react'; +import type { CodeSourceProps } from '../useCode/Pre'; import type { ContentLoadingVariant, Fallbacks, HastRoot } from './types'; -import { fallbackToHast } from './fallbackFormat'; +import { collapsedVisibleFallback, fallbackToHast, fallbackToText } from './fallbackFormat'; import { restoreFallbackLines } from './renderFallbackLines'; import { resolveCollapsedFrameType } from '../pipeline/parseSource/frameVisibility'; import { isFrameSpan } from '../pipeline/parseSource/isFrameSpan'; @@ -47,6 +48,8 @@ export interface UseCodeFallbackFile { } export interface UseCodeFallbackResult { + /** Selected source using the same renderer and key as the live view. */ + selectedFile?: React.ReactElement; source?: HastRoot; fileNames?: string[]; extraSource?: Record; @@ -98,6 +101,8 @@ export interface UseCodeFallbackVariantResult { interface UseCodeFallbackProps extends ContentLoadingVariant { initialVariant?: string; initialFilename?: string; + initialExpanded?: boolean; + initialDisabled?: boolean; extraVariants?: Record; fallbackCollapsed?: boolean; collapseToEmpty?: boolean; @@ -166,7 +171,10 @@ function convertVariantSource( * } * ``` */ -export function useCodeFallback(props?: UseCodeFallbackProps): UseCodeFallbackResult { +export function useCodeFallback( + props?: UseCodeFallbackProps, + options?: { SourceComponent?: React.ComponentType; expanded?: boolean }, +): UseCodeFallbackResult { const ctx = React.useContext(CodeHighlighterFallbackContext); const { setFallbackHasts, onHookCalled, canLoadContent } = ctx || {}; const variantName = props?.initialVariant; @@ -294,12 +302,57 @@ export function useCodeFallback(props?: UseCodeFallbackProps): UseCodeFallbackRe [converted, language, fileNames], ); + const Source = options?.SourceComponent; + const sourceWindow = props?.sourceWindow; + + const projection = React.useMemo(() => { + if (!Source || !sourceWindow || !source || props?.initialDisabled) { + return undefined; + } + + const text = + 'source' in sourceWindow + ? sourceWindow.source + : fallbackToText(collapsedVisibleFallback(source)).slice(0, sourceWindow.length); + + return { source: text, indentation: sourceWindow.indentation, start: 0, end: text.length }; + }, [Source, sourceWindow, source, props?.initialDisabled]); + if (!props) { return {}; } + let selectedFile: React.ReactElement | undefined; + + if (Source && converted.source) { + selectedFile = ( + + {converted.source} + + ); + } + return { ...converted, + selectedFile, extraVariants: resolvedExtraVariants, collapsed: props.fallbackCollapsed, code, diff --git a/packages/docs-infra/src/CodeProvider/CodeContext.tsx b/packages/docs-infra/src/CodeProvider/CodeContext.tsx index 23f59702ec..ea2391efab 100644 --- a/packages/docs-infra/src/CodeProvider/CodeContext.tsx +++ b/packages/docs-infra/src/CodeProvider/CodeContext.tsx @@ -98,7 +98,7 @@ export interface CodeContext { * up the worker. Called by `CodeHighlighter` on the editable signal with the * block's scopes. No-op during SSR or where `Worker` is unavailable. */ - ensureParseSourceWorker?: (scopes: string[]) => Promise; + ensureParseSourceWorker?: (scopes: string[]) => Promise; // Lazy accessors for the heaviest functions (dynamic-import-backed, deduped). /** Lazily loads the fallback-code loader (transitively pulls the variant loader). */ diff --git a/packages/docs-infra/src/CodeProvider/useCodeProviderValue.ts b/packages/docs-infra/src/CodeProvider/useCodeProviderValue.ts index 4e27720791..c0f39f3aae 100644 --- a/packages/docs-infra/src/CodeProvider/useCodeProviderValue.ts +++ b/packages/docs-infra/src/CodeProvider/useCodeProviderValue.ts @@ -142,7 +142,7 @@ export function useCodeProviderValue( } const needed = scopes.filter((scope) => !workerSentScopesRef.current.has(scope)); if (needed.length === 0) { - return workerChainRef.current; + return workerChainRef.current.then(() => workerRef.current?.parseSourceAsync); } // Optimistically mark as sent; the serialized chain below does the actual // send in order. Rolled back if the load/init/register fails. @@ -213,7 +213,8 @@ export function useCodeProviderValue( } setParseSourceAsync(() => client.parseSourceAsync); }); - return workerChainRef.current; + + return workerChainRef.current.then(() => workerRef.current?.parseSourceAsync); }, []); React.useEffect(() => { diff --git a/packages/docs-infra/src/NativeCodeSource/NativeCodeSource.browser.tsx b/packages/docs-infra/src/NativeCodeSource/NativeCodeSource.browser.tsx new file mode 100644 index 0000000000..91474e2002 --- /dev/null +++ b/packages/docs-infra/src/NativeCodeSource/NativeCodeSource.browser.tsx @@ -0,0 +1,216 @@ +import * as React from 'react'; +import * as ReactDOMServer from 'react-dom/server'; +import { cleanup, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, describe, expect, it } from 'vitest'; +import { cdp, server, userEvent } from 'vitest/browser'; +import type { CDPSession } from '@vitest/browser-playwright'; +import { useCodeFallback } from '../CodeHighlighter/useCodeFallback'; +import { fallbackToHast } from '../CodeHighlighter/fallbackFormat'; +import type { FallbackNode } from '../CodeHighlighter/fallbackFormat'; +import { CodeProviderLazy } from '../CodeProvider/CodeProviderLazy'; +import { useCode } from '../useCode'; +import { NativeCodeSource } from './index'; +import type { CodeSourceProps } from './index'; + +const FILE = 'example.tsx'; +const FOCUSED = ' return 1;'; +const BEFORE = 'function example(): number {\n'; +const AFTER = '\n}'; +const INITIAL = BEFORE + FOCUSED + AFTER; +const WINDOW = { source: FOCUSED, indentation: ' ' }; + +const FALLBACK: FallbackNode[] = [ + ['span', 'frame', BEFORE], + [ + 'span', + 'frame', + { dataFrameType: 'focus', dataFrameIndent: 1 }, + [' ', ['span', 'pl-k', 'return'], ' 1;\n'], + ], + ['span', 'frame', '}'], +]; + +const HAST = fallbackToHast(FALLBACK); +const CONTENT = { code: { Default: { fileName: FILE, source: HAST } } }; + +function FileInput({ fileName }: CodeSourceProps) { + return