effect-motion
Guides

Highlight code

Syntax-colored code on a single Text, with animated selection dimming

Code explainers need two things: syntax coloring, and a way to say look here — keep one range bright while the rest fades back. Both are span data on an ordinary Text, produced at authoring time by @effect-motion/code. The engine never parses; frames carry only plain { from, to, fillColor } ranges.

Install

bun add @effect-motion/code @lezer/javascript

The language grammar is your own dependency — pass any Lezer parser (@lezer/javascript, @lezer/python, @lezer/rust, …).

Highlight

import * as Highlight from "@effect-motion/code/Highlight";
import { parser } from "@lezer/javascript";

const snippet = Highlight.highlight(CODE, parser, Highlight.defaultTheme);

highlight runs the parse once, outside the scene body, and returns { text, spans } — spread it straight into a Text:

yield* Scene.instantiate("Text", {
	text: snippet.text,
	spans: snippet.spans,
	fontFamily: mono,
	fillColor: ink, // what unthemed tokens (identifiers, whitespace) paint in
});

A theme is a plain object mapping highlight tag names to Colors — write your own as a literal, or start from Highlight.defaultTheme:

const theme: Highlight.Theme = {
	keyword: Color.hex("#c678dd"),
	string: Color.hex("#98c379"),
	comment: Color.hex("#7f848e"),
};

Tokens without a theme entry stay uncovered and render in the Text's own fillColor. A monospace face reads best for code, but nothing requires one — spans ride the real shaping pipeline, so proportional fonts work too. One shaping note: a span boundary splits ligatures, so a font's =>-arrow ligature forms inside a token but never across two differently-colored ones.

Select and dim

Selection.dim derives a new span set: characters in the given ranges keep their colors, everything else mixes toward your backdrop color. Selection.selectTo animates there from whatever the Text currently shows:

import * as Selection from "@effect-motion/code/Selection";

yield* Selection.selectTo(code, snippet, [{ from: 6, to: 11 }], {
	duration: "600 millis",
	background: BACKGROUND, // the color dimmed code fades toward
	baseColor: INK, // the Text's fillColor, so plain code dims too
});

Pass the same un-dimmed snippet to every selection — each sweep re-derives from full color, so dims never compound. Selecting [{ from: 0, to: CODE.length }] restores the full highlight; [] dims everything. Colors interpolate frame-exactly and the final frame lands exactly on the derived selection, like every animator.

0:00
import * as Highlight from "@effect-motion/code/Highlight";import * as Selection from "@effect-motion/code/Selection";import { parser } from "@lezer/javascript";import * as Color from "effect-motion/Color";import * as Entity from "effect-motion/Entity";import * as Font from "effect-motion/Font";import * as Motion from "effect-motion/Motion";import * as Resource from "effect-motion/Resource";import * as Scene from "effect-motion/Scene";// Syntax highlighting is authoring-time: Lezer tokenizes the snippet ONCE,// outside the scene body, into plain span data on a single Text. The// selection sweep is `Selection.selectTo` — everything outside the selected// range dims toward the backdrop, colors interpolating frame-exactly.const JetBrainsMono = Font.Font("JetBrains Mono");const CODE = `const scene = Scene.make(function* () {  const dot = yield* Scene.instantiate("Circle", {    radius: 40,  });  yield* Motion.moveTo(dot, { x: 300 }, "1 second");});`;const BACKGROUND = Color.rgba(22, 22, 29);const INK = Color.hex("#dcdce6");const snippet = Highlight.highlight(CODE, parser, Highlight.defaultTheme);// select whole statements by their source text — plain string mathconst lineOf = (needle: string): Selection.Range => {	const from = CODE.indexOf(needle);	return { from, to: from + needle.length };};const instantiateCall = lineOf(`Scene.instantiate("Circle", {    radius: 40,  })`);const moveToCall = lineOf(`Motion.moveTo(dot, { x: 300 }, "1 second")`);export const scene = Scene.make(	"code highlight",	function* () {		const mono = yield* JetBrainsMono;		const code = yield* Scene.instantiate("Text", {			position: Entity.vec3({ x: -840, y: 300 }),			text: snippet.text,			spans: snippet.spans,			fontSize: 56,			fontFamily: mono,			fillColor: INK,			baseline: "hanging",		});		const sweep = (ranges: ReadonlyArray<Selection.Range>) =>			Selection.selectTo(code, snippet, ranges, {				duration: "600 millis",				timing: "easeInOutCubic",				background: BACKGROUND,				baseColor: INK,			});		yield* Motion.wait("1 second");		yield* sweep([instantiateCall]);		yield* Motion.wait("1200 millis");		yield* sweep([moveToCall]);		yield* Motion.wait("1200 millis");		// selecting everything restores the full highlight		yield* sweep([{ from: 0, to: CODE.length }]);		yield* Motion.wait("1 second");	},	{ width: 1920, height: 1080, backgroundColor: BACKGROUND },);export const renderLayers = Font.layer(	JetBrainsMono,	Resource.fetchBytes(		"https://cdn.jsdelivr.net/npm/@expo-google-fonts/jetbrains-mono@0.2.3/JetBrainsMono_400Regular.ttf",	),);

Evolve code with a block

For code that changes — a parameter appears, an expression gets extracted — use a code block: highlighted lines on a monospace grid that transition between source versions. Unchanged tokens slide (across lines too), removals fade out, insertions fade in.

import * as Code from "@effect-motion/code/Code";

const block = yield* Code.block({
	code: V1,
	parser,
	theme: Highlight.defaultTheme,
	fontSize: 44,
	grid: { charWidth: 0.6, lineHeight: 1.32 },
	fontFamily: mono,
	fillColor: INK,
});

yield* Code.editTo(block, V2, { duration: "900 millis" });

editTo takes the complete new source — a deterministic diff plans the transition, so there is no edit-marker DSL to learn. The same before and after always animate identically.

A block is an ordinary Group of per-line Texts, so standard animators move and fade it as one unit (Motion.moveTo(block.group, …)), and Code.selectTo(block, ranges, …) runs the selection dim across all lines in whole-source coordinates.

Three rules keep the grid honest:

  • Lines never wrap. Every position is (line, column) arithmetic; size the composition to the code.
  • Monospace fonts only, spaces only — tabs are a loud defect. Derive exact charWidth/lineHeight from your font's real metrics with Metrics.gridFromFont(bytes) (imported from @effect-motion/code/Metrics — a separate entry so its font-parsing WASM never loads when you declare the grid manually).
  • Edits diff from the block's current code. An editTo replayed by Scene.repeat is a no-op on the second pass — rebuild the block per iteration to loop an edit.
0:00
import * as Code from "@effect-motion/code/Code";import * as Highlight from "@effect-motion/code/Highlight";import { parser } from "@lezer/javascript";import * as Color from "effect-motion/Color";import * as Entity from "effect-motion/Entity";import * as Font from "effect-motion/Font";import * as Motion from "effect-motion/Motion";import * as Resource from "effect-motion/Resource";import * as Scene from "effect-motion/Scene";// A code block that EVOLVES: pass the whole new source and a deterministic// diff plans the transition — unchanged tokens slide (across lines too),// removals fade out, insertions fade in. The block is an ordinary Group of// Texts on a monospace grid, so standard animators drive everything.const JetBrainsMono = Font.Font("JetBrains Mono");const V1 = `function total(items) {  return items    .map((item) => item.price)    .reduce((sum, price) => sum + price, 0);}`;const V2 = `function total(items, taxRate) {  const subtotal = items    .map((item) => item.price)    .reduce((sum, price) => sum + price, 0);  return subtotal * (1 + taxRate);}`;const V3 = `function total(items, taxRate) {  const prices = items.map((item) => item.price);  const subtotal = prices.reduce((sum, price) => sum + price, 0);  return subtotal * (1 + taxRate);}`;const BACKGROUND = Color.rgba(22, 22, 29);const INK = Color.hex("#dcdce6");export const scene = Scene.make(	"code edit",	function* () {		const mono = yield* JetBrainsMono;		const block = yield* Code.block({			code: V1,			parser,			theme: Highlight.defaultTheme,			fontSize: 44,			// JetBrains Mono's real metrics — or derive with Metrics.gridFromFont			grid: { charWidth: 0.6, lineHeight: 1.32 },			fontFamily: mono,			fillColor: INK,			position: Entity.vec3({ x: -860, y: 240 }),		});		yield* Motion.wait("1 second");		// add a parameter and capture the intermediate value		yield* Code.editTo(block, V2, {			duration: "900 millis",			timing: "easeInOutCubic",		});		yield* Motion.wait("1400 millis");		// spotlight what the next edit will touch		yield* Code.selectTo(			block,			[{ from: V2.indexOf("const subtotal"), to: V2.indexOf("\n  return") }],			{ duration: "500 millis", background: BACKGROUND },		);		yield* Motion.wait("1 second");		yield* Code.selectTo(block, [{ from: 0, to: V2.length }], {			duration: "400 millis",			background: BACKGROUND,		});		yield* Motion.wait("400 millis");		// extract the mapped prices — watch the chain migrate across lines		yield* Code.editTo(block, V3, {			duration: "900 millis",			timing: "easeInOutCubic",		});		yield* Motion.wait("1600 millis");	},	{ width: 1920, height: 1080, backgroundColor: BACKGROUND },);export const renderLayers = Font.layer(	JetBrainsMono,	Resource.fetchBytes(		"https://cdn.jsdelivr.net/npm/@expo-google-fonts/jetbrains-mono@0.2.3/JetBrainsMono_400Regular.ttf",	),);

On this page