Dock

macOS-style dock whose icons magnify with a spring as the pointer moves over them.

pnpm dlx shadcn@latest add @leo/dock

Props

NameTypeDefaultDescription
baseItemSizenumber | undefined50
classNamestring | undefined-
distancenumber | undefined200
dockHeightnumber | undefined256
itemsDockItemData[] | undefined[ { label: "Home", onClick: noop, icon: ( <DefaultIcon> <path d="M3 11l9-8 9 8" /> <path d="M5 10v10h14V10" /> </DefaultIcon> ), }, { label: "Archive", onClick: noop, icon: ( <DefaultIcon> <rect x="3" y="4" width="18" height="4" rx="1" /> <path d="M5 8v12h14V8" /> <path d="M10 12h4" /> </DefaultIcon> ), }, { label: "Profile", onClick: noop, icon: ( <DefaultIcon> <circle cx="12" cy="8" r="4" /> <path d="M4 21c0-4 4-7 8-7s8 3 8 7" /> </DefaultIcon> ), }, { label: "Settings", onClick: noop, icon: ( <DefaultIcon> <circle cx="12" cy="12" r="3" /> <path d="M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M19 5l-2 2M7 17l-2 2" /> </DefaultIcon> ), }, ]
magnificationnumber | undefined70
panelClassNamestring | undefined-
panelHeightnumber | undefined68
springSpringOptions | undefined{ mass: 0.1, stiffness: 150, damping: 12 }

Dependencies

  • motion@^12.23.12

Source

"use client";

import {
  AnimatePresence,
  type MotionValue,
  motion,
  type SpringOptions,
  useMotionValue,
  useSpring,
  useTransform,
} from "motion/react";
import React, { Children, cloneElement, useEffect, useMemo, useRef, useState } from "react";
import { cn } from "@/lib/utils";

export type DockItemData = {
  icon: React.ReactNode;
  label: React.ReactNode;
  onClick: () => void;
  className?: string;
};

function DefaultIcon({ children }: { children: React.ReactNode }) {
  return (
    <svg
      width="22"
      height="22"
      viewBox="0 0 24 24"
      fill="none"
      stroke="#fff"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {children}
    </svg>
  );
}

const noop = () => {};

const DEFAULT_ITEMS: DockItemData[] = [
  {
    label: "Home",
    onClick: noop,
    icon: (
      <DefaultIcon>
        <path d="M3 11l9-8 9 8" />
        <path d="M5 10v10h14V10" />
      </DefaultIcon>
    ),
  },
  {
    label: "Archive",
    onClick: noop,
    icon: (
      <DefaultIcon>
        <rect x="3" y="4" width="18" height="4" rx="1" />
        <path d="M5 8v12h14V8" />
        <path d="M10 12h4" />
      </DefaultIcon>
    ),
  },
  {
    label: "Profile",
    onClick: noop,
    icon: (
      <DefaultIcon>
        <circle cx="12" cy="8" r="4" />
        <path d="M4 21c0-4 4-7 8-7s8 3 8 7" />
      </DefaultIcon>
    ),
  },
  {
    label: "Settings",
    onClick: noop,
    icon: (
      <DefaultIcon>
        <circle cx="12" cy="12" r="3" />
        <path d="M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M19 5l-2 2M7 17l-2 2" />
      </DefaultIcon>
    ),
  },
];

export type DockProps = {
  items?: DockItemData[];
  className?: string;
  panelClassName?: string;
  distance?: number;
  panelHeight?: number;
  baseItemSize?: number;
  dockHeight?: number;
  magnification?: number;
  spring?: SpringOptions;
};

type DockItemProps = {
  className?: string;
  children: React.ReactNode;
  onClick?: () => void;
  mouseX: MotionValue<number>;
  spring: SpringOptions;
  distance: number;
  baseItemSize: number;
  magnification: number;
  label?: React.ReactNode;
};

function DockItem({
  children,
  className,
  onClick,
  mouseX,
  spring,
  distance,
  magnification,
  baseItemSize,
  label,
}: DockItemProps) {
  const ref = useRef<HTMLDivElement>(null);
  const isHovered = useMotionValue(0);

  const mouseDistance = useTransform(mouseX, (val) => {
    const rect = ref.current?.getBoundingClientRect() ?? {
      x: 0,
      width: baseItemSize,
    };
    return val - rect.x - baseItemSize / 2;
  });

  const targetSize = useTransform(
    mouseDistance,
    [-distance, 0, distance],
    [baseItemSize, magnification, baseItemSize],
  );
  const size = useSpring(targetSize, spring);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      onClick?.();
    }
  };

  return (
    <motion.div
      ref={ref}
      style={{
        width: size,
        height: size,
      }}
      onHoverStart={() => isHovered.set(1)}
      onHoverEnd={() => isHovered.set(0)}
      onFocus={() => isHovered.set(1)}
      onBlur={() => isHovered.set(0)}
      onClick={onClick}
      onKeyDown={handleKeyDown}
      className={cn(
        "relative inline-flex items-center justify-center rounded-full bg-[#120F17] border-neutral-700 border-2 shadow-md",
        className,
      )}
      tabIndex={0}
      role="button"
      aria-haspopup="true"
      aria-label={typeof label === "string" ? label : undefined}
    >
      {Children.map(children, (child) =>
        React.isValidElement(child)
          ? cloneElement(child as React.ReactElement<{ isHovered?: MotionValue<number> }>, {
              isHovered,
            })
          : child,
      )}
    </motion.div>
  );
}

type DockLabelProps = {
  className?: string;
  children: React.ReactNode;
  isHovered?: MotionValue<number>;
};

function DockLabel({ children, className, isHovered }: DockLabelProps) {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    if (!isHovered) return;
    const unsubscribe = isHovered.on("change", (latest) => {
      setIsVisible(latest === 1);
    });
    return () => unsubscribe();
  }, [isHovered]);

  return (
    <AnimatePresence>
      {isVisible && (
        <motion.div
          initial={{ opacity: 0, y: 0 }}
          animate={{ opacity: 1, y: -10 }}
          exit={{ opacity: 0, y: 0 }}
          transition={{ duration: 0.2 }}
          className={cn(
            "absolute -top-6 left-1/2 w-fit whitespace-pre rounded-md border border-neutral-700 bg-[#120F17] px-2 py-0.5 text-xs text-white",
            className,
          )}
          role="tooltip"
          style={{ x: "-50%" }}
        >
          {children}
        </motion.div>
      )}
    </AnimatePresence>
  );
}

type DockIconProps = {
  className?: string;
  children: React.ReactNode;
  isHovered?: MotionValue<number>;
};

function DockIcon({ children, className }: DockIconProps) {
  return <div className={cn("flex items-center justify-center", className)}>{children}</div>;
}

export function Dock({
  items = DEFAULT_ITEMS,
  className,
  panelClassName,
  spring = { mass: 0.1, stiffness: 150, damping: 12 },
  magnification = 70,
  distance = 200,
  panelHeight = 68,
  dockHeight = 256,
  baseItemSize = 50,
}: DockProps) {
  const mouseX = useMotionValue(Infinity);
  const isHovered = useMotionValue(0);

  const maxHeight = useMemo(
    () => Math.max(dockHeight, magnification + magnification / 2 + 4),
    [dockHeight, magnification],
  );
  const heightRow = useTransform(isHovered, [0, 1], [panelHeight, maxHeight]);
  const height = useSpring(heightRow, spring);

  return (
    <motion.div
      style={{ height, scrollbarWidth: "none" }}
      className={cn("mx-2 flex max-w-full items-center", className)}
    >
      <motion.div
        onMouseMove={({ clientX }) => {
          isHovered.set(1);
          mouseX.set(clientX);
        }}
        onMouseLeave={() => {
          isHovered.set(0);
          mouseX.set(Infinity);
        }}
        className={cn(
          "absolute bottom-2 left-1/2 transform -translate-x-1/2 flex items-end w-fit gap-4 rounded-2xl border-neutral-700 border-2 pb-2 px-4",
          panelClassName,
        )}
        style={{ height: panelHeight }}
        role="toolbar"
        aria-label="Application dock"
      >
        {items.map((item, index) => (
          <DockItem
            // biome-ignore lint/suspicious/noArrayIndexKey: items carry no stable id
            key={index}
            onClick={item.onClick}
            className={item.className}
            mouseX={mouseX}
            spring={spring}
            distance={distance}
            magnification={magnification}
            baseItemSize={baseItemSize}
            label={item.label}
          >
            <DockIcon>{item.icon}</DockIcon>
            <DockLabel>{item.label}</DockLabel>
          </DockItem>
        ))}
      </motion.div>
    </motion.div>
  );
}

export default Dock;