# Animated Approval for UI SDK (/docs/components/approval)

A person says yes or no to something an AI agent wants to do. The card shows the action, the control the agent would press, details and a risk level, with Approve and Deny; once answered it closes to one line. createApprovals() wires it to UI SDK's agent bridge, whose allow callback waits for the answer. The buttons sit inside data-agent-hidden, so an agent can read the card but can never approve its own request. createApprovals' allow also refuses any step aimed inside an approval card, and while it waits UI SDK holds the waiting agent's later act and query calls.

<ComponentPreview slug="approval" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport { createAgent } from \&#x22;@ui-sdk/react/agent\&#x22;\nimport * as React from \&#x22;react\&#x22;\n\nimport { Approval, createApprovals, type ApprovalRequest, type Approvals } from \&#x22;@/components/keyframery/approval\&#x22;\nimport { Badge } from \&#x22;@/components/keyframery/badge\&#x22;\nimport { Button } from \&#x22;@/components/keyframery/button\&#x22;\nimport { CodeBlock, CodeBlockContent } from \&#x22;@/components/keyframery/code-block\&#x22;\n\ntype Risk = \&#x22;low\&#x22; | \&#x22;medium\&#x22; | \&#x22;high\&#x22;\n\n/* One bridge and one set of approvals for the page. The bridge waits in `allow` for the person:\n   the request it makes is real, and only Approve lets the press through. */\nconst settings = { risk: \&#x22;high\&#x22; as Risk }\nlet approvals: Approvals | undefined\nlet agent: ReturnType<typeof createAgent> | undefined\nfunction bridge() {\n  approvals ??= createApprovals({\n    describe: (step) =>\n      step.label === \&#x22;Refund order #1048\&#x22;\n        ? { title: \&#x22;Issue a refund\&#x22;, description: \&#x22;£84.00 back to Priya Shah's Visa ending 4242. This can't be undone.\&#x22;, risk: settings.risk }\n        : {},\n  })\n  agent ??= createAgent({ allow: approvals.allow })\n  return { approvals, agent }\n}\n\nconst none: ApprovalRequest[] = []\n\nexport default function ApprovalDemo({\n  risk = \&#x22;high\&#x22;,\n  allowAlways = true,\n  askReason = false,\n  showDescription = true,\n  showTarget = true,\n  showDetails = false,\n  themeFace = \&#x22;\&#x22;,\n  themeAccent = \&#x22;\&#x22;,\n  themeSuccess = \&#x22;\&#x22;,\n  themeRadius = 14,\n  themeInset = 14,\n  themeFont = 13,\n  themeTitleFont = 14,\n}: {\n  risk?: Risk\n  allowAlways?: boolean\n  askReason?: boolean\n  showDescription?: boolean\n  showTarget?: boolean\n  showDetails?: boolean\n  themeFace?: string\n  themeAccent?: string\n  themeSuccess?: string\n  themeRadius?: number\n  themeInset?: number\n  themeFont?: number\n  themeTitleFont?: number\n}) {\n  settings.risk = risk\n  const [refunded, setRefunded] = React.useState(false)\n  const [reply, setReply] = React.useState<string | null>(null)\n  const turn = React.useRef<AbortController | null>(null)\n  const requests = React.useSyncExternalStore(\n    (listener) => bridge().approvals.subscribe(listener),\n    () => bridge().approvals.requests(),\n    () => none,\n  )\n  const request = requests.at(-1)\n\n  /* The agent's turn: one step, pressing Refund. It waits on `allow` until the person answers. */\n  const ask = React.useCallback(() => {\n    const { agent } = bridge()\n    turn.current?.abort()\n    const controller = new AbortController()\n    turn.current = controller\n    setRefunded(false)\n    setReply(null)\n    agent.act({ steps: [{ ref: \&#x22;Refund order #1048\&#x22;, action: \&#x22;press\&#x22; }] }, { signal: controller.signal }).then((result) => {\n      if (controller.signal.aborted) return\n      setReply(result.ok ? \&#x22;Done. Priya will see £84.00 back on her card in 3 to 5 days.\&#x22; : \&#x22;Okay, I won't refund it. Want me to resend the parcel instead?\&#x22;)\n    })\n  }, [])\n\n  React.useEffect(() => {\n    ask()\n    return () => turn.current?.abort()\n  }, [ask])\n\n  const theme = {\n    ...(themeFace ? { \&#x22;--approval-face\&#x22;: themeFace } : null),\n    ...(themeAccent ? { \&#x22;--approval-accent\&#x22;: themeAccent } : null),\n    ...(themeSuccess ? { \&#x22;--approval-success\&#x22;: themeSuccess } : null),\n    ...(themeRadius !== 14 ? { \&#x22;--approval-radius\&#x22;: `${themeRadius}px` } : null),\n    ...(themeInset !== 14 ? { \&#x22;--approval-inset\&#x22;: `${themeInset}px` } : null),\n    ...(themeFont !== 13 ? { \&#x22;--approval-font\&#x22;: `${themeFont}px` } : null),\n    ...(themeTitleFont !== 14 ? { \&#x22;--approval-title-font\&#x22;: `${themeTitleFont}px` } : null),\n  } as React.CSSProperties\n\n  return (\n    <div style={theme} className=\&#x22;w-full max-w-[460px]\&#x22;>\n      <div className=\&#x22;flex justify-end\&#x22;>\n        <div className=\&#x22;max-w-[85%] rounded-[16px] rounded-br-[6px] bg-muted px-3.5 py-2.5 text-[13px] leading-snug\&#x22;>\n          Priya's parcel never arrived. Refund order #1048.\n        </div>\n      </div>\n\n      {/* The order the agent acts on. Refund is marked for a person, so the bridge asks first. */}\n      <div className=\&#x22;@container mt-5 flex items-center gap-3 rounded-[12px] px-3 py-2.5 shadow-[0_0_0_1px_rgb(0_0_0/0.07)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]\&#x22;>\n        <div className=\&#x22;min-w-0 flex-1\&#x22;>\n          <div className=\&#x22;truncate text-[13px] font-medium\&#x22;>Order #1048</div>\n          <div className=\&#x22;truncate text-[12px] text-muted-foreground\&#x22;>Priya Shah · 2 items</div>\n        </div>\n        <span className=\&#x22;text-[13px] font-medium tabular-nums @max-[20rem]:hidden\&#x22;>£84.00</span>\n        <Badge variant={refunded ? \&#x22;secondary\&#x22; : \&#x22;success\&#x22;} className=\&#x22;w-[68px] @max-[22rem]:hidden\&#x22;>{refunded ? \&#x22;Refunded\&#x22; : \&#x22;Paid\&#x22;}</Badge>\n        <Button\n          size=\&#x22;sm\&#x22;\n          aria-label=\&#x22;Refund order #1048\&#x22;\n          data-agent-confirm=\&#x22;Refunds £84.00 to Priya Shah's Visa ending 4242\&#x22;\n          disabled={refunded}\n          onClick={() => setRefunded(true)}\n        >\n          Refund\n        </Button>\n      </div>\n\n      <div className=\&#x22;mt-5 mb-2.5 flex items-center justify-between gap-3\&#x22;>\n        <div className=\&#x22;text-[12px] font-medium text-muted-foreground\&#x22;>\n          {request?.status === \&#x22;pending\&#x22; ? \&#x22;Waiting for you\&#x22; : \&#x22;Agent\&#x22;}\n        </div>\n        <button\n          type=\&#x22;button\&#x22;\n          data-action=\&#x22;ask\&#x22;\n          data-agent-hidden\n          onClick={ask}\n          className=\&#x22;inline-flex h-7 items-center rounded-[8px] px-2.5 text-[12px] leading-none font-medium text-muted-foreground outline-none transition-[scale,color,background-color] duration-[calc(200ms*var(--kf-speed,1))] ease-pop hover:bg-foreground/[0.045] hover:text-foreground active:scale-[calc(1-0.04*var(--kf-flourish,1))] focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none\&#x22;\n        >\n          Ask again\n        </button>\n      </div>\n\n      {request && (\n        <Approval\n          key={request.id}\n          request={request}\n          risk={risk}\n          description={showDescription ? undefined : \&#x22;\&#x22;}\n          target={showTarget ? undefined : \&#x22;\&#x22;}\n          allowAlways={allowAlways}\n          askReason={askReason}\n        >\n          {showDetails ? (\n            <CodeBlock code={JSON.stringify({ component: request.step.component, label: request.step.label, action: request.step.action, confirm: request.step.confirm }, null, 2)} language=\&#x22;json\&#x22; size=\&#x22;sm\&#x22; wrap>\n              <CodeBlockContent />\n            </CodeBlock>\n          ) : undefined}\n        </Approval>\n      )}\n\n      <p\n        key={reply ?? \&#x22;none\&#x22;}\n        className=\&#x22;mt-3 min-h-[1lh] text-[13px] leading-snug text-foreground animate-[kf-approval-answer_calc(360ms*var(--kf-speed,1))_var(--ease-spring)_backwards] motion-reduce:animate-none\&#x22;\n      >\n        {reply}\n      </p>\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;risk&#x22;:[1200,1206],&#x22;allowAlways&#x22;:[1224,1228],&#x22;askReason&#x22;:[1244,1249],&#x22;showDescription&#x22;:[1271,1275],&#x22;showTarget&#x22;:[1292,1296],&#x22;showDetails&#x22;:[1314,1319],&#x22;themeFace&#x22;:[1335,1337],&#x22;themeAccent&#x22;:[1355,1357],&#x22;themeSuccess&#x22;:[1376,1378],&#x22;themeRadius&#x22;:[1396,1398],&#x22;themeInset&#x22;:[1415,1417],&#x22;themeFont&#x22;:[1433,1435],&#x22;themeTitleFont&#x22;:[1456,1458]},&#x22;root&#x22;:[3497,6595],&#x22;importOffset&#x22;:401}" />

## Installation [#installation]

**React**

**CLI**

```bash
npx shadcn@latest add @keyframery/approval
```

This adds `components/keyframery/approval.tsx` and its primitive to your project, and installs UI SDK, along with `agent-content`, [badge](/docs/components/badge), [button](/docs/components/button), [checkbox](/docs/components/checkbox), [textarea](/docs/components/textarea), which it builds on. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.17 @ui-sdk/react@0.1.0-beta.17 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation/manual#add-the-motion-tokens) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "subtle" | "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"subtle"` (the default), `"calm"`, `"springy"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Add what it builds on**

Install [badge](/docs/components/badge), [button](/docs/components/button), [checkbox](/docs/components/checkbox), [textarea](/docs/components/textarea) the same way first. Add `agent-content` with the CLI: `npx shadcn@latest add @keyframery/agent-content`.

**Copy the component**

**components/keyframery/approval.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/approval"

/* Theming variables (set on a part or ancestor; absent values preserve the theme):
   --approval-face: Card surface; default: bg-card.
   --approval-accent: Risk accent (icon tile, risk label); default: muted-foreground (low), foreground (medium), destructive (high).
   --approval-success: Approved answer; default: payoff green oklch(0.62 0.16 150).
   --approval-radius: Card corners; default: rounded-[14px].
   --approval-font: Description size; default: text-[13px].
   --approval-title-font: Title size; default: text-[14px].
   --approval-inset: Card padding; default: 14px.
*/

/* Styled approval: the animated primitive plus the Keyframery look. A card on the card surface: a
   shield tile tinted by the risk, the title, what the agent would press, and a footer band with
   "Always allow", Deny and Approve (Keyframery's checkbox and buttons, hidden from agents). High
   risk turns the accent destructive, styles Approve as destructive and gives Deny the default
   focus. Once answered the card closes to its header and the answer sits where the risk was. */

import * as React from "react"

import { Badge } from "@/components/keyframery/badge"
import { Button } from "@/components/keyframery/button"
import { Checkbox } from "@/components/keyframery/checkbox"
import { Textarea } from "@/components/keyframery/textarea"
import {
  Approval as ApprovalRoot,
  ApprovalActions as ApprovalActionsPrimitive,
  ApprovalBody as ApprovalBodyPrimitive,
  ApprovalDescription as ApprovalDescriptionPrimitive,
  ApprovalDetails as ApprovalDetailsPrimitive,
  ApprovalIcon as ApprovalIconPrimitive,
  ApprovalReveal,
  ApprovalRisk as ApprovalRiskPrimitive,
  ApprovalSummary as ApprovalSummaryPrimitive,
  ApprovalTarget as ApprovalTargetPrimitive,
  ApprovalTitle as ApprovalTitlePrimitive,
  useApproval,
  type ApprovalRequest,
  type ApprovalRiskLevel,
  type ApprovalStatus,
} from "@/components/keyframery/primitives/approval"
import { Speed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/* UI SDK accepts a class name or a function of state; keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

const riskWords: Record<ApprovalRiskLevel, string> = { low: "Low risk", medium: "Medium risk", high: "High risk" }

type ApprovalProps = Omit<React.ComponentProps<typeof ApprovalRoot>, "title" | "children"> &
  SpeedProps & {
    /** What the agent wants to do, like "Issue a refund". */
    title?: React.ReactNode
    /** A sentence on what it changes, like "£84.00 back to Priya Shah's Visa ending 4242". */
    description?: React.ReactNode
    /** The control it would use, like "Press “Refund order #1048”". */
    target?: React.ReactNode
    /** Show "Always allow this action". */
    allowAlways?: boolean
    /** Focus the default button when the card arrives: Approve, or Deny at high risk. */
    autoFocus?: boolean
    /** A request from `createApprovals()`: binds title, description, target, risk, status and the answer. */
    request?: ApprovalRequest
    /** Details shown above the buttons: a diff, the arguments, a summary. */
    children?: React.ReactNode
  }

/* With no `children` it shows title, description and target; `children` adds details (a diff, the
   arguments) above the buttons. */
function Approval({
  speed,
  className,
  title,
  description,
  target,
  risk,
  status,
  onApprove,
  onDeny,
  allowAlways = false,
  autoFocus = false,
  request,
  resolvedAt,
  children,
  ...props
}: ApprovalProps) {
  const bound = request
    ? {
        title: title ?? request.title,
        description: description ?? request.description,
        target: target ?? request.target,
        risk: risk ?? request.risk,
        status: status ?? request.status,
        resolvedAt: resolvedAt ?? request.resolvedAt,
        onApprove: (details: { always: boolean }) => {
          onApprove?.(details)
          request.approve({ always: details.always })
        },
        onDeny: (reason: string | undefined) => {
          onDeny?.(reason)
          request.deny(reason)
        },
      }
    : { title, description, target, risk, status, resolvedAt, onApprove, onDeny }
  return (
    <Speed speed={speed}>
      <ApprovalRoot
        risk={bound.risk}
        status={bound.status}
        resolvedAt={bound.resolvedAt}
        onApprove={bound.onApprove}
        onDeny={bound.onDeny}
        className={withClass(
          cn(
            "@container w-full min-w-0 overflow-hidden rounded-[var(--approval-radius,14px)] bg-[var(--approval-face,var(--card))] text-card-foreground",
            "shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.12)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08),0_8px_24px_-12px_rgb(0_0_0/0.7)]",
            "[--approval-tone:var(--approval-accent,var(--foreground))] data-[risk=low]:[--approval-tone:var(--approval-accent,var(--muted-foreground))] data-[risk=high]:[--approval-tone:var(--approval-accent,var(--destructive))]",
            "[--approval-pad:var(--approval-inset,14px)]",
          ),
          className,
        )}
        {...props}
      >
        <div className="flex min-w-0 items-start gap-3 p-[var(--approval-pad)]">
          <ApprovalIcon />
          <div className="flex min-w-0 flex-1 items-center gap-3 self-center">
            <ApprovalTitle className="flex-1">{bound.title}</ApprovalTitle>
            <span className="grid shrink-0 justify-items-end *:col-start-1 *:row-start-1">
              <ApprovalRisk />
              <ApprovalSummary />
            </span>
          </div>
        </div>
        <ApprovalBody>
          {(bound.description || bound.target || children) && (
            <div className="-mt-1.5 flex min-w-0 flex-col gap-2.5 ps-[calc(var(--approval-pad)+2.75rem)] @max-[24rem]:ps-[var(--approval-pad)] @max-[24rem]:mt-0 pe-[var(--approval-pad)] pb-[var(--approval-pad)]">
              {bound.description && <ApprovalDescription>{bound.description}</ApprovalDescription>}
              {bound.target && <ApprovalTarget>{bound.target}</ApprovalTarget>}
              {children && <ApprovalDetails>{children}</ApprovalDetails>}
            </div>
          )}
          <ApprovalActions allowAlways={allowAlways} autoFocus={autoFocus} />
        </ApprovalBody>
      </ApprovalRoot>
    </Speed>
  )
}

/* A shield in a tile tinted by the risk. */
function ApprovalIcon({ className, children, ...props }: React.ComponentProps<typeof ApprovalIconPrimitive>) {
  return (
    <ApprovalIconPrimitive
      className={withClass(
        cn(
          "grid size-8 shrink-0 place-items-center rounded-[9px] text-[color:var(--approval-tone)] [&_svg]:size-4",
          "bg-[color-mix(in_oklab,var(--approval-tone)_9%,transparent)] dark:bg-[color-mix(in_oklab,var(--approval-tone)_16%,transparent)]",
          "transition-[color,background-color] duration-[calc(240ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none",
          "group-data-resolved/approval:bg-muted group-data-resolved/approval:text-muted-foreground",
        ),
        className,
      )}
      {...props}
    >
      {children ?? (
        <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M8 1.75 13 3.6v3.9c0 3.05-2.15 5.25-5 6.75-2.85-1.5-5-3.7-5-6.75V3.6Z" />
          <path d="M8 5.5v2.75M8 10.5v.01" />
        </svg>
      )}
    </ApprovalIconPrimitive>
  )
}

function ApprovalTitle({ className, ...props }: React.ComponentProps<typeof ApprovalTitlePrimitive>) {
  return (
    <ApprovalTitlePrimitive
      className={withClass(
        "min-w-0 truncate text-[length:var(--approval-title-font,14px)] leading-[1.35] font-semibold tracking-tight text-foreground",
        className,
      )}
      {...props}
    />
  )
}

function ApprovalDescription({ className, ...props }: React.ComponentProps<typeof ApprovalDescriptionPrimitive>) {
  return (
    <ApprovalDescriptionPrimitive
      className={withClass("text-[length:var(--approval-font,13px)] leading-relaxed text-muted-foreground", className)}
      {...props}
    />
  )
}

/* What the agent would press: a quiet chip with a pointer, so it reads as a control, not prose. */
function ApprovalTarget({ className, children, ...props }: Omit<React.ComponentProps<typeof ApprovalTargetPrimitive>, "children"> & { children?: React.ReactNode }) {
  return (
    <ApprovalTargetPrimitive
      className={withClass(
        "inline-flex h-7 w-fit max-w-full min-w-0 items-center gap-1.5 rounded-[8px] bg-muted px-2.5 text-[12.5px] leading-none font-medium text-foreground shadow-[inset_0_0_0_1px_rgb(0_0_0/0.04)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.05)]",
        className,
      )}
      {...props}
    >
      <svg aria-hidden viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-3.5 shrink-0 text-muted-foreground">
        <path d="m3.5 3.5 3.25 9 1.4-3.85 3.85-1.4Z M8.9 8.9l3.6 3.6" />
      </svg>
      <span className="min-w-0 truncate">{children}</span>
    </ApprovalTargetPrimitive>
  )
}

function ApprovalDetails({ className, ...props }: React.ComponentProps<typeof ApprovalDetailsPrimitive>) {
  return <ApprovalDetailsPrimitive className={withClass("min-w-0 text-[12.5px] text-muted-foreground", className)} {...props} />
}

/* The risk as a small badge; destructive at high risk. */
function ApprovalRisk({ className, children, ...props }: React.ComponentProps<typeof ApprovalRiskPrimitive>) {
  return (
    <ApprovalRiskPrimitive className={withClass("inline-flex", className)} {...props}>
      {(state) => (
        <Badge variant={state.risk === "high" ? "destructive" : "outline"} className="[--badge-ink:var(--approval-accent)]">
          {typeof children === "function" ? children(state) : (children ?? riskWords[state.risk])}
        </Badge>
      )}
    </ApprovalRiskPrimitive>
  )
}

/* "Approved · 2s ago" in the payoff green, or "Denied" in muted ink. */
function ApprovalSummary({ className, ...props }: React.ComponentProps<typeof ApprovalSummaryPrimitive>) {
  return (
    <ApprovalSummaryPrimitive
      className={withClass(
        cn(
          "flex h-5 items-center gap-1 text-[12.5px] leading-none font-medium whitespace-nowrap [&_[data-slot=approval-mark]]:size-3.5",
          "data-[status=approved]:text-[color:var(--approval-success,color-mix(in_oklch,oklch(0.62_0.16_150)_85%,var(--foreground)))] dark:data-[status=approved]:text-[color:var(--approval-success,oklch(0.62_0.16_150))]",
          "data-[status=denied]:text-muted-foreground [&_[data-slot=approval-ago]]:font-normal [&_[data-slot=approval-ago]]:text-muted-foreground",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* The body: details and buttons. Closes once the card is answered. */
const ApprovalBody = ApprovalBodyPrimitive

/* The footer band: "Always allow" on the left, Deny and Approve on the right. With `askReason` on
   the card, Deny first opens a field for the reason. Hidden from agents (from the core). */
function ApprovalActions({
  className,
  allowAlways = false,
  autoFocus = false,
  ...props
}: React.ComponentProps<typeof ApprovalActionsPrimitive> & { allowAlways?: boolean; autoFocus?: boolean }) {
  const { api } = useApproval()
  const approveRef = React.useRef<HTMLButtonElement>(null)
  const denyRef = React.useRef<HTMLButtonElement>(null)
  const reasonRef = React.useRef<HTMLTextAreaElement>(null)
  const id = React.useId()
  return (
    <ApprovalActionsPrimitive
      className={withClass(
        cn(
          "flex flex-col border-t border-border/70 bg-[color-mix(in_oklab,var(--muted)_45%,transparent)] px-[var(--approval-pad)] py-2.5",
          "dark:bg-[color-mix(in_oklab,var(--muted)_30%,transparent)]",
        ),
        className,
      )}
      {...props}
    >
      {(state) => (
        <ActionsContent
          state={state}
          api={api}
          allowAlways={allowAlways}
          autoFocus={autoFocus}
          refs={{ approveRef, denyRef, reasonRef }}
          id={id}
        />
      )}
    </ApprovalActionsPrimitive>
  )
}

type ActionsState = { stage: "ask" | "reason"; risk: ApprovalRiskLevel; always: boolean; reason: string; status: ApprovalStatus }

function ActionsContent({
  state,
  api,
  allowAlways,
  autoFocus,
  refs,
  id,
}: {
  state: ActionsState
  api: ReturnType<typeof useApproval>["api"]
  allowAlways: boolean
  autoFocus: boolean
  refs: { approveRef: React.RefObject<HTMLButtonElement | null>; denyRef: React.RefObject<HTMLButtonElement | null>; reasonRef: React.RefObject<HTMLTextAreaElement | null> }
  id: string
}) {
  const high = state.risk === "high"
  const asking = state.stage === "reason"
  /* The default button takes focus when the card arrives (if asked), and the reason field when it opens. */
  React.useEffect(() => {
    if (autoFocus && state.status === "pending") (high ? refs.denyRef : refs.approveRef).current?.focus({ preventScroll: true })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  React.useEffect(() => {
    if (asking) refs.reasonRef.current?.focus({ preventScroll: true })
  }, [asking, refs.reasonRef])
  return (
    <>
      <ApprovalReveal open={asking}>
        <div className="pt-0.5 pb-2.5">
          <Textarea
            ref={refs.reasonRef}
            aria-label="Why not? (optional)"
            placeholder="Why not? (optional)"
            value={state.reason}
            onValueChange={(value) => api.setReason(value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) api.deny()
              if (e.key === "Escape") api.back()
            }}
            className="min-h-[60px]"
          />
        </div>
      </ApprovalReveal>
      <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2">
        {allowAlways && !asking && (
          <label htmlFor={`${id}-always`} className="me-auto flex min-w-0 cursor-pointer items-center gap-2 text-[12.5px] leading-none text-muted-foreground select-none hover:text-foreground">
            <Checkbox id={`${id}-always`} checked={state.always} onCheckedChange={(checked) => api.setAlways(checked === true)} className="[--checkbox-size:16px] [--checkbox-radius:4.5px]" />
            Always allow this action
          </label>
        )}
        <div className="ms-auto flex shrink-0 items-center gap-2">
          {asking ? (
            <>
              <Button size="sm" variant="ghost" onClick={() => api.back()}>
                Back
              </Button>
              <Button size="sm" variant="destructive" onClick={(e) => api.deny(undefined, e.nativeEvent)}>
                Deny
              </Button>
            </>
          ) : (
            <>
              <Button ref={refs.denyRef} size="sm" data-action="deny" onClick={(e) => api.pressDeny(e.nativeEvent)}>
                Deny
              </Button>
              <Button
                ref={refs.approveRef}
                size="sm"
                data-action="approve"
                variant={high ? "destructive" : "primary"}
                onClick={(e) => api.approve(e.nativeEvent)}
              >
                Approve
              </Button>
            </>
          )}
        </div>
      </div>
    </>
  )
}

export {
  Approval,
  ApprovalActions,
  ApprovalBody,
  ApprovalDescription,
  ApprovalDetails,
  ApprovalIcon,
  ApprovalRisk,
  ApprovalSummary,
  ApprovalTarget,
  ApprovalTitle,
}
```

**components/keyframery/primitives/approval.tsx**

```tsx
"use client"

/* Animated approval card, on UI SDK's core. UI SDK ships no approval, so its parts are defined in
   `@/components/core/approval` with `definePrimitive` and rendered here. This file adds motion only.
   Colours, radii and spacing stay yours (style `data-risk` and `data-status`).

   Feedback (runs at any --kf-flourish):
   - Fade: the card fades in with a small rise when a request arrives.
   - Height: once answered, the body (details and buttons) closes to its header, so the card
     becomes one line; the reason field opens and closes the same way.
   - Fade: the answer ("Approved · 2s ago") fades in where the risk was.
   Flourish (scaled by --kf-flourish, gone at 0):
   - Rise and blur on arrival beyond the small feedback rise.
   - Draw and Pop: the answer's tick or cross pops in and draws itself.
   - Direction: the answer rises into place.

   `createApprovals()` (re-exported) connects the card to UI SDK's agent bridge; see the core file. */

import type { StateOf } from "@ui-sdk/core"
import { type PartProps, usePart, usePrimitive, type PrimitiveHandle } from "@ui-sdk/react/primitive"
import * as React from "react"

import { approval, type ApprovalOptions } from "@/components/keyframery/core/approval-core"
import { cn } from "@/lib/utils"

type ClassName<S> = string | ((state: S) => string | undefined) | undefined
function withClass<S>(base: string, className: ClassName<S>) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

const keyframes = [
  "@keyframes kf-approval-in{from{opacity:0;translate:0 calc(4px + 8px*var(--kf-flourish,1));scale:calc(0.985 - 0.015*var(--kf-flourish,1));filter:blur(calc(4px*var(--kf-flourish,1)))}}",
  "@keyframes kf-approval-answer{from{opacity:0;translate:0 calc(6px*var(--kf-flourish,1));filter:blur(calc(3px*var(--kf-flourish,1)))}}",
  "@keyframes kf-approval-draw{from{stroke-dashoffset:1}}",
  "@keyframes kf-approval-pop{from{scale:calc(1 - 0.6*var(--kf-flourish,1));opacity:0}}",
].join("")

/* The instance, for the controls the renderer composes (UI SDK's button, checkbox and textarea),
   which hand the person's answer back to it. */
const HandleContext = React.createContext<PrimitiveHandle<typeof approval> | null>(null)
/** The approval around this part: its `state` and `api` (`approve`, `deny`, `pressDeny`, `back`,
    `setAlways`, `setReason`). */
function useApproval() {
  const handle = React.use(HandleContext)
  if (!handle) throw new Error("Approval parts must be inside <Approval>.")
  return handle
}

type RootProps = ApprovalOptions & PartProps<"div", StateOf<typeof approval, "root">>

/* Arrives with a fade and a small rise; the rise and blur beyond that are flourish. */
function Approval({ status, defaultStatus, onStatusChange, risk, onApprove, onDeny, askReason, resolvedAt, className, ...props }: RootProps) {
  const handle = usePrimitive(approval, { status, defaultStatus, onStatusChange, risk, onApprove, onDeny, askReason, resolvedAt })
  const root = usePart(
    handle,
    "root",
    {},
    {
      ...props,
      className: withClass(
        "group/approval animate-[kf-approval-in_calc(420ms*var(--kf-speed,1))_var(--ease-spring)_backwards] motion-reduce:animate-none",
        className,
      ),
    },
    "div",
  )
  return (
    <HandleContext value={handle}>
      <style href="kf-approval" precedence="default">
        {keyframes}
      </style>
      {root}
    </HandleContext>
  )
}

function ApprovalIcon(props: PartProps<"span", StateOf<typeof approval, "icon">>) {
  return usePart(approval, "icon", {}, props, "span")
}
function ApprovalTitle(props: PartProps<"div", StateOf<typeof approval, "title">>) {
  return usePart(approval, "title", {}, props, "div")
}
function ApprovalDescription(props: PartProps<"p", StateOf<typeof approval, "description">>) {
  return usePart(approval, "description", {}, props, "p")
}
function ApprovalTarget(props: PartProps<"div", StateOf<typeof approval, "target">>) {
  return usePart(approval, "target", {}, props, "div")
}
function ApprovalDetails(props: PartProps<"div", StateOf<typeof approval, "details">>) {
  return usePart(approval, "details", {}, props, "div")
}

/* The risk in words. It steps aside (fades and shrinks to nothing) once the card is answered, so
   the answer takes its place. */
function ApprovalRisk({ className, ...props }: PartProps<"span", StateOf<typeof approval, "risk">>) {
  return usePart(
    approval,
    "risk",
    {},
    {
      ...props,
      className: withClass(
        "transition-[opacity,scale] duration-[calc(200ms*var(--kf-speed,1))] ease-house group-data-resolved/approval:pointer-events-none group-data-resolved/approval:scale-[calc(1-0.1*var(--kf-flourish,1))] group-data-resolved/approval:opacity-0 motion-reduce:transition-none",
        className,
      ),
    },
    "span",
  )
}

/* Closes to nothing once the card is answered: a grid row from 1fr to 0fr, so it needs no
   measuring. Put the details and the actions inside. */
function ApprovalBody({ className, children, ...props }: PartProps<"div", StateOf<typeof approval, "body">>) {
  return usePart(
    approval,
    "body",
    {},
    {
      ...props,
      className: withClass(
        cn(
          "grid grid-rows-[1fr] transition-[grid-template-rows,opacity] duration-[calc(380ms*var(--kf-speed,1))] ease-house",
          "data-resolved:grid-rows-[0fr] data-resolved:opacity-0 data-resolved:duration-[calc(320ms*var(--kf-speed,1))]",
          "motion-reduce:transition-none",
        ),
        className,
      ),
      children: (state) => <div className="min-h-0 overflow-hidden">{typeof children === "function" ? children(state) : children}</div>,
    },
    "div",
  )
}

/* The person's controls, inside a `data-agent-hidden` wrapper: agents never see or press them.
   The wrapper is `display: contents`, so it changes no layout. */
function ApprovalActions({ children, ...props }: PartProps<"div", StateOf<typeof approval, "actions">>) {
  return usePart(
    approval,
    "actions",
    {},
    {
      ...props,
      children: (state) => (
        <div data-agent-hidden="" data-slot="approval-controls" className="contents">
          {typeof children === "function" ? children(state) : children}
        </div>
      ),
    },
    "div",
  )
}

/* A panel that opens to its height while `open` (the reason field). Same grid-row recipe as the body. */
function ApprovalReveal({ open, className, children, ...props }: React.ComponentProps<"div"> & { open: boolean }) {
  return (
    <div
      data-slot="approval-reveal"
      data-open={open ? "" : undefined}
      inert={!open}
      className={cn(
        "grid grid-rows-[0fr] opacity-0 transition-[grid-template-rows,opacity] duration-[calc(320ms*var(--kf-speed,1))] ease-house data-open:grid-rows-[1fr] data-open:opacity-100 motion-reduce:transition-none",
        className,
      )}
      {...props}
    >
      <div className="min-h-0 overflow-hidden">{children}</div>
    </div>
  )
}

/* The answer's mark: a tick or a cross that pops in and draws itself. */
function AnswerMark({ status }: { status: string }) {
  const draw =
    "[stroke-dasharray:1] animate-[kf-approval-draw_calc(320ms*var(--kf-speed,1)*var(--kf-flourish,1))_var(--ease-house)_calc(100ms*var(--kf-speed,1)*var(--kf-flourish,1))_backwards] motion-reduce:animate-none"
  return (
    <svg
      data-slot="approval-mark"
      aria-hidden
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      className="animate-[kf-approval-pop_calc(380ms*var(--kf-speed,1)*var(--kf-flourish,1))_var(--ease-pop)_backwards] motion-reduce:animate-none"
    >
      {status === "approved" ? (
        <path d="M3.5 8.5 6.5 11.5 12.5 5" pathLength={1} className={draw} />
      ) : (
        <path d="M4.5 4.5l7 7M11.5 4.5l-7 7" pathLength={1} className={draw} />
      )}
    </svg>
  )
}

/* "Approved · 2s ago": rises into place once there is an answer. With no children it shows the
   mark, the answer and how long ago, kept current. */
function ApprovalSummary({ className, children, ...props }: PartProps<"div", StateOf<typeof approval, "summary">>) {
  return usePart(
    approval,
    "summary",
    {},
    {
      ...props,
      className: withClass(
        "animate-[kf-approval-answer_calc(360ms*var(--kf-speed,1))_var(--ease-spring)_calc(80ms*var(--kf-speed,1))_backwards] motion-reduce:animate-none",
        className,
      ),
      children: (state) =>
        typeof children === "function"
          ? children(state)
          : (children ?? (
              <>
                <AnswerMark status={state.status} />
                <span>{state.status === "approved" ? "Approved" : "Denied"}</span>
                {state.resolvedAt !== undefined && <Ago at={state.resolvedAt} />}
              </>
            )),
    },
    "div",
  )
}

/* "· just now", "· 2s ago", "· 3m ago". A clock, not an animation. */
function Ago({ at }: { at: number }) {
  const [now, setNow] = React.useState(() => Date.now())
  React.useEffect(() => {
    const timer = setInterval(() => setNow(Date.now()), 1000)
    return () => clearInterval(timer)
  }, [])
  const seconds = Math.max(0, Math.round((now - at) / 1000))
  const text = seconds < 1 ? "just now" : seconds < 60 ? `${seconds}s ago` : seconds < 3600 ? `${Math.floor(seconds / 60)}m ago` : `${Math.floor(seconds / 3600)}h ago`
  return (
    <span data-slot="approval-ago" className="tabular-nums">
      <span aria-hidden> · </span>
      {text}
    </span>
  )
}

export {
  Approval,
  ApprovalActions,
  ApprovalBody,
  ApprovalDescription,
  ApprovalDetails,
  ApprovalIcon,
  ApprovalReveal,
  ApprovalRisk,
  ApprovalSummary,
  ApprovalTarget,
  ApprovalTitle,
  useApproval,
}
export {
  createApprovals,
  describeTarget,
  type Allow,
  type ApprovalRequest,
  type ApprovalRisk as ApprovalRiskLevel,
  type Approvals,
  type ApprovalsOptions,
  type ApprovalStatus,
} from "@/components/keyframery/core/approval-core"
```

**components/keyframery/core/approval-core.ts**

```ts
/* Approval: a person says yes or no to something an AI agent wants to do, as a UI SDK primitive.
   UI SDK ships none, so it is defined with its core: the same definition renders in React, Vue,
   Svelte, Solid and web components.

   The card shows what the agent wants to do (a title, the control it would use, details, a risk
   level) with Approve and Deny. Once answered it collapses to one line. The buttons, the "Always
   allow" choice and the reason field are composed by the renderer (UI SDK's button, checkbox and
   textarea) and sit inside the `actions` part, wrapped in `data-agent-hidden`: the agent bridge
   leaves everything in it out of `snapshot` and `query`, and a step that names one of them fails
   with "isn't available to agents here. Ask the person." An agent can read the card (so it knows
   it is waiting), never answer it. The primitive also declares no agent actions, so its own
   `approve` and `deny` are never offered.

   `createApprovals()` connects cards to UI SDK's agent bridge: pass its `allow` to `createAgent`
   or `registerTools`, render a card for each request, and the bridge waits for the person. */

import { announce, createChange, definePrimitive, type ChangeDetails } from "@ui-sdk/core"
import type { AgentAction } from "@ui-sdk/core/agent"
import { elementOf } from "@ui-sdk/core/observe"

import { bindAgentContent } from "@/components/keyframery/core/agent-content-core"

type ApprovalStatus = "pending" | "approved" | "denied"
type ApprovalRisk = "low" | "medium" | "high"
type ApprovalReason = "approve-press" | "deny-press" | "imperative"

const risks: ApprovalRisk[] = ["low", "medium", "high"]
const riskOf = (risk: unknown): ApprovalRisk => (risks.includes(risk as ApprovalRisk) ? (risk as ApprovalRisk) : "medium")
const statusOf = (status: unknown): ApprovalStatus => (status === "approved" || status === "denied" ? status : "pending")

type ApprovalOptions = {
  /** Whether it waits or was answered. Set it to control the card yourself. */
  status?: ApprovalStatus
  /** Where an uncontrolled card starts. @defaultValue "pending" */
  defaultStatus?: ApprovalStatus
  /** Runs when the person answers; cancel to keep it pending. */
  onStatusChange?: (status: ApprovalStatus, details: ChangeDetails<ApprovalReason>) => void
  /** How much is at stake: changes the accent and which button takes focus. @defaultValue "medium" */
  risk?: ApprovalRisk
  /** The person approved. `always` is true when they ticked "Always allow this action". */
  onApprove?: (details: { always: boolean }) => void
  /** The person denied, with the reason they gave, if any. */
  onDeny?: (reason: string | undefined) => void
  /** Ask for an optional reason before denying. */
  askReason?: boolean
  /** When it was answered (epoch ms), for "Approved · 2s ago". Set from the answer when left out. */
  resolvedAt?: number
}

type ApprovalState = {
  status: ApprovalStatus
  risk: ApprovalRisk
  /** "ask" shows Approve and Deny; "reason" shows the reason field before denying. */
  stage: "ask" | "reason"
  always: boolean
  reason: string
  askReason: boolean
  resolvedAt: number | undefined
  /** The card's readable text, for agents. The actions are left out. */
  content: string
}

const approval = definePrimitive({
  name: "approval",
  options: {
    status: "string",
    defaultStatus: "string",
    onStatusChange: "callback",
    risk: "string",
    onApprove: "callback",
    onDeny: "callback",
    askReason: "boolean",
    resolvedAt: "number",
  },
  state: (options: ApprovalOptions): ApprovalState => ({
    status: statusOf(options.status ?? options.defaultStatus),
    risk: riskOf(options.risk),
    stage: "ask",
    always: false,
    reason: "",
    askReason: options.askReason ?? false,
    resolvedAt: options.resolvedAt,
    content: "",
  }),
  sync: (options) => ({
    risk: riskOf(options.risk),
    askReason: options.askReason ?? false,
    ...(options.status === undefined ? {} : { status: statusOf(options.status) }),
    ...(options.resolvedAt === undefined ? {} : { resolvedAt: options.resolvedAt }),
  }),
  controlled: ["status", "risk", "content"],
  api: (context) => {
    const change = createChange(context)
    const settle = (status: ApprovalStatus, reason: ApprovalReason, event?: Event) => {
      if (context.store.get().status !== "pending") return false
      if (!change("status", status, { reason, event })) return false
      if (context.options().resolvedAt === undefined) context.store.set({ resolvedAt: Date.now() })
      context.store.set({ stage: "ask" })
      return true
    }
    const deny = (reason?: string, event?: Event) => {
      const given = (reason ?? context.store.get().reason).trim() || undefined
      if (settle("denied", "deny-press", event)) context.options().onDeny?.(given)
    }
    return {
      /** The person approves. */
      approve(event?: Event) {
        const { always } = context.store.get()
        if (settle("approved", "approve-press", event)) context.options().onApprove?.({ always })
      },
      /** The person denies; `reason` is optional. */
      deny,
      /** Deny pressed: with `askReason`, the first press asks why, the second denies. */
      pressDeny(event?: Event) {
        const { askReason, stage } = context.store.get()
        if (askReason && stage === "ask") context.store.set({ stage: "reason" })
        else deny(undefined, event)
      },
      /** Back from the reason field to Approve and Deny. */
      back() {
        context.store.set({ stage: "ask", reason: "" })
      },
      setAlways(always: boolean) {
        context.store.set({ always })
      },
      setReason(reason: string) {
        context.store.set({ reason })
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { status: ApprovalStatus; risk: ApprovalRisk; stage: "ask" | "reason" }>({
      state: (state) => ({ status: state.status, risk: state.risk, stage: state.stage }),
      attrs: (state, part) => ({
        role: "group",
        "data-status": state.status,
        "data-risk": state.risk,
        "data-stage": state.stage,
        "data-resolved": state.status === "pending" ? undefined : "",
        "aria-labelledby": `${part.id}-title`,
        "aria-describedby": `${part.id}-description`,
      }),
      /* Readable for agents (the actions are hidden from them), and the answer is read out once. */
      bind: (el, part) => {
        const stopContent = bindAgentContent(el, (content) => part.store.set({ content }))
        let was = part.store.get().status
        const stop = part.store.subscribe(() => {
          const { status } = part.store.get()
          if (status === was) return
          was = status
          if (status !== "pending") announce(status === "approved" ? "Approved" : "Denied")
        })
        return () => {
          stopContent()
          stop()
        }
      },
    }),
    /* Decorative: the risk is also said in words. */
    icon: slot({ attrs: () => ({ "aria-hidden": "true" }) }),
    title: slot({ attrs: (_state, part) => ({ id: `${part.id}-title` }) }),
    description: slot({ attrs: (_state, part) => ({ id: `${part.id}-description` }) }),
    /* The control the agent would use, like "Press “Delete order #1048”". */
    target: slot({}),
    risk: slot<{}, { risk: ApprovalRisk }>({
      state: (state) => ({ risk: state.risk }),
      attrs: (state) => ({ "data-risk": state.risk }),
    }),
    details: slot({}),
    /* Everything that closes once the card is answered. Inert then, so nothing in it takes focus. */
    body: slot<{}, { status: ApprovalStatus }>({
      state: (state) => ({ status: state.status }),
      attrs: (state) => ({
        "data-resolved": state.status === "pending" ? undefined : "",
        inert: state.status === "pending" ? undefined : "",
        "aria-hidden": state.status === "pending" ? undefined : "true",
      }),
    }),
    /* The person's controls. The renderer puts them inside an element marked `data-agent-hidden`,
       so agents never see or press them: an agent approving its own request would defeat the
       point. (The mark goes inside this part, not on it: UI SDK treats a component with any part
       under `data-agent-hidden` as hidden as a whole, and the card itself should stay readable.) */
    actions: slot<{}, { stage: "ask" | "reason"; risk: ApprovalRisk; always: boolean; reason: string; status: ApprovalStatus }>({
      state: (state) => ({ stage: state.stage, risk: state.risk, always: state.always, reason: state.reason, status: state.status }),
      attrs: (state) => ({ "data-stage": state.stage }),
    }),
    /* The one-line answer, once there is one. */
    summary: slot<{}, { status: ApprovalStatus; resolvedAt: number | undefined }>({
      present: (state) => state.status !== "pending",
      state: (state) => ({ status: state.status, resolvedAt: state.resolvedAt }),
      attrs: (state) => ({ "data-status": state.status }),
    }),
  }),
  /* Readable, never operable: no actions, and the actions part is `data-agent-hidden`. */
  agent: { actions: [] },
})

/* ------------------------------------------------------------------ createApprovals */

/** What UI SDK's bridge passes to `allow` (`createAgent({ allow })`, `registerTools(agent, { allow })`). */
type Allow = (step: AgentAction, context: { signal: AbortSignal }) => boolean | Promise<boolean>

/** One thing an agent asked to do that waits, or waited, for a person. */
type ApprovalRequest = {
  id: string
  /** The step as the bridge resolved it: `component`, `label`, `action`, `args`, `confirm`. */
  step: AgentAction
  title: string
  description?: string
  /** The control the agent would use, like "Press “Refund order #1048”". */
  target: string
  risk: ApprovalRisk
  status: ApprovalStatus
  /** Why it was denied: the person's reason, or "Cancelled" when the agent stopped waiting. */
  reason?: string
  createdAt: number
  resolvedAt?: number
  /** Answer it. `always` lets the same action on the same control through from now on. */
  approve: (options?: { always?: boolean }) => void
  deny: (reason?: string) => void
}

type ApprovalsOptions = {
  /** Which steps wait for a person. Default: the ones on a control marked `data-agent-confirm`. */
  needs?: (step: AgentAction) => boolean
  /** Your words for a request. Anything left out is made from the step. */
  describe?: (step: AgentAction) => Partial<Pick<ApprovalRequest, "title" | "description" | "target" | "risk">>
  /** How many answered requests `requests()` keeps, newest last. @defaultValue 20 */
  keep?: number
}

const quote = (value: unknown) => `“${String(value)}”`

/** "Press “Refund order #1048”", "Set Region to “Europe”", "Open Shipping". */
function describeTarget(step: AgentAction): string {
  const name = step.label ?? step.component
  const [first] = step.args
  if (step.action === "press") return `Press ${quote(first ?? name)}`
  if (step.action === "setValue") return first === undefined ? `Clear ${name}` : `Set ${name} to ${quote(Array.isArray(first) ? first.join(", ") : first)}`
  if (step.action === "setOpen") return `${first === false ? "Close" : "Open"} ${name}`
  if (step.action === "setChecked") return `${first === false ? "Uncheck" : "Check"} ${name}`
  const verb = step.action.replace(/([A-Z])/g, " $1").toLowerCase()
  return `${verb.charAt(0).toUpperCase()}${verb.slice(1)} ${name}`
}

/* A step aimed at an approval card is refused outright, whatever else allows it. */
function targetsApproval(step: AgentAction) {
  try {
    return !!elementOf(step.ref)?.closest('[data-slot="approval"]')
  } catch {
    return false
  }
}

/**
 * Approval requests for UI SDK's agent bridge. Pass `allow` to `createAgent` or `registerTools`;
 * each step that needs a person becomes a request in `pending()`, and the bridge waits until it is
 * approved, denied, or the step's signal aborts (the agent's turn was stopped, or it timed out),
 * which denies it.
 *
 * @example
 * const approvals = createApprovals()
 * const agent = createAgent({ allow: approvals.allow })
 * registerTools(agent, { allow: approvals.allow })
 * const requests = useSyncExternalStore(approvals.subscribe, approvals.requests)
 * requests.map((request) => <Approval key={request.id} request={request} />)
 */
function createApprovals(options: ApprovalsOptions = {}) {
  const { needs = (step) => step.confirm !== undefined, describe, keep = 20 } = options
  const listeners = new Set<() => void>()
  const always = new Set<string>()
  const answers = new Map<string, (yes: boolean) => void>()
  let all: ApprovalRequest[] = []
  let waiting: ApprovalRequest[] = []
  let next = 1

  const keyOf = (step: AgentAction) => [step.component, step.label ?? step.ref, step.action, step.confirm ?? ""].join("\u0000")

  const emit = () => {
    waiting = all.filter((request) => request.status === "pending")
    listeners.forEach((listener) => listener())
  }

  const resolve = (id: string, status: Exclude<ApprovalStatus, "pending">, extra: { reason?: string; always?: boolean } = {}) => {
    const at = all.findIndex((request) => request.id === id)
    const request = all[at]
    if (!request || request.status !== "pending") return
    if (status === "approved" && extra.always) always.add(keyOf(request.step))
    all = all.slice()
    all[at] = { ...request, status, reason: extra.reason, resolvedAt: Date.now() }
    /* Drop the oldest answered requests beyond `keep`. */
    const answered = all.filter((item) => item.status !== "pending")
    if (answered.length > keep) {
      const drop = new Set(answered.slice(0, answered.length - keep).map((item) => item.id))
      all = all.filter((item) => !drop.has(item.id))
    }
    const answer = answers.get(id)
    answers.delete(id)
    emit()
    answer?.(status === "approved")
  }

  const allow: Allow = (step, { signal }) => {
    if (targetsApproval(step)) return false
    if (!needs(step)) return true
    if (always.has(keyOf(step))) return true
    if (signal.aborted) return false
    const id = `approval-${next++}`
    const own = describe?.(step) ?? {}
    const target = own.target ?? describeTarget(step)
    const request: ApprovalRequest = {
      id,
      step,
      title: own.title ?? step.confirm ?? target,
      description: own.description,
      target,
      risk: own.risk ?? (step.confirm !== undefined ? "high" : step.action === "press" ? "medium" : "low"),
      status: "pending",
      createdAt: Date.now(),
      approve: (answer) => resolve(id, "approved", { always: answer?.always }),
      deny: (reason) => resolve(id, "denied", { reason: reason?.trim() || undefined }),
    }
    return new Promise<boolean>((done) => {
      answers.set(id, done)
      signal.addEventListener("abort", () => resolve(id, "denied", { reason: "Cancelled" }), { once: true })
      all = [...all, request]
      emit()
    })
  }

  return {
    /** UI SDK's `allow`: `(step, { signal }) => boolean | Promise<boolean>`. */
    allow,
    /** The requests waiting for a person. The same array until something changes. */
    pending: () => waiting,
    /** Waiting and recently answered requests, oldest first, so answered cards can stay as a record. */
    requests: () => all,
    /** Calls `listener` whenever a request arrives or is answered. Returns the unsubscribe. */
    subscribe(listener: () => void) {
      listeners.add(listener)
      return () => void listeners.delete(listener)
    },
    approve: (id: string, answer?: { always?: boolean }) => resolve(id, "approved", { always: answer?.always }),
    deny: (id: string, reason?: string) => resolve(id, "denied", { reason: reason?.trim() || undefined }),
    /** Forget answered requests and every "Always allow". Waiting ones stay. */
    reset() {
      always.clear()
      all = all.filter((request) => request.status === "pending")
      emit()
    },
  }
}

type Approvals = ReturnType<typeof createApprovals>

export {
  approval,
  createApprovals,
  describeTarget,
  type Allow,
  type ApprovalOptions,
  type ApprovalRequest,
  type ApprovalRisk,
  type Approvals,
  type ApprovalsOptions,
  type ApprovalStatus,
}
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

**Vue**

```bash
npx shadcn-vue@latest add https://keyframery.com/r/vue/approval.json
```

This adds `components/keyframery/approval/` (one file per part, with the same part names as React) to your Vue or Nuxt project, installs UI SDK for Vue and adds the motion tokens to your global CSS. See [Install for Vue](/docs/installation/vue).

## Usage [#usage]

**React**

```tsx
import { Approval } from "@/components/keyframery/approval"

export default function Usage() {
  return (
    <Approval
      title="Issue a refund"
      description="£84.00 back to Priya Shah's Visa ending 4242."
      target="Press “Refund order #1048”"
      risk="high"
      onApprove={() => {}}
      onDeny={() => {}}
    />
  )
}
```

**Vue**

```vue
<script setup lang="ts">
import { Approval } from "@/components/keyframery/approval"


function onApprove() {}

function onDeny() {}
</script>

<template>
  <Approval
    title="Issue a refund"
    description="£84.00 back to Priya Shah's Visa ending 4242."
    target="Press “Refund order #1048”"
    risk="high"
    @approve="onApprove"
    @deny="onDeny"
  />
</template>
```

## Examples [#examples]

### Risk [#risk]

`risk` is "low", "medium" or "high". It tints the shield and the label; at high risk Approve turns destructive and, with `autoFocus`, Deny takes the focus instead of Approve.

<ExamplePreview name="approval/risk">
**React**

  ```tsx
  import { Approval } from "@/components/keyframery/approval"

  export default function ApprovalRisk() {
    return (
      <div className="flex w-full max-w-[440px] flex-col gap-3">
        <Approval title="Rename the project" target="Set Project name to “Atlas”" risk="low" />
        <Approval title="Invite a teammate" target="Press “Send invite”" risk="medium" allowAlways />
        <Approval title="Delete order #1048" description="It goes from the shop, the invoices and the reports." target="Press “Delete order”" risk="high" />
      </div>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { Approval } from "@/components/keyframery/approval"
  </script>

  <template>
    <div class="flex w-full max-w-[440px] flex-col gap-3">
      <Approval title="Rename the project" target="Set Project name to “Atlas”" risk="low" />
      <Approval title="Invite a teammate" target="Press “Send invite”" risk="medium" allow-always />
      <Approval
        title="Delete order #1048"
        description="It goes from the shop, the invoices and the reports."
        target="Press “Delete order”"
        risk="high"
      />
    </div>
  </template>
  ```
</ExamplePreview>

### Asking why, and the answer [#asking-why-and-the-answer]

`askReason` opens a field before Deny goes through; `onDeny` gets what was typed. Once answered the card closes to one line: "Approved · 2s ago" or "Denied". Control it with `status`.

<ExamplePreview name="approval/answered">
**React**

  ```tsx
  import * as React from "react"

  import { Approval } from "@/components/keyframery/approval"

  export default function ApprovalAnswered() {
    const [reason, setReason] = React.useState<string>()
    return (
      <div className="flex w-full max-w-[440px] flex-col gap-3">
        <Approval title="Cancel the Lisbon booking" description="Memmo Alfama, 14 to 17 March. Free to cancel until Friday." target="Press “Cancel booking”" risk="medium" askReason onDeny={(why) => setReason(why ?? "")} />
        {reason !== undefined && <p className="text-[12.5px] text-muted-foreground">Reason given: {reason || "none"}</p>}
        <Approval title="Issue a refund" risk="high" status="approved" resolvedAt={Date.now() - 12_000} />
      </div>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { ref } from "vue"

  import { Approval } from "@/components/keyframery/approval"

  const reason = ref<string>()
  </script>

  <template>
    <div class="flex w-full max-w-[440px] flex-col gap-3">
      <Approval
        title="Cancel the Lisbon booking"
        description="Memmo Alfama, 14 to 17 March. Free to cancel until Friday."
        target="Press “Cancel booking”"
        risk="medium"
        ask-reason
        @deny="(why) => reason = why ?? ''"
      />
      <p v-if="reason !== undefined" class="text-[12.5px] text-muted-foreground">Reason given: {{ reason || 'none' }}</p>
      <Approval title="Issue a refund" risk="high" status="approved" :resolved-at="Date.now() - 12_000" />
    </div>
  </template>
  ```
</ExamplePreview>

### With UI SDK's agent bridge [#with-ui-sdks-agent-bridge]

`createApprovals()` gives you an `allow` for `createAgent` and `registerTools`. A step on a control marked `data-agent-confirm` becomes a request; render a card for each and the bridge waits until the person answers, or the agent's signal aborts (that denies it). The card's buttons are hidden from agents, so the agent can read the card but never answer it.

<ExamplePreview name="approval/agent-bridge">
**React**

  ```tsx
  import { createAgent, registerTools } from "@ui-sdk/react/agent"
  import * as React from "react"

  import { Approval, createApprovals } from "@/components/keyframery/approval"
  import { Button } from "@/components/keyframery/button"

  const approvals = createApprovals()
  const agent = typeof window === "undefined" ? undefined : createAgent({ allow: approvals.allow })
  if (agent) registerTools(agent, { allow: approvals.allow })

  export default function ApprovalAgentBridge() {
    const requests = React.useSyncExternalStore(approvals.subscribe, approvals.requests, approvals.requests)
    const [deleted, setDeleted] = React.useState(false)
    return (
      <div className="flex w-full max-w-[440px] flex-col gap-3">
        <div className="flex items-center gap-2">
          <Button size="sm" data-agent-confirm="Deletes order #1048 for good" disabled={deleted} onClick={() => setDeleted(true)}>
            {deleted ? "Deleted" : "Delete order #1048"}
          </Button>
          <Button size="sm" variant="ghost" data-agent-hidden onClick={() => agent?.act({ steps: [{ ref: "Delete order #1048", action: "press" }] })}>
            Let the agent try
          </Button>
        </div>
        {requests.map((request) => (
          <Approval key={request.id} request={request} title="Delete an order" allowAlways />
        ))}
      </div>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { onBeforeUnmount, ref, shallowRef } from "vue"
  import { createAgent, registerTools } from "@ui-sdk/vue/agent"

  import { Approval, createApprovals } from "@/components/keyframery/approval"
  import { Button } from "@/components/keyframery/button"

  const approvals = createApprovals()
  const agent = typeof window === "undefined" ? undefined : createAgent({ allow: approvals.allow })
  if (agent) registerTools(agent, { allow: approvals.allow })

  const requests = shallowRef(approvals.requests())
  onBeforeUnmount(approvals.subscribe(() => (requests.value = approvals.requests())))
  const deleted = ref(false)
  </script>

  <template>
    <div class="flex w-full max-w-[440px] flex-col gap-3">
      <div class="flex items-center gap-2">
        <Button
          size="sm"
          data-agent-confirm="Deletes order #1048 for good"
          :disabled="deleted"
          @click="deleted = true"
        >
          {{ deleted ? 'Deleted' : 'Delete order #1048' }}
        </Button>
        <Button
          size="sm"
          variant="ghost"
          data-agent-hidden="true"
          @click="agent?.act({ steps: [{ ref: 'Delete order #1048', action: 'press' }] })"
        >
          Let the agent try
        </Button>
      </div>
      <Approval
        v-for="request in requests"
        :key="request.id"
        :request="request"
        title="Delete an order"
        allow-always
      />
    </div>
  </template>
  ```
</ExamplePreview>

## Motion [#motion]

| Move          | What you see                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------- |
| **Fade**      | The card fades in with a small rise when a request arrives; the extra rise and blur are flourish. |
| **Height**    | Once answered, the details and buttons close and the card becomes one line.                       |
| **Height**    | With askReason, Deny opens a reason field to its height.                                          |
| **Draw**      | The answer's tick or cross pops in and draws itself (flourish).                                   |
| **Direction** | "Approved · 2s ago" rises into the place the risk label leaves (the rise is flourish).            |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this approval moves, pass `speed`:

```tsx
<Approval speed="fast">
  …
</Approval>
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable                | What it changes  | Default                                             |
| ----------------------- | ---------------- | --------------------------------------------------- |
| `--approval-face`       | Card surface     | bg-card                                             |
| `--approval-accent`     | Risk accent      | muted-foreground / foreground / destructive by risk |
| `--approval-success`    | Approved answer  | oklch(0.62 0.16 150)                                |
| `--approval-radius`     | Card corners     | rounded-\[14px]                                     |
| `--approval-font`       | Description size | text-\[13px]                                        |
| `--approval-title-font` | Title size       | text-\[14px]                                        |
| `--approval-inset`      | Card padding     | 14px                                                |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### Approval [#approval]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast the component moves. `\&#x22;fast\&#x22;` (0.6×), `\&#x22;normal\&#x22;` (1×), `\&#x22;slow\&#x22;` (1.4×), or a multiplier like `0.8`. Popups follow it too.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;status&#x22;,&#x22;type&#x22;:&#x22;\&#x22;pending\&#x22; | \&#x22;approved\&#x22; | \&#x22;denied\&#x22;&#x22;,&#x22;full&#x22;:&#x22;ApprovalStatus&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;\&#x22;pending\&#x22;, \&#x22;approved\&#x22; or \&#x22;denied\&#x22;. Leave it out and the card keeps its own; defaultStatus sets where it starts.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultStatus&#x22;,&#x22;type&#x22;:&#x22;\&#x22;pending\&#x22; | \&#x22;approved\&#x22; | \&#x22;denied\&#x22;&#x22;,&#x22;full&#x22;:&#x22;ApprovalStatus&#x22;,&#x22;default&#x22;:&#x22;\&#x22;pending\&#x22;&#x22;,&#x22;description&#x22;:&#x22;Where an uncontrolled card starts.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onStatusChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(status: ApprovalStatus, details: ChangeDetails<\&#x22;imperative\&#x22; | \&#x22;approve-press\&#x22; | \&#x22;deny-press\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Runs when the person answers; cancel to keep it pending.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;risk&#x22;,&#x22;type&#x22;:&#x22;\&#x22;high\&#x22; | \&#x22;low\&#x22; | \&#x22;medium\&#x22;&#x22;,&#x22;full&#x22;:&#x22;ApprovalRiskLevel&#x22;,&#x22;default&#x22;:&#x22;\&#x22;medium\&#x22;&#x22;,&#x22;description&#x22;:&#x22;\&#x22;low\&#x22;, \&#x22;medium\&#x22; (the default) or \&#x22;high\&#x22;. Changes the accent; at high risk Approve turns destructive and Deny takes the default focus.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onApprove&#x22;,&#x22;type&#x22;:&#x22;(details: { always: boolean; }) => void&#x22;,&#x22;full&#x22;:&#x22;(details: { always: boolean; }) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The person approved; details.always is true when they ticked \&#x22;Always allow this action\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onDeny&#x22;,&#x22;type&#x22;:&#x22;(reason: string) => void&#x22;,&#x22;full&#x22;:&#x22;(reason: string) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The person denied, with the reason they typed, if any.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;askReason&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Deny first opens an optional reason field.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;resolvedAt&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;When it was answered (epoch ms), for \&#x22;Approved · 2s ago\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;title&#x22;,&#x22;type&#x22;:&#x22;ReactNode&#x22;,&#x22;full&#x22;:&#x22;ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;What the agent wants to do, like \&#x22;Issue a refund\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;description&#x22;,&#x22;type&#x22;:&#x22;ReactNode&#x22;,&#x22;full&#x22;:&#x22;ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A sentence on what it changes.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;target&#x22;,&#x22;type&#x22;:&#x22;ReactNode&#x22;,&#x22;full&#x22;:&#x22;ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The control it would use, like \&#x22;Press “Delete order #1048”\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;allowAlways&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Show the \&#x22;Always allow this action\&#x22; checkbox.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;request&#x22;,&#x22;type&#x22;:&#x22;ApprovalRequest&#x22;,&#x22;full&#x22;:&#x22;ApprovalRequest&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A request from createApprovals(): binds title, description, target, risk, status and the answer at once.&#x22;,&#x22;required&#x22;:false}]" />

### ApprovalActions [#approvalactions]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;allowAlways&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false}]" />

### ApprovalReveal [#approvalreveal]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;open&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true}]" />

### Other parts [#other-parts]

These take the props of the element they render, and nothing else:

* `ApprovalBody`: a `<div>`
* `ApprovalDescription`: a `<p>`
* `ApprovalDetails`: a `<div>`
* `ApprovalIcon`: a `<span>`
* `ApprovalRisk`: a `<span>`
* `ApprovalSummary`: a `<div>`
* `ApprovalTarget`: a `<div>`
* `ApprovalTitle`: a `<div>`

## Hooks [#hooks]

### useApproval [#useapproval]

Call it inside the component to read and change its state.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;primitive&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;description&#x22;:&#x22;The primitive it's an instance of.&#x22;},{&#x22;name&#x22;:&#x22;instance&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;description&#x22;:&#x22;The core instance `usePrimitive` made, with its `get()`, `part()` and `api`. In render, read `state` instead of its `get()`, which shows only what React has committed.&#x22;},{&#x22;name&#x22;:&#x22;state&#x22;,&#x22;type&#x22;:&#x22;ApprovalState&#x22;,&#x22;description&#x22;:&#x22;The state this render shows. Reading it doesn't subscribe; a part's `render` and class name functions get the state they render.&#x22;},{&#x22;name&#x22;:&#x22;api&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;description&#x22;:&#x22;The methods its definition declares, like Tabs' `setValue`.&#x22;}]" />

## Keyboard [#keyboard]

| Key                                       | What it does                                   |
| ----------------------------------------- | ---------------------------------------------- |
| <kbd>Tab</kbd>                            | Moves between Always allow, Deny and Approve.  |
| <kbd>Enter or Space</kbd>                 | Presses the focused button.                    |
| <kbd>Cmd or Ctrl</kbd> + <kbd>Enter</kbd> | In the reason field: denies with the reason.   |
| <kbd>Escape</kbd>                         | In the reason field: back to Approve and Deny. |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a approval, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/approval-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/approval`.

## Questions

### How does the animated Approval for UI SDK move?

Fade: The card fades in with a small rise when a request arrives; the extra rise and blur are flourish. Height: Once answered, the details and buttons close and the card becomes one line. Height: With askReason, Deny opens a reason field to its height. Draw: The answer's tick or cross pops in and draws itself (flourish). Direction: "Approved · 2s ago" rises into the place the risk label leaves (the rise is flourish).

### Do I need Motion or Framer Motion for the animated Approval?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no approval. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/approval-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Approval when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
