# Components — Required Evidence

Scope: choosing, composing, creating, or modifying UI components for a Mirror product interface.

## Package-first rule

Use the current `@mirror-physics/fractal-ui` package before building local UI. Use `@mirror-physics/fractal-icons` for icons. Inspect the version installed in the target project, its exported types, and its stories or package documentation before writing code; this guide defines UX intent, not volatile props or pixel values.

Required order:

1. Look for an exported component that matches the user's task.
2. Compose exported components when no single component covers the whole pattern.
3. Use a product-local composition when it is specific to one screen or workflow.
4. Propose a new Fractal UI component only when the behavior is genuinely distinct and likely to recur.
5. Modify an existing shared component only after checking its consumers and compatibility risk.

Never invent a package export, prop, variant, token, or component dimension. The installed package is authoritative for its API and current implementation values.

## Component selection

### Actions and links

| Component | Use when | Do not use when |
| --- | --- | --- |
| `Button` | A visible control commits an action, submits, creates, confirms, or triggers a consequential workflow. | The destination is ordinary navigation or the action should look like inline text. |
| `TextButton` | A low-emphasis action belongs in prose, a compact row, or secondary chrome but still behaves as a button. | It navigates to a URL; use `Link`. |
| `Link` | Activating text navigates to a destination or resource. | It mutates state without navigation. |

Use at most one Primary button per decision region. The main action may use Secondary; no Primary button is required. Label actions with specific verbs. Icon-only actions require an accessible name and, when unfamiliar, a tooltip.

### Inputs and choices

| Component | Use when | Do not use when |
| --- | --- | --- |
| `Input` | The user enters one line of text. | The value is numeric with stepping/validation, secret, or multiline. |
| `NumberInput` | The value is numeric and benefits from numeric validation or stepping. | The string only looks numeric, such as an ID, postal code, or phone number. |
| `PasswordInput` | The value is secret and needs reveal/conceal behavior. | Ordinary sensitive-looking data does not need password semantics. |
| `Textarea` | The user authors or pastes editable multiline text. | The task requires syntax-aware rich editing. |
| `Checkbox` | Each option is independently on/off, or one acknowledgment can be selected. | The setting should take effect immediately as a system state; use `Toggle`. |
| `Radio` | Exactly one option must be chosen from a visible, small set. | Zero or many choices are allowed, or the set is too long to show. |
| `Toggle` | A binary setting takes effect immediately and its current state must remain visible. | The choice belongs to a form that is committed later, or expresses agreement; use `Checkbox`. |
| `Slider` | Approximate value selection and relative position matter more than exact typing. | Precision is primary; use `NumberInput`, or pair the two. |
| `Dropdown` | The user chooses from a longer constrained set and showing all choices would be noisy. | The choices must be compared simultaneously; use radios or another visible control. |
| `FileDropzone` | Uploading files is a primary task and drag/drop is useful. | A compact, occasional attachment control is sufficient. |
| `TableSearch` | Search is scoped specifically to the adjacent data table. | Search is global or covers heterogeneous content. |
| `Label` | A form control needs a persistent accessible name. | Placeholder text would be the only label; that is never sufficient. |

Persistent labels are required. Placeholder text is a format hint, not a label. Use `--space-2` between a label and its control by default; `--space-1` is allowed in an explicitly compact composition. Do not introduce a 6px gap.

Dropdown menus have a maximum width of 24rem, further constrained by the viewport or clipping region. Truncate overflowing option labels with an ellipsis while retaining the full accessible label. Vertical menus align to the trigger’s left or right edge; switch edges on collision and reduce the width when necessary rather than shifting the menu away from both edges.

Use the dropdown multiselect variant for searchable lists of independent filter choices. Its rows use the same full-width hover treatment and content insets as single-select dropdown options; group headings align with checkbox leading edges. Keep keyboard focus indicators inside scrollable menu bounds. Selection keeps the menu open, and Escape restores focus to the trigger.

### Navigation and disclosure

| Component | Use when | Do not use when |
| --- | --- | --- |
| `Tabs` | Switching between sibling views of the same subject; 2–6 concise labels. | Views are top-level destinations, nested tabs, or steps in a process. |
| `ContentSwitcher` | Switching the representation or mode of the same content in place. | Each option is a separate destination or independent setting. |
| `Disclosure` | Expanding optional subordinate content while preserving the current context. | The content is required for the primary task or is a peer view. |
| `Breadcrumbs` | Showing location within a real hierarchy and allowing navigation to ancestors. | The sequence is history, progress, or decorative context. |
| `Sidebar` | Stable top-level application navigation or persistent grouped destinations. | A temporary object workflow; use `SidePanel`. |
| `Pagination` | A large ordered result set is split into discrete pages. | Continuous loading or a short complete set better supports the task. |

Use tabs for peer views, disclosure for optional detail, and a side panel for a temporary object-focused workspace. Do not nest tabs.

Adjacent sidebar and main navigation headers follow the [application navigation header alignment](../layout.md#application-navigation-header-alignment) rule. Use the shared shell-height token and package styling; do not independently size the brand/account header from the breadcrumb row. Page-title and description sections belong below that row.

### Surfaces and feedback

| Component | Use when | Do not use when |
| --- | --- | --- |
| `Card` | A self-contained peer unit needs separation from adjacent content. | Whitespace and headings already establish the reading flow. |
| `FeatureCard` | A peer summary or finding in a grid needs a consistent icon/title/body anatomy. | The message is a transient or urgent system notification. |
| `FolderCard` | A tile navigates to a folder-like collection. | The entity is not a collection or the layout is not navigational. |
| `PromptCard` / `PromptGrid` | A user chooses among suggested starting prompts or comparable next actions. | The content is passive information. |
| `Alert` | A persistent inline system message needs contextual severity and action. | The message is transient; use `Toast`, or it is ordinary peer content; use a card. |
| `Tooltip` | Brief, supplementary non-interactive help belongs on a focusable trigger, available on hover and keyboard focus. | Essential instructions, links, form controls, or other interactive content need visible text or a popover. |
| `Toast` | Brief feedback follows an action and does not block the workflow. | The information must persist, requires a decision, or contains complex content. |
| `Chip` | Compact metadata, status, filter state, or a removable token is needed. | A primary action or long label is needed. |
| `Modal` | A blocking decision or short focused workflow must interrupt the current context. | The user needs to compare with the underlying page or complete a broad workflow. |
| `SidePanel` | Object details or a focused workflow should remain alongside the originating collection. | The task is blocking, global, or too broad for a temporary panel. |

Tooltips use the inverse surface and foreground tokens in both light and dark themes, with a matching pointer arrow aimed at the trigger. Use the shared runtime Tooltip for hover and focus help; chart-specific tooltip layouts retain this same inverse treatment.

Choose the smallest semantic `Modal` size that supports the content; choose a larger variant only for denser material or a workflow that requires it. Do not copy modal pixel dimensions into product code or create a standard modal from scratch. Inspect the installed component.

### Data, code, and loading

| Component | Use when | Do not use when |
| --- | --- | --- |
| `DataTable` | Structured rows and columns need scanning but not interactive sorting. | The data is better expressed as prose, cards, or a chart. |
| `SortableTable` | Users need to reorder structured data by meaningful columns. | Sorting would be arbitrary or the dataset is too small to benefit. |
| `CodeBlock` | Code, commands, logs, or structured technical text needs preserved formatting. | Ordinary prose or editable code is required. |
| `UILoader` | A bounded interface region is waiting for indeterminate work. | The page structure can be represented with a skeleton. |
| `LatticeLoader` | A branded, prominent indeterminate wait is appropriate. | A compact control or quiet region needs loading feedback. |
| `Ghost` variants | The final component structure is known and a skeleton prevents layout shift. | The wait is brief or the eventual structure is unknown. |

Use loading states only while work is actually pending. Preserve container dimensions so the interface does not jump.

## Control size and alignment

Buttons, dropdown triggers, and single-line text, search, password, and number inputs share one control-size scale. A size describes shared typography and padding, not a component-specific fixed height. Match sizes within a toolbar, filter row, or form group. Inspect the package for exact props; existing size aliases remain compatible.

- Use the same font family, font size, explicit line height, vertical padding, horizontal padding, and 1px border allowance for matching sizes. A borderless visual treatment reserves a transparent border so content geometry stays equal.
- Derive the single-line minimum block size from line height + twice the vertical padding + two borders. Do not set unrelated fixed heights or clip content to force alignment. Controls can grow for larger text or custom content.
- Use the existing 12px dense and 14px primary-app type tiers. Larger control sizes add breathing room rather than promoting ordinary form text into the chat-only 16px tier.
- External persistent labels use matching size-specific text metrics and weight 500. Labels are sentence case; the semibold overline `label-01` treatment does not apply to form labels. Lay out each label/control pair with a consistent `--control-label-gap`; use grid or flex, not inline baseline behavior.
- Align adjacent controls at their block edges and text baselines. In stacked left-aligned controls, their text starts share the same inline inset. Centered action labels remain centered. Leading icons occupy a consistent icon slot plus gap; align text across icon-bearing controls by using the same slot, not by changing padding on individual components.
- Keep icons within the shared line box so they do not silently increase control height. Icon-only actions and embedded number/password actions derive their square target from the same control metrics. Preserve accessible names, focus, disabled states, and native input sizing semantics.
- Use compact sizes for pointer-based dense interfaces. Choose a size or target expansion that meets the layout guide's touch-target requirement on touch interfaces; increasing surrounding whitespace alone does not enlarge a target.

The canonical metric tokens live in `layout/layout.css`. The package owns selectors, props, anatomy, and exact component implementation. Pair size changes with a visual check of adjacent and stacked controls, numeric units and steppers, icons, label baselines, disabled states, and enlarged text.

## Floating field titles

Use the shared floating-title treatment for labeled inputs in filter bars and forms. Dropdowns use the selection-dependent treatment below. An empty inactive field shows its title inside the border in `fg-primary`, using the value text's metrics and regular weight. On input focus, the title moves smoothly into a notch in the top border and reveals the entry hint. A populated inactive field keeps its title floated in `fg-secondary`; active editing or an open dropdown uses `fg-primary`. Placeholder hints remain distinct from the persistent field title.

- Keep the existing control-size height, value baseline, icon slots, and stepper geometry. The floated title must not add a second layout row or increase the field's block size. Reserve room around the control so the title remains readable.
- Match the notch background to the control surface. Use semantic disabled colors and preserve error, read-only, and focus behavior.
- Associate the title with its actual input or trigger. Preserve controlled and uncontrolled values, zero values, form reset, and autofill. Native date/time and other controls with their own empty UI keep the title floated to prevent collisions.
- Apply the same behavior to text, number, password, search, multiline, and dropdown fields. Multiline controls retain their multiline height. Icon-only controls still require an accessible name rather than a floating title.
- Use the named motion tokens for the title transition and remove the animation under reduced motion. Exact API, scale, and implementation are owned by Fractal UI.

## Status pills and metadata tags

Use `Chip` for compact status and metadata labels. Pill/tag labels default to normal font weight (400); use another weight only when explicitly specified. All tones use a filled background and matching text without a border, outline, or simulated stroke. Use the dedicated `--tag-*-bg` / `--tag-*-fg` tokens from the color guide. Status mapping remains fixed; neutral metadata stays grey. Labels use Mirror Sans (`--font-sans`) in sentence case with normal letter spacing, including tags containing identifiers. Inspect the installed package for exact metrics; do not apply Geist Mono or the semibold overline label treatment to pills.

## Container composition

Follow [Container spacing and shared content edges](../layout.md#container-spacing-and-shared-content-edges) when composing sections, content cards, and panes. Major containers default to equal outer padding on all four sides; peers in the same page layer share a padding treatment. Keep heading, toolbar, body, and footer content edges consistent. Overlay surfaces may use a separate treatment; a persistent peer pane does not gain that exception from its name. Use the package's supported composition and styling APIs, and preserve compact controls' internal metrics.

For container partitions around tables or other content, use the layout guide's [divider conditions](../layout.md#divider-conditions). These conditions also govern card sections: full-span primary boundaries, inset secondary grouping, and a shared heading above a genuinely divided body. Do not globally add a bottom border to every `CardHeader`; heading/body separation is conditional. Table cell grids retain the rules below.

For dropdowns, prefer the field label itself as the default placeholder in `fg-tertiary`, at weight 400, instead of “All …”. Keep it inside the field while the default is selected, even when focused or open. Float the label only for a non-default selection. Show a neutral filled (Secondary) close-icon action for a clearable selection; clearing restores the configured default, hides the clear action, and returns focus to the trigger. Preserve the visible text value and an accessible clear-action name. Configure the actual default value explicitly rather than guessing from its label.

Text, search, number, dropdown, and textarea fields use the same `--radius-md` corner radius, including floating-label outlines. Search icons are a compact 16px by default.

## Tables

- Default to one value or concise content unit and one level of hierarchy per data cell. Do not stack a title/value above an ID, caption, helper label, description, or secondary metadata line. Column headers provide labels shared by rows.
- Keep headers and data-cell content on one line; do not wrap. Derive each column's preferred width from its content, capped at a maximum. Individual cells scroll horizontally when their value exceeds the allocated width. Do not substitute inaccessible clipping or ellipsis for access to content.
- Cell scroll viewports fill the cell between its borders, including the space above and below its content. Put cell padding inside the moving content so values clip at the cell walls, not at an invisible inset. Preserve the resting content inset and vertical centering. Pinned identity columns retain a trailing 1px separator, and pinned action columns retain a leading separator, while neighboring columns scroll behind them.
- Put additional independently comparable attributes in separate columns when needed for the task; put supporting detail in the object's detail view or inspector. Do not concatenate all removed metadata into a crowded cell or add columns solely to preserve decorative captions. Keep essential disambiguation, units, and date context with the value in the same text treatment when they are necessary to interpret it.
- A second hierarchy level within a cell requires an explicit user request or a specific, exceptional task need. State that need in the composition decision; available metadata, a component example, or a desire for visual richness is not sufficient justification. Hierarchy between columns does not justify adding hierarchy within cells.
- Left-align headers and cells by default, including numeric columns.
- Keep column headers and body values in the same typography size tier and font family. Column titles always use normal weight (400); distinguish headers through foreground color and surface treatment, not heavier weight or smaller text. Optional leading icons may clarify column meaning; keep the text label and treat the icon as decorative, separate from any sort indicator.
- Vertically center cell contents within each row, including text, status tags, selection controls, and overflow triggers. Different content heights must not make plain text sit above adjacent controls.
- A user may request right alignment, decimal alignment, or another domain convention; that override is allowed.
- Use tabular numerals when vertical numeric scanning matters.
- Sorting must reflect the column's meaning. Status values use an explicit lifecycle rank rather than alphabetical order.
- Do not automatically emphasize a “best” row or cell with bold, blue, or a tinted surface. Emphasis requires a product requirement or meaning present in the source data.
- If emphasis is required, choose the least forceful treatment that communicates that meaning and do not stack multiple treatments by default.
- Status chips already encode status; do not add row emphasis merely because a status is important.
- Tables need a 1px semantic outer border when a boundary is necessary and 1px semantic row/column dividers where they improve tracing.
- Within a content section, align the first and last header/body cells to the section's shared content insets. Full-width row backgrounds and dividers may reach the shell boundary while interior column spacing and row block padding stay compact. Account for wrapper padding so the effective outer inset is applied once. Follow the layout guide for intentional leading selection/icon columns.
- Tables fill the available width by default. Start from capped, content-based column widths; if they fit, distribute the remaining space across data columns according to their intrinsic sizing proportions. Selection and row-action columns stay compact. If the preferred widths already exceed the available space, retain those widths and scroll horizontally instead of stretching or squeezing the columns. The cap constrains preferred content sizing, not the extra space distributed to fill a wider container. Use container-width breakpoints to reduce default caps in narrower regions, not to introduce wrapping. Permit explicit content-only layout and column-specific minimum/maximum widths when the task warrants them; inspect the package for exact sizing APIs.
- Support a sticky first data column for row identity and sticky column headers within a bounded vertical table viewport. Keep any selection column visible alongside the pinned first data column. Use opaque backgrounds and correct intersection layering, and retain enough space to view the other columns.
- Offer an explicit optional row-overflow menu column pinned to the trailing edge. When enabled alongside the sticky first column, the middle columns scroll between them. Keep its header aligned with sticky column headers. Use accessible, row-specific menu triggers; activating a menu must not activate or select the row. Menus must escape the table's clipping region and support keyboard navigation and dismissal. Preserve visible middle-column space when both edges are pinned.
- Both cell-level and table-level scrolling must work with keyboard, trackpad, and touch. Focus only scroll regions that actually overflow; preserve sorting, selection, embedded controls, and visible focus. Never intercept vertical scrolling just to simulate horizontal scrolling.
- Horizontal gestures scroll the cell while it has room in that direction. At either cell edge, continuing the gesture scrolls the enclosing table in the same direction; do not trap scrolling at the cell boundary. Reversing direction lets the cell scroll back through its content.
- Hide horizontal scrollbars inside individual cells, including header cells. Keep the table viewport's scrollbar available; hiding cell scrollbars must not disable cell scrolling or keyboard access.

## Creating a new component

A new shared component is justified only when all are true:

- no existing export or composition covers the behavior;
- the use case is likely to recur across screens or products;
- the component has a stable semantic purpose, not only a distinctive appearance;
- its API can remain smaller and clearer than repeated local implementations.

Required design process:

1. Name the user task and why existing components fail it.
2. Define anatomy, content limits, states, keyboard behavior, focus order, validation, loading, empty, error, disabled, and responsive behavior.
3. Build from semantic color, type, spacing, radius, shadow, and motion tokens in the relevant guides.
4. Use 1px UI borders/dividers. Use the 4px spacing grid.
5. Check light/dark modes, keyboard access, screen-reader semantics, contrast, long content, and localization pressure.
6. Add it to `@mirror-physics/fractal-ui` with stories, types, and tests, then update this selection guide if it introduces a new UX choice.

Off-grid values are forbidden by default. If the user explicitly requires one as a temporary measure, implement it and leave a `TODO` that names the off-grid value and intended token-based repair.

## Modifying an existing shared component

Shared components have many consumers. Prefer additive, backward-compatible changes. Before changing behavior, anatomy, defaults, DOM semantics, class names, or existing prop meaning:

- inspect current consumers and stories;
- state the compatibility risk;
- prefer a new optional prop or composition point when that keeps the API coherent;
- update tests and documentation;
- verify representative downstream usage.

Do not add a variant solely to fix one screen. A product-local composition is safer when the need is not reusable.

## Package access and publishing

`@mirror-physics/fractal-ui` and `@mirror-physics/fractal-icons` use npm trusted publishing through GitHub Actions OIDC. Do not request npm access keys, search `.env` files for publishing credentials, or set `NPM_TOKEN` / `NODE_AUTH_TOKEN` for releases. Do not run `npm publish` locally.

Build and validate the owning package, review the diff, and bump to an unused version. Publish through the package repository's configured GitHub Actions release workflow, then verify the run and registry version before updating consumer dependencies and lockfiles. For `fractal-icons`, follow `PUBLISHING.md`: push a matching `vX.Y.Z` tag or dispatch `publish.yml` with an existing `release_tag`. Inspect the actual `fractal-ui` release workflow before releasing; do not assume it has the same trigger or filename.

The npm trusted publisher must match the GitHub organization, repository, workflow filename, and environment (if used). The publish job uses a GitHub-hosted runner, `permissions: { contents: read, id-token: write }`, Node >=22.14.0, and npm >=11.5.1. If the workflow or trust configuration is missing, configure that integration instead of falling back to a token. Public package installation and local source work do not require publishing credentials.

Local icon prototypes may stay as raw SVGs and app-local components when the user requests review before publishing. Promote and sync approved artwork before its eventual package release.

Reference: [npm trusted publishers](https://docs.npmjs.com/trusted-publishers/).


## Neutral boundary context

Ordinary resting components share the subtle border strength defined in [`../color/color-guide.md`](../color.md). Choose the reference from the two immediately adjacent backgrounds, and reset the border scope at nested boundaries when that pair changes. Do not assign stronger outlines to inputs or inspectors merely because they are interactive. Preserve focus, validation, selection, status, and accessibility-critical treatments. Inspect the installed package for its border-surface scoping support.

## Visual consistency without sameness

Keep component anatomy, states, tokens, and interaction behavior stable. Create variety at the composition level: which components are used, their information hierarchy, grouping, density within supported variants, and the page structure demanded by the content. Do not restyle the same component differently merely to make two outputs look less alike.

## Forbidden outcomes

- Rebuilding an exported Fractal UI component locally without a documented need.
- Inventing package APIs or duplicating volatile dimensions from implementation code.
- Using Carbon, `react-icons`, or an ad hoc SVG in Fractal product UI when a suitable Fractal icon exists.
- Choosing toggle, checkbox, tabs, disclosure, modal, or side panel based on appearance instead of behavior.
- Raw primitive colors in component code when a semantic token exists.
- Raw motion durations or easing curves in evidence or generated code.
- Decorative shadows on resting layout surfaces.
- Off-grid spacing without an explicit user request and a repair `TODO`.

Search fields are the exception to visible persistent field titles. Use the recognizable search icon and placeholder without a floating title. Retain an accessible name through `aria-label` or `aria-labelledby`.

### Button variants

Text and icon-only buttons follow the same [shared variant meanings](../../../../shared/primary-actions.md): Primary is blue filled, Secondary neutral filled, Tertiary outlined, and Ghost has no resting border or fill. Main-action importance does not require the Primary variant. Danger is a separate semantic treatment. Inspect the installed package for exact supported props and states; migrate it before relying on variants it does not yet expose. Keep enabled normal-size text contrast at least 4.5:1. Explicit user-selected themes remain overrides.

### Background-relative hover

Breadcrumb buttons and transparent dropdown triggers must use the hover treatment of their enclosing background. On canvas use `--hover-canvas`, not a barely distinguishable `--bg-surface-1` fill or the stronger sidebar `--nav-hover`. On surface-1 use `--hover-surface`. See the color guide's neutral hover contrast rule; preserve a comparable visible change across surfaces and themes. The runtime dropdown supports scoping `--control-hover-bg` to that surface's hover token.

### Nested actions within hovered rows

The row hover includes secondary actions such as add and pin buttons. On action hover, keep the row highlighted and return only the action background to the enclosing region’s resting surface: `--bg-canvas` in page content, `--nav-surface` in navigation. This reverses the parent hover step rather than adding another darker fill. Use sibling interactive elements inside a shared row wrapper, not nested buttons or links; the secondary action must not trigger row navigation. Preserve disabled and focus states.

### Chat presentation primitives

Use the shared user-message, composer, and tool-call primitives for conversational
surfaces. Hosts own transcript state, safe content rendering, attachments, execution,
permissions, and live announcements; presentation components must not depend on
provider SDKs or product stores. Inspect Fractal UI for current exports and props.

Keep message content at the chat typography tier. Composers support multiline and
IME input, explicit send/stop controls, accessible names, and touch-sized targets.
The host owns safe-area and keyboard viewport layout. Tool details can expand
inline on narrow screens or delegate inspection to the host. Preserve distinct
pending, running, completed, failed, and cancelled outcomes; an empty output does
not imply an unfinished or failed call. Existing products need not migrate to
these primitives merely because the shared versions exist.


## Product charts

Use the installed product line, grouped-bar, and single-series area presets when their encodings fit non-scientific metrics. Load [product visualization guidance](../visualization.md); scientific plots retain their own profile. Inspect package APIs rather than guessing props.
