Skip to content
Charts55Components12Visuals14ASCII45
GitHubGet startedGet started
All ASCIIGhost cursorsInterface
PreviousNext: Dissolve image

Watch a cold ghost rush to a fire. Your own pointer feels the cold too: warm it by a fire, and do not hold it there too long.

Ghost cursors

Interface

Company for a hero: a few ghost cursors that wander it as if reading. Out in the cold they slowly freeze, shiver, and hurry to the nearest fire, where they circle until they are cosy again.

Customize 5

3
18
#a9d8ff
#ffb22e
Install & copy sourceInstall & copy sourceSee propsSee props8

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 { CursorGhosts } from '@/components/lilt/ascii/interface/cursor-ghosts';

// Inside a positioned area. Mark each fire with data-lilt-fire; the ghosts warm up there.
export function Hero() {
  return (
    <section style={{ position: 'relative', height: 560 }}>
      <span
        data-lilt-fire=""
        style={{ position: 'absolute', left: '20%', bottom: '10%', width: 96, height: 96 }}
      />
      <CursorGhosts avoid="h1" />
      <h1>Come in from the cold</h1>
    </section>
  );
}

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/ghost-cursors.json
components/lilt/ascii/interface/cursor-ghosts.tsx

cursor-ghosts.tsx

'use client';

import { useEffect, useRef } from 'react';
import {
  createGhost,
  ghostReading,
  seededRandom,
  stepGhost,
  type Ghost,
  type GhostFire,
  type GhostRect,
  type GhostTone,
  type GhostWorld,
} from './ghost-walk';
import { fitCanvas, MONO_STACK, useReducedMotion } from './motion';

export interface CursorGhostsProps {
  /** How many ghosts share the area at once. Default 3. */
  count?: number;
  /**
   * What counts as a fire: elements inside the area matching this selector. Ghosts that get cold
   * hurry to the nearest one. Default `[data-lilt-fire]`, the same marks `CursorWarmth` warms at.
   */
  fires?: string;
  /** Elements inside the area that wandering ghosts keep clear of, such as a headline. */
  avoid?: string;
  /** Roughly how many seconds a warm ghost takes to freeze; each one differs a little. Default 18. */
  chill?: number;
  /** Show a small reading beside a ghost when it shivers, rushes or warms up. Default true. */
  readings?: boolean;
  /** Colour of the frost and of a cold reading. Default an icy blue. */
  frost?: string;
  /** Colour of the embers and of a warm reading. Default amber. */
  ember?: string;
  /** Seed for the ghosts' wandering, to replay the same walk. Default a new one each visit. */
  seed?: number;
}

/** The arrow, as `CursorWarmth` draws a burnt one, with its tip at (4, 3) in a 24 box. */
const ARROW = 'M3.5 2.5v16.2l4.3-4 2.9 6.1 2.6-1.2-2.8-6h6.1z';
const SCALE = 0.95;
const HOT = '#ff5a36';
/** Seconds between ghosts: one leaves, and a little later someone else wanders in. */
const ARRIVAL_GAP = [2, 7] as const;

interface Puff {
  x: number;
  y: number;
  age: number;
}

interface Slot {
  ghost: Ghost | null;
  /** Seconds until the next ghost arrives in an empty slot. */
  wait: number;
  breathOwed: number;
  shakeAt: number;
  shakeX: number;
  shakeY: number;
  /** How much of the reading shows, 0 to 1, so it fades rather than blinks. */
  say: number;
  said: { text: string; tone: GhostTone } | null;
}

/**
 * Other visitors' pointers, imagined: a few ghost cursors that wander an area such as a hero,
 * pausing as if reading. Away from a fire they slowly get cold; once one is freezing it shivers,
 * says so, and hurries to the nearest fire (any element inside marked `data-lilt-fire`), where it
 * circles until it is cosy again. Now and then one finds it too hot and darts off. After a while
 * each one wanders out and someone new arrives. It fills its positioned parent on one canvas that
 * never takes the pointer, rests while the area is out of view or the tab is hidden, and shows
 * nothing with reduced motion. Pair it with `CursorWarmth` so the reader's own pointer feels the
 * cold too.
 */
export function CursorGhosts({
  count = 3,
  fires = '[data-lilt-fire]',
  avoid,
  chill = 18,
  readings = true,
  frost = '#a9d8ff',
  ember = '#ffb22e',
  seed,
}: CursorGhostsProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const reduced = useReducedMotion();
  const settings = useRef({ fires, avoid, chill, readings, frost, ember });
  settings.current = { fires, avoid, chill, readings, frost, ember };

  useEffect(() => {
    const canvas = canvasRef.current;
    const area = canvas?.parentElement;
    const ctx = canvas?.getContext('2d');
    if (!canvas || !area || !ctx) return;
    if (reduced) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      return;
    }
    const rand = seededRandom(seed ?? Math.floor(Math.random() * 2 ** 31));
    const arrow = typeof Path2D === 'function' ? new Path2D(ARROW) : null;
    const world: GhostWorld = { width: 1, height: 1, fires: [], avoid: [] };
    let worldAt = -Infinity;
    let dpr = 1;
    let ink = '#e8e6f2';
    let raf = 0;
    let last = -1;
    let time = 0;
    let visible = false;
    const puffs: Puff[] = [];
    const slots: Slot[] = Array.from({ length: Math.max(0, Math.round(count)) }, () => ({
      ghost: null,
      wait: 0,
      breathOwed: 0,
      shakeAt: 0,
      shakeX: 0,
      shakeY: 0,
      say: 0,
      said: null,
    }));

    const measure = () => {
      const box = area.getBoundingClientRect();
      const local = (element: Element): GhostRect => {
        const r = element.getBoundingClientRect();
        return {
          left: r.left - box.left,
          top: r.top - box.top,
          right: r.right - box.left,
          bottom: r.bottom - box.top,
        };
      };
      world.width = Math.max(1, box.width);
      world.height = Math.max(1, box.height);
      const s = settings.current;
      world.fires = [...area.querySelectorAll(s.fires)].flatMap((element): GhostFire[] => {
        const r = local(element);
        const w = r.right - r.left;
        const h = r.bottom - r.top;
        if (!w) return [];
        return [{ x: r.left + w / 2, y: r.top + h / 2, reach: Math.max(w, h) * 1.2 }];
      });
      world.avoid = s.avoid ? [...area.querySelectorAll(s.avoid)].map(local) : [];
      ink = getComputedStyle(canvas).color || ink;
      dpr = fitCanvas(canvas, world.width, world.height);
      worldAt = time;
    };

    const arrive = (slot: Slot, inside: boolean, temp?: number) => {
      const ghost = createGhost(world, rand, { inside, temp });
      // Each ghost feels the cold a little differently around the chosen pace.
      ghost.chill = settings.current.chill * (0.7 + rand() * 0.6);
      slot.ghost = ghost;
    };

    measure();
    // The page opens with company: one ghost already cold, so the rush to the fire comes soon,
    // and the rest already about or on their way in.
    slots.forEach((slot, k) => {
      if (k === 0) arrive(slot, true, 0.2);
      else if (k % 2) arrive(slot, true);
      else slot.wait = k * 1.5;
    });

    const draw = () => {
      const s = settings.current;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      ctx.clearRect(0, 0, world.width, world.height);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.font = `600 11px ${MONO_STACK}`;
      for (const puff of puffs) {
        const t = puff.age / 1.4;
        ctx.globalAlpha = (1 - t) * 0.45;
        ctx.fillStyle = '#e6ecfb';
        ctx.fillText(t < 0.3 ? 'o' : t < 0.65 ? '°' : '.', puff.x, puff.y);
      }
      for (const slot of slots) {
        const ghost = slot.ghost;
        if (!ghost) continue;
        const x = ghost.x + slot.shakeX;
        const y = ghost.y + slot.shakeY;
        const fade = ghost.alpha;
        const cold = Math.min(1, Math.max(0, (0.5 - ghost.temp) / 0.5));
        // Frost closes in round a cold ghost, as round a cold pointer, a little smaller.
        const crystals = Math.round(cold * 6);
        const r = 19 - cold * 6;
        ctx.fillStyle = s.frost;
        for (let k = 0; k < crystals; k++) {
          const a = (k / 6) * Math.PI * 2 + time * 0.35;
          ctx.globalAlpha = (0.3 + cold * 0.5) * fade;
          ctx.fillText(k % 2 ? '+' : '*', x + 3 + Math.cos(a) * r, y + 5 + Math.sin(a) * r);
        }
        // Embers circle one warming by a fire.
        if (ghost.warmth > 0.05 && ghost.temp > 0.55) {
          const glow = Math.min(1, (ghost.temp - 0.55) / 0.45);
          ctx.fillStyle = ghost.scorched > 0 ? HOT : s.ember;
          for (let k = 0; k < 3; k++) {
            const a = (k / 3) * Math.PI * 2 - time * (1 + ghost.warmth * 2);
            ctx.globalAlpha = glow * 0.75 * fade;
            ctx.fillText(k ? '.' : '*', x + 3 + Math.cos(a) * 14, y + 5 + Math.sin(a) * 14);
          }
        }
        if (arrow) {
          ctx.save();
          ctx.translate(x, y);
          ctx.scale(SCALE, SCALE);
          ctx.translate(-4, -3);
          ctx.globalAlpha = 0.86 * fade;
          ctx.fillStyle = ink;
          ctx.fill(arrow);
          // A cold ghost takes on the frost's colour; a warm one by the fire, the ember's.
          const tint = Math.max(cold, ghost.warmth > 0.05 ? (ghost.temp - 0.6) / 0.4 : 0);
          if (tint > 0) {
            ctx.globalAlpha = Math.min(1, tint) * 0.65 * fade;
            ctx.fillStyle = cold > 0 ? s.frost : ghost.scorched > 0 ? HOT : s.ember;
            ctx.fill(arrow);
          }
          ctx.globalAlpha = 0.5 * fade;
          ctx.lineWidth = 1.1;
          ctx.lineJoin = 'round';
          ctx.strokeStyle = 'rgb(10 10 16 / 0.7)';
          ctx.stroke(arrow);
          ctx.restore();
        }
        if (slot.say > 0.01 && slot.said) {
          // The reading, in a small pill of dark glass beside the arrow.
          const tone =
            slot.said.tone === 'hot' ? HOT : slot.said.tone === 'frost' ? s.frost : s.ember;
          ctx.font = `500 10px ${MONO_STACK}`;
          const w = ctx.measureText(slot.said.text).width + 20;
          const left = x + 14 + w < world.width - 4 ? x + 14 : x - 14 - w;
          const top = y + 12;
          ctx.globalAlpha = slot.say * fade;
          ctx.fillStyle = 'rgb(16 14 24 / 0.62)';
          ctx.beginPath();
          ctx.roundRect(left, top, w, 18, 9);
          ctx.fill();
          ctx.strokeStyle = 'rgb(255 255 255 / 0.1)';
          ctx.lineWidth = 1;
          ctx.stroke();
          ctx.fillStyle = tone;
          ctx.beginPath();
          ctx.arc(left + 8, top + 9, 2, 0, Math.PI * 2);
          ctx.fill();
          ctx.textAlign = 'left';
          ctx.fillText(slot.said.text, left + 13, top + 9.5);
          ctx.textAlign = 'center';
          ctx.font = `600 11px ${MONO_STACK}`;
        }
      }
      ctx.globalAlpha = 1;
    };

    const frame = (now: number) => {
      const dt = last < 0 ? 0 : Math.min(0.1, (now - last) / 1000);
      last = now;
      time += dt;
      // Layout can shift under the area (fonts, a resize); look again every second.
      if (time - worldAt > 1) measure();
      for (const slot of slots) {
        const ghost = slot.ghost;
        if (!ghost) {
          slot.wait -= dt;
          if (slot.wait <= 0) arrive(slot, false);
          continue;
        }
        stepGhost(ghost, dt, world, rand);
        if (ghost.phase === 'gone') {
          slot.ghost = null;
          slot.wait = ARRIVAL_GAP[0] + rand() * (ARRIVAL_GAP[1] - ARRIVAL_GAP[0]);
          slot.say = 0;
          continue;
        }
        // A cold ghost's breath shows, faster the colder it is.
        if (ghost.temp < 0.4) {
          slot.breathOwed += dt / (0.8 + ghost.temp * 1.8);
          while (slot.breathOwed >= 1) {
            slot.breathOwed -= 1;
            if (puffs.length < 40) puffs.push({ x: ghost.x + 9, y: ghost.y - 6, age: 0 });
          }
        } else slot.breathOwed = 0;
        // A freezing ghost trembles, a small uneven shake a few times a second.
        const shiver = ghost.phase === 'shiver' ? 1 : Math.max(0, (0.15 - ghost.temp) / 0.15);
        if (shiver > 0 && time - slot.shakeAt > 0.035) {
          slot.shakeAt = time;
          const amp = 0.6 + shiver * 1.8;
          slot.shakeX = (rand() * 2 - 1) * amp;
          slot.shakeY = (rand() * 2 - 1) * amp * 0.6;
        } else if (shiver === 0) {
          slot.shakeX = 0;
          slot.shakeY = 0;
        }
        const reading = settings.current.readings ? ghostReading(ghost) : null;
        if (reading) slot.said = reading;
        slot.say = Math.min(1, Math.max(0, slot.say + dt * (reading ? 5 : -2.5)));
      }
      for (let i = puffs.length - 1; i >= 0; i--) {
        const puff = puffs[i]!;
        puff.age += dt;
        puff.y -= dt * 16;
        puff.x += dt * 12;
        if (puff.age > 1.4) puffs.splice(i, 1);
      }
      draw();
      raf = requestAnimationFrame(frame);
    };

    // Runs only while the area is on screen and the tab is showing; time away is not counted.
    const update = () => {
      const run = visible && document.visibilityState === 'visible';
      if (run && !raf) {
        last = -1;
        measure();
        raf = requestAnimationFrame(frame);
      } else if (!run && raf) {
        cancelAnimationFrame(raf);
        raf = 0;
      }
    };
    const seen = new IntersectionObserver(([entry]) => {
      visible = entry?.isIntersecting ?? false;
      update();
    });
    seen.observe(area);
    const resized = new ResizeObserver(() => {
      measure();
      if (!raf) draw();
    });
    resized.observe(area);
    document.addEventListener('visibilitychange', update);

    return () => {
      cancelAnimationFrame(raf);
      seen.disconnect();
      resized.disconnect();
      document.removeEventListener('visibilitychange', update);
    };
  }, [count, seed, reduced]);

  return (
    <canvas
      ref={canvasRef}
      aria-hidden="true"
      className="lilt-cursor-ghosts"
      style={{
        position: 'absolute',
        inset: 0,
        width: '100%',
        height: '100%',
        pointerEvents: 'none',
      }}
    />
  );
}
components/lilt/ascii/interface/ghost-walk.ts

ghost-walk.ts

/**
 * How a ghost cursor behaves: a pretend visitor's pointer that wanders the area and pauses as if
 * reading, slowly gets cold, shivers once it is freezing, then hurries to the nearest fire and
 * circles it until it is warm again. Now and then one lingers too long, finds it too hot and darts
 * off. After a while each one wanders out of an edge and another arrives. Pure and seeded, so a
 * host only steps it and draws it.
 */

export interface GhostFire {
  /** The heart of the fire, in the area's pixels. */
  x: number;
  y: number;
  /** How far its warmth carries, in pixels. */
  reach: number;
}

export interface GhostRect {
  left: number;
  top: number;
  right: number;
  bottom: number;
}

export interface GhostWorld {
  width: number;
  height: number;
  fires: readonly GhostFire[];
  /** Places a wandering ghost keeps clear of, such as a headline. */
  avoid: readonly GhostRect[];
}

export type GhostPhase = 'wander' | 'shiver' | 'rush' | 'warm' | 'leave' | 'gone';

export interface Ghost {
  x: number;
  y: number;
  vx: number;
  vy: number;
  /** Where it is heading. */
  tx: number;
  ty: number;
  /** 0 frozen to 1 fully warm. */
  temp: number;
  /** How warm the spot it is in is, 0 to 1, as of its last step. */
  warmth: number;
  phase: GhostPhase;
  /** Seconds left of a pause, a shiver or a linger by the fire. */
  timer: number;
  /** The fire it is heading for or circling. */
  fire: number;
  /** Where it is round the fire, in radians. */
  angle: number;
  /** Seconds a warm ghost takes to freeze. */
  chill: number;
  /** Seconds left before it heads out. */
  stay: number;
  /** Seconds left of "too hot!" after it darts from a fire. */
  scorched: number;
  /** Seconds since it arrived, for the curve of its path. */
  age: number;
  /** 0 to 1, how much it has faded in. */
  alpha: number;
}

/** Seconds a frozen ghost takes to thaw right by a fire, as for a real pointer. */
const THAW = 3;
/** Below this it freezes: it shivers, then rushes to a fire. */
const FREEZING = 0.14;
/** Readings run from −12° frozen to 24° fully warm, as for a real pointer. */
const COLDEST = -12;
const WARMEST = 24;

const between = (rand: () => number, lo: number, hi: number) => lo + rand() * (hi - lo);

/** How warm a spot is, 0 to 1: the nearest fire's warmth, falling off over its reach. */
export function warmthAt(world: GhostWorld, x: number, y: number) {
  let most = 0;
  for (const fire of world.fires) {
    const d = Math.hypot(x - fire.x, y - fire.y);
    most = Math.max(most, Math.max(0, 1 - d / fire.reach) ** 1.3);
  }
  return most;
}

/** A place to wander to: in the sky, clear of anything to avoid and out of the fires' warmth. */
export function pickSpot(world: GhostWorld, rand: () => number) {
  const { width, height } = world;
  let x = width / 2;
  let y = height / 3;
  for (let tries = 0; tries < 16; tries++) {
    x = between(rand, 0.06, 0.94) * width;
    y = between(rand, 0.08, 0.78) * height;
    const blocked = world.avoid.some(
      (box) => x > box.left - 24 && x < box.right + 24 && y > box.top - 24 && y < box.bottom + 24,
    );
    if (!blocked && warmthAt(world, x, y) === 0) break;
  }
  return { x, y };
}

/**
 * A new ghost. `inside` places it in the area already (fading in), for the first ones on a page;
 * otherwise it comes in from a side or the top. `temp` sets how warm it arrives.
 */
export function createGhost(
  world: GhostWorld,
  rand: () => number,
  { inside = false, temp }: { inside?: boolean; temp?: number } = {},
): Ghost {
  const spot = pickSpot(world, rand);
  let x = spot.x;
  let y = spot.y;
  if (!inside) {
    const edge = rand();
    if (edge < 0.4) x = -20;
    else if (edge < 0.8) x = world.width + 20;
    else y = -20;
  }
  const target = pickSpot(world, rand);
  return {
    x,
    y,
    vx: 0,
    vy: 0,
    tx: target.x,
    ty: target.y,
    temp: temp ?? between(rand, 0.3, 0.85),
    warmth: 0,
    phase: 'wander',
    timer: 0,
    fire: 0,
    angle: 0,
    chill: between(rand, 12, 22),
    stay: between(rand, 35, 80),
    scorched: 0,
    age: rand() * 10,
    alpha: 0,
  };
}

/** Eases the ghost toward its target, no faster than `speed` pixels a second, with a hand's curve. */
function steer(ghost: Ghost, dt: number, speed: number, grip: number) {
  const dx = ghost.tx - ghost.x;
  const dy = ghost.ty - ghost.y;
  const d = Math.hypot(dx, dy);
  if (d > 0.01) {
    // A hand never moves dead straight: far off, the heading sways a little either side.
    const sway = Math.sin(ghost.age * 1.7) * 0.28 * Math.min(1, d / 160);
    const cos = Math.cos(sway);
    const sin = Math.sin(sway);
    const ux = dx / d;
    const uy = dy / d;
    const v = Math.min(speed, d * 3.5);
    const wantX = (ux * cos - uy * sin) * v;
    const wantY = (ux * sin + uy * cos) * v;
    const k = Math.min(1, dt * grip);
    ghost.vx += (wantX - ghost.vx) * k;
    ghost.vy += (wantY - ghost.vy) * k;
  } else {
    ghost.vx *= 0.8;
    ghost.vy *= 0.8;
  }
  ghost.x += ghost.vx * dt;
  ghost.y += ghost.vy * dt;
  return d;
}

function nearestFire(world: GhostWorld, x: number, y: number) {
  let best = 0;
  let bestD = Infinity;
  world.fires.forEach((fire, k) => {
    const d = Math.hypot(x - fire.x, y - fire.y);
    if (d < bestD) {
      bestD = d;
      best = k;
    }
  });
  return best;
}

function wanderOn(ghost: Ghost, world: GhostWorld, rand: () => number, pause = 0) {
  const spot = pickSpot(world, rand);
  ghost.phase = 'wander';
  ghost.tx = spot.x;
  ghost.ty = spot.y;
  ghost.timer = pause;
}

/** One step of `dt` seconds. A ghost that has left is marked `gone` for the host to replace. */
export function stepGhost(ghost: Ghost, dt: number, world: GhostWorld, rand: () => number) {
  if (ghost.phase === 'gone') return;
  ghost.age += dt;
  ghost.alpha = Math.min(1, ghost.alpha + dt * 2);
  ghost.scorched = Math.max(0, ghost.scorched - dt);
  const warm = warmthAt(world, ghost.x, ghost.y);
  ghost.warmth = warm;
  ghost.temp = Math.min(1, Math.max(0, ghost.temp + dt * (warm / THAW - (1 - warm) / ghost.chill)));
  const hasFire = world.fires.length > 0;

  switch (ghost.phase) {
    case 'wander': {
      ghost.stay -= dt;
      if (ghost.temp < FREEZING && hasFire) {
        ghost.phase = 'shiver';
        ghost.timer = between(rand, 1, 2);
        break;
      }
      if (ghost.stay <= 0) {
        // Out through the nearer side, a little above or below where it is.
        ghost.phase = 'leave';
        ghost.tx = ghost.x < world.width / 2 ? -40 : world.width + 40;
        ghost.ty = ghost.y + between(rand, -0.2, 0.2) * world.height;
        break;
      }
      if (ghost.timer > 0) {
        // Paused, as if reading: it barely drifts.
        ghost.timer -= dt;
        steer(ghost, dt, 6, 3);
        break;
      }
      const d = steer(ghost, dt, 110, 3);
      if (d < 6) wanderOn(ghost, world, rand, between(rand, 0.3, 2.4));
      break;
    }
    case 'shiver': {
      // Frozen to the spot for a moment before it thinks of the fire.
      ghost.tx = ghost.x;
      ghost.ty = ghost.y;
      steer(ghost, dt, 0, 8);
      ghost.timer -= dt;
      if (ghost.timer <= 0) {
        ghost.phase = 'rush';
        ghost.fire = nearestFire(world, ghost.x, ghost.y);
      }
      break;
    }
    case 'rush': {
      const fire = world.fires[ghost.fire];
      if (!fire) {
        wanderOn(ghost, world, rand);
        break;
      }
      ghost.tx = fire.x;
      ghost.ty = fire.y;
      const d = steer(ghost, dt, 560, 5);
      if (d < fire.reach * 0.32) {
        ghost.phase = 'warm';
        ghost.angle = Math.atan2(ghost.y - fire.y, ghost.x - fire.x);
        ghost.timer = between(rand, 1.5, 4);
      }
      break;
    }
    case 'warm': {
      const fire = world.fires[ghost.fire];
      if (!fire) {
        wanderOn(ghost, world, rand);
        break;
      }
      // Hands held out round the fire, moving a little, flatter than a circle.
      ghost.angle += dt * (0.8 + Math.sin(ghost.age * 0.9) * 0.4);
      const r = fire.reach * (0.2 + Math.sin(ghost.age * 1.3) * 0.06);
      ghost.tx = fire.x + Math.cos(ghost.angle) * r;
      ghost.ty = fire.y + Math.sin(ghost.angle) * r * 0.55;
      steer(ghost, dt, 90, 6);
      // Once it is warm through, it lingers a moment, then goes back to wandering.
      if (ghost.temp >= 0.98) ghost.timer -= dt;
      if (ghost.timer <= 0) {
        if (rand() < 0.3) {
          // Too close for too long: it darts up and away from the heat.
          ghost.scorched = 1.4;
          ghost.phase = 'wander';
          ghost.tx = fire.x + between(rand, -1, 1) * fire.reach;
          ghost.ty = Math.max(20, fire.y - fire.reach * between(rand, 1, 1.6));
          ghost.vx = (ghost.tx - ghost.x) * 3;
          ghost.vy = (ghost.ty - ghost.y) * 3;
          ghost.timer = 0;
        } else wanderOn(ghost, world, rand, between(rand, 0, 0.6));
      }
      break;
    }
    case 'leave': {
      steer(ghost, dt, 150, 3);
      if (ghost.x < -24 || ghost.x > world.width + 24 || ghost.y < -24) ghost.phase = 'gone';
      break;
    }
  }
}

/** The ghost's temperature in degrees, on the same scale a real pointer's reading uses. */
export function ghostDegrees(ghost: Ghost) {
  return Math.round(COLDEST + ghost.temp * (WARMEST - COLDEST));
}

export type GhostTone = 'frost' | 'ember' | 'hot';

/**
 * What a ghost's reading says, when it has something to say: shivering, hurrying to a fire,
 * warming by one, or darting off too hot. A ghost simply wandering keeps quiet.
 */
export function ghostReading(ghost: Ghost): { text: string; tone: GhostTone } | null {
  if (ghost.scorched > 0) return { text: 'too hot!', tone: 'hot' };
  const degrees = ghostDegrees(ghost);
  const shown = `${degrees < 0 ? '−' : ''}${Math.abs(degrees)}°`;
  if (ghost.phase === 'shiver') return { text: `freezing ${shown}`, tone: 'frost' };
  if (ghost.phase === 'rush') return { text: `brr ${shown}`, tone: 'frost' };
  if (ghost.phase === 'warm') {
    return { text: `${ghost.temp > 0.75 ? 'cosy' : 'warming up'} ${shown}`, tone: 'ember' };
  }
  return null;
}

/** A small seeded random source, so a run of ghosts can be replayed. */
export function seededRandom(seed: number) {
  let s = seed >>> 0;
  return () => {
    s = (s + 0x6d2b79f5) >>> 0;
    let t = s;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
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.

Put CursorGhosts inside a positioned area, such as a hero, and mark each fire there with data-lilt-fire: any element works, drawn or not. The ghosts fill the area on one canvas that never takes the pointer and run only while it is on screen and the tab is showing. They are imagined, not real visitors, so do not label them as people online. Pass avoid with a selector to keep them off a headline. With reduced motion they do not appear. Pair it with CursorWarmth so the reader’s pointer feels the cold too; the demo also lights its fires with the Logo scene’s fires prop.

Props8

Every option.

Pass these directly to CursorGhosts.

PropTypeDefaultWhat it does
firesstring'[data-lilt-fire]'Selector for the fires inside the area. Each warms within about its own size.
avoidstringnoneSelector for elements inside the area that wandering ghosts keep clear of.
seednumberrandomSeed for the walk, to replay the same one.
countnumber3How many share the area at once. When one leaves, someone new arrives.
chillnumber18Roughly how many seconds a warm ghost takes to freeze.
readingsbooleantrueShow a small reading beside a ghost when it shivers, rushes or warms up.
froststring'#a9d8ff'Colour of the frost and of a cold reading.
emberstring'#ffb22e'Colour of the embers and of a warm reading.
Previous sceneCursor trailNext sceneDissolve image

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