Dot rings

Concentric rings of dots that shrink away from the cursor and ease back.

Installation

CLI

pnpm dlx shadcn@latest add @riff/dot-rings

Manual

  1. Copy the component

    Save this as components/ui/dot-rings.tsx:

    'use client';
    import {
      useEffect,
      useMemo,
      useRef,
      type CSSProperties,
      type ReactNode,
    } from 'react';
    import './dot-rings.css';
    
    type CustomProperties = CSSProperties & Record<`--${string}`, string | number>;
    /** Custom properties for `style`, typed without a global declaration. */
    const cssVars = (values: CustomProperties): CSSProperties => values;
    
    export type RingOptions = {
      /** The empty centre's radius; the first ring keeps clear of it. */
      core: number;
      /** The first ring's dot diameter. */
      start: number;
      /** Each ring's dots are this fraction of the previous ring's. */
      shrink: number;
      /** The space between neighbouring dots, as a fraction of their diameter. */
      gap: number;
      /** Rings stop once their dots would start beyond this radius. */
      extent: number;
      /**
       * Fills the core with one dot of radius `core`, which the pointer pushes
       * aside like the rest, instead of leaving it empty for children.
       */
      centre?: boolean;
    };
    
    type Ring = { radius: number; count: number; r: number; phase: number };
    type Dot = { x: number; y: number; r: number };
    
    /** The pattern around the portfolio's 144px avatar, in CSS pixels. */
    export const DEFAULT_RINGS: RingOptions = {
      core: 69,
      start: 32,
      shrink: 0.88,
      gap: 0.24,
      extent: 300,
    };
    
    // `rings(DEFAULT_RINGS)`, rounded; stored because the search takes a moment.
    const DEFAULT_LAYOUT: readonly Ring[] = [
      { radius: 92.68, count: 14, r: 16.78, phase: -1.5708 },
      { radius: 130.76, count: 23, r: 14.43, phase: -1.5708 },
      { radius: 164.15, count: 33, r: 12.63, phase: -1.5708 },
      { radius: 193.05, count: 44, r: 11.16, phase: -1.5529 },
      { radius: 218.65, count: 57, r: 9.74, phase: -1.5529 },
      { radius: 241.09, count: 72, r: 8.49, phase: -1.5529 },
      { radius: 261.02, count: 89, r: 7.43, phase: -1.5529 },
      { radius: 278.56, count: 107, r: 6.61, phase: -1.5529 },
      { radius: 293.82, count: 129, r: 5.77, phase: -1.5529 },
      { radius: 307.38, count: 153, r: 5.1, phase: -1.5529 },
    ];
    
    const TURN = 2 * Math.PI;
    
    function ring(radius: number, diameter: number, gap: number, phase: number) {
      const count = Math.max(3, Math.floor((TURN * radius) / (diameter + gap)));
      const chord = 2 * radius * Math.sin(Math.PI / count);
      return { radius, count, r: (chord - gap) / 2, phase };
    }
    
    function centre({ radius, count, phase }: Ring, index: number) {
      const angle = phase + (index / count) * TURN;
      return { x: radius * Math.cos(angle), y: radius * Math.sin(angle) };
    }
    
    /** The narrowest gap between the outer ring's dots and the inner's. */
    function clearance(inner: Ring, outer: Ring) {
      let least = Infinity;
      for (let index = 0; index < outer.count; index += 1) {
        const dot = centre(outer, index);
        const angle = outer.phase + (index / outer.count) * TURN - inner.phase;
        const nearest = Math.round((angle / TURN) * inner.count);
        for (let offset = -1; offset <= 1; offset += 1) {
          const other = centre(inner, nearest + offset);
          least = Math.min(
            least,
            Math.hypot(dot.x - other.x, dot.y - other.y) - inner.r - outer.r,
          );
        }
      }
      return least;
    }
    
    /**
     * Concentric rings of dots, shrinking outwards. Each ring sits as close to
     * the last as the gap allows, turned so its dots nest in the last ring's gaps.
     */
    function rings({
      core,
      start,
      shrink,
      gap,
      extent,
      centre: filled = false,
    }: RingOptions): Ring[] {
      let diameter = start;
      let previous = ring(
        core + gap * diameter + diameter / 2,
        diameter,
        gap * diameter,
        -Math.PI / 2,
      );
      // Around a centre dot, the first ring's dots grow to fill their whole
      // count; it moves out until the gap fits those dots, as every later ring's
      // gap fits its own.
      if (filled)
        while (previous.radius - previous.r - core < gap * 2 * previous.r)
          previous = ring(
            previous.radius + 0.5,
            diameter,
            gap * diameter,
            -Math.PI / 2,
          );
      const result: Ring[] = filled
        ? [{ radius: 0, count: 1, r: core, phase: 0 }, previous]
        : [previous];
      while (previous.radius - previous.r < extent) {
        diameter *= shrink;
        const space = gap * diameter;
        let next: Ring | undefined;
        for (let radius = previous.radius + diameter / 2; !next; radius += 0.5) {
          const pitch = TURN / ring(radius, diameter, space, 0).count;
          for (let step = 0; step < 24 && !next; step += 1) {
            const candidate = ring(
              radius,
              diameter,
              space,
              previous.phase + (step / 24) * pitch,
            );
            if (clearance(previous, candidate) >= space) next = candidate;
          }
        }
        result.push(next);
        previous = next;
      }
      return result;
    }
    
    const round = (value: number) => Math.round(value * 10) / 10;
    
    function dotsOf(layout: readonly Ring[]): Dot[] {
      return layout.flatMap((each) =>
        Array.from({ length: each.count }, (_, index) => {
          const { x, y } = centre(each, index);
          return { x: round(x), y: round(y), r: round(each.r) };
        }),
      );
    }
    
    /** The dots, and the radii the box sizes and fades the pattern by. */
    function patternOf(layout: readonly Ring[]) {
      // The first ring around the centre; a centre dot is not a ring.
      const first = layout.find(({ count }) => count > 1) ??
        layout[0] ?? { radius: 0, r: 0 };
      const last = layout.at(-1) ?? first;
      const beforeLast = layout.at(-2) ?? first;
      let reach = 0;
      for (const { radius, r } of layout) reach = Math.max(reach, radius + r);
      return {
        dots: dotsOf(layout),
        reach: Math.ceil(reach),
        clear: Math.ceil(first.radius + first.r),
        // An imaginary ring one step past the last, where the fade ends.
        fade: Math.ceil(2 * last.radius - beforeLast.radius),
      };
    }
    
    // The pointer's field: dots inside it shrink to make way, in px.
    const FIELD = 96;
    
    /**
     * A dot's scale at `distance` from the pointer: smallest under it, back to
     * full size at the field's edge, then a slight swell just beyond, as if the
     * pointer had pushed the dots aside.
     */
    function fieldScale(distance: number) {
      const t = distance / FIELD;
      const swell = 0.18 * Math.exp(-(((t - 1.15) / 0.3) ** 2));
      if (t >= 1) return 1 + swell;
      const ease = t * t * (3 - 2 * t);
      return 0.2 + 0.8 * ease + swell;
    }
    
    /**
     * Faint concentric rings of dots that fill their box, fading out from the
     * centre. Under a mouse or pen the dots near the pointer shrink away and
     * ease back when it leaves. Anything you pass as children sits at the
     * centre, such as an avatar.
     */
    export function DotRings({
      options,
      children,
    }: {
      /** The pattern's geometry; DEFAULT_RINGS when omitted. */
      options?: RingOptions;
      children?: ReactNode;
    }) {
      const box = useRef<HTMLDivElement>(null);
      const svg = useRef<SVGSVGElement>(null);
      const { dots, reach, clear, fade } = useMemo(
        () => patternOf(options ? rings(options) : DEFAULT_LAYOUT),
        [options],
      );
    
      useEffect(() => {
        const container = box.current;
        const element = svg.current;
        if (!container || !element) return;
        const reduced = matchMedia('(prefers-reduced-motion: reduce)');
        const circles = [...element.querySelectorAll('circle')];
        const scales = new Float32Array(dots.length).fill(1);
        let cursor: { x: number; y: number } | undefined;
        let frame = 0;
        const target = (index: number) => {
          const dot = dots[index];
          if (!cursor || !dot) return 1;
          const distance = Math.hypot(dot.x - cursor.x, dot.y - cursor.y);
          return distance > FIELD * 2 ? 1 : fieldScale(distance);
        };
        const step = () => {
          frame = 0;
          let moving = false;
          for (const [index, circle] of circles.entries()) {
            const goal = target(index);
            const current = scales[index] ?? 1;
            if (Math.abs(goal - current) < 0.002) {
              if (current === goal) continue;
              scales[index] = goal;
            } else {
              // Each frame closes a fifth of the gap to the target scale.
              scales[index] = reduced.matches
                ? goal
                : current + (goal - current) * 0.2;
              if (!reduced.matches) moving = true;
            }
            circle.setAttribute(
              'r',
              ((dots[index]?.r ?? 0) * (scales[index] ?? 1)).toFixed(2),
            );
          }
          if (moving) frame = requestAnimationFrame(step);
        };
        const schedule = () => {
          if (!frame) frame = requestAnimationFrame(step);
        };
        const move = (event: PointerEvent) => {
          if (event.pointerType === 'touch') return;
          const rect = element.getBoundingClientRect();
          if (rect.width === 0) return;
          const unit = (2 * reach) / rect.width;
          cursor = {
            x: (event.clientX - rect.left) * unit - reach,
            y: (event.clientY - rect.top) * unit - reach,
          };
          schedule();
        };
        const leave = () => {
          cursor = undefined;
          schedule();
        };
        container.addEventListener('pointermove', move, { passive: true });
        container.addEventListener('pointerleave', leave);
        return () => {
          container.removeEventListener('pointermove', move);
          container.removeEventListener('pointerleave', leave);
          cancelAnimationFrame(frame);
        };
      }, [dots, reach]);
    
      return (
        <div
          ref={box}
          className="riff-rings"
          style={cssVars({
            '--riff-rings-reach': `${reach}px`,
            '--riff-rings-clear': `${clear}px`,
            '--riff-rings-fade': `${fade}px`,
          })}
        >
          <svg
            ref={svg}
            className="riff-rings-dots"
            viewBox={`${-reach} ${-reach} ${2 * reach} ${2 * reach}`}
            aria-hidden="true"
            focusable="false"
          >
            {dots.map(({ x, y, r }) => (
              <circle key={`${x},${y}`} cx={x} cy={y} r={r} />
            ))}
          </svg>
          {children && <div className="riff-rings-centre">{children}</div>}
        </div>
      );
    }
  2. Copy its styles

    Save this beside it as dot-rings.css:

    /* Host roles first, system colours after: the component reads your theme
       when it has these properties and stays legible when it does not. The box
       fills its container (give it a height); the pattern keeps its pixel size,
       centred, and fades out past the first ring. */
    @layer components {
      .riff-rings {
        position: relative;
        display: grid;
        min-height: 12rem;
        overflow: hidden;
        place-items: center;
        mask-image: radial-gradient(
          circle,
          black var(--riff-rings-clear),
          transparent var(--riff-rings-fade)
        );
      }
      .riff-rings-dots {
        position: absolute;
        top: 50%;
        left: 50%;
        width: calc(var(--riff-rings-reach) * 2);
        max-width: none;
        height: auto;
        fill: var(--riff-rings-color, var(--color-foreground, CanvasText));
        opacity: var(--riff-rings-opacity, 0.15);
        translate: -50% -50%;
      }
      .riff-rings-centre {
        position: relative;
      }
    }

Usage

import { DotRings } from '@/components/ui/dot-rings';

<DotRings>
  <img src="/me.webp" alt="Sarthak" width={144} height={144} />
</DotRings>;

The rings fill their box and fade out from the centre, so give the box a height. Move a mouse over them to push the dots aside. Children sit in the empty centre; set centre in options to fill it with a dot that moves with the rest. Set --riff-rings-color and --riff-rings-opacity to tint them, or pass options for another pattern.

Props

PropTypeDefaultDescription
optionsRingOptionsDEFAULT_RINGScore, start, shrink, gap and extent, in pixels, and centre.
childrenReactNodeShown at the centre.