Warning
This is an internal project, and is not intended for public use. No support or stability guarantees are provided.
The enhanceCodeEmphasis source enhancer adds visual emphasis to specific lines in code examples by marking them with a data-hl attribute. This allows you to highlight important code patterns or call attention to specific sections in demos using simple comment annotations.
@highlight comments@highlight-start / @highlight-end pairs@highlight-text "text"@highlight "description")! at the end of descriptions (e.g., @highlight "We must do this!")import { enhanceCodeEmphasis } from '@mui/internal-docs-infra/pipeline/enhanceCodeEmphasis';
// Use as a source enhancer
const sourceEnhancers = [enhanceCodeEmphasis];
// Pass to CodeHighlighter or use with enhanceCode
The enhancer processes @highlight comments in your source files and adds data-hl to the corresponding line elements in the HAST tree.
Emphasize the line containing the comment:
export default function Button() {
return (
<button className="primary">Click me</button> {/* @highlight */}
);
}
The line with the <button> element will be emphasized.
Add context about what's being emphasized:
export default function Component() {
const [count, setCount] = useState(0); // @highlight "We track state"
return <div>{count}</div>;
}
End a description with ! to mark it as strong emphasis (data-hl="strong"):
export default function Component() {
const apiKey = process.env.API_KEY; // @highlight "We must provide the API key!"
return <div>...</div>;
}
Strong emphasis is useful for highlighting critical code that users must pay attention to or modify.
Emphasize a range of lines between start and end markers:
export default function Component() {
return (
// @highlight-start
<div>
<h1>Heading 1</h1>
<p>Some content</p>
</div>
// @highlight-end
);
}
Lines 4-7 (from <div> through </div>) will be emphasized. The range starts at the first line after @highlight-start and ends at the last line before @highlight-end.
Explain what the emphasized section demonstrates:
export default function Component() {
return (
// @highlight-start "We add a heading with an h1"
<div>
<h1>Heading 1</h1>
</div>
// @highlight-end
);
}
Highlight specific text within a line:
export default function Component() {
return (
<div>
<h1>Heading 1</h1> {/* @highlight-text "Heading 1" */}
</div>
);
}
This wraps the specified text in a <mark> element, allowing you to highlight a specific word or phrase within a line rather than the entire line.
Highlight multiple texts within a single line by providing multiple quoted strings:
export default function Component() {
return (
<div>
<h1 className="primary">Heading 1</h1> {/* @highlight-text "primary" "Heading 1" */}
</div>
);
}
Each quoted text is independently wrapped in a <mark> element.
Configure in your webpack loader or server-side loading:
import { enhanceCodeEmphasis } from '@mui/internal-docs-infra/pipeline/enhanceCodeEmphasis';
import { createLoadServerSource } from '@mui/internal-docs-infra/pipeline/loadServerSource';
import { loadCodeVariant } from '@mui/internal-docs-infra/pipeline/loadCodeVariant';
const sourceEnhancers = [enhanceCodeEmphasis];
For configurable padding, use the factory:
import { createEnhanceCodeEmphasis } from '@mui/internal-docs-infra/pipeline/enhanceCodeEmphasis';
const sourceEnhancers = [
createEnhanceCodeEmphasis({
paddingFrameMaxSize: 3,
focusFramesMaxSize: 10,
}),
];
Then pass to your loading pipeline:
// Create a loadSource that extracts emphasis and focus comments
const loadSource = createLoadServerSource({
notableCommentsPrefix: ['@highlight', '@focus'],
removeCommentsWithPrefix: ['@highlight', '@focus'],
});
// Use with loadCodeVariant
const { code } = await loadCodeVariant(url, variantName, variant, {
loadSource,
sourceEnhancers,
sourceParser,
});
// Or with CodeHighlighter
<CodeHighlighter
sourceEnhancers={sourceEnhancers}
// ... other props
/>
// Or with useCode
const { selectedFile } = useCode(props, {
sourceEnhancers,
});
The default comment prefixes are @highlight and @focus, exported as EMPHASIS_COMMENT_PREFIX and FOCUS_COMMENT_PREFIX:
import {
EMPHASIS_COMMENT_PREFIX,
FOCUS_COMMENT_PREFIX,
} from '@mui/internal-docs-infra/pipeline/enhanceCodeEmphasis';
console.log(EMPHASIS_COMMENT_PREFIX); // '@highlight'
console.log(FOCUS_COMMENT_PREFIX); // '@focus'
The enhancer recognizes these comment patterns:
| Pattern | Effect |
|---|---|
@highlight | Emphasize current line |
@highlight "description" | Emphasize with description |
@highlight-start | Start multi-line block |
@highlight-start "desc" | Start block with description |
@highlight-end | End multi-line block |
@highlight-text "text" | Highlight specific text within the line |
@highlight-text "one" "two" | Highlight multiple texts within the line |
@focus | Focus current line (no line highlight) |
@focus-start | Start focused block (no line highlight) |
@focus-end | End focused block |
@highlight @padding 2 | Highlight line with per-directive padding override |
@highlight-start @padding 2 | Highlight block with per-directive padding override |
@focus @padding 2 | Focus line with per-directive padding override |
@focus-start @padding 2 | Focus block with per-directive padding override |
@highlight @min 6 | Highlight line with per-directive focus max override |
@highlight-start @min 6 | Highlight block with per-directive focus max override |
@focus @min 6 | Focus line with per-directive focus max override |
@focus-start @min 6 | Focus block with per-directive focus max override |
Descriptions are provided as quoted strings:
// @highlight "We initialize the state"
const [value, setValue] = useState(0);
// @highlight-start "We render the component"
<div>
<p>Content</p>
</div>;
// @highlight-end
By default, @highlight comments are stripped from the rendered code. To show the comment syntax in documentation (while still applying the emphasis), use the displayComments code block attribute:
```jsx displayComments
export default function Button() {
return (
<button className="primary">Click me</button> {/* @highlight */}
);
}
```
This is useful for documentation pages where you want to show users the comment syntax itself.
You can emphasize multiple individual lines:
export default function Form() {
const [name, setName] = useState(''); // @highlight
const [email, setEmail] = useState(''); // @highlight
return (
<form>
<input value={name} onChange={(e) => setName(e.target.value)} />
<input value={email} onChange={(e) => setEmail(e.target.value)} /> {/* @highlight */}
</form>
);
}
The enhancer handles nested emphasis blocks using a stack-based algorithm. Lines that fall within multiple emphasis ranges are automatically marked with strong emphasis (data-hl="strong"):
export default function Component() {
return (
// @highlight-start "outer block"
<div>
<header>Title</header>
{/* @highlight-start "inner block" */}
<main>
<p>Content</p>
</main>
{/* @highlight-end */}
<footer>Footer</footer>
</div>
// @highlight-end
);
}
In this example:
<div>, <header>, <footer>, </div>) get normal emphasis<main>, <p>, </main>) get strong emphasis because they're nested within both rangesdata-hl-position) are preserved from the innermost rangeCombine both patterns in the same file:
export default function Dashboard() {
const [data, setData] = useState([]); // @highlight
return (
<div>
<Header />
{/* @highlight-start */}
<Chart data={data} />
<Table data={data} />
{/* @highlight-end */}
<Footer /> {/* @highlight */}
</div>
);
}
When any emphasis is present, the enhancer splits the code block's frame structure around highlighted lines. Each original frame is broken into typed sub-frames that CSS can target for collapsing, animating, or scrolling to the focused area.
Given a 7-line code block where line 4 is highlighted, the frames are restructured:
| Frame # | Lines | data-frame-type |
|---|---|---|
| 1 | 1–3 | (none) |
| 2 | 4 | highlighted |
| 3 | 5–7 | (none) |
When padding is configured (see Configurable Padding), additional typed frames surround the focused highlight region:
| Frame # | Lines | data-frame-type |
|---|---|---|
| 1 | 1 | (none) |
| 2 | 2–3 | padding-top |
| 3 | 4 | highlighted |
| 4 | 5–6 | padding-bottom |
| 5 | 7 | (none) |
| Attribute | Type | Description |
|---|---|---|
data-frame-type | string | "highlighted" (focused region with line highlights), "highlighted-unfocused" (non-focused regions with line highlights), "focus" (focused region without line highlights), "focus-unfocused" (non-focused region without line highlights), "padding-top", or "padding-bottom". Normal frames have no type attribute. |
data-frame-indent | number | Only on highlighted, highlighted-unfocused, focus, and focus-unfocused frames. The shared indent level of the highlighted lines (min leading spaces ÷ 2). |
data-frame-description | string | Present on highlighted frames when the @highlight or @highlight-start directive includes a description (e.g., @highlight "description"). Not set when highlighting is at the line level (inside a focus region or when strong). |
Use createEnhanceCodeEmphasis to configure padding frames around the focused highlight region:
import { createEnhanceCodeEmphasis } from '@mui/internal-docs-infra/pipeline/enhanceCodeEmphasis';
const sourceEnhancers = [
createEnhanceCodeEmphasis({
paddingFrameMaxSize: 3,
focusFramesMaxSize: 10,
}),
];
| Option | Type | Default | Description |
|---|---|---|---|
paddingFrameMaxSize | number | 0 | Maximum number of context lines above/below the focused region |
focusFramesMaxSize | number | — | Maximum total lines in the focus area (padding + region). When the region fits, remaining budget is split floor/ceil between padding-top and padding-bottom. When the region exceeds this limit, a focused window is taken from the start of the region, and the remaining overflow lines are marked as unfocused. |
strictHighlightText | boolean | false | When true, throws an error if a @highlight-text match has to be fragmented across element boundaries (producing data-hl-part spans). Highlights that wrap multiple complete elements in a single data-hl span are still allowed. |
When paddingFrameMaxSize is 0 (the default), no padding frames are created and only region frames (highlighted, focus, etc.) and normal frames are produced.
@padding NUse @padding N directly on emphasis directives to override padding for that region:
const important = loadData(); // @highlight @padding 1
// @highlight-start @focus @padding 4 "Primary preview area"
<Panel>
<Widget />
</Panel>;
// @highlight-end
In this example, the focused block uses padding 4 while the single highlighted line uses padding 1.
Padding precedence is:
@padding N on the focused regioncreateEnhanceCodeEmphasis({ paddingFrameMaxSize })@min NUse @min N on emphasis directives to override focusFramesMaxSize for the focused region:
// @highlight-start @focus @min 6
<form>
<Field name="firstName" />
<Field name="lastName" />
<Field name="email" />
<Field name="company" />
<Field name="role" />
<Field name="location" />
<Field name="timezone" />
</form>
// @highlight-end
In this example, the focused region is constrained to a visible window of 6 lines when collapsed, regardless of the global focusFramesMaxSize option.
Focus max size precedence is:
@min N on the focused regioncreateEnhanceCodeEmphasis({ focusFramesMaxSize })@focus DirectiveWhen multiple highlight regions exist, padding is added around the first region by default. Add @focus to override which region receives padding:
const theme = getTheme(); // @highlight
const config = getConfig();
// @highlight-start @focus
<ThemeProvider theme={theme}>
<App config={config} /> {/* @highlight-text "config" */}
</ThemeProvider>;
// @highlight-end
In this example, @focus directs the padding frames to surround the ThemeProvider block instead of the theme line.
@focus can be combined with any highlight directive:
// @highlight @focus// @highlight-start @focus// @highlight-start @focus "We render the provider"@focus (Focus Without Highlight)Use @focus, @focus-start, and @focus-end to mark a region as focused without adding line-level highlighting (data-hl). Lines in a standalone @focus region will be part of a focused frame but won't have visual emphasis on individual lines:
const theme = getTheme(); // @highlight
const config = getConfig();
// @focus-start
<ThemeProvider theme={theme}>
<App config={config} />
</ThemeProvider>;
// @focus-end
In this example, the ThemeProvider block is focused (padding frames surround it), but only the theme line has line-level highlighting.
This is particularly useful when an ESLint rule like lintJavascriptDemoFocus auto-inserts focus markers — the auto-generated @focus-start/@focus-end marks the preview area without adding highlight styling, leaving @highlight for manual use.
Target frame types with CSS to style highlighted frames and create collapsible code blocks:
/* Highlighted frames get rounded corners and background */
.codeBlock .frame[data-frame-type='highlighted'],
.codeBlock .frame[data-frame-type='highlighted-unfocused'] {
background: #ebe4ff;
border-radius: 8px;
margin: 0 6px;
padding: 0 6px;
}
/* Normal frames and unfocused highlighted/focus frames are hidden by default (collapsed) */
.codeBlock .frame:not([data-frame-type]),
.codeBlock .frame[data-frame-type='highlighted-unfocused'],
.codeBlock .frame[data-frame-type='focus-unfocused'] {
max-height: 0;
overflow: hidden;
opacity: 0;
transition:
max-height 0.3s cubic-bezier(0.5, 0, 0, 1),
opacity 0.2s ease 0.1s;
}
/* When supported, use interpolate-size for smoother height animation */
@supports (interpolate-size: allow-keywords) {
.codeBlock .frame:not([data-frame-type]),
.codeBlock .frame[data-frame-type='highlighted-unfocused'],
.codeBlock .frame[data-frame-type='focus-unfocused'] {
interpolate-size: allow-keywords;
max-height: unset;
height: 0;
overflow: clip;
transition:
height 0.3s ease,
opacity 0.3s ease;
}
}
/* Padding frames appear dimmed when collapsed */
.codeBlock .frame[data-frame-type='padding-top'],
.codeBlock .frame[data-frame-type='padding-bottom'] {
opacity: 0.5;
transition: opacity 0.3s ease;
}
/* When expanded, show all frames */
/* max-height = line height (18.5px) × max frame size (120 lines) = 2220px */
.expanded .codeBlock .frame:not([data-frame-type]),
.expanded .codeBlock .frame[data-frame-type='highlighted-unfocused'],
.expanded .codeBlock .frame[data-frame-type='focus-unfocused'] {
max-height: 2220px;
opacity: 1;
transition:
max-height 1.5s cubic-bezier(0.25, 0.46, 0.45, 0.94),
opacity 0.15s ease;
}
@supports (interpolate-size: allow-keywords) {
.expanded .codeBlock .frame:not([data-frame-type]),
.expanded .codeBlock .frame[data-frame-type='highlighted-unfocused'],
.expanded .codeBlock .frame[data-frame-type='focus-unfocused'] {
max-height: unset;
height: auto;
overflow: clip;
transition:
height 0.3s ease,
opacity 0.3s ease;
}
}
.expanded .codeBlock .frame[data-frame-type='padding-top'],
.expanded .codeBlock .frame[data-frame-type='padding-bottom'] {
opacity: 1;
}
/* Use indent level to shift highlighted/focus frames left when collapsed */
.codeBlock .frame[data-frame-type='highlighted'],
.codeBlock .frame[data-frame-type='focus'] {
transition: transform 0.3s ease;
}
.codeBlock .frame[data-frame-type='highlighted'][data-frame-indent='1'],
.codeBlock .frame[data-frame-type='focus'][data-frame-indent='1'] {
transform: translateX(-2ch);
}
.codeBlock .frame[data-frame-type='highlighted'][data-frame-indent='2'],
.codeBlock .frame[data-frame-type='focus'][data-frame-indent='2'] {
transform: translateX(-4ch);
}
/* Reset indent shift when expanded */
.expanded .codeBlock .frame[data-frame-type='highlighted'],
.expanded .codeBlock .frame[data-frame-type='focus'] {
transform: translateX(0);
}
When a code block has both visible frames (highlighted, focus, padding) and hidden frames (normal, unfocused), the <code> element receives a data-collapsible attribute. Use this to conditionally show an expand/collapse toggle — code blocks without collapsible frames won't render the button:
/* Hide toggle by default */
.toggle {
display: none;
}
/* Show only when the code block has collapsible frames */
.pre code:has([data-collapsible]) ~ .toggle {
display: block;
}
The following demo shows a code block that starts collapsed, revealing only the highlighted and padding frames. Click Expand to show the full source.
import * as React from 'react';
import { fetchUser } from './api';
interface User {
name: string;
email: string;
}
export function UserProfile({ id }: { id: string }) {
const [user, setUser] = React.useState<User | null>(null);
React.useEffect(() => {
let cancelled = false;
fetchUser(id).then((data) => {
if (!cancelled) {
setUser(data);
}
});
return () => {
cancelled = true;
};
}, [id]);
if (!user) {
return <p>Loading...</p>;
}
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}import * as React from 'react';
import type { Code as CodeType } from '@mui/internal-docs-infra/CodeHighlighter/types';
import { parseImportsAndComments } from '@mui/internal-docs-infra/pipeline/loaderUtils';
import { EMPHASIS_COMMENT_PREFIX } from '@mui/internal-docs-infra/pipeline/enhanceCodeEmphasis';
import { Code } from './Code';
const source = `import * as React from 'react';
import { fetchUser } from './api';
interface User {
name: string;
email: string;
}
export function UserProfile({ id }: { id: string }) {
const [user, setUser] = React.useState<User | null>(null);
// @highlight-start
React.useEffect(() => {
let cancelled = false;
fetchUser(id).then((data) => {
if (!cancelled) {
setUser(data);
}
});
return () => {
cancelled = true;
};
}, [id]);
// @highlight-end
if (!user) {
return <p>Loading...</p>;
}
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}`;
export async function CollapsibleCode() {
const { code: strippedSource, comments } = await parseImportsAndComments(source, '/demo.tsx', {
removeCommentsWithPrefix: [EMPHASIS_COMMENT_PREFIX],
notableCommentsPrefix: [EMPHASIS_COMMENT_PREFIX],
});
const code: CodeType = {
Default: {
language: 'tsx',
source: strippedSource!,
comments,
},
};
return <Code code={code} />;
}
A full demo component with a live preview, file tabs, and collapsible code. The code section starts collapsed, showing only the focused region.
'use client';
import * as React from 'react';
export function Counter() {
const [count, setCount] = React.useState(0);
return (
<button type="button" onClick={() => setCount((c) => c + 1)}>
Count: {count}
</button>
);
}
This demo uses @highlight on the formatDate call and standalone @focus-start/@focus-end around the useEffect block. The useEffect region is focused (padding frames surround it) but has no line-level highlighting, while the formatDate line has line-level highlighting but is unfocused.
import * as React from 'react';
import { formatDate } from './formatDate';
import { fetchEvents } from './fetchEvents';
const today = formatDate(new Date());
export function Calendar() {
const [events, setEvents] = React.useState([]);
React.useEffect(() => {
fetchEvents(today).then(setEvents);
}, []);
return (
<div className="calendar">
<h2>{today}</h2>
<ul>
{events.map((event) => (
<li key={event.id}>{event.title}</li>
))}
</ul>
</div>
);
}import * as React from 'react';
import type { Code as CodeType } from '@mui/internal-docs-infra/CodeHighlighter/types';
import { parseImportsAndComments } from '@mui/internal-docs-infra/pipeline/loaderUtils';
import {
EMPHASIS_COMMENT_PREFIX,
FOCUS_COMMENT_PREFIX,
} from '@mui/internal-docs-infra/pipeline/enhanceCodeEmphasis';
import { Code } from './Code';
const source = `import * as React from 'react';
import { formatDate } from './formatDate';
import { fetchEvents } from './fetchEvents';
const today = formatDate(new Date()); // @highlight
export function Calendar() {
const [events, setEvents] = React.useState([]);
// @focus-start
React.useEffect(() => {
fetchEvents(today).then(setEvents);
}, []);
// @focus-end
return (
<div className="calendar">
<h2>{today}</h2>
<ul>
{events.map((event) => (
<li key={event.id}>{event.title}</li>
))}
</ul>
</div>
);
}`;
export async function FocusCode() {
const { code: strippedSource, comments } = await parseImportsAndComments(source, '/demo.tsx', {
removeCommentsWithPrefix: [EMPHASIS_COMMENT_PREFIX, FOCUS_COMMENT_PREFIX],
notableCommentsPrefix: [EMPHASIS_COMMENT_PREFIX, FOCUS_COMMENT_PREFIX],
});
const code: CodeType = {
Default: {
language: 'tsx',
source: strippedSource!,
comments,
},
};
return <Code code={code} />;
}
With no padding configured, only highlighted/focus and normal frames are produced. The data-frame-indent attribute on region frames tells CSS how far the code is indented. This demo highlights an import statement (indent 0) and uses standalone @focus-start/@focus-end around the deeply nested <DatePicker> usage (indent 3). When collapsed, the focused frame shifts left by 6ch so it aligns with the left edge, then resets when expanded.
import * as React from 'react';
import { DatePicker } from './DatePicker';
export function ScheduleView() {
const [date, setDate] = React.useState(null);
return (
<main>
<header>
<h1>Schedule</h1>
</header>
<section>
<form>
<label htmlFor="date">Pick a date</label>
<DatePicker
id="date"
value={date}
onChange={setDate}
minDate={new Date()}
format="MM/dd/yyyy"
/>
</form>
</section>
<footer>
<p>All times shown in UTC</p>
</footer>
</main>
);
}import * as React from 'react';
import type { Code as CodeType } from '@mui/internal-docs-infra/CodeHighlighter/types';
import { parseImportsAndComments } from '@mui/internal-docs-infra/pipeline/loaderUtils';
import {
EMPHASIS_COMMENT_PREFIX,
FOCUS_COMMENT_PREFIX,
} from '@mui/internal-docs-infra/pipeline/enhanceCodeEmphasis';
import { CodeIndent } from './CodeIndent';
const source = `import * as React from 'react';
import { DatePicker } from './DatePicker'; // @highlight
export function ScheduleView() {
const [date, setDate] = React.useState(null);
return (
<main>
<header>
<h1>Schedule</h1>
</header>
<section>
<form>
<label htmlFor="date">Pick a date</label>
{/* @focus-start */}
<DatePicker
id="date"
value={date}
onChange={setDate}
minDate={new Date()}
format="MM/dd/yyyy"
/>
{/* @focus-end */}
</form>
</section>
<footer>
<p>All times shown in UTC</p>
</footer>
</main>
);
}`;
export async function IndentCode() {
const { code: strippedSource, comments } = await parseImportsAndComments(source, '/demo.tsx', {
removeCommentsWithPrefix: [EMPHASIS_COMMENT_PREFIX, FOCUS_COMMENT_PREFIX],
notableCommentsPrefix: [EMPHASIS_COMMENT_PREFIX, FOCUS_COMMENT_PREFIX],
});
const code: CodeType = {
Default: {
language: 'tsx',
source: strippedSource!,
comments,
},
};
return <CodeIndent code={code} />;
}
When focusFramesMaxSize is set and a highlighted region exceeds that limit, a focused window is taken from the start of the region, and the remaining overflow lines are marked as unfocused. This demo uses focusFramesMaxSize: 6 with the <form> JSX highlighted (10 lines). When collapsed, only the first 6 lines of the region are visible; expanding reveals the full highlighted region with the overflow lines.
import * as React from 'react';
interface FormData {
name: string;
email: string;
message: string;
}
export function ContactForm() {
const [form, setForm] = React.useState<FormData>({
name: '',
email: '',
message: '',
});
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
const response = await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
});
if (!response.ok) {
throw new Error('Failed to submit');
}
setForm({ name: '', email: '', message: '' });
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name</label>
<input id="name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
<label htmlFor="email">Email</label>
<input id="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
<label htmlFor="message">Message</label>
<textarea id="message" value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} />
<button type="submit">Send</button>
</form>
);
}import * as React from 'react';
import type { Code as CodeType } from '@mui/internal-docs-infra/CodeHighlighter/types';
import { parseImportsAndComments } from '@mui/internal-docs-infra/pipeline/loaderUtils';
import { EMPHASIS_COMMENT_PREFIX } from '@mui/internal-docs-infra/pipeline/enhanceCodeEmphasis';
import { CodeMaxSize } from './CodeMaxSize';
const source = `import * as React from 'react';
interface FormData {
name: string;
email: string;
message: string;
}
export function ContactForm() {
const [form, setForm] = React.useState<FormData>({
name: '',
email: '',
message: '',
});
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
const response = await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
});
if (!response.ok) {
throw new Error('Failed to submit');
}
setForm({ name: '', email: '', message: '' });
};
return (
// @highlight-start
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name</label>
<input id="name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
<label htmlFor="email">Email</label>
<input id="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
<label htmlFor="message">Message</label>
<textarea id="message" value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} />
<button type="submit">Send</button>
</form>
// @highlight-end
);
}`;
export async function MaxSizeCode() {
const { code: strippedSource, comments } = await parseImportsAndComments(source, '/demo.tsx', {
removeCommentsWithPrefix: [EMPHASIS_COMMENT_PREFIX],
notableCommentsPrefix: [EMPHASIS_COMMENT_PREFIX],
});
const code: CodeType = {
Default: {
language: 'tsx',
source: strippedSource!,
comments,
},
};
return <CodeMaxSize code={code} />;
}
When @highlight is used without @focus, the enhancer wraps highlighted lines in a frame with data-frame-type="highlighted". Style these frames with background and rounded corners:
/* Highlighted frames get rounded corners and background */
.frame[data-frame-type='highlighted'],
.frame[data-frame-type='highlighted-unfocused'] {
background: #ebe4ff;
border-radius: 8px;
margin: 0 6px;
padding: 0 6px;
}
The margin: 0 6px pulls the frame inward from the padding: 0 12px on the parent .frame, so highlighted frames appear visually inset. The padding: 0 6px ensures child content still has horizontal spacing.
When @highlight lines appear inside a @focus region, or when highlights are nested, the individual lines receive data-hl attributes. Style these with negative margins that expand into the parent frame's padding:
/* Required: Display lines as blocks for line-based highlighting */
.frame[data-lined] {
display: block;
white-space: normal;
}
.frame[data-lined] .line {
display: block;
white-space: pre;
}
/* Line-level highlight inside a frame (nested emphasis) */
.line[data-hl] {
background: #ebe4ff;
margin: 0 -6px;
padding: 0 6px;
}
/* Text-level highlight (from @highlight-text) */
mark {
background: #ebe4ff;
border-radius: 4px;
}
/* Text-level highlight inside a containing highlight range */
mark[data-hl] {
background: #e1d9ff;
}
/* Text-level highlight inside 2+ nested highlight ranges */
mark[data-hl='strong'] {
background: #d4c8ff;
}
/* Strong emphasis for nested highlights or descriptions ending with ! */
.line[data-hl='strong'] {
background: #e1d9ff;
margin: 0 -6px;
padding: 0 6px;
}
/* Single-line emphasis - rounded on all corners */
.line[data-hl-position='single'] {
border-radius: 8px;
}
/* Multiline block start - rounded top corners */
.line[data-hl-position='start'] {
border-top-left-radius: 8px;
border-top-right-radius: 8px;
}
/* Multiline block end - rounded bottom corners */
.line[data-hl-position='end'] {
border-bottom-left-radius: 8px;
border-bottom-right-radius: 8px;
}
Descriptions can appear on lines (for nested highlights) or frames (for standalone highlights).
Line-level descriptions (highlight inside focus, or nested/strong):
.line[data-hl-description]::after {
content: attr(data-hl-description);
float: right;
background: #8145b5;
border-radius: 8px;
color: white;
padding: 2px 4px;
margin-right: -6px;
}
Frame-level descriptions (standalone highlights):
.frame[data-frame-description]::before {
content: attr(data-frame-description);
float: right;
background: #8145b5;
border-radius: 8px;
color: white;
padding: 2px 4px;
}
Use single-line emphasis for specific statements:
// ✓ Good - highlights the important line
const result = await fetchData();
// ✗ Avoid - too vague
function processData() {
const result = await fetchData();
return result;
}
Add context when the emphasis isn't obvious:
// ✓ Good - explains what to notice
<div className="container"> {/* @highlight "We add the container class" */}
// ✗ Less helpful - just marks the line
<div className="container"> {/* @highlight */}
Use multi-line emphasis for logical code blocks:
// ✓ Good - emphasizes the complete pattern
// @highlight-start "We handle the form submission"
<form onSubmit={handleSubmit}>
<input type="text" value={name} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
// @highlight-end
Use the appropriate comment style for your language:
// JSX/TSX - use {/* */} for inline, // for block
<div>{/* @highlight */}</div>
// @highlight-start
// JavaScript/TypeScript - use //
const x = 42; // @highlight
// CSS - use /* */
.button {
color: blue; /* @highlight */
}
Check that:
notableCommentsPrefix: ['@highlight']If you have unmatched @highlight-start or @highlight-end:
@highlight-end → ignored (no effect)@highlight-start → ignored (no matching end)Check your code for balanced pairs.
Verify that:
dataLn properties)notableCommentsPrefix: ['@highlight', '@focus']@highlight, @highlight-start, @highlight-end, @highlight-text, @focus, @focus-start, @focus-end, and optional @padding N / @min N modifiers@highlight-start to the last line before @highlight-enddataHl: '' (or dataHl: 'strong' for nested lines or descriptions ending with !) to line elements. Text highlights (@highlight-text) wrap matched text in <mark> elements, which inherit data-hl from their containing highlight range via containingRangeDepthLines in the HAST tree have this structure after enhancement:
{
type: 'element',
tagName: 'span',
properties: {
className: 'line',
dataLn: 3, // Line number
dataHl: '', // Added by enhancer (or 'strong' for nested/!)
dataHlDescription: 'We track state', // Optional description
dataHlPosition: 'single', // 'single' | 'start' | 'end' for line position
},
children: [/* code tokens */]
}
For text highlighting with @highlight-text "text", the specified text within the line is wrapped in a <mark> element:
{
type: 'element',
tagName: 'mark',
properties: {},
children: [{ type: 'text', value: 'text' }]
}
When the <mark> is inside a containing highlight range, it inherits data-hl based on the nesting depth: data-hl="" for one containing range, data-hl="strong" for two or more. When the highlighted text matches a single syntax-highlighting <span>, the span is replaced in-place (its tagName becomes mark and highlight properties are merged) to keep the output flat.
The enhancer adds these attributes to line elements when the highlight is nested (inside a focus frame or strong from nesting):
| Attribute | Type | Description |
|---|---|---|
data-hl | string | "" for normal, "strong" if description ends with ! or line is nested |
data-hl-description | string | Description text (if provided in comment) |
data-hl-position | string | "single" for single-line, "start" or "end" for multiline range bounds (from innermost range) |
For standalone highlights (no focus context, not nested), the visual emphasis is
handled entirely at the frame level. The frame receives data-frame-description
if a description was provided (see Frame Data Attributes).
For single-line emphasis with @highlight:
data-hl is set (or data-hl="strong" if description ends with !)data-hl-description is set if a description was provideddata-hl-position="single" is set to distinguish from multiline range boundariesFor multi-line emphasis with @highlight-start / @highlight-end:
data-hl is set on all lines in the range (or data-hl="strong" if description ends with ! or line is nested)data-hl-description is set on the first line (if provided)data-hl-position="start" is set on the first line (only for ranges with more than one line)data-hl-position="end" is set on the last line (only for ranges with more than one line)Note: The above line-level attributes are only applied when the highlight is inside a focus region or is nested (strong). For standalone highlights, descriptions are placed on the frame element as
data-frame-descriptioninstead.
For text highlighting with @highlight-text "text":
<mark> elementdata-hl based on nesting depth ("" for 1 range, "strong" for 2+)Multi-line directives are paired using a stack:
@highlight-start pushes onto the stack@highlight-end pops from the stack and emphasizes the rangeDefault source enhancer that adds emphasis to code lines based on @highlight comments.
Uses no padding frames by default. Use createEnhanceCodeEmphasis for configurable padding.
| Parameter | Type | Description |
|---|---|---|
| root | | |
| comments | | |
| fileName | |
HastRoot | Promise<HastRoot>The prefix used to identify emphasis comments in source code. Comments starting with this prefix will be processed for emphasis.
type EMPHASIS_COMMENT_PREFIX = '@highlight'Metadata for an emphasized line.
type EmphasisMeta = {
/** Optional description for this emphasis */
description?: string;
/** Position: 'single' for single-line, 'start'/'end' for multiline range bounds, undefined for middle */
position?: 'single' | 'start' | 'end';
/** Whether this is a strong emphasis (description ended with !) */
strong?: boolean;
/** For text highlighting: the specific texts to highlight within the line */
highlightTexts?: string[];
/** Whether this line's region is the focused region (for padding) */
focus?: boolean;
/** Whether the line itself should receive data-hl. True for highlight directives and false for focus-only directives. */
lineHighlight: boolean;
/** How many containing highlight ranges wrap this line (used for mark data-hl propagation) */
containingRangeDepth?: number;
/** Optional per-directive padding override for this region */
paddingFrameMaxSize?: number;
/** Optional per-directive focus max size override for this region */
focusFramesMaxSize?: number;
/**
* True when the overrides were propagated from a multiline range
* rather than set by an explicit per-line directive.
* Explicit overrides take precedence over propagated ones in regions.
*/
propagatedOverride?: boolean;
}Options for the enhance code emphasis factory.
type EnhanceCodeEmphasisOptions = {
/**
* Maximum number of padding lines above and below the focused highlight region.
* Padding frames provide surrounding context for the highlighted code.
* Set to 0 or omit to disable padding frames.
*/
paddingFrameMaxSize?: number;
/**
* Maximum total number of lines in the focus area (padding-top + focused region + padding-bottom).
* Defaults to `12` when not explicitly configured.
* @default 12
When the region fits within this limit, padding sizes are reduced so the total focus area
fits. The remainder after subtracting the region size is split: floor(remainder/2) for
padding-top and ceil(remainder/2) for padding-bottom.
When the region exceeds this limit, a focused window is taken from the start of the
region, and the remaining overflow lines are marked as unfocused.
*/
focusFramesMaxSize?: number;
/**
* When `true`, throws an error if a `@highlight-text` match has to be
* fragmented across element boundaries (producing `data-hl-part` spans).
* Wrapping multiple complete elements in a single `data-hl` span is still
* allowed — only boundary-straddling matches are rejected.
*/
strictHighlightText?: boolean;
}The prefix used to identify focus-only comments in source code. Comments starting with this prefix will mark the region as focused without highlighting.
type FOCUS_COMMENT_PREFIX = '@focus'A range of lines that forms a frame in the output.
type FrameRange = {
/** First line number (1-based, inclusive) */
startLine: number;
/** Last line number (1-based, inclusive) */
endLine: number;
/** The type of frame */
type:
| 'normal'
| 'padding-top'
| 'highlighted'
| 'highlighted-unfocused'
| 'focus'
| 'focus-unfocused'
| 'padding-bottom'
| 'comment';
/** Index of the highlighted region this frame belongs to. Present on region-type frames. */
regionIndex?: number;
/**
* Present on frames created by splitting an oversized region via `focusFramesMaxSize`.
* - `'visible'` — the focused window kept visible when collapsed.
* - `'hidden'` — the overflow portion hidden when collapsed.
*/
truncated?: 'visible' | 'hidden';
}Modifier token used inside @highlight / @focus comments
to override focus max size for that directive.
Example:
type MIN_COMMENT_PREFIX = '@min'Modifier token used inside @highlight / @focus comments
to override padding for that directive.
Example:
type PADDING_COMMENT_PREFIX = '@padding'