Skip to content
Shaken UI
Sign in

Reactions

Save

Emoji reaction chips with counts under a message: press a chip to toggle your reaction, or pick from a tray and watch the emoji fly into its chip while the count rolls.

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

Preview

Reactions preview

Mara Okafor

The eval suite is green on the new retrieval prompt: answer accuracy went from 81% to 88% with no extra latency. Shipping it behind the flag this afternoon.

Installation

npx @shakenui/cli add reactions

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

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

Usage

reactions-example.tsx
"use client";

import { Reactions } from "@/components/shaken/ui/reactions";

export default function ReactionsExample() {
  return (
    <article className="grid w-full max-w-md grid-cols-[auto_1fr] gap-x-3 gap-y-2">
      <span
        aria-hidden="true"
        className="row-span-3 flex size-8 items-center justify-center rounded-full bg-zinc-950/[0.06] text-xs font-medium text-zinc-700 dark:bg-white/[0.1] dark:text-zinc-300"
      >
        MO
      </span>
      <p className="flex items-baseline gap-2 text-sm">
        <span className="font-semibold text-zinc-950 dark:text-white">Mara Okafor</span>
        <time className="text-xs text-zinc-500">10:42</time>
      </p>
      <p className="text-sm leading-relaxed text-zinc-700 dark:text-zinc-300">
        The eval suite is green on the new retrieval prompt: answer accuracy went from 81% to 88% with no extra latency. Shipping it
        behind the flag this afternoon.
      </p>
      <Reactions
        className="pt-1"
        defaultValue={[
          { emoji: "๐ŸŽ‰", label: "Party popper", count: 4 },
          { emoji: "๐Ÿš€", label: "Rocket", count: 2, reacted: true },
          { emoji: "๐Ÿ‘€", label: "Eyes", count: 1 },
        ]}
      />
    </article>
  );
}

API

PropTypeDefaultDescription
value / defaultValue{ emoji, label, count, reacted? }[]โ€”The reactions. label is the spoken name, such as Thumbs up; reacted marks the current user's own.
onValueChange(value) => voidโ€”Called with the next reactions when you add, toggle, or remove one. Chips that reach zero are removed.
options{ emoji, label }[]defaultReactionOptionsEmoji offered by the add button's tray.
readOnlybooleanfalseHides the add button and disables the chips.
addLabelstring"Add reaction"Accessible name of the add button.

Accessibility

  • The row is a group labeled Reactions; each chip is a toggle button with aria-pressed and a name like "Party popper, 4 reactions". Emoji glyphs are hidden from screen readers.
  • The add button opens a Base UI Popover tray; focus starts on the first emoji, Left and Right Arrow, Home and End move between them, and Escape closes it and returns focus.
  • Adding or removing a reaction is announced in a polite live region with the new total.
  • Under reduced motion the emoji does not fly and counts change in place without rolling.

Files

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

  • src/components/shaken/ui/reactions.tsxreactions
  • 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/reactions/0.1.0.json.

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

import { Popover as BasePopover } from "@base-ui/react/popover";
import { AnimatePresence, MotionConfig, animate, motion, useReducedMotion } from "motion/react";
import { useEffect, useLayoutEffect, useRef, useState } from "react";

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

export interface Reaction {
  emoji: string;
  /** Spoken name, such as "Thumbs up". */
  label: string;
  count: number;
  /** Whether the current user is one of the reactors. */
  reacted?: boolean;
}

export interface ReactionOption {
  emoji: string;
  label: string;
}

export const defaultReactionOptions: ReactionOption[] = [
  { emoji: "๐Ÿ‘", label: "Thumbs up" },
  { emoji: "โค๏ธ", label: "Heart" },
  { emoji: "๐Ÿ˜‚", label: "Laughing" },
  { emoji: "๐ŸŽ‰", label: "Party popper" },
  { emoji: "๐Ÿ‘€", label: "Eyes" },
  { emoji: "๐Ÿš€", label: "Rocket" },
];

export interface ReactionsProps {
  /** Controlled reactions. */
  value?: Reaction[];
  defaultValue?: Reaction[];
  onValueChange?: (value: Reaction[]) => void;
  /** Emoji offered by the add button. */
  options?: ReactionOption[];
  /** Hides the add button, for read-only messages. */
  readOnly?: boolean;
  /** Label of the add button. */
  addLabel?: string;
  className?: string;
}

interface Flight {
  id: number;
  emoji: string;
  from: DOMRect;
}

/**
 * Emoji reaction chips with counts. Pressing a chip toggles your reaction; the add button opens a
 * tray of emoji, and the picked one flies along a short arc into its chip before the count rolls.
 * Under reduced motion the chip updates in place.
 */
export function Reactions({
  value: valueProp,
  defaultValue = [],
  onValueChange,
  options = defaultReactionOptions,
  readOnly = false,
  addLabel = "Add reaction",
  className,
}: ReactionsProps) {
  const reduce = useReducedMotion();
  const rootRef = useRef<HTMLDivElement>(null);
  const [valueState, setValueState] = useState(defaultValue);
  const value = valueProp ?? valueState;
  const [open, setOpen] = useState(false);
  const [flights, setFlights] = useState<Flight[]>([]);
  // Emoji whose increment is still in the air: their chip shows the old count until it lands.
  const [inAir, setInAir] = useState<string[]>([]);
  // Emoji whose chip just received a reaction, for the landing pop.
  const [popKey, setPopKey] = useState<Record<string, number>>({});
  const [message, setMessage] = useState("");
  const flightId = useRef(0);

  const commit = (next: Reaction[]) => {
    if (valueProp === undefined) setValueState(next);
    onValueChange?.(next);
  };

  const pop = (emoji: string) => setPopKey((keys) => ({ ...keys, [emoji]: (keys[emoji] ?? 0) + 1 }));

  const toggle = (emoji: string, from?: DOMRect) => {
    const existing = value.find((r) => r.emoji === emoji);
    const label = existing?.label ?? options.find((o) => o.emoji === emoji)?.label ?? emoji;
    if (existing?.reacted) {
      commit(
        value
          .map((r) => (r.emoji === emoji ? { ...r, count: r.count - 1, reacted: false } : r))
          .filter((r) => r.count > 0),
      );
      setMessage(`Removed your ${label} reaction.`);
      return;
    }
    const next = existing
      ? value.map((r) => (r.emoji === emoji ? { ...r, count: r.count + 1, reacted: true } : r))
      : [...value, { emoji, label, count: 1, reacted: true }];
    commit(next);
    setMessage(`You reacted with ${label}. ${(existing?.count ?? 0) + 1} in total.`);
    if (from && !reduce) {
      setInAir((list) => [...list, emoji]);
      setFlights((list) => [...list, { id: ++flightId.current, emoji, from }]);
    } else {
      pop(emoji);
    }
  };

  const land = (flight: Flight) => {
    setFlights((list) => list.filter((f) => f.id !== flight.id));
    setInAir((list) => {
      const index = list.indexOf(flight.emoji);
      return index === -1 ? list : [...list.slice(0, index), ...list.slice(index + 1)];
    });
    pop(flight.emoji);
  };

  return (
    <MotionConfig reducedMotion="user">
      <div ref={rootRef} role="group" aria-label="Reactions" className={cx("relative flex flex-wrap items-center gap-1.5", className)}>
        <AnimatePresence initial={false} mode="popLayout">
          {value.map((reaction) => {
            const pending = inAir.filter((e) => e === reaction.emoji).length;
            const shownCount = reaction.count - pending;
            const arriving = shownCount <= 0;
            return (
              <motion.button
                key={reaction.emoji}
                type="button"
                layout="position"
                aria-pressed={!!reaction.reacted}
                aria-label={`${reaction.label}, ${reaction.count} ${reaction.count === 1 ? "reaction" : "reactions"}`}
                disabled={readOnly}
                onClick={() => toggle(reaction.emoji)}
                initial={{ opacity: 0, scale: 0.8 }}
                animate={{ opacity: arriving ? 0.001 : 1, scale: arriving ? 0.85 : 1 }}
                exit={{ opacity: 0, scale: 0.85, transition: { duration: reduce ? 0 : 0.14, ease: "easeOut" } }}
                transition={
                  reduce
                    ? { duration: 0 }
                    : { layout: { type: "spring", bounce: 0, duration: 0.3 }, default: { type: "spring", bounce: 0.35, duration: 0.4 } }
                }
                className={cx(
                  "inline-flex h-7 items-center gap-1.5 rounded-lg border pr-2 pl-1.5 select-none",
                  "transition-[background-color,border-color,color] duration-150 ease-out motion-reduce:transition-none",
                  "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
                  "disabled:cursor-default",
                  reaction.reacted
                    ? "border-zinc-950/25 bg-zinc-950/[0.05] text-zinc-950 dark:border-white/30 dark:bg-white/[0.1] dark:text-white"
                    : "border-zinc-950/10 bg-white text-zinc-600 enabled:hover:border-zinc-950/20 enabled:hover:bg-zinc-950/[0.04] dark:border-white/10 dark:bg-black dark:text-zinc-400 dark:enabled:hover:border-white/20 dark:enabled:hover:bg-white/[0.06]",
                )}
              >
                <motion.span
                  key={popKey[reaction.emoji] ?? 0}
                  data-reaction-emoji={reaction.emoji}
                  aria-hidden="true"
                  initial={popKey[reaction.emoji] ? { scale: reduce ? 1 : 1.35 } : false}
                  animate={{ scale: 1 }}
                  transition={{ type: "spring", bounce: 0.45, duration: 0.45 }}
                  className="text-[15px] leading-none"
                >
                  {reaction.emoji}
                </motion.span>
                <RollingCount value={Math.max(shownCount, 0)} reduce={!!reduce} />
              </motion.button>
            );
          })}
          {readOnly ? null : (
            <motion.div key="__add" layout="position" transition={reduce ? { duration: 0 } : { type: "spring", bounce: 0, duration: 0.3 }}>
              <BasePopover.Root open={open} onOpenChange={setOpen}>
                <BasePopover.Trigger
                  aria-label={addLabel}
                  className={cx(
                    "inline-flex size-7 items-center justify-center rounded-lg border select-none",
                    "border-zinc-950/10 bg-white text-zinc-500 hover:border-zinc-950/20 hover:bg-zinc-950/[0.04] hover:text-zinc-950",
                    "dark:border-white/10 dark:bg-black dark:hover:border-white/20 dark:hover:bg-white/[0.06] dark:hover:text-white",
                    "data-[popup-open]:border-zinc-950/20 data-[popup-open]:text-zinc-950 dark:data-[popup-open]:border-white/20 dark:data-[popup-open]:text-white",
                    "transition-[background-color,border-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.94] motion-reduce:transition-none",
                    "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
                  )}
                >
                  <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-4">
                    <path d="M13.9 8.6A6 6 0 1 1 7.4 2.1" />
                    <path d="M5.5 9.75c.6.8 1.45 1.25 2.5 1.25s1.9-.45 2.5-1.25" />
                    <path d="M6 6.25v.5M10 6.25v.5" />
                    <path d="M12.5 1.75v4M10.5 3.75h4" />
                  </svg>
                </BasePopover.Trigger>
                <BasePopover.Portal>
                  <BasePopover.Positioner side="top" align="start" sideOffset={8} className="z-50">
                    <BasePopover.Popup
                      aria-label="Pick a reaction"
                      className={cx(
                        "flex origin-(--transform-origin) gap-0.5 rounded-xl border p-1",
                        "border-zinc-950/10 bg-white shadow-[0_12px_32px_-8px_rgb(0_0_0/0.18)]",
                        "dark:border-white/15 dark:bg-black dark:shadow-[0_16px_48px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]",
                        "transition-[opacity,scale,translate] duration-160 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
                        "data-[starting-style]:opacity-0 motion-safe:data-[starting-style]:translate-y-1 motion-safe:data-[starting-style]:scale-95",
                        "data-[ending-style]:opacity-0 data-[ending-style]:duration-110 data-[ending-style]:ease-out",
                        "outline-none",
                      )}
                      onKeyDown={(event) => {
                        const buttons = Array.from(event.currentTarget.querySelectorAll<HTMLButtonElement>("button"));
                        const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
                        const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
                        if (step) {
                          event.preventDefault();
                          buttons[(index + step + buttons.length) % buttons.length]?.focus();
                        } else if (event.key === "Home" || event.key === "End") {
                          event.preventDefault();
                          buttons[event.key === "Home" ? 0 : buttons.length - 1]?.focus();
                        }
                      }}
                    >
                      {options.map((option) => {
                        const mine = value.some((r) => r.emoji === option.emoji && r.reacted);
                        return (
                          <button
                            key={option.emoji}
                            type="button"
                            aria-label={option.label}
                            aria-pressed={mine}
                            onClick={(event) => {
                              const from = event.currentTarget.querySelector("span")!.getBoundingClientRect();
                              setOpen(false);
                              toggle(option.emoji, mine ? undefined : from);
                            }}
                            className={cx(
                              "group/opt inline-flex size-9 items-center justify-center rounded-lg",
                              "transition-[background-color] duration-150 ease-out hover:bg-zinc-950/[0.05] dark:hover:bg-white/[0.08] motion-reduce:transition-none",
                              mine && "bg-zinc-950/[0.06] dark:bg-white/[0.1]",
                              "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
                            )}
                          >
                            <span
                              aria-hidden="true"
                              className={cx(
                                "text-xl leading-none",
                                "transition-[scale,translate] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
                                "motion-safe:group-hover/opt:-translate-y-0.5 motion-safe:group-hover/opt:scale-[1.18]",
                                "motion-safe:group-active/opt:scale-95",
                              )}
                            >
                              {option.emoji}
                            </span>
                          </button>
                        );
                      })}
                    </BasePopover.Popup>
                  </BasePopover.Positioner>
                </BasePopover.Portal>
              </BasePopover.Root>
            </motion.div>
          )}
        </AnimatePresence>
        <span role="status" aria-live="polite" className="sr-only">
          {message}
        </span>
        {flights.map((flight) => (
          <FlyingEmoji key={flight.id} flight={flight} root={rootRef} onLand={() => land(flight)} />
        ))}
      </div>
    </MotionConfig>
  );
}

/**
 * The picked emoji, tossed along a quadratic arc from the tray to its chip. Positioned inside the
 * reactions row and re-aimed every frame, so a chip that shifts while it flies still catches it.
 */
function FlyingEmoji({ flight, root, onLand }: { flight: Flight; root: React.RefObject<HTMLDivElement | null>; onLand: () => void }) {
  const ref = useRef<HTMLSpanElement>(null);
  const landRef = useRef(onLand);
  landRef.current = onLand;

  useLayoutEffect(() => {
    const el = ref.current;
    const host = root.current;
    if (!el || !host) return;
    const origin = host.getBoundingClientRect();
    // The start stays fixed in the row's coordinates; the end is measured each frame.
    const start = { x: flight.from.left + flight.from.width / 2 - origin.left, y: flight.from.top + flight.from.height / 2 - origin.top };
    const target = () => {
      const base = host.getBoundingClientRect();
      const r = host.querySelector<HTMLElement>(`[data-reaction-emoji="${flight.emoji}"]`)?.getBoundingClientRect();
      return r ? { x: r.left + r.width / 2 - base.left, y: r.top + r.height / 2 - base.top } : start;
    };
    const first = target();
    const lift = 28 + Math.hypot(first.x - start.x, first.y - start.y) * 0.35;
    const place = (t: number) => {
      const end = target();
      const control = { x: (start.x + end.x) / 2, y: Math.min(start.y, end.y) - lift };
      const u = 1 - t;
      const x = u * u * start.x + 2 * u * t * control.x + t * t * end.x;
      const y = u * u * start.y + 2 * u * t * control.y + t * t * end.y;
      el.style.transform = `translate(${x}px, ${y}px) translate(-50%, -50%) scale(${1.35 - 0.35 * t}) rotate(${-14 * u}deg)`;
    };
    place(0);
    const controls = animate(0, 1, {
      duration: 0.56,
      ease: [0.35, 0, 0.25, 1],
      onUpdate: place,
      onComplete: () => landRef.current(),
    });
    return () => controls.stop();
  }, [flight, root]);

  return (
    <span ref={ref} aria-hidden="true" className="pointer-events-none absolute top-0 left-0 z-10 text-[15px] leading-none will-change-transform">
      {flight.emoji}
    </span>
  );
}

/** A count whose changed digits roll: up when it grows, down when it shrinks. */
function RollingCount({ value, reduce }: { value: number; reduce: boolean }) {
  const previous = useRef(value);
  const direction = value >= previous.current ? 1 : -1;
  useEffect(() => {
    previous.current = value;
  }, [value]);
  const digits = String(value).split("");

  return (
    <span className="inline-flex font-mono text-xs leading-4 tabular-nums">
      {digits.map((digit, i) => (
        <span key={digits.length - i} className="relative inline-flex h-4 overflow-hidden">
          <AnimatePresence initial={false} mode="popLayout" custom={direction}>
            <motion.span
              key={digit}
              custom={direction}
              variants={{
                enter: (d: number) => ({ y: reduce ? 0 : `${d * 100}%`, opacity: reduce ? 1 : 0 }),
                center: { y: 0, opacity: 1 },
                exit: (d: number) => ({ y: reduce ? 0 : `${-d * 100}%`, opacity: 0 }),
              }}
              initial="enter"
              animate="center"
              exit="exit"
              transition={reduce ? { duration: 0 } : { type: "spring", bounce: 0.2, duration: 0.32 }}
              className="inline-block"
            >
              {digit}
            </motion.span>
          </AnimatePresence>
        </span>
      ))}
    </span>
  );
}