# Animated Description list for UI SDK (/docs/components/description-list)

The label and value rows of a detail page, with real dl, dt and dd. Rows with a label column and hairlines, stacked, or a grid of two or three columns, reflowing to stacked on a phone by container queries. Values arrive in a short cascade, and a copy button copies its value and confirms on itself with a drawn check.

<ComponentPreview slug="description-list" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport { Pencil } from \&#x22;lucide-react\&#x22;\nimport * as React from \&#x22;react\&#x22;\n\nimport { Badge } from \&#x22;@/components/keyframery/badge\&#x22;\nimport { Button } from \&#x22;@/components/keyframery/button\&#x22;\nimport {\n  DescriptionList,\n  DescriptionListActions,\n  DescriptionListCopy,\n  DescriptionListDetails,\n  DescriptionListItem,\n  DescriptionListTerm,\n  DescriptionListValue,\n} from \&#x22;@/components/keyframery/description-list\&#x22;\n\nexport default function DescriptionListDemo({\n  layout = \&#x22;rows\&#x22;,\n  columns = 2,\n  truncate = false,\n  copy = true,\n  edit = true,\n  title = \&#x22;Customer\&#x22;,\n  label = 10,\n  gap = 12,\n  font = 13,\n  term = \&#x22;\&#x22;,\n  ink = \&#x22;\&#x22;,\n  rule = \&#x22;\&#x22;,\n}: {\n  layout?: \&#x22;rows\&#x22; | \&#x22;stacked\&#x22; | \&#x22;grid\&#x22;\n  columns?: number\n  truncate?: boolean\n  copy?: boolean\n  edit?: boolean\n  title?: string\n  label?: number\n  gap?: number\n  font?: number\n  term?: string\n  ink?: string\n  rule?: string\n}) {\n  const style = {\n    \&#x22;--description-list-label\&#x22;: `${label}rem`,\n    \&#x22;--description-list-gap\&#x22;: `${gap}px`,\n    \&#x22;--description-list-font\&#x22;: `${font}px`,\n    ...(term ? { \&#x22;--description-list-term\&#x22;: term } : null),\n    ...(ink ? { \&#x22;--description-list-ink\&#x22;: ink } : null),\n    ...(rule ? { \&#x22;--description-list-rule\&#x22;: rule } : null),\n  } as React.CSSProperties\n\n  return (\n    <div\n      style={style}\n      className=\&#x22;w-full max-w-[560px] rounded-[16px] bg-background px-5 pt-4 pb-2 shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.12)] dark:bg-card dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07)]\&#x22;\n    >\n      <div className=\&#x22;flex items-baseline justify-between gap-3 pb-2\&#x22;>\n        <div className=\&#x22;text-[15px] font-semibold tracking-tight\&#x22;>{title}</div>\n        <div className=\&#x22;text-[12px] text-muted-foreground\&#x22;>Since March 2021</div>\n      </div>\n      <DescriptionList aria-label={title} layout={layout} columns={columns} truncate={truncate}>\n        <DescriptionListItem>\n          <DescriptionListTerm>Name</DescriptionListTerm>\n          <DescriptionListDetails>\n            <DescriptionListValue>Maya Okafor</DescriptionListValue>\n          </DescriptionListDetails>\n        </DescriptionListItem>\n        <DescriptionListItem data-item=\&#x22;email\&#x22;>\n          <DescriptionListTerm>Email</DescriptionListTerm>\n          <DescriptionListDetails>\n            <DescriptionListValue>maya.okafor@northwind-studio.com</DescriptionListValue>\n            {copy && (\n              <DescriptionListActions>\n                <DescriptionListCopy />\n              </DescriptionListActions>\n            )}\n          </DescriptionListDetails>\n        </DescriptionListItem>\n        <DescriptionListItem data-item=\&#x22;phone\&#x22;>\n          <DescriptionListTerm>Phone</DescriptionListTerm>\n          <DescriptionListDetails>\n            <DescriptionListValue>+44 20 7946 0321</DescriptionListValue>\n            {copy && (\n              <DescriptionListActions>\n                <DescriptionListCopy />\n              </DescriptionListActions>\n            )}\n          </DescriptionListDetails>\n        </DescriptionListItem>\n        <DescriptionListItem>\n          <DescriptionListTerm>Customer since</DescriptionListTerm>\n          <DescriptionListDetails>\n            <DescriptionListValue>14 March 2021</DescriptionListValue>\n          </DescriptionListDetails>\n        </DescriptionListItem>\n        <DescriptionListItem>\n          <DescriptionListTerm>Lifetime spend</DescriptionListTerm>\n          <DescriptionListDetails>\n            <DescriptionListValue className=\&#x22;font-medium\&#x22;>$4,812.60 · 23 orders</DescriptionListValue>\n          </DescriptionListDetails>\n        </DescriptionListItem>\n        <DescriptionListItem>\n          <DescriptionListTerm>Default address</DescriptionListTerm>\n          <DescriptionListDetails>\n            <DescriptionListValue>Flat 4, 18 Clerkenwell Close, London EC1R 0AA, United Kingdom</DescriptionListValue>\n            {edit && (\n              <DescriptionListActions>\n                <Button variant=\&#x22;ghost\&#x22; size=\&#x22;sm\&#x22; aria-label=\&#x22;Edit default address\&#x22;>\n                  <Pencil size={14} strokeWidth={1.75} aria-hidden />\n                  Edit\n                </Button>\n              </DescriptionListActions>\n            )}\n          </DescriptionListDetails>\n        </DescriptionListItem>\n        <DescriptionListItem>\n          <DescriptionListTerm>Tags</DescriptionListTerm>\n          <DescriptionListDetails>\n            <DescriptionListValue className=\&#x22;flex flex-wrap gap-1.5\&#x22;>\n              <Badge variant=\&#x22;secondary\&#x22;>Wholesale</Badge>\n              <Badge variant=\&#x22;secondary\&#x22;>Newsletter</Badge>\n              <Badge variant=\&#x22;success\&#x22;>Repeat buyer</Badge>\n            </DescriptionListValue>\n          </DescriptionListDetails>\n        </DescriptionListItem>\n        <DescriptionListItem>\n          <DescriptionListTerm>Notes</DescriptionListTerm>\n          <DescriptionListDetails>\n            <DescriptionListValue className=\&#x22;text-muted-foreground\&#x22;>\n              Prefers delivery after 2pm. Ask before substituting linen colours on wholesale orders.\n            </DescriptionListValue>\n          </DescriptionListDetails>\n        </DescriptionListItem>\n      </DescriptionList>\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;layout&#x22;:[475,481],&#x22;columns&#x22;:[495,496],&#x22;truncate&#x22;:[511,516],&#x22;copy&#x22;:[527,531],&#x22;edit&#x22;:[542,546],&#x22;title&#x22;:[558,568],&#x22;label&#x22;:[580,582],&#x22;gap&#x22;:[592,594],&#x22;font&#x22;:[605,607],&#x22;term&#x22;:[618,620],&#x22;ink&#x22;:[630,632],&#x22;rule&#x22;:[643,645]},&#x22;root&#x22;:[1247,5144],&#x22;importOffset&#x22;:416}" />

## Installation [#installation]

**CLI**

```bash
npx shadcn@latest add @keyframery/description-list
```

This adds `components/keyframery/description-list.tsx` and its primitive to your project, and installs UI SDK. 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.9 @ui-sdk/react@0.1.0-beta.9 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation#what-the-cli-adds-to-your-css) 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 = "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: `"springy"` (the default), `"calm"`, `"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
}
```

**Copy the component**

**components/keyframery/description-list.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/description-list"

/* Styled description list: the animated primitive plus the Keyframery look. The label and value rows
   of a detail page. `layout="rows"` puts the labels in a fixed column with hairlines between items,
   `"stacked"` puts each label above its value, `"grid"` lays items in two or three columns. Every
   layout falls back to stacked when the list is narrower than 28rem (a container query), so it
   reflows on a phone without a prop.

   Theming: set these CSS variables on the list or anything around it. Each falls back to the
   theme's own token, so nothing changes until you set one.
     --description-list-term    the labels                   (default: --muted-foreground)
     --description-list-ink     the values                   (default: --foreground)
     --description-list-rule    the hairlines between rows   (default: --border)
     --description-list-label   the label column in rows     (default: 10rem)
     --description-list-gap     the space above and below an item (default: 0.75rem)
     --description-list-font    the values' size             (default: 13px) */

import * as React from "react"

import {
  DescriptionList as DescriptionListPrimitive,
  DescriptionListActions as DescriptionListActionsPrimitive,
  DescriptionListCopy as DescriptionListCopyPrimitive,
  DescriptionListDetails as DescriptionListDetailsPrimitive,
  DescriptionListItem as DescriptionListItemPrimitive,
  DescriptionListTerm as DescriptionListTermPrimitive,
  DescriptionListValue as DescriptionListValuePrimitive,
} from "@/components/keyframery/primitives/description-list"
import { Speed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/* UI SDK parts take a class name or a function of the part's 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)
}

function DescriptionList({ speed, className, ...props }: React.ComponentProps<typeof DescriptionListPrimitive> & SpeedProps) {
  return (
    <Speed speed={speed}>
      <DescriptionListPrimitive
        className={withClass(
          cn(
            "@container/dl grid w-full min-w-0 text-[length:var(--description-list-font,13px)] leading-[1.45]",
            /* Grid: the given number of columns while each can be at least 11rem wide, fewer below that. */
            "data-[layout=grid]:gap-x-8 data-[layout=grid]:gap-y-1",
            "data-[layout=grid]:grid-cols-[repeat(auto-fill,minmax(max(11rem,calc((100%-(var(--description-list-columns,2)-1)*2rem)/var(--description-list-columns,2))),1fr))]",
          ),
          className,
        )}
        {...props}
      />
    </Speed>
  )
}

function DescriptionListItem({ className, ...props }: React.ComponentProps<typeof DescriptionListItemPrimitive>) {
  return (
    <DescriptionListItemPrimitive
      className={withClass(
        cn(
          "flex min-w-0 flex-col gap-1 py-[var(--description-list-gap,0.75rem)]",
          /* Rows and stacked: hairlines between items. */
          "not-data-[layout=grid]:border-b not-data-[layout=grid]:border-[color:var(--description-list-rule,var(--border))] not-data-[layout=grid]:last:border-b-0",
          /* Rows: a fixed label column once there is room. */
          "@md/dl:data-[layout=rows]:grid @md/dl:data-[layout=rows]:grid-cols-[var(--description-list-label,10rem)_minmax(0,1fr)] @md/dl:data-[layout=rows]:items-baseline @md/dl:data-[layout=rows]:gap-4",
        ),
        className,
      )}
      {...props}
    />
  )
}

function DescriptionListTerm({ className, ...props }: React.ComponentProps<typeof DescriptionListTermPrimitive>) {
  return (
    <DescriptionListTermPrimitive
      className={withClass("text-[12px] leading-[1.45] font-medium text-[color:var(--description-list-term,var(--muted-foreground))]", className)}
      {...props}
    />
  )
}

/* The value cell: the value, then any actions at its end. */
function DescriptionListDetails({ className, ...props }: React.ComponentProps<typeof DescriptionListDetailsPrimitive>) {
  return (
    <DescriptionListDetailsPrimitive
      className={withClass(
        "flex min-h-7 min-w-0 items-center gap-2 text-[color:var(--description-list-ink,var(--foreground))] tabular-nums",
        className,
      )}
      {...props}
    />
  )
}

function DescriptionListValue({ className, ...props }: React.ComponentProps<typeof DescriptionListValuePrimitive>) {
  return (
    <DescriptionListValuePrimitive
      className={withClass("min-w-0 flex-1 [overflow-wrap:anywhere] data-truncate:truncate", className)}
      {...props}
    />
  )
}

function DescriptionListActions({ className, ...props }: React.ComponentProps<typeof DescriptionListActionsPrimitive>) {
  return (
    <DescriptionListActionsPrimitive
      className={withClass("-my-1 ml-auto flex shrink-0 items-center gap-1", className)}
      {...props}
    />
  )
}

/* A quiet square key; copied, it turns the success green for as long as it says so. */
function DescriptionListCopy({ className, ...props }: React.ComponentProps<typeof DescriptionListCopyPrimitive>) {
  return (
    <DescriptionListCopyPrimitive
      className={withClass(
        cn(
          "grid size-7 shrink-0 cursor-pointer place-items-center rounded-[7px] text-muted-foreground outline-none",
          "hover:bg-[color-mix(in_oklab,var(--foreground)_6%,transparent)] hover:text-foreground",
          "focus-visible:ring-2 focus-visible:ring-ring",
          "data-copied:text-[oklch(0.62_0.16_150)] data-copied:hover:text-[oklch(0.62_0.16_150)]",
        ),
        className,
      )}
      {...props}
    />
  )
}

export {
  DescriptionList,
  DescriptionListActions,
  DescriptionListCopy,
  DescriptionListDetails,
  DescriptionListItem,
  DescriptionListTerm,
  DescriptionListValue,
}
```

**components/keyframery/primitives/description-list.tsx**

```tsx
"use client"

/* Animated description list, on UI SDK's core. UI SDK ships none, so the behaviour is defined in
   `@/components/core/description-list` with `definePrimitive` and rendered here: a `dl` of items,
   each a `dt` and a `dd`. This file adds motion only. Colours, borders and spacing stay yours.

   - Cascade: items arrive one after another when the list first shows (40ms apart, up to twelve).
   - Press: the copy button sinks and springs back.
   - Draw: copied, the copy icon shrinks into a blur and a check pops in and draws itself; two seconds
     later they swap back. */

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

import { descriptionList, descriptionListCopy, type DescriptionListCopyOptions } from "@/components/keyframery/core/description-list-core"
import { cn } from "@/lib/utils"

const {
  Root: DescriptionListRoot,
  Item: DescriptionListItemPart,
  Term: DescriptionListTerm,
  Details: DescriptionListDetails,
  Value: DescriptionListValue,
  Actions: DescriptionListActions,
} = createParts(descriptionList, { root: "dl", item: "div", term: "dt", details: "dd", value: "span", actions: "span" })

/* UI SDK parts take a class name or a function of the part's 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)
}

/* Keyframes with a backwards fill, so an item is hidden on its first frame and the delay never slows
   a later change. */
const keyframes =
  "@keyframes kf-dl-in{from{opacity:0;translate:0 6px;filter:blur(4px)}}" +
  "@keyframes kf-dl-tick{from{stroke-dashoffset:1}}" +
  Array.from({ length: 12 }, (_, i) => `[data-slot=description-list]>[data-slot=description-list-item]:nth-of-type(${i + 1}){--kf-dl:${i}}`).join("") +
  "[data-slot=description-list]>[data-slot=description-list-item]:nth-of-type(n+13){--kf-dl:12}"

function DescriptionList({ className, ...props }: React.ComponentProps<typeof DescriptionListRoot>) {
  return (
    <>
      <style href="kf-description-list" precedence="default">
        {keyframes}
      </style>
      <DescriptionListRoot className={className} {...props} />
    </>
  )
}

/* Cascade: each item rises in after the one before it. */
function DescriptionListItem({ className, ...props }: React.ComponentProps<typeof DescriptionListItemPart>) {
  return (
    <DescriptionListItemPart
      className={withClass(
        "animate-[kf-dl-in_calc(460ms*var(--kf-speed,1))_var(--ease-spring)_backwards] [animation-delay:calc((var(--kf-dl,0)*40ms+40ms)*var(--kf-speed,1))] motion-reduce:animate-none",
        className,
      )}
      {...props}
    />
  )
}

function CopyIcon({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden className={className}>
      <rect x="5.25" y="5.25" width="8" height="8" rx="2" />
      <path d="M10.75 5.25V4.5a1.75 1.75 0 0 0-1.75-1.75H4.5A1.75 1.75 0 0 0 2.75 4.5V9c0 .97.78 1.75 1.75 1.75h.75" />
    </svg>
  )
}

const swapIn = "transition-[opacity,scale,filter] duration-[calc(420ms*var(--kf-speed,1))] ease-pop motion-reduce:transition-none!"
const swapOut = "transition-[opacity,scale,filter] duration-[calc(160ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none!"

/* Copies one value: the `value` you give it, or the value it sits beside. With no children it shows a
   copy icon that turns into a drawn check once copied. */
function DescriptionListCopy({
  value,
  label,
  onCopy,
  className,
  children,
  ...props
}: DescriptionListCopyOptions & PartProps<"button", StateOf<typeof descriptionListCopy, "root">>) {
  const handle = usePrimitive(descriptionListCopy, { value, label, onCopy })
  return usePart(
    handle,
    "root",
    {},
    {
      ...props,
      className: withClass(
        "relative transition-[scale] duration-[calc(260ms*var(--kf-speed,1))] ease-pop active:scale-[0.9] active:duration-[calc(90ms*var(--kf-speed,1))] motion-reduce:transition-none!",
        className,
      ),
      children:
        children ??
        ((state) => (
          <span className="grid place-items-center *:[grid-area:1/1]">
            <CopyIcon className={cn("size-3.5", state.copied ? cn(swapOut, "scale-50 opacity-0 blur-[3px]") : swapIn)} />
            <svg
              viewBox="0 0 16 16"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.75"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden
              className={cn("size-3.5", state.copied ? swapIn : cn(swapOut, "scale-[0.6] opacity-0"))}
            >
              {state.copied && (
                <path
                  d="M3.5 8.5 6.5 11.5 12.5 4.75"
                  pathLength={1}
                  className="[stroke-dasharray:1] animate-[kf-dl-tick_calc(300ms*var(--kf-speed,1))_var(--ease-house)_calc(80ms*var(--kf-speed,1))_backwards] motion-reduce:animate-none"
                />
              )}
            </svg>
          </span>
        )),
    },
    "button",
  )
}

export {
  DescriptionList,
  DescriptionListActions,
  DescriptionListCopy,
  DescriptionListDetails,
  DescriptionListItem,
  DescriptionListTerm,
  DescriptionListValue,
}
```

**components/keyframery/core/description-list-core.ts**

```ts
/* Description lists, as UI SDK primitives. UI SDK ships none, so they are defined with its core: the
   same definitions render in React, Vue, Svelte, Solid and web components.

   `descriptionList` is the label and value rows of a detail page (a customer, an order), with real
   `dl` / `dt` / `dd` semantics. It lays them out as rows, stacked or a grid (`layout`), wraps or
   truncates long values (`truncate`, with the full text as a title), and keeps every label and value
   readable for agents as its `items`.

   `descriptionListCopy` is a button that copies one value: the text you give it, or the value it
   sits beside. It says "Copied" on itself for two seconds and tells screen readers. */

import { announce, css, definePrimitive } from "@ui-sdk/core"

type DescriptionListLayout = "rows" | "stacked" | "grid"

type DescriptionListOptions = {
  /** "rows" (a label column and hairlines, the default), "stacked" (label above value) or "grid". */
  layout?: DescriptionListLayout
  /** For the grid: how many columns, at full width. */
  columns?: number
  /** Long values stay on one line, ending in an ellipsis, with the full text as a title. */
  truncate?: boolean
}

type DescriptionListItem = { value: string; label: string }

type DescriptionListState = {
  layout: DescriptionListLayout
  columns: number
  truncate: boolean
  /** Every label with its value, read from the page. */
  items: DescriptionListItem[]
}

const fromOptions = (options: DescriptionListOptions) => ({
  layout: options.layout ?? "rows",
  columns: Math.max(1, Math.min(4, options.columns ?? 2)),
  truncate: options.truncate ?? false,
})

/* The text a value part shows, without its actions or anything hidden from readers. */
function readText(node: Node): string {
  if (node.nodeType === Node.TEXT_NODE) return node.textContent ?? ""
  if (!(node instanceof Element)) return ""
  if (node.matches('[aria-hidden="true"], [hidden], [data-agent-hidden], [data-slot="description-list-actions"], .sr-only')) return ""
  if (node.hasAttribute("data-agent-secret")) return "[redacted]"
  return Array.from(node.childNodes, readText).join(" ")
}

const clean = (text: string) => text.replace(/\s+/g, " ").trim()

/** The value of one item element: its value part if it has one, else its details. */
function valueOf(item: Element) {
  const value = item.querySelector('[data-slot="description-list-value"]') ?? item.querySelector('[data-slot="description-list-details"]')
  return value ? clean(readText(value)) : ""
}

function labelOf(item: Element) {
  const term = item.querySelector('[data-slot="description-list-term"]')
  return term ? clean(readText(term)) : ""
}

const descriptionList = definePrimitive({
  name: "description-list",
  options: { layout: "string", columns: "number", truncate: "boolean" },
  state: (options: DescriptionListOptions): DescriptionListState => ({ ...fromOptions(options), items: [] }),
  sync: (options) => fromOptions(options),
  controlled: ["items", "layout"],
  api: (context) => ({
    /** @internal Reads every label and value from the page into `items`. */
    read(el: HTMLElement) {
      const items = Array.from(el.querySelectorAll('[data-slot="description-list-item"]'), (item) => ({
        label: labelOf(item),
        value: valueOf(item),
      })).filter((item) => item.label || item.value)
      const now = context.store.get().items
      if (items.length === now.length && items.every((item, index) => item.label === now[index].label && item.value === now[index].value)) return
      context.store.set({ items })
    },
  }),
  slots: (slot) => ({
    root: slot<{}, { layout: DescriptionListLayout; columns: number; truncate: boolean }>({
      state: (state) => ({ layout: state.layout, columns: state.columns, truncate: state.truncate }),
      attrs: (state) => ({
        "data-layout": state.layout,
        "data-truncate": state.truncate ? "" : undefined,
        style: css({ "--description-list-columns": state.columns }),
      }),
      bind: (el, part) => {
        part.api.read(el)
        const observer = new MutationObserver(() => part.api.read(el))
        observer.observe(el, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["aria-hidden", "hidden"] })
        return () => observer.disconnect()
      },
    }),
    /* One label with its value. A `div` around a `dt` and its `dd`s is valid inside a `dl`. */
    item: slot<{ value?: string }, { layout: DescriptionListLayout }>({
      props: { value: "string" },
      state: (state) => ({ layout: state.layout }),
      attrs: (state) => ({ "data-layout": state.layout }),
    }),
    term: slot({}),
    details: slot<{}, { truncate: boolean }>({
      state: (state) => ({ truncate: state.truncate }),
      attrs: (state) => ({ "data-truncate": state.truncate ? "" : undefined }),
    }),
    /* The value itself, beside any actions. Truncated, it carries its full text as a title. */
    value: slot<{}, { truncate: boolean }>({
      state: (state) => ({ truncate: state.truncate }),
      attrs: (state) => ({ "data-truncate": state.truncate ? "" : undefined }),
      bind: (el, part) => {
        const title = () => {
          const text = clean(readText(el))
          if (part.store.get().truncate && text) el.setAttribute("title", text)
          else el.removeAttribute("title")
        }
        title()
        const observer = new MutationObserver(title)
        observer.observe(el, { subtree: true, childList: true, characterData: true })
        const stop = part.store.subscribe(title)
        return () => {
          observer.disconnect()
          stop()
        }
      },
    }),
    /* Buttons or links that act on the value: a copy button, an Edit link. */
    actions: slot({}),
  }),
  /* Agents read every label and value; the list itself has no actions. */
  agent: { actions: [] },
})

type DescriptionListCopyOptions = {
  /** The text to copy. Leave it out to copy the value the button sits beside. */
  value?: string
  /** What the value is called, for the button's name ("Copy Email"). Read from the item's label when left out. */
  label?: string
  /** Runs after the text was copied. */
  onCopy?: (text: string) => void
}

type DescriptionListCopyState = {
  copied: boolean
  /** What the button copies, read from the page when no `value` is given. */
  text: string
  /** What the value is called. */
  label: string
}

const descriptionListCopy = definePrimitive({
  name: "description-list-copy",
  options: { value: "string", label: "string", onCopy: "callback" },
  state: (options: DescriptionListCopyOptions): DescriptionListCopyState => ({
    copied: false,
    text: options.value ?? "",
    label: options.label ?? "",
  }),
  sync: (options) => ({
    ...(options.value === undefined ? {} : { text: options.value }),
    ...(options.label === undefined ? {} : { label: options.label }),
  }),
  controlled: ["copied", "text"],
  api: (context) => {
    let timer: ReturnType<typeof setTimeout> | undefined
    let button: HTMLElement | undefined
    context.onDestroy(() => clearTimeout(timer))

    const write = async (text: string) => {
      try {
        await navigator.clipboard.writeText(text)
      } catch {
        /* No clipboard permission (an insecure page, an embedded frame): the old way still works. */
        const area = document.createElement("textarea")
        area.value = text
        area.setAttribute("readonly", "")
        area.style.position = "fixed"
        area.style.opacity = "0"
        document.body.append(area)
        area.select()
        document.execCommand("copy")
        area.remove()
      }
    }

    return {
      /** @internal Reads the value and label beside the button, when they weren't given. */
      attach(el: HTMLElement) {
        button = el
        const item = el.closest('[data-slot="description-list-item"]')
        if (!item) return () => {}
        const read = () => {
          const options = context.options()
          const next: Partial<DescriptionListCopyState> = {}
          if (options.value === undefined) next.text = valueOf(item)
          if (options.label === undefined) next.label = labelOf(item)
          const now = context.store.get()
          if ((next.text ?? now.text) !== now.text || (next.label ?? now.label) !== now.label) context.store.set(next)
        }
        read()
        const observer = new MutationObserver(read)
        observer.observe(item, { subtree: true, childList: true, characterData: true })
        return () => {
          observer.disconnect()
          button = undefined
        }
      },
      /** Copies the value, says "Copied" on the button for two seconds and tells screen readers. */
      async copy() {
        const { text } = context.store.get()
        await write(text)
        clearTimeout(timer)
        context.store.set({ copied: true })
        announce("Copied")
        context.options().onCopy?.(text)
        const speed = (button && parseFloat(getComputedStyle(button).getPropertyValue("--kf-speed"))) || 1
        timer = setTimeout(() => context.store.set({ copied: false }), 2000 * speed)
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { copied: boolean }>({
      role: "button",
      focus: "native",
      state: (state) => ({ copied: state.copied }),
      attrs: (state) => ({
        type: "button",
        "aria-label": state.copied ? "Copied" : state.label ? `Copy ${state.label}` : "Copy",
        "data-copied": state.copied ? "" : undefined,
      }),
      press: ({ api }) => void api.copy(),
      bind: (el, part) => part.api.attach(el),
    }),
  }),
  agent: { actions: ["copy"] },
})

export {
  descriptionList,
  descriptionListCopy,
  type DescriptionListCopyOptions,
  type DescriptionListItem,
  type DescriptionListLayout,
  type DescriptionListOptions,
}
```

**Check the import paths**

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

## Usage [#usage]

```tsx
import {
  DescriptionList,
  DescriptionListDetails,
  DescriptionListItem,
  DescriptionListTerm,
  DescriptionListValue,
} from "@/components/keyframery/description-list"

export default function Usage() {
  return (
    <DescriptionList aria-label="Order">
      <DescriptionListItem>
        <DescriptionListTerm>Order</DescriptionListTerm>
        <DescriptionListDetails>
          <DescriptionListValue>#1048</DescriptionListValue>
        </DescriptionListDetails>
      </DescriptionListItem>
    </DescriptionList>
  )
}
```

### Anatomy [#anatomy]

How the parts fit together:

```text
DescriptionList
└── DescriptionListItem
    ├── DescriptionListTerm
    └── DescriptionListDetails
        └── DescriptionListValue
```

## Examples [#examples]

### An order's details, with copy buttons [#an-orders-details-with-copy-buttons]

A copy button copies the value beside it and confirms on itself with a drawn check. Below 28rem wide the rows stack.

<ExamplePreview name="description-list/rows">
  ```tsx
  import {
    DescriptionList,
    DescriptionListActions,
    DescriptionListCopy,
    DescriptionListDetails,
    DescriptionListItem,
    DescriptionListTerm,
    DescriptionListValue,
  } from "@/components/keyframery/description-list"

  const rows = [
    { label: "Order", value: "#1048", copy: true },
    { label: "Placed", value: "18 November 2026, 14:02" },
    { label: "Payment", value: "Visa ending 4242" },
    { label: "Tracking", value: "1Z 999 AA1 01 2345 6784", copy: true },
  ]

  export default function DescriptionListRows() {
    return (
      <DescriptionList aria-label="Order details" className="max-w-md">
        {rows.map((row) => (
          <DescriptionListItem key={row.label}>
            <DescriptionListTerm>{row.label}</DescriptionListTerm>
            <DescriptionListDetails>
              <DescriptionListValue>{row.value}</DescriptionListValue>
              {row.copy && (
                <DescriptionListActions>
                  <DescriptionListCopy />
                </DescriptionListActions>
              )}
            </DescriptionListDetails>
          </DescriptionListItem>
        ))}
      </DescriptionList>
    )
  }
  ```
</ExamplePreview>

### A grid that truncates [#a-grid-that-truncates]

`layout="grid"` with `columns={3}` lays items side by side, fewer columns when there is less room. `truncate` keeps long values on one line with the full text as a title.

<ExamplePreview name="description-list/grid">
  ```tsx
  import {
    DescriptionList,
    DescriptionListDetails,
    DescriptionListItem,
    DescriptionListTerm,
    DescriptionListValue,
  } from "@/components/keyframery/description-list"

  const facts = [
    ["Plan", "Team, billed yearly"],
    ["Seats", "14 of 20"],
    ["Renews", "2 February 2027"],
    ["Billing email", "accounts-payable@harbour-and-finch.co.uk"],
    ["VAT number", "GB 123 4567 89"],
    ["Region", "Europe (Frankfurt)"],
  ]

  export default function DescriptionListGrid() {
    return (
      <DescriptionList aria-label="Subscription" layout="grid" columns={3} truncate className="max-w-2xl">
        {facts.map(([label, value]) => (
          <DescriptionListItem key={label}>
            <DescriptionListTerm>{label}</DescriptionListTerm>
            <DescriptionListDetails>
              <DescriptionListValue>{value}</DescriptionListValue>
            </DescriptionListDetails>
          </DescriptionListItem>
        ))}
      </DescriptionList>
    )
  }
  ```
</ExamplePreview>

## Motion [#motion]

| Move        | What you see                                                                                                                |
| ----------- | --------------------------------------------------------------------------------------------------------------------------- |
| **Cascade** | Items rise in one after another, 40ms apart, with a little blur, when the list first shows.                                 |
| **Press**   | The copy button sinks and springs back.                                                                                     |
| **Draw**    | Copied, the copy icon shrinks into a blur, a check pops in and draws itself in green, and two seconds later they swap back. |

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

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

`"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            |
| -------------------------- | ----------------------------- | ------------------ |
| `--description-list-term`  | The labels                    | --muted-foreground |
| `--description-list-ink`   | The values                    | --foreground       |
| `--description-list-rule`  | Hairlines between rows        | --border           |
| `--description-list-label` | The label column in rows      | 10rem              |
| `--description-list-gap`   | Space above and below an item | 0.75rem            |
| `--description-list-font`  | The values' size              | 13px               |

## 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`.

### DescriptionList [#descriptionlist]

Renders a `<dlist>`, 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 it moves: \&#x22;fast\&#x22;, \&#x22;normal\&#x22;, \&#x22;slow\&#x22; or a multiplier.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;layout&#x22;,&#x22;type&#x22;:&#x22;\&#x22;grid\&#x22; | \&#x22;rows\&#x22; | \&#x22;stacked\&#x22;&#x22;,&#x22;full&#x22;:&#x22;DescriptionListLayout&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;\&#x22;rows\&#x22; (labels in a fixed column, hairlines between, the default), \&#x22;stacked\&#x22; (label above value) or \&#x22;grid\&#x22;. All three stack below 28rem.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;columns&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;For the grid: how many columns at full width, 1 to 4. Defaults to 2. Fewer show when a column would be under 11rem.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;truncate&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Keeps long values on one line with an ellipsis and the full text as a title. Off, they wrap.&#x22;,&#x22;required&#x22;:false}]" />

### DescriptionListItem [#descriptionlistitem]

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

<PropsTable rows="[{&#x22;name&#x22;:&#x22;value&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;An id for the item, when you need to key it.&#x22;,&#x22;required&#x22;:false}]" />

### DescriptionListCopy [#descriptionlistcopy]

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

<PropsTable rows="[{&#x22;name&#x22;:&#x22;value&#x22;,&#x22;type&#x22;:&#x22;string | (string & readonly string[])&#x22;,&#x22;full&#x22;:&#x22;string | (string & readonly string[])&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The text to copy. Leave it out to copy the value beside the button.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;label&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;What the value is called, for the button's name (\&#x22;Copy Email\&#x22;). Read from the item's label when left out.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onCopy&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;((text: string) => void) & React.ClipboardEventHandler<HTMLButtonElement>&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Runs with the copied text.&#x22;,&#x22;required&#x22;:false}]" />

### Other parts [#other-parts]

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

* `DescriptionListTerm`
* `DescriptionListDetails`
* `DescriptionListValue`: a `<span>`
* `DescriptionListActions`: a `<span>`

## Keyboard [#keyboard]

| Key                      | What it does                                            |
| ------------------------ | ------------------------------------------------------- |
| <kbd>Tab</kbd>           | Moves to each copy button and action in the list.       |
| <kbd>Enter / Space</kbd> | Copies the focused value; screen readers hear "Copied". |

## 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 description list, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/description-list-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/description-list`.

## Questions

### How does the animated Description list for UI SDK move?

Cascade: Items rise in one after another, 40ms apart, with a little blur, when the list first shows. Press: The copy button sinks and springs back. Draw: Copied, the copy icon shrinks into a blur, a check pops in and draws itself in green, and two seconds later they swap back.

### Do I need Motion or Framer Motion for the animated Description list?

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

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

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/description-list-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 Description list when someone turns on reduced motion?

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