Dock

Horizontal app dock with magnification, a gliding label and a launch bounce.

Installation

CLI

pnpm dlx shadcn@latest add @riff/dock

Manual

  1. Copy the component

    Save this as components/ui/dock.tsx:

    'use client';
    import {
      createContext,
      use,
      useEffect,
      useId,
      useRef,
      useState,
      type AnimationEvent,
      type CSSProperties,
      type FocusEvent,
      type MouseEvent,
      type PointerEvent,
      type ReactNode,
      type RefObject,
    } from 'react';
    import './dock.css';
    
    type CustomProperties = CSSProperties & Record<`--${string}`, string | number>;
    /** Custom properties for `style`, typed without a global declaration. */
    const cssVars = (values: CustomProperties): CSSProperties => values;
    
    // The pointer swells targets within 2.5 slots, at most to 1.25× their size.
    const REACH_IN_SLOTS = 2.5;
    const MAGNIFICATION = 0.25;
    // Moving between neighbours keeps the label open and gliding.
    const LABEL_CLOSE_MS = 120;
    // A launch bounce stops after a few hops even if the item never opens.
    const MAX_HOPS = 3;
    
    type Label = { id: string; text: string; x: number; gliding: boolean };
    
    type DockContext = {
      label: Label | null;
      bouncing: ReadonlySet<string>;
      target: (
        id: string,
        text: string,
      ) => {
        onPointerEnter: (event: PointerEvent<HTMLElement>) => void;
        onPointerLeave: () => void;
        onFocus: (event: FocusEvent<HTMLElement>) => void;
        onBlur: () => void;
      };
      launch: (id: string, event: MouseEvent) => void;
      land: (id: string, current: boolean) => (event: AnimationEvent) => void;
    };
    
    const Context = createContext<DockContext | null>(null);
    
    function useDockContext() {
      const context = use(Context);
      if (!context) throw new Error('DockItem must be rendered inside a Dock');
      return context;
    }
    
    /** The label: shown at once for a hovered or keyboard-focused item. */
    function useDockLabel(bar: RefObject<HTMLElement | null>) {
      const [label, setLabel] = useState<Label | null>(null);
      const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
      const hovered = useRef<string | null>(null);
      useEffect(() => () => clearTimeout(timer.current), []);
      useEffect(() => {
        if (!label) return;
        const close = (event: KeyboardEvent) => {
          if (event.key === 'Escape') setLabel(null);
        };
        window.addEventListener('keydown', close);
        return () => window.removeEventListener('keydown', close);
      }, [label]);
      const show = (id: string, text: string, element: Element) => {
        clearTimeout(timer.current);
        const slot = element.closest('.riff-dock-item')?.getBoundingClientRect();
        const box = bar.current?.getBoundingClientRect();
        if (!slot || !box) return;
        const x = slot.left - box.left + slot.width / 2;
        setLabel((current) => ({ id, text, x, gliding: current !== null }));
      };
      const hide = () => {
        clearTimeout(timer.current);
        timer.current = setTimeout(() => setLabel(null), LABEL_CLOSE_MS);
      };
      // Touch never labels; tapping opens the item.
      const target = (id: string, text: string) => ({
        onPointerEnter: (event: PointerEvent<HTMLElement>) => {
          if (event.pointerType === 'touch') return;
          hovered.current = id;
          show(id, text, event.currentTarget);
        },
        onPointerLeave: () => {
          hovered.current = null;
          hide();
        },
        onFocus: (event: FocusEvent<HTMLElement>) => {
          if (event.currentTarget.matches(':focus-visible'))
            show(id, text, event.currentTarget);
        },
        onBlur: () => {
          if (hovered.current !== id) hide();
        },
      });
      return { label, target };
    }
    
    /**
     * Scales each target by the pointer's distance from its stationary slot.
     * Targets grow upward in place, so the label can anchor to the slots.
     */
    function useMagnification(list: RefObject<HTMLUListElement | null>) {
      useEffect(() => {
        const element = list.current;
        if (!element) return;
        const eligible = matchMedia(
          '(hover: hover) and (pointer: fine) and (prefers-reduced-motion: no-preference)',
        );
        let frame = 0;
        let pointer = 0;
        const targets = () => [
          ...element.querySelectorAll<HTMLElement>('.riff-dock-target'),
        ];
        const reset = () => {
          cancelAnimationFrame(frame);
          frame = 0;
          for (const target of targets()) target.style.removeProperty('scale');
        };
        const magnify = () => {
          frame = 0;
          const all = targets();
          // Read every slot before writing any scale.
          const scales = all.map((target) => {
            const slot = target.parentElement?.getBoundingClientRect();
            if (!slot) return 1;
            const distance = Math.min(
              Math.abs(pointer - (slot.left + slot.width / 2)) /
                (slot.width * REACH_IN_SLOTS),
              1,
            );
            return 1 + MAGNIFICATION * ((Math.cos(distance * Math.PI) + 1) / 2);
          });
          for (const [index, target] of all.entries()) {
            const scale = scales[index] ?? 1;
            if (scale === 1) target.style.removeProperty('scale');
            else target.style.scale = String(scale);
          }
        };
        const move = (event: globalThis.PointerEvent) => {
          if (!eligible.matches || event.pointerType !== 'mouse') return reset();
          delete element.dataset.keyboard;
          pointer = event.clientX;
          if (!frame) frame = requestAnimationFrame(magnify);
        };
        const keyboard = () => {
          element.dataset.keyboard = '';
          reset();
        };
        element.addEventListener('pointermove', move);
        element.addEventListener('pointerleave', reset);
        element.addEventListener('keydown', keyboard);
        eligible.addEventListener('change', reset);
        window.addEventListener('blur', reset);
        return () => {
          reset();
          element.removeEventListener('pointermove', move);
          element.removeEventListener('pointerleave', reset);
          element.removeEventListener('keydown', keyboard);
          eligible.removeEventListener('change', reset);
          window.removeEventListener('blur', reset);
        };
      }, [list]);
    }
    
    /**
     * The macOS launch bounce: a pressed item hops until it becomes current,
     * then stops on its next landing. A modified click (opening elsewhere)
     * hops once. Reduced motion never hops.
     */
    function useBounce() {
      const [bouncing, setBouncing] = useState<ReadonlySet<string>>(new Set());
      const launches = useRef(new Map<string, { hops: number; ready: boolean }>());
      const stop = (id: string) => {
        launches.current.delete(id);
        setBouncing((current) => {
          const next = new Set(current);
          next.delete(id);
          return next;
        });
      };
      const launch = (id: string, event: MouseEvent) => {
        if (
          launches.current.has(id) ||
          matchMedia('(prefers-reduced-motion: reduce)').matches
        )
          return;
        const ready = event.metaKey || event.ctrlKey || event.shiftKey;
        // A newer launch supersedes running ones.
        for (const running of launches.current.values()) running.ready = true;
        launches.current.set(id, { hops: 0, ready });
        setBouncing((current) => new Set(current).add(id));
      };
      const land = (id: string, current: boolean) => (event: AnimationEvent) => {
        const launched = launches.current.get(id);
        if (event.animationName !== 'riff-dock-bounce' || !launched) return;
        launched.hops += 1;
        if (launched.ready || current || launched.hops >= MAX_HOPS) stop(id);
      };
      return { bouncing, launch, land };
    }
    
    /**
     * A horizontal dock of app icons. The pointer magnifies nearby icons, one
     * label glides between them, the current item shows a dot, and a pressed
     * item bounces until it opens.
     */
    export function Dock({
      label = 'Dock',
      children,
    }: {
      /** Names the dock's navigation landmark. */
      label?: string;
      children: ReactNode;
    }) {
      const bar = useRef<HTMLElement>(null);
      const list = useRef<HTMLUListElement>(null);
      const tooltip = useId();
      const { label: shown, target } = useDockLabel(bar);
      const { bouncing, launch, land } = useBounce();
      useMagnification(list);
      return (
        <Context value={{ label: shown, bouncing, target, launch, land }}>
          <nav ref={bar} className="riff-dock" aria-label={label}>
            <ul ref={list} className="riff-dock-list">
              {children}
            </ul>
            {shown && (
              <span
                id={tooltip}
                role="tooltip"
                className="riff-dock-label"
                data-glide={shown.gliding ? '' : undefined}
                data-hidden={bouncing.has(shown.id) ? '' : undefined}
                style={cssVars({ '--riff-dock-label-x': `${shown.x}px` })}
              >
                {shown.text}
              </span>
            )}
          </nav>
        </Context>
      );
    }
    
    /**
     * One item: a link when it has `href`, otherwise a button. `icon` is its
     * artwork, decorative and up to 32px square.
     */
    export function DockItem({
      label,
      icon,
      href,
      current = false,
      onClick,
    }: {
      label: string;
      icon: ReactNode;
      href?: string;
      /** The page or app being shown; it gets a dot and `aria-current`. */
      current?: boolean;
      onClick?: (event: MouseEvent<HTMLElement>) => void;
    }) {
      const id = useId();
      const dock = useDockContext();
      const handlers = dock.target(id, label);
      const press = (event: MouseEvent<HTMLElement>) => {
        dock.launch(id, event);
        onClick?.(event);
      };
      const content = (
        <span className="riff-dock-icon" aria-hidden="true">
          {icon}
        </span>
      );
      return (
        <li
          className="riff-dock-item"
          data-bouncing={dock.bouncing.has(id) ? '' : undefined}
          onAnimationIteration={dock.land(id, current)}
        >
          {href ? (
            <a
              {...handlers}
              href={href}
              className="riff-dock-target"
              aria-label={label}
              aria-current={current ? 'page' : undefined}
              onClick={press}
            >
              {content}
            </a>
          ) : (
            <button
              {...handlers}
              type="button"
              className="riff-dock-target"
              aria-label={label}
              aria-current={current ? 'true' : undefined}
              onClick={press}
            >
              {content}
            </button>
          )}
          {current && <span className="riff-dock-dot" aria-hidden="true" />}
        </li>
      );
    }
    
    /** A thin divider between groups of items. */
    export function DockSeparator() {
      return <li className="riff-dock-separator" aria-hidden="true" />;
    }
  2. Copy its styles

    Save this beside it as dock.css:

    /* Host roles first, system colours after: the component reads your theme
       when it has these properties and stays legible when it does not. 44px
       slots hold 32px artwork with 2px between them. */
    @layer components {
      .riff-dock {
        --riff-dock-slot: 2.75rem;
        --riff-dock-art: 2rem;
        --riff-dock-ease: cubic-bezier(0.23, 1, 0.32, 1);
        position: relative;
        display: inline-flex;
        max-width: 100%;
        border: 1px solid var(--color-border, GrayText);
        border-radius: 1.125rem;
        padding: 0.375rem 0.375rem 0.5rem;
        background-color: color-mix(
          in srgb,
          var(--color-popover, Canvas) 85%,
          transparent
        );
        box-shadow:
          0 1px 2px rgb(0 0 0 / 6%),
          0 8px 24px rgb(0 0 0 / 10%);
        color: var(--color-foreground, CanvasText);
        backdrop-filter: blur(12px);
      }
      .riff-dock-list {
        display: flex;
        align-items: flex-end;
        gap: 2px;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      .riff-dock-item {
        position: relative;
        flex: none;
        width: var(--riff-dock-slot);
        height: var(--riff-dock-slot);
      }
      .riff-dock-separator {
        flex: none;
        width: 1px;
        height: var(--riff-dock-art);
        margin: auto 0.375rem;
        background-color: var(--color-border, GrayText);
      }
      /* Targets swell upward from the slot's base (scale, written by the
         magnification); the bounce translates the artwork inside. */
      .riff-dock-target {
        display: grid;
        width: 100%;
        height: 100%;
        place-items: center;
        border: 0;
        border-radius: 0.75rem;
        padding: 0;
        background: none;
        color: inherit;
        cursor: pointer;
        transform-origin: bottom center;
        transition: scale 150ms var(--riff-dock-ease);
        &:focus-visible {
          outline: 2px solid var(--color-ring, Highlight);
          outline-offset: -2px;
        }
        &:active:not(:focus-visible) > .riff-dock-icon {
          scale: 0.96;
        }
        .riff-dock-list[data-keyboard] & {
          transition: none;
        }
      }
      .riff-dock-icon {
        display: grid;
        width: var(--riff-dock-art);
        height: var(--riff-dock-art);
        place-items: center;
        transition: scale 150ms var(--riff-dock-ease);
        & > :is(img, svg) {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
      /* The current item's dot, below its slot. */
      .riff-dock-dot {
        position: absolute;
        bottom: -0.3125rem;
        left: calc(50% - 2px);
        width: 4px;
        height: 4px;
        border-radius: 999px;
        background-color: currentColor;
        pointer-events: none;
      }
      /* One arrowless pill above the dock, centred on its item; it fades in,
         then glides between items. */
      .riff-dock-label {
        position: absolute;
        z-index: 1;
        bottom: calc(100% + 0.5rem);
        left: 0;
        border: 1px solid var(--color-border, GrayText);
        border-radius: 999px;
        padding: 0.25rem 0.625rem;
        background-color: var(--color-popover, Canvas);
        color: var(--color-foreground, CanvasText);
        font-size: 0.75rem;
        font-weight: 500;
        line-height: 1rem;
        white-space: nowrap;
        pointer-events: none;
        transform: translateX(calc(var(--riff-dock-label-x) - 50%));
        transition:
          opacity 125ms var(--riff-dock-ease),
          scale 125ms var(--riff-dock-ease);
        @starting-style {
          opacity: 0;
          scale: 0.97;
        }
        /* A bouncing item's label returns once it lands. */
        &[data-hidden] {
          opacity: 0;
        }
      }
      @media (prefers-reduced-motion: no-preference) {
        .riff-dock-label[data-glide] {
          transition:
            opacity 125ms var(--riff-dock-ease),
            scale 125ms var(--riff-dock-ease),
            transform 200ms var(--riff-dock-ease);
        }
        /* Each hop rises half the artwork over 650ms on a gravity curve. */
        .riff-dock-item[data-bouncing] .riff-dock-icon {
          animation: riff-dock-bounce 650ms infinite;
        }
      }
      @keyframes riff-dock-bounce {
        0% {
          translate: 0;
          animation-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94);
        }
        50% {
          translate: 0 calc(var(--riff-dock-art) * -0.5);
          animation-timing-function: cubic-bezier(0.55, 0.085, 0.68, 0.53);
        }
        100% {
          translate: 0;
        }
      }
      @media (prefers-reduced-motion: reduce) {
        .riff-dock-target,
        .riff-dock-icon,
        .riff-dock-label {
          transition: none;
        }
      }
      @media (forced-colors: active) {
        .riff-dock-dot {
          background-color: CanvasText;
          forced-color-adjust: none;
        }
      }
    }

Usage

import { Dock, DockItem, DockSeparator } from '@/components/ui/dock';

<Dock label="Apps">
  <DockItem label="Mail" icon={<MailIcon />} href="/mail" current />
  <DockItem label="Notes" icon={<NotesIcon />} href="/notes" />
</Dock>;

Under a mouse, icons near the pointer swell and a single label glides between them. A pressed item bounces until it becomes current, as macOS does while an app launches. Items with href are links; others are buttons. Icons are decorative, so the label names each item.

Props

PropTypeDefaultDescription
Dock.labelstring'Dock'Names the navigation.
DockItem.labelstringThe item’s name and its hover label.
DockItem.iconReactNodeSquare artwork, up to 32px.
DockItem.hrefstringMakes the item a link.
DockItem.currentbooleanfalseShows the dot and sets aria-current.
DockItem.onClick(event) => voidRuns on press.