Skip to content
Charts55Components12Visuals14ASCII45
GitHubGet startedGet started
All ASCIIScroll meterInterface
PreviousNext: Dot grid

Lilt draws charts that feel alive, and scenes made of type for the pages people land on.

Every scene is a small world with its own clock. It fills its parent, takes its ink from the text colour, and rests when it scrolls out of sight.

Components are complete pieces rather than primitives: a board that flips, a log that streams, a rail that tells you how the month went.

Copy any of them into your project with the shadcn CLI. The source is yours from then on, to change as you like.

The meter on the right fills as you read. Its leading cell scrambles like a cursor, and while you scroll it tells you how far through you are.

Reduced motion is respected everywhere: scenes hold a still frame, text appears at once, and nothing slides.

That is the end. Scroll back up and watch it drain.

Scroll the article on the stage.

Scroll meter

Interface

A reading meter in type along the edge of the page or a scrolling box. It fills as you read, its leading cell scrambling like a cursor, and shows how far through you are.

Customize 4

Colours
11px
Install & copy sourceInstall & copy sourceSee propsSee props6

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 { AsciiScrollMeter } from '@/components/lilt/ascii/interface/ascii-scroll-meter';

// Once, in your layout: it fixes itself to the edge of the window.
export function Reading() {
  return <AsciiScrollMeter />;
}

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/scroll-meter.json
components/lilt/ascii/interface/ascii-scroll-meter.tsx

ascii-scroll-meter.tsx

'use client';

import { useEffect, useRef, useState, type CSSProperties, type RefObject } from 'react';
import { CODE_GLYPHS, rand } from '../text/text-kit';
import { MONO_STACK, useReducedMotion } from './motion';

export interface AsciiScrollMeterProps {
  /**
   * The element whose scrolling it measures. Default the page, with the meter fixed to the edge of
   * the window; with a target it fills its positioned parent's edge instead.
   */
  target?: RefObject<HTMLElement | null>;
  /** Which edge it runs along. Default 'right'. */
  side?: 'left' | 'right';
  /** Gradient stops the read part takes, top to bottom. */
  colors?: readonly string[];
  /** Glyph for read and unread cells. Default '█' and '·'. */
  read?: string;
  unread?: string;
  /** Show how far through you are beside the head while scrolling. Default true. */
  label?: boolean;
  /** Font size of the cells, in pixels. Default 11. */
  cellSize?: number;
  className?: string;
  style?: CSSProperties;
}

/** Mixes the gradient at `t`, 0 → 1, as a CSS colour. */
const along = (stops: readonly string[], t: number) => {
  if (stops.length <= 1) return stops[0] ?? 'currentColor';
  const k = Math.min(stops.length - 2, Math.floor(t * (stops.length - 1)));
  const f = t * (stops.length - 1) - k;
  return `color-mix(in srgb, ${stops[k]} ${Math.round((1 - f) * 100)}%, ${stops[k + 1]})`;
};

/**
 * A reading meter in type, along the edge of the page or of a scrolling box. It fills with solid
 * cells as you read, the leading cell scrambling like a cursor, and shows how far through you are
 * beside it while you scroll, then fades back.
 */
export function AsciiScrollMeter({
  target,
  side = 'right',
  colors = ['#7c5cff', '#e5489c', '#ffb36b'],
  read = '█',
  unread = '·',
  label = true,
  cellSize = 11,
  className,
  style,
}: AsciiScrollMeterProps) {
  const ref = useRef<HTMLDivElement>(null);
  const reduced = useReducedMotion();
  const [progress, setProgress] = useState(0);
  const [cells, setCells] = useState(0);
  const [moving, setMoving] = useState(false);
  const [tick, setTick] = useState(0);

  useEffect(() => {
    const scroller = target?.current ?? null;
    let still = 0;
    const measure = () => {
      const el = scroller ?? document.scrollingElement ?? document.documentElement;
      const room = el.scrollHeight - el.clientHeight;
      setProgress(room > 0 ? Math.min(1, Math.max(0, el.scrollTop / room)) : 0);
    };
    const onScroll = () => {
      measure();
      setMoving(true);
      setTick((n) => n + 1);
      window.clearTimeout(still);
      still = window.setTimeout(() => setMoving(false), 900);
    };
    const source: HTMLElement | Window = scroller ?? window;
    source.addEventListener('scroll', onScroll, { passive: true });
    measure();
    const sized = new ResizeObserver(() => {
      const h = ref.current?.getBoundingClientRect().height ?? 0;
      setCells(Math.max(4, Math.floor(h / (cellSize * 1.2))));
      measure();
    });
    if (ref.current) sized.observe(ref.current);
    return () => {
      source.removeEventListener('scroll', onScroll);
      sized.disconnect();
      window.clearTimeout(still);
    };
  }, [target, cellSize]);

  const head = Math.min(cells - 1, Math.floor(progress * cells));
  return (
    <div
      ref={ref}
      aria-hidden="true"
      className={className}
      style={{
        position: target ? 'absolute' : 'fixed',
        top: 8,
        bottom: 8,
        [side]: 6,
        width: cellSize,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        fontFamily: MONO_STACK,
        fontSize: cellSize,
        lineHeight: 1.2,
        pointerEvents: 'none',
        zIndex: 20,
        ...style,
      }}
    >
      {Array.from({ length: cells }, (_, i) => {
        const done = i < head || progress >= 1;
        const isHead = i === head && progress > 0 && progress < 1;
        const glyph =
          isHead && !reduced
            ? CODE_GLYPHS[Math.floor(rand(i, tick, 3) * CODE_GLYPHS.length)]
            : done
              ? read
              : unread;
        return (
          <span
            key={i}
            style={{
              color: done || isHead ? along(colors, i / Math.max(1, cells - 1)) : 'currentColor',
              opacity: done || isHead ? 1 : 0.3,
            }}
          >
            {glyph}
          </span>
        );
      })}
      {label && cells ? (
        <span
          style={{
            position: 'absolute',
            top: `${(head / cells) * 100}%`,
            [side === 'right' ? 'right' : 'left']: cellSize + 6,
            padding: '1px 6px',
            borderRadius: 4,
            background: 'color-mix(in srgb, currentColor 10%, transparent)',
            whiteSpace: 'nowrap',
            opacity: moving ? 1 : 0,
            transform: moving ? 'none' : `translateX(${side === 'right' ? 4 : -4}px)`,
            transition: 'opacity 240ms, transform 240ms',
          }}
        >
          {Math.round(progress * 100)}%
        </span>
      ) : null}
    </div>
  );
}
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);
}
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)}`;
}

Usage

How it behaves.

The scene fills its parent, so give the parent a size. The canvas takes its type from CSS font-family and its ink from color. It pauses off screen and in hidden tabs, and shows one still frame when the reader prefers reduced motion.

Props6

Every option.

Pass these directly to AsciiScrollMeter.

PropTypeDefaultWhat it does
targetRefObject<HTMLElement | null>the pageThe element whose scrolling it measures. With one, it fills the edge of its positioned parent instead of the window.
read, unreadstring'█', '·'Glyphs for read and unread cells.
sidestring'right'Which edge it runs along.
colorsstring[]['#7c5cff', '#e5489c', '#ffb36b']Gradient stops the read part takes, top to bottom.
labelbooleantrueShow how far through you are beside the head while scrolling.
cellSizenumber11Font size of the cells, in pixels.
Previous sceneDissolve imageNext sceneDot grid

Ready when your data is. Start with one install.

Install a package, import the stylesheet once, and drop in a card or a scene.

Read the guideRead the guideView on GitHubView on GitHub
ChartsAll chartsAll chartsFinanceFinanceCustomizeCustomizeFeaturesFeatures
ComponentsAll componentsAll componentsAIAIStatusStatusActionsActionsDataData
VisualsAll visualsAll visualsAIAIDataDataSecuritySecurityProductProduct
ASCIIAll scenesAll scenesTextTextInterfaceInterfaceBackgroundsBackgroundsMediaMediaDataData
DocsGetting startedGetting startedAPI referenceAPI referenceMotion & accessibilityMotion & accessibilityllms.txtllms.txt
React components with a little lilt.GitHubGitHubnpmnpm