Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions docs/app/docs-infra/components/code-highlighter/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<CodeSourceProps>; expanded?: boolean }` | - | - |

**useCodeFallback Return Value:**

Expand All @@ -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<string, UseCodeFallbackFile>;
Expand Down Expand Up @@ -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). */
Expand Down Expand Up @@ -923,6 +928,7 @@ type ContentFrameProps<T extends {}> = ContentLoadingVariant &
fallbackCollapsed?: boolean;
collapseToEmpty?: boolean;
initialExpanded?: boolean;
initialDisabled?: boolean;
} & { children: React.ReactNode };
```

Expand Down Expand Up @@ -957,13 +963,16 @@ type ContentLoadingProps<T extends {}> = ContentLoadingVariant &
fallbackCollapsed?: boolean;
collapseToEmpty?: boolean;
initialExpanded?: boolean;
initialDisabled?: boolean;
};
```

### 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). */
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/app/docs-infra/components/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions docs/app/docs-infra/hooks/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions docs/app/docs-infra/hooks/use-code/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <section>{live?.selectedFile ?? loading.selectedFile}</section>;
}
```

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
Expand Down
2 changes: 2 additions & 0 deletions docs/app/docs-infra/hooks/use-code/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ type CodeComponentsContext = React.Context<Partial<Components> | undefined>;

```typescript
type UseCodeOpts = {
/** Renderer shared with the loading view to preserve the selected source element. */
SourceComponent?: React.ComponentType<CodeSourceProps>;
preClassName?: string;
copy?: UseCopierOpts;
githubUrlPrefix?: string;
Expand Down
2 changes: 2 additions & 0 deletions docs/app/docs-infra/hooks/use-demo/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<CodeSourceProps>;
preClassName?: string;
copy?: UseCopierOpts;
githubUrlPrefix?: string;
Expand Down
1 change: 1 addition & 0 deletions packages/docs-infra/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
33 changes: 32 additions & 1 deletion packages/docs-infra/src/CodeHighlighter/prepareInitialSource.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export function prepareInitialSource<T extends {}>(
} = 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
Expand All @@ -87,6 +87,8 @@ export function prepareInitialSource<T extends {}>(
props.initialExpanded !== undefined
? props.initialExpanded
: contentPropsFlags?.initialExpanded;

const initialDisabled = props.initialDisabled ?? contentPropsFlags?.initialDisabled;
const collapseToEmptyEnabled = collapseToEmpty === true;
const initialExpandedEnabled = initialExpanded === true;

Expand Down Expand Up @@ -331,6 +333,24 @@ export function prepareInitialSource<T extends {}>(
// 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,
Expand All @@ -351,8 +371,19 @@ export function prepareInitialSource<T extends {}>(
// 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<T>;

if (
sourceWindow &&
!initialDisabled &&
fallbackProps.focusedLines !== 0 &&
!collapseToEmptyEnabled &&
!initialExpandedEnabled
) {
contentProps.sourceWindow = sourceWindow;
}

const fallback = <ContentLoading {...contentProps} />;

return { fallback, residualFallbacks, codeForClient };
Expand Down
10 changes: 10 additions & 0 deletions packages/docs-infra/src/CodeHighlighter/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ export interface EditableSourceProjection {
indentation?: string;
}

type SourceWindow =
| Pick<EditableSourceProjection, 'source' | 'indentation'>
| { length: number; indentation?: string };

export type Transforms = Record<
string,
{
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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}. */
Expand Down Expand Up @@ -366,6 +374,8 @@ export type ContentLoadingProps<T extends {}> = 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
Expand Down
57 changes: 55 additions & 2 deletions packages/docs-infra/src/CodeHighlighter/useCodeFallback.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<CodeSourceProps>;
source?: HastRoot;
fileNames?: string[];
extraSource?: Record<string, UseCodeFallbackFile>;
Expand Down Expand Up @@ -98,6 +101,8 @@ export interface UseCodeFallbackVariantResult {
interface UseCodeFallbackProps extends ContentLoadingVariant {
initialVariant?: string;
initialFilename?: string;
initialExpanded?: boolean;
initialDisabled?: boolean;
extraVariants?: Record<string, ContentLoadingVariant>;
fallbackCollapsed?: boolean;
collapseToEmpty?: boolean;
Expand Down Expand Up @@ -166,7 +171,10 @@ function convertVariantSource(
* }
* ```
*/
export function useCodeFallback(props?: UseCodeFallbackProps): UseCodeFallbackResult {
export function useCodeFallback(
props?: UseCodeFallbackProps,
options?: { SourceComponent?: React.ComponentType<CodeSourceProps>; expanded?: boolean },
): UseCodeFallbackResult {
const ctx = React.useContext(CodeHighlighterFallbackContext);
const { setFallbackHasts, onHookCalled, canLoadContent } = ctx || {};
const variantName = props?.initialVariant;
Expand Down Expand Up @@ -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<CodeSourceProps> | undefined;

if (Source && converted.source) {
selectedFile = (
<Source
key={mainFile}
fileName={mainFile}
language={language}
expanded={options?.expanded ?? props.initialExpanded}
loading
editable={!props.initialDisabled}
shouldHighlight
fallbackLineCounts={
totalLines === undefined
? undefined
: {
totalLines,
focusedLines: focusedLines ?? totalLines,
collapsible: collapsible ?? false,
}
}
sourceProjection={projection}
>
{converted.source}
</Source>
);
}

return {
...converted,
selectedFile,
extraVariants: resolvedExtraVariants,
collapsed: props.fallbackCollapsed,
code,
Expand Down
2 changes: 1 addition & 1 deletion packages/docs-infra/src/CodeProvider/CodeContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>;
ensureParseSourceWorker?: (scopes: string[]) => Promise<ParseSourceAsync | void>;

// Lazy accessors for the heaviest functions (dynamic-import-backed, deduped).
/** Lazily loads the fallback-code loader (transitively pulls the variant loader). */
Expand Down
5 changes: 3 additions & 2 deletions packages/docs-infra/src/CodeProvider/useCodeProviderValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -213,7 +213,8 @@ export function useCodeProviderValue(
}
setParseSourceAsync(() => client.parseSourceAsync);
});
return workerChainRef.current;

return workerChainRef.current.then(() => workerRef.current?.parseSourceAsync);
}, []);

React.useEffect(() => {
Expand Down
Loading
Loading