Skip to main content

Expanding Box

A frame that morphs from one box into another with View Transitions: a field-like trigger grows into its panel and shrinks back. The header search dialog is built on it.

import {
  ExpandingBox,
  ExpandingBoxExtra,
  ExpandingBoxMain,
  expandingBoxParts,
  startExpandingTransition,
  useExpandingBoxName,
} from '@fairgarden/design/foundations/expanding-box'

The box has no behavior of its own. An owner renders two boxes, the trigger's (collapsed) and the panel's, under one name from useExpandingBoxName(), and keeps exactly one of them active. The state change that swaps them runs inside startExpandingTransition(update, { direction }), and the browser animates each named piece from the old box to the new one.

How the morph works

The frame is a 9-slice: a head row and a foot row of corner and edge cells, and a content row whose face and two side-edge pieces fill in the rest. While a box is active, each piece carries its own view-transition-name, set inline per instance, so two boxes on a page never collide. The corners translate without scaling, so their radii stay crisp. The four edges stretch only along their length, so they keep their weight, and the face stretches behind them. ExpandingBoxMain rides the left edge, the one element marked expandingBoxParts.end rides the right edge, and ExpandingBoxExtra grows out of the trigger's empty extra.

Only geometry moves. No piece fades: each shows its new state from the first frame while its box travels, and the page behind it does not crossfade either. Opening takes 333 ms on a critically damped curve that never overshoots (--fgd-duration-expand, --fgd-ease-expand). Closing takes 200 ms (--fgd-duration-disclosure), so the way back is faster. The trigger's focus ring does not travel with the frame. It stays hidden for 200 ms and shows once the frame has landed.

Both states share one radius, --radius-2-25, and one edge, --border-size-2, so the corners keep their shape and only travel; the focus ring follows the radius. Only the edge color changes: --role-rule collapsed, stepping to --primary12 on hover, and --primary12 expanded. Opening switches to the expanded color as the box starts to move. Closing keeps the expanded color while the box shrinks, and the landed trigger eases back to --role-rule once the morph has finished. The face is --primary1. sheet marks the dialog's box below 768 px, where its owner insets the panel by the page margin; the frame stays the same.

The morph

The morph

Select the trigger to open the panel, then press Escape or Close to shrink it back. Focus moves to Close on open and returns to the trigger on close. The owner moves focus inside the update, so the ring shows in the new snapshot, not the old one.

'use client'

import * as React from 'react'
import { Button } from '@fairgarden/design/actions/button'
import { Icon } from '@fairgarden/design/foundations/icon'
import {
  ExpandingBox,
  ExpandingBoxExtra,
  ExpandingBoxMain,
  expandingBoxParts,
  startExpandingTransition,
  useExpandingBoxName,
} from '@fairgarden/design/foundations/expanding-box'
import type { PrimaryScale } from '@fairgarden/design/utils/scales'
import styles from './morph.module.css'

type MorphPanelProps = {
  /** The trigger's label and the panel's title. */
  label: string
  /** The panel's body. */
  children: React.ReactNode
  primary?: PrimaryScale
}

/**
 * A minimal owner: a button-shaped box that morphs into a panel on click
 * and back on Escape or Close. Both boxes share one name; exactly one is
 * active at a time, and the state change that swaps them runs inside
 * `startExpandingTransition`.
 */
export function MorphPanel({ label, children, primary }: MorphPanelProps) {
  const name = useExpandingBoxName()
  const panelId = React.useId()
  const titleId = React.useId()
  const [open, setOpen] = React.useState(false)
  const busy = React.useRef(false)
  const wasOpen = React.useRef(false)
  const triggerRef = React.useRef<HTMLButtonElement>(null)
  const closeRef = React.useRef<HTMLButtonElement>(null)

  const change = (next: boolean) => {
    if (busy.current) return
    busy.current = true
    void startExpandingTransition(() => setOpen(next), {
      direction: next ? 'open' : 'close',
    }).then(() => {
      busy.current = false
    })
  }

  // Focus moves inside the morph's flushSync, so the new snapshot already has it.
  React.useLayoutEffect(() => {
    if (open) closeRef.current?.focus()
    else if (wasOpen.current) triggerRef.current?.focus()
    wasOpen.current = open
  }, [open])

  return (
    <div className={styles.stage}>
      <button
        ref={triggerRef}
        type="button"
        className={`${expandingBoxParts.host} ${styles.trigger}`}
        aria-expanded={open}
        aria-controls={panelId}
        onClick={() => change(true)}
      >
        <ExpandingBox
          as="span"
          name={name}
          active={!open}
          collapsed
          primary={primary}
          className={styles.triggerInner}
        >
          <ExpandingBoxMain className={styles.triggerMain}>
            <span className={styles.triggerLabel}>{label}</span>
            <Icon name="expand_more" className={expandingBoxParts.end} />
          </ExpandingBoxMain>
        </ExpandingBox>
      </button>

      <div
        id={panelId}
        role="region"
        aria-labelledby={titleId}
        hidden={!open}
        className={`${expandingBoxParts.host} ${styles.panel}`}
        onKeyDown={(event) => {
          if (event.key === 'Escape') change(false)
        }}
      >
        <ExpandingBox name={name} active={open} primary={primary} className={styles.panelInner}>
          <ExpandingBoxMain className={styles.panelMain}>
            <h4 id={titleId} className={styles.panelTitle}>
              {label}
            </h4>
            <Button
              ref={closeRef}
              iconOnly
              icon="close"
              size="sm"
              variant="text"
              primary={primary}
              className={expandingBoxParts.end}
              onClick={() => change(false)}
            >
              Close {label}
            </Button>
          </ExpandingBoxMain>
          <ExpandingBoxExtra className={styles.panelBody}>{children}</ExpandingBoxExtra>
        </ExpandingBox>
      </div>
    </div>
  )
}

export function ExpandingBoxMorph() {
  return (
    <MorphPanel label="Trail notes">
      <p>The ridge loop is 6.4 km with 212 m of climb. Allow three hours.</p>
      <p>The creek crossing floods after heavy rain; take the upper bridge.</p>
    </MorphPanel>
  )
}

Two pairs and the primary scale

Two pairs and the primary scale

Each owner takes its own name, so each pair morphs on its own. primary recolors the edges, the face and the focus ring.

import { MorphPanel } from './ExpandingBoxMorph'
import styles from './pairs.module.css'

/** Two owners side by side: each takes its own name, so neither morph disturbs the other. */
export function ExpandingBoxPairs() {
  return (
    <div className={styles.row}>
      <MorphPanel label="Opening hours">
        <p>Gates open at 7:00 and close at dusk, 365 days a year.</p>
      </MorphPanel>
      <MorphPanel label="Parking" primary="plum">
        <p>The lower lot holds 40 cars; overflow parks on Mill Lane.</p>
      </MorphPanel>
    </div>
  )
}

Reduced motion and fallbacks

startExpandingTransition reads prefers-reduced-motion when it is called. Under reduced motion, or in a browser without View Transitions and view-transition-class, it runs the update directly and the panel appears at once. The owner can add its own fallback where motion is allowed, as the search dialog does with the Dialog's clip reveal. The promise it returns resolves when the morph finishes, or straight away when there is none, and it never rejects.

While a morph runs, <html> carries data-fgd-expanding="open" or "close", so an owner's CSS can step aside (for example, to turn off a clip reveal that would fight the morph). The global rules live in utils/view-transitions.css, which utils/global.css imports.

In print the box drops its slices and prints its content inside one black --border-size-1 frame.

API Reference

ExpandingBox

A 9-slice frame in three rows (head, content, foot), rendered as direct children of the host (give that element expandingBoxParts.host). Each row carries the scope attributes and the scale classes. While active, its pieces carry View Transition names, so the owner’s startExpandingTransition morphs this box into the pair’s other box: corners translate, edges stretch, main rides the left edge, end the right, and the extra grows.

PropTypeDescription
name
string

The pair’s name base, shared by the two boxes that morph into each other (trigger and dialog). Get it once in the owner with useExpandingBoxName(), so two pairs never collide.

active
boolean | undefined

This box holds the transition names now. Exactly one box of a pair is active at a time. Default false.

as
'div' | 'span' | undefined

span inside phrasing-only hosts such as a <button>. Default 'div'.

collapsed
boolean | undefined

Trigger-sized state: the field edge color (--role-rule), hover edge step, focus-ring hand-off. Default false.

primary
| 'olive'
| 'sage'
| 'slate'
| 'sand'
| 'gray'
| 'mauve'
| 'brown'
| 'bronze'
| 'gold'
| 'red'
| 'ruby'
| 'crimson'
| 'tomato'
| 'pink'
| 'plum'
| 'indigo'
| 'iris'
| 'violet'
| 'purple'
| null
| undefined

Primary Radix scale: edges (hover and expanded --primary12), face (--primary1), focus ring. Never defaulted; omitted, it inherits the scope [D133].

secondary
| 'olive'
| 'sage'
| 'slate'
| 'sand'
| 'gray'
| 'mauve'
| 'brown'
| 'bronze'
| 'gold'
| 'red'
| 'ruby'
| 'crimson'
| 'tomato'
| 'pink'
| 'plum'
| 'indigo'
| 'iris'
| 'violet'
| 'purple'
| 'amber'
| 'blue'
| 'cyan'
| 'grass'
| 'green'
| 'jade'
| 'lime'
| 'mint'
| 'orange'
| 'sky'
| 'teal'
| 'yellow'
| null
| undefined

Secondary Radix scale, accepted for the shared color contract; no part draws in it today. Never defaulted.

sheet
boolean | undefined

The expanded box is the dialog’s sheet below --md-n-above. The box keeps its radius and frame; the owner insets the host by the page margin (and the safe areas). Marks the rows data-sheet. Default false.

children
React.ReactNode

ExpandingBoxMain, then an optional ExpandingBoxExtra, then anything else (unnamed, such as a stats row).

className
string | undefined

On the content wrapper.

ExpandingBoxMain and ExpandingBoxExtra

The main piece (trigger: icon, label and shortcut hint; dialog: the input row). Rides the left edge. Renders the box’s as.

The extra piece (dialog: the results). If omitted, the box renders an empty one, so the trigger’s empty extra grows into the dialog’s.

useExpandingBoxName and startExpandingTransition

A pair name from useId(), sanitized to a custom-ident: fgd-xb-<id> with [^A-Za-z0-9_-] replaced by -. Call it once in the owner and pass it to both boxes of the pair.

Returns
string

Runs update (the state change that swaps which box is active) as the morph. Resolves once the morph finishes, or on a microtask when it doesn’t run. Never rejects.

Without View Transitions or view-transition-class, under prefers-reduced-motion: reduce, in forced colors or print, with enabled: false, where --fgd-outline-morph: none applies to the source, or with the direction’s duration token at 0 (read at call time), it calls update() directly and the change is instant. Otherwise it sets <html data-fgd-expanding="open|close"> and calls document.startViewTransition(() => flushSync(update)), removing the flag when the last running morph settles. Re-entry guards are the owner’s.

ParameterTypeDescription
update
() => void
options
StartExpandingTransitionOptions
Returns
Promise<void>

Additional types

expandingBox
ExpandingBoxPartProps

Props for ExpandingBoxMain and ExpandingBoxExtra: HTML attributes and a ref.

type ExpandingBoxPartProps = React.HTMLAttributes<HTMLElement> & { ref?: React.Ref<HTMLElement> }
expandingBoxParts

Class names for the owner’s elements.

type expandingBoxParts = {
  /**
   * On the owner's element that hosts the rows (the trigger button, the
   * dialog popup): positions the box and hands its focus ring to the box.
   */
  host: string;
  /**
   * On one element inside `ExpandingBoxMain` that rides the right edge (the
   * shortcut hint, the esc or close button). At most one displayed per box.
   */
  end: string;
}
ExpandingBoxProps

Props for ExpandingBox.

type ExpandingBoxProps = {
  /**
   * The pair's name base, shared by the two boxes that morph into each other
   * (trigger and dialog). Get it once in the owner with `useExpandingBoxName()`,
   * so two pairs never collide.
   */
  name: string;
  /** This box holds the transition names now. Exactly one box of a pair is active at a time. Default `false`. */
  active?: boolean;
  /** Trigger-sized state: the field edge color (`--role-rule`), hover edge step, focus-ring hand-off. Default `false`. */
  collapsed?: boolean;
  /**
   * The expanded box is the dialog's sheet below `--md-n-above`. The box keeps
   * its radius and frame; the owner insets the host by the page margin (and
   * the safe areas). Marks the rows `data-sheet`. Default `false`.
   */
  sheet?: boolean;
  /** `span` inside phrasing-only hosts such as a `<button>`. Default `'div'`. */
  as?: 'div' | 'span';
  /** On the content wrapper. */
  className?: string;
  /** `ExpandingBoxMain`, then an optional `ExpandingBoxExtra`, then anything else (unnamed, such as a stats row). */
  children: React.ReactNode;
  /**
   * Primary Radix scale: edges (hover and expanded `--primary12`), face
   * (`--primary1`), focus ring. Never defaulted; omitted, it inherits the
   * scope [D133].
   */
  primary?:
    | 'olive'
    | 'sage'
    | 'slate'
    | 'sand'
    | 'gray'
    | 'mauve'
    | 'brown'
    | 'bronze'
    | 'gold'
    | 'red'
    | 'ruby'
    | 'crimson'
    | 'tomato'
    | 'pink'
    | 'plum'
    | 'indigo'
    | 'iris'
    | 'violet'
    | 'purple'
    | null;
  /** Secondary Radix scale, accepted for the shared color contract; no part draws in it today. Never defaulted. */
  secondary?:
    | 'olive'
    | 'sage'
    | 'slate'
    | 'sand'
    | 'gray'
    | 'mauve'
    | 'brown'
    | 'bronze'
    | 'gold'
    | 'red'
    | 'ruby'
    | 'crimson'
    | 'tomato'
    | 'pink'
    | 'plum'
    | 'indigo'
    | 'iris'
    | 'violet'
    | 'purple'
    | 'amber'
    | 'blue'
    | 'cyan'
    | 'grass'
    | 'green'
    | 'jade'
    | 'lime'
    | 'mint'
    | 'orange'
    | 'sky'
    | 'teal'
    | 'yellow'
    | null;
}
ExpandingTransitionDirection

Which way the morph runs: open grows the trigger into the dialog; close is the faster way back.

type ExpandingTransitionDirection = 'open' | 'close'
StartExpandingTransitionOptions

Options for startExpandingTransition.

type StartExpandingTransitionOptions = {
  /** `open` or `close`: sets `<html data-fgd-expanding>`, which picks the timing. */
  direction: ExpandingTransitionDirection;
  /** The owner's `morph` prop. Default `true`; `false` applies the update at once, with no morph. */
  enabled?: boolean;
  /**
   * The element the morph reads the shared switch and tokens on, usually the
   * trigger (default: the root): `--fgd-outline-morph: none` there, or the
   * direction's duration token (`--fgd-duration-expand` to open,
   * `--fgd-duration-collapse` to close) resolving to 0, applies the update
   * at once [D204].
   */
  source?: Element | null;
}

Specification: DESIGN-SYSTEM.md §9.10 (search) [D194], §10.14 (the overlay frame) and §1.5.15 (motion).