Skip to content
Shaken UI
Sign in

Recommendation Card

Save

One action an agent suggests, with a short rationale, a three-bar confidence meter, Accept, and an alternatives drawer that swaps another option into the main slot as a shared element.

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

Preview

Recommendation Card preview

Who should own the Northwind renewal?

PR

Assign to Priya Raman

She ran the last two Northwind renewals and closed both a week early. Her pipeline has room this quarter.

High confidence
Accepted

Other options

Installation

npx @shakenui/cli add recommendation-card

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

npx @shakenui/cli add recommendation-card --dry-run

Usage

recommendation-card-example.tsx
"use client";

import { RecommendationCard, type RecommendationOption } from "@/components/shaken/agent/recommendation-card";

function Initials({ children }: { children: string }) {
  return (
    <span className="flex size-full items-center justify-center rounded-full border border-zinc-950/10 bg-zinc-950/[0.04] text-[11px] font-medium text-zinc-700 dark:border-white/15 dark:bg-white/[0.06] dark:text-zinc-300">
      {children}
    </span>
  );
}

const options: RecommendationOption[] = [
  {
    id: "priya",
    title: "Assign to Priya Raman",
    rationale: "She ran the last two Northwind renewals and closed both a week early. Her pipeline has room this quarter.",
    confidence: "high",
    media: <Initials>PR</Initials>,
  },
  {
    id: "tomas",
    title: "Assign to Tomas Lindqvist",
    rationale: "Owns the Kestrel account in the same region, but is carrying 14 open deals.",
    confidence: "medium",
    media: <Initials>TL</Initials>,
    note: "Needs review",
  },
  {
    id: "queue",
    title: "Leave it in the renewals queue",
    rationale: "Nobody has touched the account in 60 days, so there is little history to go on.",
    confidence: "none",
    media: <Initials>Q</Initials>,
    note: "No signal",
  },
];

export default function RecommendationCardExample() {
  return (
    <RecommendationCard
      className="max-w-md"
      question="Who should own the Northwind renewal?"
      options={options}
      onDismiss={() => {}}
      onUndo={() => {}}
    />
  );
}

API

PropTypeDefaultDescription
options{ id, title, rationale?, confidence, media?, note? }[]—The first option is the recommendation; the rest are alternatives. confidence is high, medium, low or none.
questionReactNode—The question being answered, shown above the suggestion.
defaultValuestringthe first optionId of the option in the main slot initially.
onValueChange(id) => void—Called when an alternative is swapped in.
onAccept(option) => void—Called with the option in the main slot when Accept is pressed.
onDismiss() => void—Adds a Dismiss button.
onUndo() => void—Adds an Undo button after accepting.
acceptLabelstring"Accept"Text of the primary button.
acceptedLabel(option) => ReactNode"Accepted"Text after accepting.
ConfidenceMeter level"high" | "medium" | "low" | "none"—ConfidenceMeter: three rising bars; three for high, two for medium, one for low, none for no signal.
ConfidenceMeter showLabelbooleanfalseConfidenceMeter: shows the level as text beside the bars.

Accessibility

  • The card is a section labelled by the suggestion's title. The confidence meter is role="img" with its level as the label, and the level is also written out.
  • Alternatives is a button with aria-expanded and aria-controls; the closed drawer is inert. Each alternative is a button that swaps it in, and focus stays on the same row afterwards.
  • Swapping and accepting are announced through a polite live region ("Now suggesting: Assign to Tomas Lindqvist. Medium confidence.").
  • Under reduced motion the shared-element travel, the rationale cross-fade and the drawer are instant.

Files

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

  • src/components/shaken/agent/recommendation-card.tsxrecommendation-card
  • npm packages: motion@^14.14.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/recommendation-card/0.1.0.json.

agent/recommendation-card.tsxShow
agent/recommendation-card.tsx
"use client";

import { AnimatePresence, LayoutGroup, motion, useReducedMotion } from "motion/react";
import { type ComponentProps, type ReactNode, useEffect, useId, useRef, useState } from "react";

/*
 * Recommendation card: one action an agent suggests, why, and how sure it is, with Accept as the
 * main action. Alternatives open in a drawer inside the card; choosing one swaps it into the main
 * slot as a shared element (its title and media travel up while the previous suggestion travels
 * down into the list), and the confidence meter refills bar by bar.
 *
 * Under reduced motion the swap and the drawer are instant.
 */

export type ConfidenceLevel = "high" | "medium" | "low" | "none";

export interface RecommendationOption {
  id: string;
  /** The action, for example "Assign to Priya Raman". */
  title: ReactNode;
  /** One or two sentences on why. */
  rationale?: ReactNode;
  confidence: ConfidenceLevel;
  /** A small leading visual: an avatar, a logo, an icon. Travels with the title on a swap. */
  media?: ReactNode;
  /** Short status shown for this option in the alternatives list, for example "Needs review". */
  note?: ReactNode;
}

export interface RecommendationCardProps extends Omit<ComponentProps<"section">, "title"> {
  /** The question being answered, for example "Who should own the Northwind renewal?". */
  question?: ReactNode;
  /** The first option is the recommendation; the rest are alternatives. */
  options: RecommendationOption[];
  /** Id of the option in the main slot initially. Defaults to the first. */
  defaultValue?: string;
  /** Called when an alternative is swapped into the main slot. */
  onValueChange?: (id: string) => void;
  onAccept?: (option: RecommendationOption) => void;
  /** Adds a Dismiss button. */
  onDismiss?: () => void;
  /** Adds an Undo button after accepting. */
  onUndo?: () => void;
  acceptLabel?: string;
  /** Text after accepting. Receives the accepted option. */
  acceptedLabel?: (option: RecommendationOption) => ReactNode;
}

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

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";

const levels: Record<ConfidenceLevel, { bars: number; label: string; fill: string; text: string }> = {
  high: { bars: 3, label: "High confidence", fill: "bg-emerald-500 dark:bg-emerald-400", text: "text-emerald-700 dark:text-emerald-400" },
  medium: { bars: 2, label: "Medium confidence", fill: "bg-amber-500 dark:bg-amber-400", text: "text-amber-700 dark:text-amber-400" },
  low: { bars: 1, label: "Low confidence", fill: "bg-zinc-500 dark:bg-zinc-400", text: "text-zinc-600 dark:text-zinc-400" },
  none: { bars: 0, label: "No signal", fill: "bg-zinc-500", text: "text-zinc-500" },
};

export interface ConfidenceMeterProps extends Omit<ComponentProps<"span">, "children"> {
  level: ConfidenceLevel;
  /** Shows "High confidence" and so on beside the bars. */
  showLabel?: boolean;
  size?: "sm" | "md";
}

/**
 * Three short bars of rising height, like a signal meter: three for high, two for medium, one for
 * low, none for no signal. Bars refill one after another when the level changes.
 */
export function ConfidenceMeter({ level, showLabel = false, size = "md", className, ...props }: ConfidenceMeterProps) {
  const config = levels[level];
  const heights = size === "sm" ? ["h-1.5", "h-2", "h-2.5"] : ["h-2", "h-2.5", "h-3"];
  return (
    <span role="img" aria-label={config.label} className={cx("inline-flex items-center gap-2", className)} {...props}>
      <span aria-hidden="true" className="inline-flex items-end gap-[2px]">
        {heights.map((height, i) => (
          <span
            key={i}
            className={cx(
              "w-[3px] rounded-full transition-colors duration-300 motion-reduce:transition-none",
              ease,
              height,
              i < config.bars ? config.fill : "bg-zinc-950/[0.12] dark:bg-white/[0.14]",
            )}
            // Fill climbs from the short bar to the tall one.
            style={{ transitionDelay: `${i * 60}ms` }}
          />
        ))}
      </span>
      {showLabel ? <span className={cx("text-xs font-medium transition-colors duration-300 motion-reduce:transition-none", config.text)}>{config.label}</span> : null}
    </span>
  );
}

const button = {
  base: "inline-flex h-8 items-center justify-center gap-1.5 rounded-lg px-2.5 text-sm font-medium whitespace-nowrap select-none transition-[background-color,border-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.97] motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
  primary: "bg-zinc-950 text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.12),0_1px_2px_rgb(0_0_0/0.2)] hover:bg-zinc-800 dark:bg-white dark:text-black dark:shadow-[inset_0_-1px_0_rgb(0_0_0/0.12)] dark:hover:bg-zinc-200",
  secondary: "border border-zinc-950/12 bg-white hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] dark:border-white/15 dark:bg-black dark:hover:border-white/25 dark:hover:bg-white/[0.06]",
  ghost: "text-zinc-600 hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white",
};

/** One suggested action with its rationale, a confidence meter, Accept, and a drawer of alternatives. */
export function RecommendationCard({
  question,
  options,
  defaultValue,
  onValueChange,
  onAccept,
  onDismiss,
  onUndo,
  acceptLabel = "Accept",
  acceptedLabel,
  className,
  ...props
}: RecommendationCardProps) {
  const reduce = useReducedMotion();
  const uid = useId();
  const [order, setOrder] = useState<string[]>(() => {
    const ids = options.map((o) => o.id);
    const first = defaultValue && ids.includes(defaultValue) ? defaultValue : ids[0];
    return first ? [first, ...ids.filter((id) => id !== first)] : ids;
  });
  const [drawer, setDrawer] = useState(false);
  const [accepted, setAccepted] = useState(false);
  const [announcement, setAnnouncement] = useState("");
  const focusIndex = useRef<number | null>(null);
  const rowRefs = useRef<(HTMLButtonElement | null)[]>([]);
  const acceptRef = useRef<HTMLButtonElement>(null);

  const byId = new Map(options.map((o) => [o.id, o]));
  // Options that arrive later go to the end; options that disappear drop out.
  const ids = [...order.filter((id) => byId.has(id)), ...options.map((o) => o.id).filter((id) => !order.includes(id))];
  const main = byId.get(ids[0] ?? "");
  const alternatives = ids.slice(1).map((id) => byId.get(id)!);

  useEffect(() => {
    if (focusIndex.current == null) return;
    rowRefs.current[focusIndex.current]?.focus({ preventScroll: true });
    focusIndex.current = null;
  }, [order]);

  if (!main) return null;

  function swap(index: number) {
    const next = [...ids];
    const chosen = next[index + 1]!;
    next[index + 1] = next[0]!;
    next[0] = chosen;
    // Keep focus where the user was: the row now holds the previous suggestion.
    focusIndex.current = index;
    setOrder(next);
    const option = byId.get(chosen)!;
    setAnnouncement(`Now suggesting: ${typeof option.title === "string" ? option.title : "the selected option"}. ${levels[option.confidence].label}.`);
    onValueChange?.(chosen);
  }

  const layout = reduce ? { duration: 0 } : { type: "spring" as const, duration: 0.45, bounce: 0 };
  const drawerId = `${uid}-alternatives`;
  const titleId = `${uid}-title`;

  return (
    <section
      aria-labelledby={titleId}
      data-accepted={accepted || undefined}
      className={cx(
        "w-full overflow-hidden rounded-xl border border-zinc-950/10 bg-white text-left text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
        "dark:border-white/10 dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
        className,
      )}
      {...props}
    >
      <span role="status" className="sr-only">
        {announcement}
      </span>
      <LayoutGroup id={uid}>
        <div className="px-4 pt-4 pb-3">
          {question ? <p className="mb-2.5 text-xs font-medium text-zinc-500">{question}</p> : null}
          <div className="flex items-start gap-3">
            {main.media ? (
              <motion.span layoutId={`${uid}-media-${main.id}`} transition={layout} className="mt-0.5 flex size-8 shrink-0 items-center justify-center">
                {main.media}
              </motion.span>
            ) : null}
            <div className="min-w-0 flex-1">
              <motion.h3
                id={titleId}
                layoutId={`${uid}-title-${main.id}`}
                transition={layout}
                className="inline-block text-base leading-6 font-semibold text-balance"
              >
                {main.title}
              </motion.h3>
              <AnimatePresence mode="popLayout" initial={false}>
                {main.rationale ? (
                  <motion.p
                    key={main.id}
                    initial={reduce ? false : { opacity: 0, y: 4, filter: "blur(2px)" }}
                    animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
                    exit={reduce ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, transition: { duration: 0.1 } }}
                    transition={{ duration: 0.28, ease: [0.23, 1, 0.32, 1], delay: reduce ? 0 : 0.22 }}
                    className="mt-1 text-sm leading-relaxed text-pretty text-zinc-600 dark:text-zinc-400"
                  >
                    {main.rationale}
                  </motion.p>
                ) : null}
              </AnimatePresence>
            </div>
          </div>
        </div>

        <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-3 px-4 pb-4">
          <ConfidenceMeter level={main.confidence} showLabel />
          <div className="relative flex min-w-0 items-center gap-2">
            <div
              inert={accepted || undefined}
              className={cx("flex flex-wrap items-center justify-end gap-2 transition-[opacity,translate] duration-200 motion-reduce:transition-none", ease, accepted && "pointer-events-none translate-y-1 opacity-0")}
            >
              {onDismiss ? (
                <button type="button" onClick={onDismiss} className={cx(button.base, button.ghost)}>
                  Dismiss
                </button>
              ) : null}
              {alternatives.length ? (
                <button
                  type="button"
                  aria-expanded={drawer}
                  aria-controls={drawerId}
                  onClick={() => setDrawer((open) => !open)}
                  className={cx(button.base, button.secondary)}
                >
                  Alternatives
                  <span className="font-mono text-xs text-zinc-500 tabular-nums">{alternatives.length}</span>
                  <svg aria-hidden="true" viewBox="0 0 16 16" className={cx("size-3.5 text-zinc-500 transition-transform duration-200 motion-reduce:transition-none", ease, drawer && "rotate-180")}>
                    <path d="m4.5 6.25 3.5 3.5 3.5-3.5" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </button>
              ) : null}
              <button
                ref={acceptRef}
                type="button"
                onClick={() => {
                  setAccepted(true);
                  setDrawer(false);
                  setAnnouncement(`Accepted: ${typeof main.title === "string" ? main.title : "the suggestion"}.`);
                  onAccept?.(main);
                }}
                className={cx(button.base, button.primary)}
              >
                {acceptLabel}
              </button>
            </div>
            <div
              inert={!accepted || undefined}
              className={cx(
                "absolute inset-y-0 right-0 flex items-center gap-3 transition-[opacity,translate] duration-200 motion-reduce:transition-none",
                ease,
                accepted ? "opacity-100 delay-100" : "pointer-events-none translate-y-1 opacity-0",
              )}
            >
              <span className="flex items-center gap-1.5 text-sm whitespace-nowrap text-zinc-600 dark:text-zinc-400">
                <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4 text-emerald-600 dark:text-emerald-400">
                  <path d="m3.5 8.5 3 3 6-7" />
                </svg>
                {acceptedLabel ? acceptedLabel(main) : "Accepted"}
              </span>
              {onUndo ? (
                <button
                  type="button"
                  onClick={() => {
                    setAccepted(false);
                    setAnnouncement("");
                    onUndo();
                    requestAnimationFrame(() => acceptRef.current?.focus({ preventScroll: true }));
                  }}
                  className={cx(button.base, button.ghost)}
                >
                  Undo
                </button>
              ) : null}
            </div>
          </div>
        </div>

        {alternatives.length ? (
          <div
            id={drawerId}
            inert={!drawer || undefined}
            className={cx(
              "grid grid-cols-[minmax(0,1fr)] transition-[grid-template-rows] duration-300 motion-reduce:transition-none",
              ease,
              drawer ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
            )}
          >
            <div className="min-h-0 overflow-hidden">
              <div
                className={cx(
                  "border-t border-zinc-950/[0.07] px-2 pt-2.5 pb-2 transition-opacity duration-200 motion-reduce:transition-none dark:border-white/[0.08]",
                  drawer ? "opacity-100 delay-75" : "opacity-0",
                )}
              >
                <p className="px-2 pb-1.5 text-xs font-medium text-zinc-500">Other options</p>
                <ul className="grid grid-cols-[minmax(0,1fr)] gap-0.5">
                  {alternatives.map((option, index) => (
                    <li key={option.id}>
                      <button
                        ref={(el) => {
                          rowRefs.current[index] = el;
                        }}
                        type="button"
                        onClick={() => swap(index)}
                        className={cx(
                          "group/row flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left",
                          "transition-[background-color] duration-150 ease-out hover:bg-zinc-950/[0.04] motion-reduce:transition-none dark:hover:bg-white/[0.06]",
                          "focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
                        )}
                      >
                        {option.media ? (
                          <motion.span layoutId={`${uid}-media-${option.id}`} transition={layout} className="flex size-6 shrink-0 items-center justify-center">
                            {option.media}
                          </motion.span>
                        ) : null}
                        <span className="min-w-0 flex-1">
                          <motion.span layoutId={`${uid}-title-${option.id}`} transition={layout} className="inline-block max-w-full truncate align-top text-sm leading-5 font-medium">
                            {option.title}
                          </motion.span>
                          {option.rationale ? <span className="block truncate text-xs leading-5 text-zinc-500">{option.rationale}</span> : null}
                        </span>
                        <span className="flex shrink-0 items-center gap-2.5">
                          {option.note ? <span className="hidden text-xs text-zinc-500 sm:inline">{option.note}</span> : null}
                          <ConfidenceMeter level={option.confidence} size="sm" />
                          <span className="text-xs font-medium text-zinc-500 transition-colors duration-150 group-hover/row:text-zinc-950 motion-reduce:transition-none dark:group-hover/row:text-white">
                            Use
                          </span>
                        </span>
                      </button>
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          </div>
        ) : null}
      </LayoutGroup>
    </section>
  );
}