Design / 4 min read
Interactive Code Window.
A code viewer linked to a live preview. Selecting a block of lines outlines the element it renders, and the steps can play as a walkthrough.
Add className="my-interactive-code-window" to your component.
Make a change to create your CSS.
<article className="field-note"> <header className="note-header"> <span>FIELD NOTES / 004</span> <span>↗</span> </header> <div className="note-artwork"> <GlassStudy /> <span>STUDY IN STILLNESS</span> </div> <div className="note-story"> <p>Design / 4 min read</p> <h2>Somewhere in between.</h2> <span>Small observations. Better ideas.</span> </div></article>Somewhere
Small observations. Better ideas.Installation
In a project with React and shadcn configured, run:
npx shadcn@latest add https://aduneer.github.io/opalframe/r/interactive-code-window.jsonCopies the component and its stylesheet into components/ui. No additional runtime dependencies. Tailwind classes work through className.
For manual installation, copy both files from Source below. Keep the CSS import alongside the component.
Usage
import { InteractiveCodeWindow } from "@/components/ui/interactive-code-window";
export default function Example() {
return (
<InteractiveCodeWindow
files={[{
id: "card", name: "card.tsx",
code: '<h2 className="title">Pricing</h2>',
}]}
steps={[{
id: "title", title: "Typography", fileId: "card",
lines: [1, 1], target: ".title",
description: "The heading uses the display font.",
}]}
preview={<h2 className="title">Pricing</h2>}
/>
);
}Customize
Colors and sizes are scoped CSS variables. Override them on your own class.
<InteractiveCodeWindow
files={yourFiles}
steps={yourSteps}
preview={(step) => <YourPreview selected={step.id} />}
className="your-code-window"
stepDuration={2000}
/>
.your-code-window {
--code-accent: #a6cfff;
--code-preview-background: #e6effa;
--code-preview-accent: #315f9e;
--code-line-height: 24px;
}Props
| Prop | Type | What it does |
|---|---|---|
files | CodeWindowFile[] | Files with unique id, display name, and plain source code. Source is displayed, never executed. |
steps | CodeWindowStep[] | Unique id, title, description, fileId, inclusive one-based lines, and optional preview target selector. Keep line ranges disjoint within a file. |
preview | ReactNode | (step) => ReactNode | Your rendered interface. The render function can respond to the selected step. |
value / defaultValue | string | Controlled or initial selected step ID. |
onValueChange | (id: string) => void | Called on selection and playback. Update value in controlled mode. |
renderLine | (line, number, file) => ReactNode | Optional syntax renderer. Plain source is the default; no highlighting dependency required. |
autoPlay / stepDuration | boolean / number | Start a single walkthrough on visibility; defaults false. Duration per step in milliseconds, default 1600, minimum 300. |
reducedMotion | boolean | Disable transitions and finish replay immediately; also respects the OS preference. |
focusPadding | number | Local CSS pixels around a measured target, default 6. |
label / previewLabel | string | Window and preview accessible labels. |
className | string | Root customization. Colors and line height use scoped CSS variables. |
Accessibility & motion
File tabs support Arrow Left/Right, Home, and End. Code blocks and walkthrough steps are native buttons with a pressed state. The source panel scrolls with a keyboard; captions announce politely. Target outlines are decorative. Replay stops after one sequence, pauses off-screen or in hidden tabs, and finishes immediately with reduced motion. Copy uses the browser clipboard API and reports unavailable access. Source strings are never evaluated; provide your own rendered preview.
Dependencies
React only. Styles live in a plain CSS file next to the component, and Tailwind utilities work through className.
Source
interactive-code-window.tsx
"use client";
import {
useEffect,
useId,
useRef,
useState,
useSyncExternalStore,
type KeyboardEvent,
type ReactNode,
} from "react";
import "./interactive-code-window.css";
export interface CodeWindowFile {
id: string;
name: string;
code: string;
}
export interface CodeWindowStep {
id: string;
title: string;
description: string;
fileId: string;
/** Inclusive, one-based source line range. Keep ranges within a file disjoint. */
lines: [number, number];
/** Optional CSS selector scoped to the preview. */
target?: string;
}
export interface InteractiveCodeWindowProps {
files: CodeWindowFile[];
steps: CodeWindowStep[];
preview: ReactNode | ((step: CodeWindowStep) => ReactNode);
value?: string;
defaultValue?: string;
onValueChange?: (id: string) => void;
renderLine?: (
line: string,
lineNumber: number,
file: CodeWindowFile,
) => ReactNode;
className?: string;
label?: string;
previewLabel?: string;
autoPlay?: boolean;
stepDuration?: number;
reducedMotion?: boolean;
focusPadding?: number;
}
function subscribeMotion(callback: () => void) {
const query = window.matchMedia("(prefers-reduced-motion: reduce)");
query.addEventListener("change", callback);
return () => query.removeEventListener("change", callback);
}
function getMotion() {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
function subscribeVisibility(callback: () => void) {
document.addEventListener("visibilitychange", callback);
return () => document.removeEventListener("visibilitychange", callback);
}
function getVisibility() {
return !document.hidden;
}
export function InteractiveCodeWindow({
files,
steps,
preview,
value,
defaultValue,
onValueChange,
renderLine,
className = "",
label = "Interactive code walkthrough",
previewLabel = "Live preview",
autoPlay = false,
stepDuration = 1600,
reducedMotion = false,
focusPadding = 6,
}: InteractiveCodeWindowProps) {
const uid = useId();
const root = useRef<HTMLDivElement>(null);
const scene = useRef<HTMLDivElement>(null);
const source = useRef<HTMLDivElement>(null);
const [internalValue, setInternalValue] = useState(
defaultValue ?? steps[0]?.id,
);
const [fileOverride, setFileOverride] = useState<string>();
const [playing, setPlaying] = useState(autoPlay);
const [visible, setVisible] = useState(false);
const documentVisible = useSyncExternalStore(
subscribeVisibility,
getVisibility,
() => true,
);
const [copyStatus, setCopyStatus] = useState("");
const [focus, setFocus] = useState<{
x: number;
y: number;
width: number;
height: number;
radius: string;
}>();
const osReduced = useSyncExternalStore(
subscribeMotion,
getMotion,
() => true,
);
const reduced = reducedMotion || osReduced;
const active =
steps.find((step) => step.id === (value ?? internalValue)) ?? steps[0];
const file =
files.find((entry) => entry.id === (fileOverride ?? active?.fileId)) ??
files[0];
const index = steps.indexOf(active);
const ready = !!active && !!file;
useEffect(() => {
const panel = source.current;
if (!panel) return;
const fit = () => {
const block = panel.querySelector<HTMLButtonElement>(
'[aria-pressed="true"]',
);
if (!block) return;
const bounds = block.getBoundingClientRect();
const viewport = panel.getBoundingClientRect();
const scale = viewport.height / panel.offsetHeight;
if (!scale) return;
if (
bounds.height > viewport.height - 24 * scale ||
bounds.top < viewport.top + 12 * scale
)
panel.scrollTop += (bounds.top - viewport.top) / scale - 12;
else if (bounds.bottom > viewport.bottom - 12 * scale)
panel.scrollTop += (bounds.bottom - viewport.bottom) / scale + 12;
};
const observer = new ResizeObserver(fit);
observer.observe(panel);
const frame = requestAnimationFrame(fit);
return () => {
observer.disconnect();
cancelAnimationFrame(frame);
};
}, [active?.id, file?.id]);
useEffect(() => {
const element = root.current;
if (!element) return;
const observer = new IntersectionObserver(
([entry]) => setVisible(entry.isIntersecting),
{ threshold: 0.15 },
);
observer.observe(element);
return () => {
observer.disconnect();
};
}, [ready]);
useEffect(() => {
if (!playing || !visible || !documentVisible || !active || !ready) return;
// Read the client preference here: the hydration snapshot is conservative.
const skipMotion = reducedMotion || getMotion();
const timer = window.setTimeout(
() => {
const next = skipMotion ? steps[steps.length - 1] : steps[index + 1];
if (next) {
if (value === undefined) setInternalValue(next.id);
setFileOverride(undefined);
onValueChange?.(next.id);
}
if (skipMotion || !next) setPlaying(false);
},
skipMotion ? 0 : Math.max(300, stepDuration),
);
return () => window.clearTimeout(timer);
}, [
playing,
visible,
documentVisible,
active,
index,
reduced,
reducedMotion,
steps,
stepDuration,
value,
onValueChange,
ready,
]);
useEffect(() => {
const container = scene.current;
if (!container || !active?.target) return;
const element = container.querySelector(active.target);
if (!element) return;
const measure = () => {
const frame = container.getBoundingClientRect();
const target = element.getBoundingClientRect();
if (!frame.width || !frame.height) return;
const px = (focusPadding * frame.width) / container.offsetWidth;
const py = (focusPadding * frame.height) / container.offsetHeight;
setFocus({
x: ((target.left - frame.left - px) / frame.width) * 100,
y: ((target.top - frame.top - py) / frame.height) * 100,
width: ((target.width + px * 2) / frame.width) * 100,
height: ((target.height + py * 2) / frame.height) * 100,
radius: getComputedStyle(element).borderRadius,
});
};
const observer = new ResizeObserver(measure);
observer.observe(container);
observer.observe(element);
const frame = requestAnimationFrame(measure);
return () => {
observer.disconnect();
cancelAnimationFrame(frame);
};
}, [active?.id, active?.target, preview, focusPadding]);
useEffect(() => {
if (!copyStatus) return;
const timer = window.setTimeout(() => setCopyStatus(""), 2000);
return () => window.clearTimeout(timer);
}, [copyStatus]);
if (!active || !file) return null;
const sourceLines = file.code.split("\n");
function select(step: CodeWindowStep) {
setPlaying(false);
setFileOverride(undefined);
if (value === undefined) setInternalValue(step.id);
onValueChange?.(step.id);
}
function selectFile(entry: CodeWindowFile) {
const step = steps.find((item) => item.fileId === entry.id);
if (step) select(step);
else {
setPlaying(false);
setFileOverride(entry.id);
}
}
function navigateFiles(
event: KeyboardEvent<HTMLButtonElement>,
current: number,
) {
let next = current;
if (event.key === "ArrowRight") next = (current + 1) % files.length;
else if (event.key === "ArrowLeft")
next = (current - 1 + files.length) % files.length;
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = files.length - 1;
else return;
event.preventDefault();
selectFile(files[next]);
document.getElementById(`${uid}-file-${files[next].id}`)?.focus();
}
function replay() {
const skipMotion = reducedMotion || getMotion();
const first = skipMotion ? steps[steps.length - 1] : steps[0];
select(first);
setPlaying(!skipMotion);
}
return (
<div
className={`is-code-window ${className}`}
ref={root}
data-reduced-motion={reducedMotion || undefined}
role="group"
aria-label={label}
>
<div className="is-code-header">
<span className="is-code-window-dots" aria-hidden="true">
<i />
<i />
<i />
</span>
<span>{label}</span>
<span className="is-code-header-mark" aria-hidden="true">
↗
</span>
</div>
<div className="is-code-layout">
<div className="is-code-editor">
<div className="is-code-editor-bar">
<div
className="is-code-files"
role="tablist"
aria-label="Source files"
>
{files.map((entry, i) => (
<button
type="button"
role="tab"
key={entry.id}
id={`${uid}-file-${entry.id}`}
aria-selected={entry.id === file.id}
aria-controls={`${uid}-source`}
tabIndex={entry.id === file.id ? 0 : -1}
onClick={() => selectFile(entry)}
onKeyDown={(event) => navigateFiles(event, i)}
>
{entry.name}
</button>
))}
</div>
<button
className="is-code-copy"
type="button"
aria-label={`Copy ${file.name}`}
onClick={async () => {
try {
await navigator.clipboard.writeText(file.code);
setCopyStatus("Copied");
} catch {
setCopyStatus("Copy unavailable in this browser.");
}
}}
>
{copyStatus === "Copied" ? "✓" : "⧉"}
</button>
<span className="is-code-copy-feedback" role="status">
{copyStatus}
</span>
</div>
<div
className="is-code-source"
ref={source}
id={`${uid}-source`}
role="tabpanel"
aria-labelledby={`${uid}-file-${file.id}`}
tabIndex={0}
>
<div
className="is-code-lines"
style={{
gridTemplateRows: `repeat(${sourceLines.length}, var(--code-line-height))`,
}}
>
{sourceLines.map((line, i) => (
<div
className="is-code-line"
key={i}
style={{ gridRow: i + 1 }}
data-highlighted={
file.id === active.fileId &&
i + 1 >= active.lines[0] &&
i + 1 <= active.lines[1]
}
>
<span className="is-code-line-number" aria-hidden="true">
{String(i + 1).padStart(2, "0")}
</span>
<code>
{renderLine ? renderLine(line, i + 1, file) : line || " "}
</code>
</div>
))}
{steps
.filter(
(step) =>
step.fileId === file.id &&
step.lines[0] <= sourceLines.length,
)
.map((step) => (
<button
key={step.id}
type="button"
className="is-code-snippet"
style={{
gridRow: `${Math.max(1, step.lines[0])} / ${Math.min(sourceLines.length, step.lines[1]) + 1}`,
}}
aria-label={`Show ${step.title}`}
aria-pressed={step.id === active.id}
aria-controls={`${uid}-preview`}
onClick={() => select(step)}
>
<span>
{String(steps.indexOf(step) + 1).padStart(2, "0")}
</span>
</button>
))}
</div>
</div>
<div className="is-code-editor-bottom">
<span>SELECT A BLOCK ↗</span>
<span>React + CSS</span>
</div>
</div>
<div
className="is-code-preview"
id={`${uid}-preview`}
role="region"
aria-label={previewLabel}
>
<div className="is-code-preview-bar">
<span>
<i /> {previewLabel}
</span>
<span>localhost</span>
</div>
<div className="is-code-scene" ref={scene}>
{typeof preview === "function" ? preview(active) : preview}
{active.target && focus && (
<div
className="is-code-focus"
aria-hidden="true"
style={{
left: `${focus.x}%`,
top: `${focus.y}%`,
width: `${focus.width}%`,
height: `${focus.height}%`,
borderRadius: focus.radius,
}}
>
<span>{String(index + 1).padStart(2, "0")}</span>
</div>
)}
</div>
</div>
</div>
<div className="is-code-walkthrough">
<div
className="is-code-step-list"
role="group"
aria-label="Walkthrough steps"
>
{steps.map((step, i) => (
<button
key={step.id}
type="button"
aria-pressed={active.id === step.id}
onClick={() => select(step)}
>
<span>{String(i + 1).padStart(2, "0")}</span>
{step.title}
</button>
))}
</div>
<button
className="is-code-replay"
type="button"
aria-label={playing ? "Pause walkthrough" : "Replay walkthrough"}
onClick={playing ? () => setPlaying(false) : replay}
>
{playing ? "Ⅱ" : "↻"}
<span>{playing ? "Pause" : "Replay"}</span>
</button>
</div>
<div className="is-code-caption" aria-live="polite" aria-atomic="true">
<span className="is-code-caption-index">
{String(index + 1).padStart(2, "0")} /{" "}
{String(steps.length).padStart(2, "0")}
</span>
<span className="is-code-captions">
{steps.map((step) => (
<span
key={step.id}
data-active={step.id === active.id}
aria-hidden={step.id !== active.id}
>
{step.description}
</span>
))}
</span>
</div>
</div>
);
}
interactive-code-window.css
.is-code-window {
--code-surface: var(--surface, #18181b);
--code-editor: var(--bg, #101012);
--code-text: var(--text, #f4f4f5);
--code-muted: var(--muted, #a7a7af);
--code-border: var(--line, #34343b);
--code-accent: var(--accent, #b2cfff);
--code-line-height: 23px;
width: 100%;
min-width: 0;
overflow: hidden;
border: 1px solid var(--code-border);
border-radius: 12px;
color: var(--code-text);
background: var(--code-surface);
text-align: left;
}
.is-code-window button {
font: inherit;
cursor: pointer;
}
.is-code-window button:focus-visible,
.is-code-source:focus-visible {
outline: 2px solid var(--code-accent);
outline-offset: -3px;
}
.is-code-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 14px 20px;
border-bottom: 1px solid var(--code-border);
color: var(--code-muted);
font:
10px ui-monospace,
monospace;
}
.is-code-window-dots {
display: flex;
gap: 5px;
}
.is-code-window-dots i {
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--code-muted);
opacity: 0.65;
}
.is-code-header-mark {
font-size: 16px;
}
.is-code-layout {
display: grid;
grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr);
}
.is-code-editor {
display: flex;
flex-direction: column;
min-width: 0;
background: var(--code-editor);
}
.is-code-editor-bar {
position: relative;
display: flex;
align-items: center;
border-bottom: 1px solid var(--code-border);
min-height: 46px;
}
.is-code-files {
display: flex;
flex: 1;
min-width: 0;
overflow-x: auto;
}
.is-code-files button {
border: 0;
border-right: 1px solid var(--code-border);
padding: 16px 20px;
background: transparent;
color: var(--code-muted);
font:
10px ui-monospace,
monospace;
white-space: nowrap;
}
.is-code-files button[aria-selected="true"] {
color: var(--code-text);
background: var(--code-surface);
box-shadow: inset 0 -1px var(--code-accent);
}
.is-code-copy {
border: 0;
background: none;
color: var(--code-muted);
font-size: 17px !important;
padding: 10px 16px;
}
.is-code-copy-feedback {
position: absolute;
right: 10px;
top: calc(100% + 6px);
max-width: 190px;
z-index: 4;
border: 1px solid var(--code-border);
border-radius: 5px;
padding: 7px 10px;
background: var(--code-surface);
color: var(--code-text);
font:
10px/1.5 ui-monospace,
monospace;
pointer-events: none;
}
.is-code-copy-feedback:empty {
display: none;
}
.is-code-source {
min-width: 0;
min-height: 355px;
max-height: 355px;
overflow: auto;
padding: 24px 18px;
flex: 1;
}
.is-code-lines {
display: grid;
position: relative;
min-width: max-content;
}
.is-code-line {
grid-column: 1;
display: flex;
align-items: center;
gap: 17px;
padding: 0 12px;
z-index: 1;
pointer-events: none;
color: var(--code-muted);
font:
11px/var(--code-line-height) ui-monospace,
monospace;
transition: color 180ms;
}
.is-code-line code {
font: inherit;
white-space: pre;
}
.is-code-line[data-highlighted="true"] {
color: var(--code-text);
}
.is-code-line-number {
color: var(--code-muted);
font-size: 9px;
min-width: 15px;
user-select: none;
}
.is-code-snippet {
grid-column: 1;
z-index: 2;
position: relative;
border: 1px solid transparent;
border-radius: 6px;
background: transparent;
min-height: 0;
color: var(--code-accent);
padding: 0;
transition:
background 180ms,
border-color 180ms;
}
.is-code-snippet:hover {
border-color: var(--code-border);
}
.is-code-snippet[aria-pressed="true"] {
border-color: color-mix(in srgb, var(--code-accent) 48%, transparent);
background: color-mix(in srgb, var(--code-accent) 7%, transparent);
}
.is-code-snippet > span {
position: absolute;
top: 5px;
right: 7px;
font:
8px ui-monospace,
monospace;
background: var(--code-surface);
padding: 2px 3px;
border-radius: 2px;
opacity: 0;
}
.is-code-snippet[aria-pressed="true"] > span,
.is-code-snippet:hover > span {
opacity: 1;
}
.is-code-editor-bottom {
display: flex;
justify-content: space-between;
gap: 10px;
padding: 12px 20px;
margin-top: auto;
color: var(--code-muted);
font:
8px ui-monospace,
monospace;
}
.is-code-preview {
display: flex;
flex-direction: column;
min-width: 0;
border-left: 1px solid var(--code-border);
background: var(--code-preview-background, #dbe8f8);
color: var(--code-preview-text, #293a51);
}
.is-code-preview-bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 16px 20px;
font:
9px ui-monospace,
monospace;
border-bottom: 1px solid #293a5120;
}
.is-code-preview-bar > span:first-child {
display: flex;
align-items: center;
gap: 6px;
}
.is-code-preview-bar i {
display: inline-block;
width: 4px;
height: 4px;
background: currentColor;
border-radius: 50%;
}
.is-code-scene {
position: relative;
flex: 1;
display: grid;
place-items: center;
padding: 32px;
isolation: isolate;
}
.is-code-focus {
position: absolute;
pointer-events: none;
border: 1px solid var(--code-preview-accent, #315f9e);
border-radius: 9px;
box-shadow: 0 0 0 4px #315f9e08;
transition:
left 350ms,
top 350ms,
width 350ms,
height 350ms;
z-index: 2;
}
.is-code-focus > span {
position: absolute;
right: -1px;
top: -17px;
background: var(--code-preview-accent, #315f9e);
color: #fff;
padding: 3px 5px;
border-radius: 3px 3px 0 0;
font:
8px ui-monospace,
monospace;
}
.is-code-walkthrough {
display: flex;
align-items: center;
justify-content: space-between;
border-top: 1px solid var(--code-border);
padding: 14px 20px;
gap: 12px;
}
.is-code-step-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.is-code-step-list button {
display: flex;
align-items: center;
gap: 7px;
font-size: 10px;
padding: 6px 8px;
border: 1px solid transparent;
background: none;
color: var(--code-muted);
border-radius: 4px;
}
.is-code-step-list button > span {
font:
8px ui-monospace,
monospace;
}
.is-code-step-list button[aria-pressed="true"] {
background: color-mix(in srgb, var(--code-accent) 8%, transparent);
color: var(--code-accent);
border-color: var(--code-border);
}
.is-code-replay {
display: flex;
align-items: center;
gap: 7px;
padding: 6px 0 6px 10px;
background: none;
border: 0;
color: var(--code-text);
font-size: 17px !important;
}
.is-code-replay > span {
font-size: 10px;
}
.is-code-caption {
display: flex;
align-items: center;
gap: 14px;
padding: 0 22px 18px;
min-height: 40px;
font-size: 11px;
color: var(--code-muted);
}
.is-code-caption-index {
font:
9px ui-monospace,
monospace;
color: var(--code-accent);
white-space: nowrap;
}
.is-code-captions {
display: grid;
}
.is-code-captions > span {
grid-area: 1/1;
visibility: hidden;
}
.is-code-captions > span[data-active="true"] {
visibility: visible;
}
.is-code-window[data-reduced-motion] *,
.is-code-window[data-reduced-motion] *::before {
transition: none !important;
}
@media (max-width: 680px) {
.is-code-layout {
grid-template-columns: 1fr;
}
.is-code-header {
padding: 12px 14px;
font-size: 8px;
}
.is-code-source {
min-height: 250px;
max-height: 250px;
padding: 15px 10px;
}
.is-code-line {
font-size: 10px;
gap: 10px;
}
.is-code-files button {
padding: 14px;
font-size: 9px;
}
.is-code-preview {
border-left: 0;
border-top: 1px solid var(--code-border);
}
.is-code-scene {
min-height: 335px;
padding: 28px;
}
.is-code-editor-bottom {
padding: 10px 14px;
}
.is-code-walkthrough {
padding: 12px;
gap: 4px;
}
.is-code-step-list {
gap: 2px;
}
.is-code-step-list button {
font-size: 9px;
padding: 5px;
gap: 4px;
}
.is-code-replay > span {
display: none;
}
.is-code-caption {
font-size: 10px;
padding: 0 16px 14px;
}
}
@media (prefers-reduced-motion: reduce) {
.is-code-window *,
.is-code-window *::before {
transition: none !important;
}
}