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 6216fcc7d9..0cabba5712 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 + - 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 994f560902..9e1d999065 100644 --- a/docs/app/docs-infra/hooks/use-code/page.mdx +++ b/docs/app/docs-infra/hooks/use-code/page.mdx @@ -45,6 +45,27 @@ 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. +### Render a native input on the server + +Pass `{ SourceComponent: NativeCodeSource }` to both `useCodeFallback` and +`useCode` or `useDemo`. Render the returned element in the same slot of a +persistent content frame. + +```tsx +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}
; +} +``` + +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 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..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; diff --git a/docs/app/docs-infra/hooks/use-demo/types.md b/docs/app/docs-infra/hooks/use-demo/types.md index ae2c527658..d0ae77ac7c 100644 --- a/docs/app/docs-infra/hooks/use-demo/types.md +++ b/docs/app/docs-infra/hooks/use-demo/types.md @@ -434,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