Skip to content
Shaken UI
Sign in

Toolbar

Save

A toolbar with one shared tooltip that glides and resizes between items, one hover highlight, and toggle groups whose adjacent pressed toggles merge into a single shape.

Category
Layout
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Toolbar preview

Release notes for 2.4: approvals now time out after 24 hours, and a reviewer can reassign a pending tool call without restarting the run.

Installation

npx @shakenui/cli add toolbar

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add toolbar --dry-run

Usage

toolbar-example.tsx
"use client";

import { useState } from "react";
import { Toolbar, ToolbarButton, ToolbarSeparator, ToolbarToggle, ToolbarToggleGroup } from "@/components/shaken/ui/toolbar";

const icon = { viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" } as const;

const align = { left: "text-left", center: "text-center", right: "text-right" } as const;

export default function ToolbarExample() {
  const [style, setStyle] = useState<string[]>(["bold"]);
  const [alignment, setAlignment] = useState<string[]>(["left"]);
  const bold = style.includes("bold");
  const italic = style.includes("italic");
  const underline = style.includes("underline");

  return (
    <div className="grid w-full max-w-md gap-4">
      <Toolbar aria-label="Text formatting" className="justify-self-start">
        <ToolbarToggleGroup multiple aria-label="Text style" value={style} onValueChange={setStyle}>
          <ToolbarToggle value="bold" label="Bold" shortcut="⌘B" keys="Meta+B">
            <svg {...icon}><path d="M4.75 2.75h4a2.5 2.5 0 0 1 0 5h-4zM4.75 7.75h4.75a2.75 2.75 0 0 1 0 5.5H4.75z" /></svg>
          </ToolbarToggle>
          <ToolbarToggle value="italic" label="Italic" shortcut="⌘I" keys="Meta+I">
            <svg {...icon}><path d="M6.75 2.75h5M4.25 13.25h5M9.75 2.75l-3.5 10.5" /></svg>
          </ToolbarToggle>
          <ToolbarToggle value="underline" label="Underline" shortcut="⌘U" keys="Meta+U">
            <svg {...icon}><path d="M4.25 2.75v4.5a3.75 3.75 0 0 0 7.5 0v-4.5M3.25 13.75h9.5" /></svg>
          </ToolbarToggle>
        </ToolbarToggleGroup>
        <ToolbarSeparator />
        <ToolbarToggleGroup aria-label="Alignment" value={alignment} onValueChange={setAlignment}>
          <ToolbarToggle value="left" label="Align left">
            <svg {...icon}><path d="M2.75 3.75h10.5M2.75 7.25h6.5M2.75 10.75h10.5M2.75 14.25h6.5" /></svg>
          </ToolbarToggle>
          <ToolbarToggle value="center" label="Align center">
            <svg {...icon}><path d="M2.75 3.75h10.5M4.75 7.25h6.5M2.75 10.75h10.5M4.75 14.25h6.5" /></svg>
          </ToolbarToggle>
          <ToolbarToggle value="right" label="Align right">
            <svg {...icon}><path d="M2.75 3.75h10.5M6.75 7.25h6.5M2.75 10.75h10.5M6.75 14.25h6.5" /></svg>
          </ToolbarToggle>
        </ToolbarToggleGroup>
        <ToolbarSeparator />
        <ToolbarButton label="Insert link" shortcut="⌘K" keys="Meta+K">
          <svg {...icon}><path d="M6.75 9.25a2.75 2.75 0 0 0 3.9.1l2-2a2.75 2.75 0 0 0-3.9-3.9l-.6.6M9.25 6.75a2.75 2.75 0 0 0-3.9-.1l-2 2a2.75 2.75 0 0 0 3.9 3.9l.6-.6" /></svg>
        </ToolbarButton>
        <ToolbarButton label="Add comment" shortcut="⌘⌥M" keys="Meta+Alt+M">
          <svg {...icon}><path d="M2.75 4.25a1.5 1.5 0 0 1 1.5-1.5h7.5a1.5 1.5 0 0 1 1.5 1.5v5.5a1.5 1.5 0 0 1-1.5 1.5H7l-3 2.5v-2.5h0a1.25 1.25 0 0 1-1.25-1.25z" /></svg>
        </ToolbarButton>
      </Toolbar>
      <p
        className={
          "text-sm leading-relaxed text-zinc-700 transition-[font-weight] duration-200 ease-out motion-reduce:transition-none dark:text-zinc-300 " +
          align[(alignment[0] ?? "left") as keyof typeof align] +
          (bold ? " font-semibold text-zinc-950 dark:text-white" : " font-normal") +
          (italic ? " italic" : "")
        }
      >
        <span
          className={
            "bg-[linear-gradient(currentColor,currentColor)] bg-[length:0%_1px] bg-left-bottom bg-no-repeat pb-px " +
            "transition-[background-size] duration-300 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none " +
            (underline ? "bg-[length:100%_1px]" : "")
          }
        >
          Release notes for 2.4: approvals now time out after 24 hours, and a reviewer can reassign a pending tool call
          without restarting the run.
        </span>
      </p>
    </div>
  );
}

API

PropTypeDefaultDescription
aria-labelstring—Toolbar, ToolbarToggleGroup: names the toolbar or group for screen readers. Required.
tooltipSide"top" | "bottom""top"Toolbar: side the shared tooltip appears on.
tooltipDelaynumber400Toolbar: hover time before the tooltip first appears. Moving between items while it is up, or returning within 400ms, is instant.
orientation / loopFocus / disabledBase UI Toolbar props—Toolbar: passed to Base UI Toolbar.Root.
label / shortcut / keysstring—ToolbarButton, ToolbarToggle: the tooltip text and accessible name, the shortcut shown in the tooltip, and its aria-keyshortcuts form such as Meta+B.
multiplebooleanfalseToolbarToggleGroup: lets several toggles be pressed; adjacent pressed toggles join into one shape. Without it one fill glides to the pressed toggle.
value / defaultValue / onValueChangestring[]—ToolbarToggleGroup: the pressed values.
allowEmptybooleanfalseToolbarToggleGroup: in single mode, lets the pressed toggle be released.
ToolbarToggle valuestring—The value this toggle adds to its group.

Accessibility

  • Built on Base UI Toolbar: role="toolbar" with a roving tabindex, so Tab enters once and Arrow keys, Home, and End move between items.
  • Toggles are buttons with aria-pressed inside labeled groups; every icon-only item takes its accessible name from label and can expose aria-keyshortcuts.
  • The shared tooltip repeats the visible label, so it is aria-hidden. It appears on keyboard focus in place without gliding, hides on Escape, on press, and when focus or the pointer leaves.
  • Keyboard moves never animate position; only pointer hover glides the tooltip and highlight.
  • Under reduced motion the tooltip, hover highlight, and alignment fill move without animating and toggles press without scaling.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/toolbar.tsxtoolbar
  • npm packages: @base-ui/react@^1.9.0, motion@^14.14.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/toolbar/0.1.0.json.

ui/toolbar.tsxShow
ui/toolbar.tsx
"use client";

import { Toggle as BaseToggle } from "@base-ui/react/toggle";
import { ToggleGroup as BaseToggleGroup } from "@base-ui/react/toggle-group";
import { Toolbar as BaseToolbar } from "@base-ui/react/toolbar";
import { AnimatePresence, MotionConfig, motion, useReducedMotion } from "motion/react";
import {
  createContext,
  useContext,
  useEffect,
  useId,
  useLayoutEffect,
  useRef,
  useState,
} from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const ease = [0.23, 1, 0.32, 1] as const;
const glide = { type: "spring", bounce: 0, duration: 0.28 } as const;

interface Tip {
  label: string;
  shortcut?: string;
  /** Center of the item, relative to the toolbar. */
  center: number;
  /** Whether the bubble jumps there instead of gliding. */
  snap: boolean;
}

interface Highlight {
  x: number;
  width: number;
  visible: boolean;
  snap: boolean;
}

export interface ToolbarProps extends Omit<BaseToolbar.Root.Props, "className"> {
  /** Names the toolbar for screen readers. */
  "aria-label": string;
  /** Side of the toolbar the shared tooltip appears on. */
  tooltipSide?: "top" | "bottom";
  /** Milliseconds of hover before the tooltip first appears. Moving to another item while it is up is instant. */
  tooltipDelay?: number;
  className?: string;
}

/**
 * A toolbar with one shared tooltip and one hover highlight. The tooltip waits briefly before it
 * first appears, then glides and resizes from item to item instead of popping per item, and hides
 * at once when the pointer leaves. Arrow keys move focus between items (roving tabindex); keyboard
 * focus shows the tooltip in place without gliding.
 */
export function Toolbar({ tooltipSide = "top", tooltipDelay = 400, className, children, ...props }: ToolbarProps) {
  const reduce = useReducedMotion();
  const rootRef = useRef<HTMLDivElement>(null);
  const [tip, setTip] = useState<Tip | null>(null);
  const [tipVisible, setTipVisible] = useState(false);
  const [highlight, setHighlight] = useState<Highlight>({ x: 0, width: 0, visible: false, snap: true });
  const showTimer = useRef<number | undefined>(undefined);
  const lastHidden = useRef(0);
  const visibleRef = useRef(false);
  visibleRef.current = tipVisible;

  useEffect(() => () => window.clearTimeout(showTimer.current), []);

  const measure = (item: HTMLElement) => {
    const root = rootRef.current!;
    const r = item.getBoundingClientRect();
    const base = root.getBoundingClientRect();
    return { x: r.left - base.left - root.clientLeft, width: r.width };
  };

  const describe = (item: HTMLElement, snap: boolean): Tip | null => {
    const label = item.dataset.toolbarLabel;
    if (!label) return null;
    const { x, width } = measure(item);
    return { label, shortcut: item.dataset.toolbarShortcut || undefined, center: x + width / 2, snap };
  };

  const hideTip = () => {
    window.clearTimeout(showTimer.current);
    if (visibleRef.current) lastHidden.current = Date.now();
    setTipVisible(false);
  };

  const itemFrom = (target: EventTarget | null) => {
    const el = (target as HTMLElement | null)?.closest<HTMLElement>("[data-toolbar-item]");
    return el && rootRef.current?.contains(el) && !el.hasAttribute("data-disabled") ? el : null;
  };

  return (
    <MotionConfig reducedMotion="user">
      <BaseToolbar.Root
        ref={rootRef}
        className={cx(
          "relative isolate inline-flex items-center gap-0.5 rounded-xl border p-1",
          "border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
          "dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
          className,
        )}
        onPointerOver={(event) => {
          if (event.pointerType === "touch") return;
          const item = itemFrom(event.target);
          if (!item) return;
          const { x, width } = measure(item);
          setHighlight((h) => ({ x, width, visible: true, snap: !h.visible }));
          if (visibleRef.current) {
            const next = describe(item, false);
            if (next) setTip(next);
            return;
          }
          window.clearTimeout(showTimer.current);
          // Recently hidden: come back without the delay.
          const warm = Date.now() - lastHidden.current < 400;
          showTimer.current = window.setTimeout(
            () => {
              const next = describe(item, true);
              if (!next) return;
              setTip(next);
              setTipVisible(true);
            },
            warm ? 0 : tooltipDelay,
          );
        }}
        onPointerLeave={() => {
          setHighlight((h) => ({ ...h, visible: false }));
          hideTip();
        }}
        onPointerDown={hideTip}
        onFocus={(event) => {
          const item = itemFrom(event.target);
          if (!item || !item.matches(":focus-visible")) return;
          window.clearTimeout(showTimer.current);
          const next = describe(item, true);
          if (!next) return;
          setTip(next);
          setTipVisible(true);
        }}
        onBlur={(event) => {
          if (!rootRef.current?.contains(event.relatedTarget as Node | null)) hideTip();
        }}
        onKeyDown={(event) => {
          if (event.key === "Escape" && visibleRef.current) {
            event.stopPropagation();
            hideTip();
          }
        }}
        {...props}
      >
        <motion.span
          aria-hidden="true"
          className="pointer-events-none absolute inset-y-1 left-0 -z-10 rounded-md bg-zinc-950/[0.045] dark:bg-white/[0.07]"
          initial={false}
          animate={{ x: highlight.x, width: highlight.width, opacity: highlight.visible ? 1 : 0 }}
          transition={
            reduce
              ? { duration: 0 }
              : {
                  x: highlight.snap ? { duration: 0 } : glide,
                  width: highlight.snap ? { duration: 0 } : glide,
                  opacity: { duration: highlight.visible ? 0.15 : 0.12, ease: "easeOut" },
                }
          }
        />
        {children}
        <SharedTooltip tip={tip} visible={tipVisible} side={tooltipSide} reduce={!!reduce} />
      </BaseToolbar.Root>
    </MotionConfig>
  );
}

function SharedTooltip({ tip, visible, side, reduce }: { tip: Tip | null; visible: boolean; side: "top" | "bottom"; reduce: boolean }) {
  const labelRef = useRef<HTMLSpanElement>(null);
  const [width, setWidth] = useState(0);
  const key = tip ? `${tip.label}|${tip.shortcut ?? ""}` : "";

  useLayoutEffect(() => {
    if (labelRef.current) setWidth(labelRef.current.offsetWidth + 16);
  }, [key]);

  if (!tip) return null;
  const snap = reduce || tip.snap;

  return (
    <motion.div
      aria-hidden="true"
      className={cx(
        "pointer-events-none absolute left-0 z-10 flex h-6 items-center justify-center overflow-hidden rounded-md",
        "bg-zinc-900 text-xs font-medium whitespace-nowrap text-white shadow-[0_4px_12px_-4px_rgb(0_0_0/0.3)]",
        "dark:bg-zinc-100 dark:text-zinc-900",
        side === "top" ? "bottom-full mb-2 origin-bottom" : "top-full mt-2 origin-top",
      )}
      initial={false}
      animate={{ x: tip.center - width / 2, width, opacity: visible ? 1 : 0, scale: visible || reduce ? 1 : 0.97 }}
      transition={{
        x: snap ? { duration: 0 } : glide,
        width: snap ? { duration: 0 } : glide,
        opacity: visible ? { duration: reduce ? 0 : 0.14, ease } : { duration: 0.05 },
        scale: visible ? { duration: 0.16, ease } : { duration: 0 },
      }}
    >
      <AnimatePresence mode="popLayout" initial={false}>
        <motion.span
          key={key}
          ref={labelRef}
          className="inline-flex items-center gap-1.5"
          initial={snap ? false : { opacity: 0, filter: "blur(2px)" }}
          animate={{ opacity: 1, filter: "blur(0px)" }}
          exit={snap ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, filter: "blur(2px)", transition: { duration: 0.1 } }}
          transition={{ duration: 0.16, ease }}
        >
          {tip.label}
          {tip.shortcut ? <span className="font-mono text-[11px] text-white/55 dark:text-zinc-900/55">{tip.shortcut}</span> : null}
        </motion.span>
      </AnimatePresence>
    </motion.div>
  );
}

const itemClass = cx(
  "group/tog relative inline-flex size-8 shrink-0 items-center justify-center rounded-md select-none",
  "text-zinc-600 hover:text-zinc-950 data-[pressed]:text-zinc-950 dark:text-zinc-400 dark:hover:text-white dark:data-[pressed]:text-white",
  "transition-[color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none",
  "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-1 focus-visible:outline-sky-500",
  "data-[disabled]:pointer-events-none data-[disabled]:opacity-40",
  "[&_svg]:size-4 [&_svg]:shrink-0",
);

export interface ToolbarButtonProps extends Omit<BaseToolbar.Button.Props, "className"> {
  /** Shown in the shared tooltip and used as the accessible name. */
  label: string;
  /** Shown beside the label in the tooltip and exposed as `aria-keyshortcuts` when `keys` is set. */
  shortcut?: string;
  /** The shortcut in `aria-keyshortcuts` form, such as `Meta+K`. */
  keys?: string;
  className?: string;
}

/** An icon button in the toolbar. */
export function ToolbarButton({ label, shortcut, keys, className, children, ...props }: ToolbarButtonProps) {
  return (
    <BaseToolbar.Button
      aria-label={label}
      aria-keyshortcuts={keys}
      data-toolbar-item=""
      data-toolbar-label={label}
      data-toolbar-shortcut={shortcut}
      className={cx(itemClass, className)}
      {...props}
    >
      <span className="relative flex items-center justify-center">{children}</span>
    </BaseToolbar.Button>
  );
}

const GroupContext = createContext<{ multiple: boolean; value: readonly string[]; layoutId: string } | null>(null);

export interface ToolbarToggleGroupProps extends Omit<BaseToggleGroup.Props<string>, "className" | "value" | "defaultValue" | "onValueChange"> {
  /** Names the group, such as "Text style". */
  "aria-label": string;
  /** Pressed values. */
  value?: string[];
  defaultValue?: string[];
  onValueChange?: (value: string[]) => void;
  /** Lets several toggles be pressed at once. Adjacent pressed toggles merge into one shape. */
  multiple?: boolean;
  /** In single mode, lets the pressed toggle be released so none is pressed. */
  allowEmpty?: boolean;
  className?: string;
}

/**
 * A group of toggles. With `multiple`, neighbors that are pressed together join into one continuous
 * shape. Without it, one fill glides to the pressed toggle.
 */
export function ToolbarToggleGroup({
  multiple = false,
  allowEmpty = false,
  value: valueProp,
  defaultValue = [],
  onValueChange,
  className,
  children,
  ...props
}: ToolbarToggleGroupProps) {
  const ref = useRef<HTMLDivElement>(null);
  const [valueState, setValueState] = useState<string[]>(defaultValue);
  const value = valueProp ?? valueState;
  const layoutId = `toolbar-fill-${useId()}`;

  // Mark which pressed toggles touch a pressed neighbor, before paint, so the shapes join without a flash.
  useLayoutEffect(() => {
    const items = Array.from(ref.current?.querySelectorAll<HTMLElement>("[data-toggle-value]") ?? []);
    const pressed = items.map((el) => value.includes(el.dataset.toggleValue ?? ""));
    items.forEach((el, i) => {
      el.toggleAttribute("data-join-prev", multiple && pressed[i] && !!pressed[i - 1]);
      el.toggleAttribute("data-join-next", multiple && pressed[i] && !!pressed[i + 1]);
    });
  }, [value, multiple]);

  return (
    <GroupContext.Provider value={{ multiple, value, layoutId }}>
      <BaseToggleGroup
        ref={ref}
        multiple={multiple}
        value={value}
        onValueChange={(next) => {
          if (!multiple && next.length === 0 && !allowEmpty) return;
          if (valueProp === undefined) setValueState(next);
          onValueChange?.(next);
        }}
        render={<BaseToolbar.Group />}
        className={cx("flex items-center gap-0.5", className)}
        {...props}
      >
        {children}
      </BaseToggleGroup>
    </GroupContext.Provider>
  );
}

export interface ToolbarToggleProps extends Omit<BaseToggle.Props<string>, "className" | "value"> {
  value: string;
  /** Shown in the shared tooltip and used as the accessible name. */
  label: string;
  shortcut?: string;
  /** The shortcut in `aria-keyshortcuts` form, such as `Meta+B`. */
  keys?: string;
  className?: string;
}

/** A toggle inside a ToolbarToggleGroup. */
export function ToolbarToggle({ value, label, shortcut, keys, className, children, ...props }: ToolbarToggleProps) {
  const group = useContext(GroupContext);
  const pressed = group?.value.includes(value) ?? false;

  return (
    <BaseToolbar.Button
      render={<BaseToggle value={value} {...props} />}
      aria-label={label}
      aria-keyshortcuts={keys}
      data-toolbar-item=""
      data-toolbar-label={label}
      data-toolbar-shortcut={shortcut}
      data-toggle-value={value}
      className={cx(itemClass, className)}
    >
      {group?.multiple === false ? (
        pressed ? (
          <motion.span
            aria-hidden="true"
            layoutId={group.layoutId}
            transition={{ type: "spring", bounce: 0, duration: 0.32 }}
            className="absolute inset-0 rounded-md bg-zinc-950/[0.08] shadow-[inset_0_0_0_1px_rgb(0_0_0/0.06)] dark:bg-white/[0.13] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.08)]"
          />
        ) : null
      ) : (
        <span
          aria-hidden="true"
          className={cx(
            "absolute inset-0 rounded-md bg-zinc-950/[0.08] dark:bg-white/[0.13]",
            "opacity-0 motion-safe:scale-x-[0.55]",
            "transition-[opacity,scale,border-radius] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
            "group-data-[pressed]/tog:opacity-100 group-data-[pressed]/tog:scale-x-100",
            // Joined to a pressed neighbor: square that side, bridge the 2px gap, and grow from it.
            "group-data-[join-prev]/tog:-left-px group-data-[join-prev]/tog:origin-left group-data-[join-prev]/tog:rounded-l-none",
            "group-data-[join-next]/tog:-right-px group-data-[join-next]/tog:origin-right group-data-[join-next]/tog:rounded-r-none",
            "group-data-[join-prev]/tog:group-data-[join-next]/tog:origin-center",
          )}
        />
      )}
      <span className="relative flex items-center justify-center">{children}</span>
    </BaseToolbar.Button>
  );
}

/** A hairline between groups. */
export function ToolbarSeparator({ className, ...props }: Omit<BaseToolbar.Separator.Props, "className"> & { className?: string }) {
  return <BaseToolbar.Separator className={cx("mx-1 h-5 w-px shrink-0 bg-zinc-950/10 dark:bg-white/15", className)} {...props} />;
}