Magnify dock

A floating bar of icon tiles where the tiles near the pointer swell, largest under the cursor and falling off smoothly over their neighbours, while the bar grows with them so nothing overlaps. A label rises above the hovered or focused tile and active items get a small dot. Works as a horizontal bottom dock or a vertical tool rail, with groups split by thin dividers and count badges that pop when they change. The avatars variant becomes a presence dock that opens a list of members and their status on click. It is a toolbar with arrow-key, Home and End navigation (focus swells like hover), labelled tiles, aria-current on the active one and announced badge counts. Touch screens get a simple press state and reduced motion a plain lift.

NavigationComponentTailwind v4

Source

"use client";

import {
  Fragment, useEffect, useId, useRef, useState,
  type ComponentType, type FocusEvent as ReactFocusEvent, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent,
} from "react";
import { cn } from "@/lib/utils";

export type PresenceStatus = "online" | "away" | "busy" | "offline";

export interface DockItem {
  id: string;
  label: string;
  /** An icon component, e.g. from lucide-react. */
  icon?: ComponentType<{ className?: string; "aria-hidden"?: boolean | "true" }>;
  /** For the avatars variant: initials, a colour and a presence status. */
  avatar?: { initials: string; color?: string; status?: PresenceStatus };
  href?: string;
  onSelect?: () => void;
  active?: boolean;
  badge?: number | string;
}

export interface MagnifyDockProps {
  items?: DockItem[];
  /** Items split into groups with a thin divider between them. Used instead of `items`. */
  groups?: DockItem[][];
  orientation?: "horizontal" | "vertical";
  /** Resting tile size in px. */
  baseSize?: number;
  /** Size of the tile under the pointer relative to baseSize. */
  maxScale?: number;
  /** How many tiles either side the swell reaches. */
  range?: number;
  /** Off: tiles only lift on hover. */
  magnify?: boolean;
  /** "avatars" turns the dock into a presence dock that opens a member list on click. */
  variant?: "icons" | "avatars";
  /** Accessible name of the toolbar. */
  label?: string;
  /** Avatars variant: where the member list opens and whether it starts open. */
  panelPlacement?: "above" | "below" | "beside";
  defaultExpanded?: boolean;
  panelTitle?: string;
  className?: string;
}

const GAP = 6;
const statusTone: Record<PresenceStatus, string> = {
  online: "bg-emerald-500",
  away: "bg-amber-400",
  busy: "bg-red-500",
  offline: "bg-muted-foreground/50",
};
const statusText: Record<PresenceStatus, string> = { online: "Online", away: "Away", busy: "Busy", offline: "Offline" };

function useMedia(query: string) {
  const [match, setMatch] = useState(false);
  useEffect(() => {
    const list = window.matchMedia?.(query);
    if (!list) return;
    const update = () => setMatch(list.matches);
    update();
    list.addEventListener("change", update);
    return () => list.removeEventListener("change", update);
  }, [query]);
  return match;
}

function Avatar({ avatar, label, size = "100%" }: { avatar: NonNullable<DockItem["avatar"]>; label: string; size?: string }) {
  return (
    <span className="relative block" style={{ width: size, height: size }}>
      <span
        aria-hidden="true"
        className="grid size-full place-items-center rounded-full text-[0.38em] font-semibold text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.4)]"
        style={{ background: avatar.color ?? "var(--chart-2)" }}
      >
        {avatar.initials}
      </span>
      {avatar.status && (
        <span
          aria-hidden="true"
          title={`${label}: ${statusText[avatar.status]}`}
          className={cn("absolute bottom-0 right-0 size-[28%] min-h-2 min-w-2 rounded-full ring-2 ring-card", statusTone[avatar.status])}
        />
      )}
    </span>
  );
}

export function MagnifyDock({
  items, groups, orientation = "horizontal", baseSize = 40, maxScale = 1.6, range = 3, magnify = true,
  variant = "icons", label = "Dock", panelPlacement = "above", defaultExpanded = false, panelTitle = "People here", className,
}: MagnifyDockProps) {
  const uid = useId();
  const panelId = `${uid}-panel`;
  const sets = groups ?? [items ?? []];
  const flat = sets.flat();
  const horizontal = orientation === "horizontal";
  const coarse = useMedia("(pointer: coarse)");
  const reduce = useMedia("(prefers-reduced-motion: reduce)");
  const swell = magnify && !coarse && !reduce;

  const tiles = useRef<(HTMLDivElement | null)[]>([]);
  const buttons = useRef<(HTMLElement | null)[]>([]);
  const sizes = useRef<number[]>([]);
  const pointer = useRef<number | null>(null);
  const frame = useRef(0);
  const [focusIndex, setFocusIndex] = useState(() => Math.max(0, flat.findIndex((item) => item.active)));
  const [hovered, setHovered] = useState<number | null>(null);
  const [focused, setFocused] = useState<number | null>(null);
  const [expanded, setExpanded] = useState(defaultExpanded && variant === "avatars");
  const [announce, setAnnounce] = useState("");

  // Announce badge changes politely.
  const lastBadges = useRef<Record<string, DockItem["badge"]>>({});
  useEffect(() => {
    for (const item of flat) {
      const before = lastBadges.current[item.id];
      if (before !== undefined && item.badge !== undefined && before !== item.badge) setAnnounce(`${item.label}: ${item.badge} new`);
      lastBadges.current[item.id] = item.badge;
    }
  });

  // Each frame: target size from distance to the pointer (cosine falloff), eased toward it.
  function tick() {
    const reach = range * (baseSize + GAP);
    let moving = false;
    tiles.current.forEach((tile, i) => {
      if (!tile) return;
      let target = baseSize;
      if (pointer.current !== null && swell) {
        const rect = tile.getBoundingClientRect();
        const centre = horizontal ? rect.left + rect.width / 2 : rect.top + rect.height / 2;
        const distance = Math.abs(pointer.current - centre);
        if (distance < reach) target = baseSize * (1 + (maxScale - 1) * ((1 + Math.cos((Math.PI * distance) / reach)) / 2));
      }
      const current = sizes.current[i] ?? baseSize;
      const next = Math.abs(target - current) < 0.2 ? target : current + (target - current) * 0.24;
      if (next !== target) moving = true;
      sizes.current[i] = next;
      tile.style.width = tile.style.height = `${next}px`;
    });
    frame.current = moving || pointer.current !== null ? requestAnimationFrame(tick) : 0;
  }
  function wake() {
    if (!frame.current) frame.current = requestAnimationFrame(tick);
  }
  useEffect(() => () => cancelAnimationFrame(frame.current), []);
  useEffect(() => {
    if (!swell) {
      pointer.current = null;
      tiles.current.forEach((tile, i) => {
        sizes.current[i] = baseSize;
        if (tile) tile.style.width = tile.style.height = `${baseSize}px`;
      });
    }
  }, [swell, baseSize]);

  function nearest(position: number) {
    let best: number | null = null;
    let bestDistance = Infinity;
    tiles.current.forEach((tile, i) => {
      if (!tile) return;
      const rect = tile.getBoundingClientRect();
      const d = Math.abs(position - (horizontal ? rect.left + rect.width / 2 : rect.top + rect.height / 2));
      if (d < bestDistance) {
        bestDistance = d;
        best = i;
      }
    });
    return best;
  }

  function onPointerMove(event: ReactPointerEvent<HTMLDivElement>) {
    if (event.pointerType === "touch") return;
    const position = horizontal ? event.clientX : event.clientY;
    setHovered(nearest(position));
    if (!swell) return;
    pointer.current = position;
    wake();
  }
  function onPointerLeave() {
    setHovered(null);
    pointer.current = null;
    if (swell) wake();
  }

  function focusTile(index: number) {
    const next = (index + flat.length) % flat.length;
    setFocusIndex(next);
    buttons.current[next]?.focus();
  }

  function onKeyDown(event: ReactKeyboardEvent<HTMLDivElement>) {
    if (event.key === "Escape" && expanded) {
      setExpanded(false);
      buttons.current[focusIndex]?.focus();
      return;
    }
    if (!(event.target instanceof HTMLElement) || !event.target.hasAttribute("data-dock-tile")) return;
    const prev = horizontal ? "ArrowLeft" : "ArrowUp";
    const next = horizontal ? "ArrowRight" : "ArrowDown";
    if (event.key === prev) focusTile(focusIndex - 1);
    else if (event.key === next) focusTile(focusIndex + 1);
    else if (event.key === "Home") focusTile(0);
    else if (event.key === "End") focusTile(flat.length - 1);
    else return;
    event.preventDefault();
  }

  function onTileFocus(index: number, element: HTMLElement) {
    setFocusIndex(index);
    if (!element.matches(":focus-visible")) return;
    setFocused(index);
    if (!swell) return;
    const rect = element.getBoundingClientRect();
    pointer.current = horizontal ? rect.left + rect.width / 2 : rect.top + rect.height / 2;
    wake();
  }
  function onTileBlur() {
    setFocused(null);
    if (hovered === null) {
      pointer.current = null;
      if (swell) wake();
    }
  }

  const avatars = variant === "avatars";
  let running = -1;

  return (
    <div className={cn("relative inline-flex", className)}>
      <style>{`@keyframes magnify-dock-pop{0%{transform:scale(.4)}55%{transform:scale(1.25)}100%{transform:scale(1)}}`}</style>
      <div
        role="toolbar"
        aria-label={label}
        aria-orientation={orientation}
        onPointerMove={onPointerMove}
        onPointerLeave={onPointerLeave}
        onKeyDown={onKeyDown}
        className={cn(
          "flex rounded-2xl border border-border bg-card/85 shadow-[0_10px_30px_-12px_rgb(0_0_0/0.3)] backdrop-blur-md",
          horizontal ? "flex-row items-end px-2 pb-2 pt-2" : "flex-col items-start px-2 py-2",
        )}
        style={{ gap: GAP }}
      >
        {sets.map((set, groupIndex) => (
          <Fragment key={groupIndex}>
            {groupIndex > 0 && (
              <span
                aria-hidden="true"
                className={cn("shrink-0 self-center bg-border", horizontal ? "mx-1 w-px" : "my-1 h-px")}
                style={horizontal ? { height: baseSize * 0.7 } : { width: baseSize * 0.7 }}
              />
            )}
            {set.map((item) => {
              running += 1;
              const index = running;
              const Icon = item.icon;
              const showLabel = hovered === index || focused === index;
              const tileLabel = `${item.label}${item.badge !== undefined && item.badge !== 0 ? `, ${item.badge} new` : ""}${
                item.avatar?.status ? `, ${statusText[item.avatar.status]}` : ""}`;
              const shared = {
                ref: (element: HTMLElement | null) => {
                  buttons.current[index] = element;
                },
                "data-dock-tile": "",
                tabIndex: index === focusIndex ? 0 : -1,
                "aria-label": tileLabel,
                "aria-current": item.active && !avatars ? ("page" as const) : undefined,
                onFocus: (event: ReactFocusEvent<HTMLElement>) => onTileFocus(index, event.currentTarget),
                onBlur: onTileBlur,
                className: cn(
                  "grid size-full place-items-center outline-hidden transition-[background-color,translate] duration-150",
                  "focus-visible:ring-[3px] focus-visible:ring-ring/60 active:scale-95",
                  avatars ? "rounded-full" : "rounded-[28%] bg-muted text-foreground hover:bg-accent",
                  item.active && !avatars && "bg-primary text-primary-foreground hover:bg-primary/90",
                  !swell && (horizontal ? "hover:-translate-y-1 focus-visible:-translate-y-1" : "hover:translate-x-1 focus-visible:translate-x-1"),
                  reduce && "transition-none",
                ),
              };
              const inner = (
                <>
                  {avatars && item.avatar ? (
                    <Avatar avatar={item.avatar} label={item.label} />
                  ) : Icon ? (
                    <Icon aria-hidden="true" className="size-[48%]" />
                  ) : (
                    <span aria-hidden="true" className="text-[0.4em] font-semibold">{item.label.slice(0, 2)}</span>
                  )}
                </>
              );
              return (
                <div
                  key={item.id}
                  ref={(element) => {
                    tiles.current[index] = element;
                  }}
                  className="relative shrink-0"
                  style={{ width: sizes.current[index] ?? baseSize, height: sizes.current[index] ?? baseSize, fontSize: baseSize }}
                >
                  {avatars ? (
                    <button
                      {...shared}
                      type="button"
                      aria-expanded={expanded}
                      aria-controls={panelId}
                      onClick={() => setExpanded((open) => !open)}
                    >
                      {inner}
                    </button>
                  ) : item.href ? (
                    <a {...shared} href={item.href} onClick={() => item.onSelect?.()}>{inner}</a>
                  ) : (
                    <button {...shared} type="button" onClick={() => item.onSelect?.()}>{inner}</button>
                  )}

                  {item.badge !== undefined && item.badge !== 0 && (
                    <span
                      key={String(item.badge)}
                      aria-hidden="true"
                      className="pointer-events-none absolute -right-1 -top-1 grid h-[18px] min-w-[18px] place-items-center rounded-full bg-destructive px-1 dark:bg-red-600 text-[10px] font-semibold leading-none text-white ring-2 ring-card motion-safe:animate-[magnify-dock-pop_.45s_ease-out]"
                    >
                      {item.badge}
                    </span>
                  )}
                  {item.active && !avatars && (
                    <span
                      aria-hidden="true"
                      className={cn(
                        "absolute size-1 rounded-full bg-foreground/70",
                        horizontal ? "-bottom-[5px] left-1/2 -translate-x-1/2" : "-left-[5px] top-1/2 -translate-y-1/2",
                      )}
                    />
                  )}
                  <span
                    aria-hidden="true"
                    className={cn(
                      "pointer-events-none absolute z-10 whitespace-nowrap rounded-md bg-foreground px-2 py-1 text-xs font-medium text-background shadow-md",

                      horizontal ? "bottom-full left-1/2 mb-2.5 -translate-x-1/2" : "left-full top-1/2 ml-2.5 -translate-y-1/2",
                      showLabel ? "opacity-100" : "opacity-0",
                      avatars && expanded && "hidden",
                    )}
                  >
                    {item.label}
                  </span>
                </div>
              );
            })}
          </Fragment>
        ))}
      </div>

      {avatars && (
        <div
          id={panelId}
          role="region"
          aria-label={panelTitle}
          hidden={!expanded}
          className={cn(
            "absolute z-20 w-64 max-w-[calc(100vw-2rem)] rounded-2xl border border-border bg-popover p-2 text-popover-foreground shadow-[0_18px_48px_-16px_rgb(0_0_0/0.35)]",
            "origin-bottom motion-safe:transition-[opacity,scale] motion-safe:starting:scale-95 motion-safe:starting:opacity-0",
            panelPlacement === "above" && "bottom-full right-0 mb-3 origin-bottom-right",
            panelPlacement === "below" && "right-0 top-full mt-3 origin-top-right",
            panelPlacement === "beside" && "left-full top-0 ml-3 origin-top-left",
          )}
        >
          <p className="px-2 pb-1.5 pt-1 text-xs font-medium text-muted-foreground">
            {panelTitle} · {flat.filter((item) => item.avatar?.status === "online").length} online
          </p>
          <ul>
            {flat.map((item) => (
              <li key={item.id} className="flex items-center gap-3 rounded-lg px-2 py-1.5 hover:bg-accent">
                {item.avatar && (
                  <span className="shrink-0 text-[28px]">
                    <Avatar avatar={item.avatar} label={item.label} size="28px" />
                  </span>
                )}
                <span className="min-w-0 flex-1 truncate text-sm font-medium">{item.label}</span>
                {item.avatar?.status && <span className="text-xs text-muted-foreground">{statusText[item.avatar.status]}</span>}
              </li>
            ))}
          </ul>
        </div>
      )}
      <span className="sr-only" aria-live="polite">{announce}</span>
    </div>
  );
}