The stage changes the board every few seconds. Type your own text to send it there.
Live code
As tuned above.
Every control in the inspector updates this snippet directly. Defaults are omitted to keep your markup minimal.
example.tsx
import { useEffect, useState } from 'react';
import { AsciiSplitFlap } from '@/components/lilt/ascii/text/ascii-split-flap';
const BOARD = ['LILT UI\nON TIME', 'CHARTS\nBOARDING'];
export function Departures() {
const [i, setI] = useState(0);
useEffect(() => {
const timer = setInterval(() => setI((n) => n + 1), 4000);
return () => clearInterval(timer);
}, []);
return <AsciiSplitFlap text={BOARD[i % BOARD.length]} length={8} />;
}
Installation3
Source you own.
This is source, not a package: the shadcn CLI copies it into your project with the shared pieces it needs. Its only dependency is React.
npx shadcn@latest add https://liltui.vercel.app/r/split-flap.jsoncomponents/lilt/ascii/text/ascii-split-flap.tsx
ascii-split-flap.tsx
'use client';
import {
createElement,
useEffect,
useLayoutEffect,
useRef,
useState,
type CSSProperties,
type ElementType,
} from 'react';
import { MONO_STACK } from '../interface/motion';
import { VISUALLY_HIDDEN, useReducedMotion } from './text-kit';
export interface AsciiSplitFlapProps {
/** What the board shows. Each line break starts a new row. Default 'DEPARTURES'. */
text?: string;
/** Tiles a row; shorter lines are padded with blanks. Default the longest line. */
length?: number;
/** The order the flaps turn through. Every letter goes the long way round to its own. */
characters?: string;
/** Seconds each flap takes to fall. Default 0.06. */
speed?: number;
/** Colour of the tiles. Default near black. */
tile?: string;
/** Colour of the characters. Default warm white. */
ink?: string;
/** The element to render, such as 'h1' or 'p'. Default 'div'. */
as?: ElementType;
className?: string;
style?: CSSProperties;
}
export const FLAP_CHARACTERS = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,:!?-/&+';
interface FlapProps {
target: string;
characters: string;
speed: number;
delay: number;
reduced: boolean;
tile: string;
ink: string;
}
const HALF: CSSProperties = {
position: 'absolute',
left: 0,
right: 0,
height: '50%',
overflow: 'hidden',
backfaceVisibility: 'hidden',
};
/** One half of a character: the top or the bottom of it, cut at the tile's hinge. */
function Half({
char,
part,
tile,
style,
}: {
char: string;
part: 'top' | 'bottom';
tile: string;
style?: CSSProperties;
}) {
return (
<span
style={{
...HALF,
...(part === 'top'
? { top: 0, borderRadius: '0.12em 0.12em 0 0' }
: { bottom: 0, borderRadius: '0 0 0.12em 0.12em' }),
background: tile,
...style,
}}
>
<span
style={{
position: 'absolute',
left: 0,
right: 0,
height: '200%',
top: part === 'top' ? 0 : '-100%',
display: 'grid',
placeItems: 'center',
}}
>
{char === ' ' ? ' ' : char}
</span>
</span>
);
}
/**
* One tile. Given a new character it turns through the alphabet to it, a flap at a time: the top
* half of the old character falls away to show the new one behind it, and the bottom half of the
* new one swings down over the old.
*/
function Flap({ target, characters, speed, delay, reduced, tile, ink }: FlapProps) {
const [shown, setShown] = useState(reduced ? target : ' ');
const [previous, setPrevious] = useState(' ');
const [turns, setTurns] = useState(0);
const falling = useRef<HTMLSpanElement>(null);
const landing = useRef<HTMLSpanElement>(null);
useEffect(() => {
if (reduced) {
setShown(target);
setPrevious(target);
return;
}
let current = shown;
let timer = 0;
const want = characters.includes(target) ? target : ' ';
const step = () => {
if (current === want) return;
const index = characters.indexOf(current);
const next = characters[(index + 1) % characters.length] ?? ' ';
setPrevious(current);
setShown(next);
setTurns((n) => n + 1);
current = next;
timer = window.setTimeout(step, speed * 1000);
};
timer = window.setTimeout(step, delay * 1000);
return () => window.clearTimeout(timer);
// `shown` is read once as the starting point; it must not restart the run.
}, [target, characters, speed, delay, reduced]);
// Each turn plays its fall before the frame paints, so the new character never pops in.
useLayoutEffect(() => {
if (!turns || reduced) return;
const duration = speed * 1000;
falling.current?.animate?.(
[
{ transform: 'rotateX(0deg)', filter: 'brightness(1)' },
{ transform: 'rotateX(-90deg)', filter: 'brightness(0.6)' },
],
{ duration: duration / 2, easing: 'ease-in', fill: 'forwards' },
);
landing.current?.animate?.(
[
{ transform: 'rotateX(90deg)', filter: 'brightness(1.3)' },
{ transform: 'rotateX(90deg)', filter: 'brightness(1.3)', offset: 0.5 },
{ transform: 'rotateX(0deg)', filter: 'brightness(1)' },
],
{ duration, easing: 'ease-out', fill: 'forwards' },
);
}, [turns, speed, reduced]);
return (
<span
style={{
position: 'relative',
display: 'inline-block',
width: '0.95em',
height: '1.4em',
margin: '0 0.05em',
color: ink,
perspective: '3em',
boxShadow: '0 0.08em 0.16em rgb(0 0 0 / 0.35)',
borderRadius: '0.12em',
}}
>
<Half char={shown} part="top" tile={tile} />
<Half char={reduced ? shown : previous} part="bottom" tile={tile} />
{reduced ? null : (
<>
<span ref={falling} style={{ ...HALF, top: 0, transformOrigin: 'bottom', zIndex: 2 }}>
<Half char={previous} part="top" tile={tile} style={{ height: '100%' }} />
</span>
<span
ref={landing}
style={{
...HALF,
bottom: 0,
transformOrigin: 'top',
zIndex: 2,
transform: 'rotateX(90deg)',
}}
>
<Half char={shown} part="bottom" tile={tile} style={{ height: '100%' }} />
</span>
</>
)}
{/* The hinge: a hairline across the middle of the tile. */}
<span
aria-hidden="true"
style={{
position: 'absolute',
left: 0,
right: 0,
top: 'calc(50% - 0.5px)',
height: 1,
background: 'rgb(0 0 0 / 0.55)',
zIndex: 3,
}}
/>
</span>
);
}
/**
* A split-flap board, like a station's departures. Change the text and every tile turns through
* the alphabet to its new character, a flap at a time and a beat after its neighbour, with the
* clatter you can almost hear. Screen readers get the text itself.
*/
export function AsciiSplitFlap({
text = 'DEPARTURES',
length,
characters = FLAP_CHARACTERS,
speed = 0.06,
tile = '#1b1b1f',
ink = '#f5f1e6',
as = 'div',
className,
style,
}: AsciiSplitFlapProps) {
const reduced = useReducedMotion();
const lines = text.toUpperCase().split('\n');
const width = Math.max(1, length ?? Math.max(...lines.map((line) => line.length)));
const set = characters.length > 1 ? characters : FLAP_CHARACTERS;
return createElement(
as,
{
className,
style: { fontFamily: MONO_STACK, fontWeight: 600, lineHeight: 1, ...style },
},
<span style={VISUALLY_HIDDEN}>{text}</span>,
<span aria-hidden="true" style={{ display: 'inline-grid', gap: '0.12em' }}>
{lines.map((line, row) => (
<span key={row} style={{ display: 'flex', whiteSpace: 'nowrap' }}>
{Array.from({ length: width }, (_, col) => (
<Flap
key={col}
target={line[col] ?? ' '}
characters={set}
speed={Math.max(0.02, speed)}
delay={col * 0.035 + row * 0.08}
reduced={reduced}
tile={tile}
ink={ink}
/>
))}
</span>
))}
</span>,
);
}
components/lilt/ascii/interface/motion.tsascii-motion
motion.ts
import { useEffect, useState } from 'react';
/** True when the reader asks for less motion. False on the server and before the first effect. */
export function useReducedMotion() {
const [reduced, setReduced] = useState(false);
useEffect(() => {
if (typeof window.matchMedia !== 'function') return;
const query = window.matchMedia('(prefers-reduced-motion: reduce)');
const update = () => setReduced(query.matches);
update();
query.addEventListener('change', update);
return () => query.removeEventListener('change', update);
}, []);
return reduced;
}
/**
* Seconds since the clock started, re-rendering at most `fps` times a second while `running`.
* Stopped, it costs nothing and holds its last value.
*/
export function useClock(running: boolean, fps = 30) {
const [time, setTime] = useState(0);
useEffect(() => {
if (!running) return;
let raf = 0;
let last = -1;
const start = performance.now();
const tick = (now: number) => {
// A frame's timestamp can fall a little before the clock started; time never runs back.
const t = Math.max(0, (now - start) / 1000);
const frame = Math.floor(t * fps);
if (frame !== last) {
last = frame;
setTime(t);
}
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [running, fps]);
return time;
}
/** A monospace stack for components that set their own type. */
export const MONO_STACK =
'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';
/**
* The font a canvas overlay draws its glyphs in: the element's own family when it is monospace,
* otherwise a monospace stack at the element's size, so glyphs always sit on a grid.
*/
export function monoFont(ctx: CanvasRenderingContext2D, element: Element, weight = 500) {
const css = getComputedStyle(element);
const size = parseFloat(css.fontSize) || 14;
const own = `${weight} ${size}px ${css.fontFamily || 'monospace'}`;
ctx.font = own;
const mono = Math.abs(ctx.measureText('i').width - ctx.measureText('M').width) < 0.01;
const font = mono ? own : `${weight} ${size}px ${MONO_STACK}`;
ctx.font = font;
return { font, size, cw: Math.max(4, ctx.measureText('M').width) };
}
/** Sizes a canvas's backing store to its box at the device's pixel ratio, capped at 2. */
export function fitCanvas(canvas: HTMLCanvasElement, width: number, height: number) {
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const w = Math.max(1, Math.round(width * dpr));
const h = Math.max(1, Math.round(height * dpr));
if (canvas.width !== w) canvas.width = w;
if (canvas.height !== h) canvas.height = h;
return dpr;
}
/** Mixes two `#rrggbb` colours; anything else returns the nearer one unchanged. */
export function mixHex(a: string, b: string, t: number) {
const pa = /^#([0-9a-f]{6})$/i.exec(a);
const pb = /^#([0-9a-f]{6})$/i.exec(b);
if (!pa || !pb) return t < 0.5 ? a : b;
const na = parseInt(pa[1]!, 16);
const nb = parseInt(pb[1]!, 16);
const ch = (shift: number) =>
Math.round(((na >> shift) & 255) * (1 - t) + ((nb >> shift) & 255) * t);
return `#${((1 << 24) | (ch(16) << 16) | (ch(8) << 8) | ch(0)).toString(16).slice(1)}`;
}
components/lilt/ascii/text/text-kit.tsascii-text-kit
text-kit.ts
'use client';
import {
useEffect,
useState,
useSyncExternalStore,
type CSSProperties,
type RefObject,
} from 'react';
/** Hides text from sight but keeps it for screen readers, copy and find-in-page. */
export const VISUALLY_HIDDEN: CSSProperties = {
position: 'absolute',
width: 1,
height: 1,
padding: 0,
margin: -1,
overflow: 'hidden',
clip: 'rect(0 0 0 0)',
clipPath: 'inset(50%)',
whiteSpace: 'nowrap',
border: 0,
};
/** Characters text scrambles through: code-like, so the decode reads as computing. */
export const CODE_GLYPHS = '01<>/\\{}[]#$%&*+=?~';
/** A stable pseudo-random number in [0, 1) for a pair of integers and a salt. */
export function rand(a: number, b: number, salt = 0): number {
let h =
Math.imul(a | 0, 0x27d4eb2d) ^ Math.imul(b | 0, 0x165667b1) ^ Math.imul(salt | 0, 0x9e3779b1);
h = Math.imul(h ^ (h >>> 15), 0x85ebca6b);
h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}
const REDUCED = '(prefers-reduced-motion: reduce)';
function subscribeReduced(onChange: () => void) {
if (typeof window === 'undefined' || !window.matchMedia) return () => undefined;
const query = window.matchMedia(REDUCED);
query.addEventListener?.('change', onChange);
return () => query.removeEventListener?.('change', onChange);
}
const readReduced = () =>
typeof window !== 'undefined' && !!window.matchMedia && window.matchMedia(REDUCED).matches;
/** True when the reader prefers reduced motion. False on the server. */
export function useReducedMotion(): boolean {
return useSyncExternalStore(subscribeReduced, readReduced, () => false);
}
/**
* Becomes true the first time the element scrolls into view, and stays true. Without an
* IntersectionObserver (old browsers, tests) it is true at once.
*/
export function useSeen(ref: RefObject<Element | null>, enabled = true): boolean {
const [seen, setSeen] = useState(false);
useEffect(() => {
if (!enabled || seen) return;
const el = ref.current;
if (!el || typeof IntersectionObserver === 'undefined') {
setSeen(true);
return;
}
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
setSeen(true);
observer.disconnect();
}
},
{ threshold: 0.35 },
);
observer.observe(el);
return () => observer.disconnect();
}, [ref, enabled, seen]);
return seen;
}
/** requestAnimationFrame, or a 60 Hz timer where there is none. Returns a cancel function. */
export function frame(callback: (now: number) => void): () => void {
if (typeof requestAnimationFrame === 'function') {
const id = requestAnimationFrame(callback);
return () => cancelAnimationFrame(id);
}
const id = setTimeout(() => callback(performance.now()), 16);
return () => clearTimeout(id);
}
Usage
How it behaves.
The board is real text in the reader’s monospace face, sized by `font-size`, so it scales with whatever it sits in. Every tile turns forward through `characters` to its letter, the way a real board does, so a change can take a moment; pass a shorter set to make it quicker. Characters it does not have show as blanks. Screen readers get the text once, not the flaps.
Props7
Every option.
Pass these directly to AsciiSplitFlap.
| Prop | Type | Default | What it does |
|---|---|---|---|
length | number | the longest line | Tiles a row; shorter lines are padded with blanks. Fix it so the board keeps its width as the text changes. |
characters | string | ' A–Z 0–9 .,:!?-/&+' | The order the flaps turn through. |
as | ElementType | 'div' | The element to render, such as 'h1' or 'p'. |
text | string | 'DEPARTURES' | What the board shows. A line break starts a new row. |
speed | number | 0.06 | Seconds each flap takes to fall. |
tile | string | '#1b1b1f' | Colour of the tiles. |
ink | string | '#f5f1e6' | Colour of the characters. |