# React + Tyrell Guide

Use Tyrell web components in React with `tyrell-react` — typed wrappers with React-idiomatic event handling, ref forwarding, and controlled component patterns.

## Setup

### 1. Install packages

```bash
npm install tyrell-components tyrell-react
```

Two packages, two roles:
- **`tyrell-components`** — the web components, CSS, and 1,600+ tree-shakeable icons.
- **`tyrell-react`** — typed React wrappers that render `<ty-*>` elements with React-idiomatic props and event handlers.

### 2. Load Tyrell's web components

You have two options. Pick one — they're mutually exclusive.

#### Option A — Bundler imports (recommended)

Import `tyrell-components` once at your app's entry point. Each component file runs `customElements.define(...)` as a side effect when imported, registering all `<ty-*>` elements:

```tsx
// app/layout.tsx (Next.js) or src/main.tsx (Vite)
import 'tyrell-components/css/tyrell.css'        // structure — no color tokens
import 'tyrell-components/css/tyrell-theme.css'  // colors — auto-contrast, seed-based rebranding
import 'tyrell-components'                       // registers all <ty-*> components
```

For smaller bundles, register only the components you use:

```tsx
import 'tyrell-components/css/tyrell.css'
import 'tyrell-components/css/tyrell-theme.css'
import 'tyrell-components/button'
import 'tyrell-components/input'
import 'tyrell-components/select'
import 'tyrell-components/modal'
```

Available subpaths match the component names — `button`, `input`, `select`, `selected-tags`, `modal`, `popup`, `tooltip`, `tag`, `option`, `icon`, `checkbox`, `textarea`, `copy`, `tabs`, `tab`, `calendar`, `calendar-month`, `calendar-navigation`, `date-picker`.

#### Option B — CDN script tag

Skip the bundler — load Tyrell from a `<script>` tag in your HTML head:

```html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tyrell-components@latest/css/tyrell.css">
<!-- tyrell-theme.css: auto-contrast, seed-based rebranding, themes. See TY_GUIDE.md#quick-start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tyrell-components@latest/css/tyrell-theme.css">
<script type="module" src="https://cdn.jsdelivr.net/npm/tyrell-components@latest/dist/tyrell.js"></script>
```

Or self-host by copying `node_modules/tyrell-components/dist/tyrell.js`, `node_modules/tyrell-components/css/tyrell.css`, and `node_modules/tyrell-components/css/tyrell-theme.css` into your `public/` directory and pointing the tags there.

#### Which should I pick?

| | Bundler imports | CDN script tag |
|--|--|--|
| Component tree-shaking | ✅ Selective subpath imports | ❌ Whole bundle (~all components) |
| Icon registration | ✅ `registerIcons` directly imported | ⚠️ Must use `window.tyIcons.register` (timing-sensitive) |
| Build complexity | Standard import | One-time `<script>` tag in HTML |
| First paint | Same bundle as your app | Separate request, can FOUC |

Bundler imports are the better default for SPAs and SSR apps (Next.js, Remix, Vite). CDN is fine for prototyping or when you don't control the bundler.

### 3. Import and use

```tsx
import { TyButton, TyInput, TySelect } from 'tyrell-react'

function App() {
  const [name, setName] = useState('')

  return (
    <div className="ty-canvas p-8">
      <TyInput
        label="Name"
        value={name}
        onChange={(e) => setName(e.detail.value)}
      />
      <TyButton flavor="primary" onClick={() => alert(name)}>
        Submit
      </TyButton>
    </div>
  )
}
```

## Import Styles

Two naming conventions:

```tsx
// Tyrell-prefixed (explicit)
import { TyButton, TyInput, TySelect } from 'tyrell-react'

// Short names (clean)
import { Button, Input, Select } from 'tyrell-react'
```

## Event Handling

Always access values through `event.detail.value`:

```tsx
// Correct
<TyInput onChange={(e) => setValue(e.detail.value)} />

// Wrong — event.value does not exist
<TyInput onChange={(e) => setValue(e.value)} />
```

### Input Components

- `onChange` fires on every keystroke (mapped from `input` event)
- `onChangeCommit` fires on blur (mapped from `change` event)

```tsx
<TyInput
  value={query}
  onChange={(e) => setQuery(e.detail.value)}
  onChangeCommit={(e) => search(e.detail.value)}
/>
```

Event detail structure:
```ts
interface TyInputEventDetail {
  value: any
  formattedValue: string
  rawValue: string
  originalEvent: Event
}
```

### Selection Components

```tsx
<TySelect onChange={(e) => setCountry(e.detail.value)}>
  <TyOption value="us">United States</TyOption>
  <TyOption value="de">Germany</TyOption>
</TySelect>
```

`TySelect` is THE select control.
Single select by default — `e.detail.value` is the scalar value. Add `multiple`
for multi-select (`e.detail.value` becomes an array; `e.detail.values` is always
the array form):

```tsx
<TySelect multiple value={tags} onChange={(e) => setTags(e.detail.values)}>
  <TyOption value="react">React</TyOption>
  <TyOption value="vue">Vue</TyOption>
</TySelect>
```

### Checkbox

```tsx
<TyCheckbox
  checked={agreed}
  onChange={(e) => setAgreed(e.detail.value)}
/>
```

### Modal Events

```tsx
<TyModal
  open={isOpen}
  onOpen={() => console.log('opened')}
  onClose={(e) => {
    setIsOpen(false)
    console.log('reason:', e.detail.reason)
  }}
>
  <div className="p-6 ty-elevated rounded-lg">
    Modal content
  </div>
</TyModal>
```

When React controls the `open` state, the modal can still close itself via backdrop click or ESC — firing `onClose` — but if you haven't updated your state in the handler, the next render reopens it. For full React control, disable those close paths explicitly:

```tsx
<TyModal
  open={isOpen}
  preventOutsideClick
  preventEscape
  onClose={() => setIsOpen(false)}
>
  ...
</TyModal>
```

Now only programmatic state changes (`setIsOpen(false)`) close the modal — note a fully guarded modal hides the built-in ✕, so render your own close button inside (WCAG 2.1.2). The older `closeOnOutsideClick={false}` / `closeOnEscape={false}` props are deprecated but still work.

### Tag Events

```tsx
<TyTag
  value="react"
  dismissible
  onTagClick={(e) => console.log('clicked', e.detail.value)}
  onTagDismiss={(e) => removeTag(e.detail.value)}
>
  React
</TyTag>
```

## Controlled Components

```tsx
function ContactForm() {
  const [form, setForm] = useState({
    name: '',
    email: '',
    country: '',
    message: ''
  })

  const update = (field: string) => (e: any) =>
    setForm(prev => ({ ...prev, [field]: e.detail.value }))

  return (
    <form onSubmit={handleSubmit}>
      <TyInput label="Name" value={form.name} onChange={update('name')} required />
      <TyInput label="Email" type="email" value={form.email} onChange={update('email')} required />
      <TySelect label="Country" value={form.country} onChange={update('country')}>
        <TyOption value="us">United States</TyOption>
        <TyOption value="de">Germany</TyOption>
      </TySelect>
      <TyTextarea label="Message" value={form.message} onChange={update('message')} rows={4} />
      <TyButton type="submit" flavor="primary">Send</TyButton>
    </form>
  )
}
```

## Multi-select — `<TySelect multiple>`

> With `multiple`, options are `<TyOption>` children (not `<TyTag>`), and selected
> chips render out-of-band via `<TySelectedOptions>` wherever you want them.

```tsx
const [selected, setSelected] = useState<string[]>([])

<TySelect
  multiple
  id="tags"
  value={selected}
  onChange={(e) => setSelected(e.detail.values)}
  label="Tags"
  placeholder="Select tags..."
>
  <TyOption value="react">React</TyOption>
  <TyOption value="vue">Vue</TyOption>
  <TyOption value="angular">Angular</TyOption>
</TySelect>

{/* dismissible chips — anywhere in the layout */}
<TySelectedOptions htmlFor="tags" />
```

`TyOption` supports rich HTML children; give it a `label` prop for clean display
text in summaries/chips, and `data-*` attributes to feed `TySelectedOptions`
`<template>` chips.

## Select with Data

Map your data to `<TyOption>` children:

```tsx
<TySelect value={country} onChange={(e) => setCountry(e.detail.value)}>
  {countries.map(({ value, text }) => (
    <TyOption key={value} value={value}>{text}</TyOption>
  ))}
</TySelect>
```

`value` is the only selection input; `<TyOption selected>` selects nothing, except with `externalSelection`.

## App-held selection — `externalSelection`

For hundreds of picks or a remote list, the app keeps the selection. Mark the picked options `selected`; a pick fires `onChange` with `{ value, selected }` (the option and its requested state) and changes nothing until you re-render. The select holds no `value`, submits nothing and doesn't enforce `required`, so show your own summary. Usually paired with `externalSearch`.

```tsx
<TySelect multiple externalSelection
  onChange={(e) => toggle(e.detail.value, e.detail.selected)}>
  {rows.map((r) => (
    <TyOption key={r.id} value={r.id} selected={picked.has(r.id)}>{r.name}</TyOption>
  ))}
</TySelect>
```

## Refs and Imperative API

### Modal

```tsx
const modalRef = useRef<TyModalRef>(null)

<TyButton onClick={() => modalRef.current?.show()}>Open Modal</TyButton>

<TyModal ref={modalRef} onClose={() => console.log('closed')}>
  <div className="p-6 ty-elevated rounded-lg">
    <p>Modal content</p>
    <TyButton onClick={() => modalRef.current?.hide()}>Close</TyButton>
  </div>
</TyModal>
```

### Popup

```tsx
const popupRef = useRef<TyPopupElement>(null)

// The popup's parent is its trigger: a click, Enter or Space toggles it.
// type="button" keeps the trigger from submitting a form it sits in.
<TyButton type="button">
  Share
  <TyPopup ref={popupRef}>
    <div className="p-4 ty-floating rounded-lg">
      Popup content
      <TyButton onClick={() => popupRef.current?.closePopup()}>Done</TyButton>
    </div>
  </TyPopup>
</TyButton>
```

### Scroll Container

```tsx
const scrollRef = useRef<TyScrollContainerRef>(null)

<TyScrollContainer ref={scrollRef} maxHeight="300px" shadow>
  {/* Long content */}
</TyScrollContainer>

<TyButton onClick={() => scrollRef.current?.scrollToTop()}>Back to top</TyButton>
```

## Calendar with Custom Rendering

```tsx
<TyCalendar
  value="2026-03-24"
  onChange={(e) => setDate(e.detail.value)}
  dayContentFn={(ctx) => {
    const el = document.createElement('div')
    el.textContent = ctx.day
    if (ctx.day === 25) {
      el.style.fontWeight = 'bold'
      el.style.color = 'var(--ty-color-primary)'
    }
    return el
  }}
  customCSS=".day-cell { border-radius: 8px; }"
/>
```

## Custom Styling via CSS Variables

All components accept a typed `style` prop that supports CSS custom properties for per-instance color overrides. These cascade into the shadow DOM so they work despite encapsulation.

### Input components

`TyInput`, `TyTextarea`, and `TySelect` all share the same tokens:

| Token | Purpose |
|-------|---------|
| `--input-bg` | Background |
| `--input-color` | Text color |
| `--input-border` | Border (default) |
| `--input-border-hover` | Border on hover |
| `--input-border-focus` | Border when focused |
| `--input-shadow-focus` | Focus ring (3px outer glow) |
| `--input-placeholder` | Placeholder text color |
| `--input-disabled-bg` | Disabled background |
| `--input-disabled-border` | Disabled border |
| `--input-disabled-color` | Disabled text |

```tsx
<TyInput
  label="Custom input"
  style={{
    '--input-bg': '#fdf4ff',
    '--input-border': '#c084fc',
    '--input-color': '#7e22ce',
    '--input-border-focus': '#a855f7',
    '--input-shadow-focus': 'rgba(168, 85, 247, 0.2)',
  }}
/>

<TySelect style={{ '--input-bg': '#fdf4ff', '--input-border': '#c084fc' }}>
  <TyOption value="a">Option A</TyOption>
</TySelect>
```

You can also scope overrides to a container — all input components inside inherit:

```tsx
<div style={{ '--input-border': '#16a34a', '--input-border-focus': '#15803d' } as any}>
  <TyInput label="Name" value={name} onChange={...} />
  <TySelect label="Role" value={role} onChange={...}>...</TySelect>
</div>
```

### Button

```tsx
<TyButton
  appearance="outlined"
  style={{
    '--ty-button-color': '#8b5cf6',
    '--ty-button-border': '#8b5cf6',
    '--ty-button-bg-hover': '#ede9fe',
  }}
>
  Custom button
</TyButton>
```

Available button tokens: `--ty-button-bg`, `--ty-button-bg-hover`, `--ty-button-color`, `--ty-button-border`.

### Tag

```tsx
<TyTag style={{ '--tag-color': '#e53e3e', '--tag-border-color': '#e53e3e' }}>
  12 / 12
</TyTag>
```

Available tag tokens: `--tag-bg`, `--tag-color`, `--tag-border-color`. For stylesheet-level overrides use `::part(container)`:

```css
ty-tag.my-tag::part(container) {
  color: #e53e3e;
  border-color: #e53e3e;
}
```

## Surface Levels

Surfaces are CSS classes — apply them via `className` on any HTML element. No React component required.

Five levels, from lowest to highest elevation:

| Class | Typical use |
|-------|------------|
| `ty-canvas` | App background, outermost wrapper |
| `ty-content` | Main content areas, page bodies |
| `ty-elevated` | Cards, panels, sidebars |
| `ty-floating` | Modals, drawers, sticky headers |
| `ty-input` | Form controls (handled automatically by form components) |

```tsx
// App shell
<div className="ty-canvas min-h-screen p-8">

  {/* Card */}
  <div className="ty-elevated rounded-xl p-6 border ty-border">
    <h2 className="ty-text++ text-xl font-bold">Card title</h2>
    <p className="ty-text-">Card body</p>
  </div>

  {/* Modal content panel */}
  <TyModal open={isOpen} onClose={() => setIsOpen(false)}>
    <div className="ty-floating p-6 rounded-xl max-w-md">
      Modal content
    </div>
  </TyModal>

</div>
```

Surfaces handle background color and text color automatically via the Tyrell design system. Pair with Tailwind for spacing, layout, and typography — but use only Tyrell classes for colors:

```tsx
// Correct: Tyrell for color, Tailwind for everything else
<div className="ty-elevated p-6 rounded-lg flex items-center gap-4">

// Wrong: mixing color systems
<div className="bg-white p-6 rounded-lg">
```

## Text Classes

Five emphasis levels — no color, just weight:

```tsx
<h1 className="ty-text++ text-3xl">Page title</h1>
<h2 className="ty-text+ text-xl">Section heading</h2>
<p className="ty-text">Body text</p>
<span className="ty-text-">Secondary info</span>
<small className="ty-text--">Fine print</small>
```

Semantic text colors follow the same five-variant pattern:

```tsx
<p className="ty-text-primary">Primary</p>
<p className="ty-text-primary+">Stronger primary</p>
<p className="ty-text-primary-">Softer primary</p>
```

Available colors: `primary`, `success`, `danger`, `warning`, `neutral`.

## Border Classes

Five emphasis levels:

```tsx
<div className="border ty-border++">Strong border</div>
<div className="border ty-border+">Heavy border</div>
<div className="border ty-border">Normal border</div>
<div className="border ty-border-">Soft border</div>
<div className="border ty-border--">Minimal border</div>
```

Semantic borders:

```tsx
<div className="border ty-border-primary">Primary border</div>
<div className="border ty-border-danger">Danger border</div>
<div className="border ty-border-success">Success border</div>
```

Available colors: `primary`, `success`, `danger`, `warning`, `neutral`. 

## Background Colors

Use `ty-bg-*` for small UI elements — badges, alerts, status indicators. Not for cards or layout areas (use surfaces for those).

```tsx
{/* Status badge */}
<span className="ty-bg-success- ty-text-success rounded-full px-2 py-0.5 text-xs">Active</span>

{/* Alert banner */}
<div className="ty-bg-danger- ty-text-danger rounded-lg p-4">
  Something went wrong
</div>
```

Three variants per color — stronger (`+`), base, softer (`-`):

```tsx
<div className="ty-bg-primary+">Stronger</div>
<div className="ty-bg-primary">Base</div>
<div className="ty-bg-primary-">Softer</div>
```

Available colors: `primary`, `success`, `danger`, `warning`, `neutral`.

## Dark Mode

Tyrell responds to a `dark` class on `<html>`. All color variables switch automatically.

```tsx
// Simple toggle hook
function useTheme() {
  const [dark, setDark] = useState(
    () => localStorage.getItem('theme') === 'dark'
      || window.matchMedia('(prefers-color-scheme: dark)').matches
  )

  useEffect(() => {
    document.documentElement.classList.toggle('dark', dark)
    localStorage.setItem('theme', dark ? 'dark' : 'light')
  }, [dark])

  return { dark, toggleTheme: () => setDark(d => !d) }
}
```

Restore preference before first render to avoid flash (add to your HTML `<head>`):

```html
<script>
  const theme = localStorage.getItem('theme')
    || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
  if (theme === 'dark') document.documentElement.classList.add('dark')
</script>
```

### Next.js

In Next.js, add the script to your root layout and mark it `suppressHydrationWarning` on `<html>`:

```tsx
// app/layout.tsx
export default function RootLayout({ children }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <script dangerouslySetInnerHTML={{ __html: `
          const t = localStorage.getItem('theme')
            || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
          if (t === 'dark') document.documentElement.classList.add('dark')
        `}} />
      </head>
      <body className="ty-canvas">{children}</body>
    </html>
  )
}
```

## Global Color Customization

Override the whole palette at `:root` level to rebrand Tyrell:

```css
:root {
  --ty-color-primary-strong: #0034c7;
  --ty-color-primary-bold:   #1c40a8;
  --ty-color-primary:        #4367cd;
  --ty-color-primary-soft:   #60a5fa;
  --ty-color-primary-faint:  #93c5fd;
  --ty-bg-primary-bold:      #bfdbfe;
  --ty-bg-primary:           #dbeafe;
  --ty-bg-primary-soft:      #eff6ff;
}

:root.dark {
  --ty-color-primary-strong: #93c5fd;
  --ty-color-primary:        #3b82f6;
  --ty-bg-primary:           #172554;
}
```

Token pattern: `--ty-color-{name}-{strong|bold|soft|faint}`, `--ty-bg-{name}-{bold|soft}`, `--ty-border-{name}`.

This retunes every component that uses that color. To override a single instance only, use the per-component CSS variables in the section above.

## Numeric Input Types

```tsx
// Currency
<TyInput type="currency" currency="EUR" locale="de-DE" value={price}
  onChange={(e) => setPrice(e.detail.value)} />

// Percentage
<TyInput type="percent" precision={1} value={rate}
  onChange={(e) => setRate(e.detail.value)} />

// Compact numbers (1K, 1M)
<TyInput type="compact" value={count}
  onChange={(e) => setCount(e.detail.value)} />
```

## Tabs and Wizard

`TyTabs` dispatches its change event with detail `{ activeId, activeIndex, previousId, previousIndex }` — read `event.detail.activeId` (not `value`):

```tsx
import { TyTabs, TyTab, type TabChangeDetail } from 'tyrell-react'

const [activeTab, setActiveTab] = useState('overview')

<TyTabs
  active={activeTab}
  onChange={(e: CustomEvent<TabChangeDetail>) => setActiveTab(e.detail.activeId)}
>
  <TyTab id="overview" label="Overview">
    <p>Overview content</p>
  </TyTab>
  <TyTab id="settings" label="Settings">
    <p>Settings content</p>
  </TyTab>
</TyTabs>
```

A `lazy` tab with no content calls `onTabLoad` when it's shown (never the tab
shown first, the `active` one: render its content up front). It spins until children arrive;
if loading fails, call `loadFailed()` on the element for an error and Retry:

```tsx
const ref = useRef<HTMLElement & { loadFailed(): void }>(null);

<TyTab ref={ref} id="reports" label="Reports" lazy
  onTabLoad={() => fetchReports().then(setReports, () => ref.current?.loadFailed())}>
  {reports && <ReportList reports={reports} />}
</TyTab>
```

Tabs scroll by default — each button has a `min-width: 72px` floor
(`--ty-tab-min-width`) and the bar grows a `…` jump menu once they no longer fit. Pass `fixed` to divide the bar
equally between them instead: no floor, no overflow, no jump menu, labels
ellipsize if squeezed. It's a presence boolean, so `fixed={false}` renders no
attribute at all. Use it for **2–5** tabs — past that the shares are too narrow
to read, and the scrollable default with its `…` menu is the right tool:

```tsx
<TyTabs fixed height="300px" active={activeTab} onChange={…}>
```

```tsx
<TyWizard active={step} completed={completedSteps.join(',')}>
  <TyStep id="info" label="Information">Step 1 content</TyStep>
  <TyStep id="review" label="Review">Step 2 content</TyStep>
  <TyStep id="confirm" label="Confirm">Step 3 content</TyStep>
</TyWizard>
```

## Reorderable lists (ty-sortable)

`TySortable` never moves its children. A drop (or a keyboard move) calls `onChange` (`ty-sortable-change`) on the destination list, and the list holds the result on screen until you re-render the items in the new order. Give each item a stable `key` and a `data-key` (or `id`):

```tsx
import { useState } from 'react'
import { TySortable, TyIcon, type TySortableChangeDetail } from 'tyrell-react'

function Board() {
  const [cols, setCols] = useState<Record<string, string[]>>({ todo: ['a', 'b'], done: ['c'] })
  const [saving, setSaving] = useState(false)

  const onChange = async (e: CustomEvent<TySortableChangeDetail>) => {
    const { value } = e.detail
    setSaving(true)
    try {
      await save(value)
      setCols((c) => ({ ...c, ...value.order }))  // new key order per touched list
    } finally {
      setSaving(false)                           // order unchanged: the item snaps back
    }
  }

  const column = (id: string, label: string) => (
    <TySortable id={id} group="board" label={label} aria-busy={saving || undefined} onChange={onChange}>
      {cols[id].map((k) => (
        <div key={k} data-key={k}>
          <button type="button" data-handle aria-label={`Move ${k}`}>
            <TyIcon name="grip-vertical" />
          </button>
          {k}
        </div>
      ))}
    </TySortable>
  )

  return <>{column('todo', 'To do')}{column('done', 'Done')}</>
}
```

- `value` is `{ key, group, source, from, to, order }`. `order` is the new key order of each list the move touched, by list id. For fractional ranking, save a rank between `value.to.prev` and `value.to.next` instead.
- `aria-busy` while saving makes a refused save snap back as soon as it clears. Without it, call `settle('rejected')` on the element (`e.currentTarget`, read before the first `await`), or `e.preventDefault()` to reject at once. To update optimistically, call `setCols` before saving.
- On touch, a `data-handle` drags at once and leaves the rest of the row to scroll; give it a 44px target. Without a handle the whole item drags after a 250 ms press.
- `onStart`, `onCancel` and `onSettle` map the other events. `canDrop` and `labels` are set as properties; the ref's `move('a', { to: 'done', index: 0 })` moves without a pointer. Full prop list: [tyrell-react README](../../packages/react/README.md#sortable-lists).

## Icons

Register once, from the same client-side entry that imports `tyrell-components` (in Next.js, a `'use client'` module):

```js
import { registerIcons } from 'tyrell-components/icons/registry'
import { check, chevronDown } from 'tyrell-components/icons/lucide'

registerIcons({ check, 'action-down': chevronDown })  // the key is the name
```

```tsx
<TyIcon name="check" size="sm" />
<TyIcon name="action-down" />
```

On the CDN setup, register with `window.tyIcons.register` instead: `registerIcons` from npm would write to a second copy of the registry that the CDN components never read.

Sets, tree-shaking, custom SVGs and troubleshooting: [ICONS_GUIDE.md](../ICONS_GUIDE.md#in-javascript).

## Slots

Use `slot="start"` and `slot="end"` for icons inside buttons, inputs, and tags. The component handles spacing automatically.

```tsx
{/* Button with start icon */}
<TyButton flavor="primary">
  <TyIcon slot="start" name="save" size="sm" />
  Save
</TyButton>

{/* Button with end icon */}
<TyButton flavor="neutral">
  Next
  <TyIcon slot="end" name="chevron-right" size="sm" />
</TyButton>

{/* Input with icon slots */}
<TyInput type="currency" currency="EUR" label="Price">
  <TyIcon slot="start" name="euro" />
</TyInput>

<TyInput type="email" label="Email">
  <TyIcon slot="start" name="mail" size="sm" />
  <TyIcon slot="end" name="check" size="sm" />
</TyInput>

{/* Tag with icon */}
<TyTag flavor="primary" dismissible>
  <TyIcon slot="start" name="star" size="sm" />
  Featured
</TyTag>

{/* Rich tab labels via slot="label-{id}" */}
<TyTabs height="400px">
  <span slot="label-settings" className="flex items-center gap-2">
    <TyIcon name="settings" size="sm" />
    Settings
  </span>
  <TyTab id="settings" label="Settings">Content</TyTab>
</TyTabs>
```

## Form Integration

Tyrell components participate in HTML forms via `ElementInternals`:

```tsx
<form onSubmit={(e) => {
  e.preventDefault()
  const data = new FormData(e.currentTarget)
  console.log(Object.fromEntries(data.entries()))
}}>
  <TyInput name="email" type="email" required label="Email" />
  <TySelect name="role" label="Role">
    <TyOption value="admin">Admin</TyOption>
    <TyOption value="user">User</TyOption>
  </TySelect>
  <label><TyCheckbox name="agree" required /> I agree to terms</label>
  <TyButton type="submit" flavor="primary">Submit</TyButton>
</form>
```

The browser validates before `submit` fires, so `onSubmit` only runs when every field passes. Failing fields show their message under the field; see [TY_GUIDE → Forms and validation](../TY_GUIDE.md#forms-and-validation).

### Validation and form props

| Component | Props |
|-----------|-------|
| `TyInput` | `required`, `pattern`, `minLength`, `maxLength`, `min`, `max`, `tooShortMessage`, `tooLongMessage`, `error` |
| `TyTextarea` | `required`, `minLength`, `maxLength`, `tooShortMessage`, `tooLongMessage`, `error`. Passed as the `minlength`, `maxlength`, `too-short-message` and `too-long-message` attributes, same as `TyInput` |
| `TySelect` | `required`, `error?: string` (message under the field; `''` or leaving it out clears it) |
| `TyDatePicker` | `required`, `error?: string`, `native` (submit `YYYY-MM-DD` / `YYYY-MM-DDTHH:mm` like `<input type="date">` instead of a UTC instant). `value` takes any string the element reads, or epoch milliseconds |
| `TyCalendar` | `required`, `min`, `max`, `name`. No error line: the browser shows its bubble on the day grid |
| `TyButton` | `type`, `name`, `value`, `form` (id of the form to submit or reset when the button sits outside it), `loading`, `disabled` |

`error` is yours: validation never overwrites or removes it, so set it to `''` to let the field's own messages show again.

`TyButton` submits through `form.requestSubmit()`, so validation runs and `onSubmit` gets the browser's real submit event. `onClick` runs first, and `e.preventDefault()` there stops the submit:

```tsx
<TyButton type="submit" onClick={(e) => { if (!confirm('Send?')) e.preventDefault() }}>
  Send
</TyButton>
```

To show a spinner while saving, set `loading` from the click handler: that press still submits, and later presses are blocked until `loading` is cleared. A disabled or loading button fires no `onClick`.

### File uploads

`TyFileUpload` is uncontrolled — it owns the `File[]`. Read it from `event.detail.files` in `onChange`, or pull it off the form via `FormData` on submit:

```tsx
import { TyFileUpload } from 'tyrell-react'

function UploadForm() {
  return (
    <form
      encType="multipart/form-data"
      onSubmit={async (e) => {
        e.preventDefault()
        const fd = new FormData(e.currentTarget)
        await fetch('/api/upload', { method: 'POST', body: fd })
      }}
    >
      <TyFileUpload
        name="docs"
        label="Attachments"
        multiple
        accept=".pdf,.docx"
        onChange={(e) => console.log(e.detail.files)}
      />
      <TyButton type="submit" flavor="primary">Upload</TyButton>
    </form>
  )
}
```

The `change` event fires on browse, drop, and remove (including the empty array when the last file is removed). For per-file upload progress, drive an `XMLHttpRequest.upload.onprogress` from your own state — the component is a picker, not an uploader.

## Next.js Integration

### App Router Setup

```tsx
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tyrell-components@latest/css/tyrell.css" />
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tyrell-components@latest/css/tyrell-theme.css" />
        <script type="module" src="https://cdn.jsdelivr.net/npm/tyrell-components@latest/dist/tyrell.js" />
      </head>
      <body className="ty-canvas">{children}</body>
    </html>
  )
}
```

### Client Components

Tyrell components require the browser — use `'use client'` directive:

```tsx
'use client'

import { useState } from 'react'
import { TyInput, TyButton } from 'tyrell-react'

export default function SearchForm() {
  const [query, setQuery] = useState('')
  return (
    <div className="flex gap-2">
      <TyInput value={query} onChange={(e) => setQuery(e.detail.value)} placeholder="Search..." />
      <TyButton flavor="primary" onClick={() => search(query)}>Search</TyButton>
    </div>
  )
}
```

### Wait for Components

If you see FOUC (flash of unstyled content), gate rendering until Tyrell is loaded:

```tsx
'use client'
import { useState, useEffect } from 'react'

export function TyLoader({ children }: { children: React.ReactNode }) {
  const [loaded, setLoaded] = useState(false)

  useEffect(() => {
    const check = () => {
      if (window.customElements?.get('ty-button')) {
        setLoaded(true)
      } else {
        setTimeout(check, 50)
      }
    }
    check()
  }, [])

  if (!loaded) return null
  return <>{children}</>
}
```

## Component Reference

| Component | Value Prop | Event | Ref Methods |
|-----------|-----------|-------|-------------|
| `TyButton` | -- | `onClick` | -- |
| `TyInput` | `value` | `onChange` / `onChangeCommit` | -- |
| `TyTextarea` | `value` | `onChange` / `onChangeCommit` | -- |
| `TyCheckbox` | `checked` | `onChange` | -- |
| `TySelect` | `value` (string, or array when `multiple`) | `onChange` / `onSearch` / `onOpen` / `onClose` | -- |
| `TySelectedOptions` | `htmlFor` | -- | -- |
| `TyDatePicker` | `value` (ISO string or epoch ms; `native` for `YYYY-MM-DD`) | `onChange` / `onOpen` / `onClose` | -- |
| `TyCalendar` | `value` (ISO) | `onChange` / `onNavigate` | -- |
| `TyTabs` | `active` | `onChange` | -- |
| `TyModal` | `open` | `onOpen` / `onClose` | `show()` / `hide()` |
| `TyPopup` | `manual` | -- | `openPopup()` / `closePopup()` / `togglePopup()` |
| `TyTag` | `value` | `onTagClick` / `onTagDismiss` | -- |
| `TyIcon` | `name` | -- | -- |
| `TyCopy` | `value` | -- | -- |
| `TyFileUpload` | -- (uncontrolled, read `files` from event) | `onChange` | -- |
| `TyTooltip` | -- | -- | -- |
| `TyScrollContainer` | -- | -- | `scrollToTop()` / `scrollToBottom()` / `updateShadows()` |
| `TyWizard` | `active` | -- | -- |
| `TySortable` | -- (render children in `detail.value.order`) | `onChange` / `onStart` / `onCancel` / `onSettle` | `move()` / `settle()` |
