Dock

A frosted glass dock of app icons, shown over a wash of blue light. Icons swell as the pointer passes, hop when opened and show their name above.

Options

Screen

Code

import { useRef, useState } from "react";
import "./dock.css";

const reach = 100;
const growth = 0.4;

export function Dock({ apps, label = "Apps", onOpen }) {
  const dock = useRef(null);
  const centres = useRef([]);
  const width = useRef(0);
  const [scales, setScales] = useState(null);
  const [opening, setOpening] = useState(null);

  function measure() {
    centres.current = [...dock.current.children].map((app) => app.offsetLeft + app.offsetWidth / 2);
    width.current = dock.current.offsetWidth;
  }

  function move(event) {
    if (event.pointerType !== "mouse") return;
    if (matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    if (!scales) measure();
    const box = dock.current.getBoundingClientRect();
    const x = (event.clientX - box.left) / box.width * width.current;
    setScales(
      centres.current.map((centre) => {
        const away = Math.min(Math.abs(x - centre) / reach, 1);
        return 1 + growth * (Math.cos(away * Math.PI) + 1) / 2;
      }),
    );
  }

  return (
    <nav
      className="dh-dock"
      aria-label={label}
      ref={dock}
      data-near={scales ? "" : undefined}
      onPointerMove={move}
      onPointerLeave={() => setScales(null)}
    >
      {apps.map((app, index) => (
        <a
          key={app.name}
          href={app.href ?? "#"}
          data-running={app.running ? "" : undefined}
          data-opening={opening === app.name ? "" : undefined}
          style={scales ? { "--dh-dock-scale": scales[index].toFixed(3) } : undefined}
          onClick={(event) => {
            if (!app.href) event.preventDefault();
            setOpening(app.name);
            onOpen?.(app);
          }}
          onAnimationEnd={() => setOpening(null)}
        >
          <img src={app.icon} alt={app.name} width="44" height="44" />
          <span aria-hidden="true">{app.name}</span>
        </a>
      ))}
    </nav>
  );
}