# JavaScript + Tyrell Guide

Use Tyrell web components from vanilla JavaScript and any bundler. This guide covers distribution, the side-effects model, subpath imports, icon tree-shaking, code splitting, and the SSR boundary — the substrate every framework integration sits on.

For framework-specific patterns, see [REACT_TY_GUIDE.md](./REACT_TY_GUIDE.md), [VUE_TY_GUIDE.md](./VUE_TY_GUIDE.md), and [SVELTE_TY_GUIDE.md](./SVELTE_TY_GUIDE.md).

## Two distribution channels

Tyrell ships through two channels — pick one based on your build setup, not both at once.

### CDN — zero build

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

The CDN bundle (`dist/tyrell.js`) registers every component and exposes the icon registry on `window.tyIcons`. Use this for HTMX, server-rendered apps, prototypes, multi-app domains where browser cache wins, or strict no-bundler workflows.

### NPM — tree-shakeable

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

```js
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 everything
```

Use this when you have a bundler (Vite, Webpack, Rollup, esbuild, Parcel, Bun). Subpath imports let you ship only the components you use.

## How registration works

Each component file ends with the same pattern:

```ts
// src/components/button.ts
export class TyButton extends TyComponent { ... }

if (!customElements.get("ty-button")) {
  customElements.define("ty-button", TyButton);
}
```

`customElements.define(...)` is a **side effect** — calling it makes `<ty-button>` work in the DOM. Importing the file triggers that side effect; once registered, the component class is rarely referenced from your code (you write `<ty-button>` in HTML or JSX, not `new TyButton()`).

This matters because modern bundlers eliminate "unused" code aggressively. Tyrell's `package.json` declares the side-effectful files explicitly:

```json
"sideEffects": [
  "./lib/index.js",
  "./lib/components/**/*.js",
  "./dist/*.js"
]
```

Translation: "These files do real work just by being imported — keep them in the bundle even if no exported symbols are referenced." Everything else (utils, types, icon data) is pure and freely tree-shaken.

## Subpath imports

Import only the components you use:

```js
import 'tyrell-components/button'
import 'tyrell-components/input'
import 'tyrell-components/dropdown'
import 'tyrell-components/option'      // dropdown children
import 'tyrell-components/modal'
```

Available subpaths (each registers exactly one custom element):

```
button         input          textarea       checkbox
dropdown       option         multiselect    tag
modal          popup          tooltip
calendar       calendar-month calendar-navigation  date-picker
tabs           tab            wizard
icon           copy           file-upload    sortable
```

Subpath imports compose with `import('...')` for code splitting:

```js
// Calendar/date-picker is the heaviest component — defer until needed
async function openDatePicker() {
  await import('tyrell-components/date-picker')
  document.getElementById('picker').showModal()
}
```

Webpack, Rollup, Vite, esbuild, and Parcel all honor subpath exports. Bun and Deno also work via the standard `exports` field.

## CSS distribution

Two files, both required: `css/tyrell.css` (structure — spacing, typography, shadows, component CSS; zero color tokens) and `css/tyrell-theme.css` (every color, via an OKLCH engine — auto-contrast, seed-based rebranding, themes). Load `tyrell-theme.css` after `tyrell.css`. Don't want the theme engine? Swap it for `css/tyrell-colors-static.css` — a plain hardcoded hex fallback, no theming API. Two consumption modes — pick whichever fits your build:

```js
// Bundler picks it up (Vite, Webpack, Next.js, etc.)
import 'tyrell-components/css/tyrell.css'
import 'tyrell-components/css/tyrell-theme.css'
```

```html
<!-- Or load directly -->
<link rel="stylesheet" href="/node_modules/tyrell-components/css/tyrell.css">
<link rel="stylesheet" href="/node_modules/tyrell-components/css/tyrell-theme.css">
```

Neither file is split per-component. Both are small enough that splitting would cost more in HTTP overhead than it saves, and the design tokens (colors, surfaces, text classes) need to be globally available regardless of which components are loaded.

## Icons

`<ty-icon name="…">` is a runtime lookup, so the bundler can't see which icons you use. Import them by name and register them; everything you don't import is dropped.

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

Avoid `import * as lucide` + `registerIcons(lucide)`: it ships the whole set. On the CDN build, use `window.tyIcons.register`.

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

## Vanilla JS usage

Once components are registered, write plain HTML and listen for events:

```html
<ty-input id="email" type="email" label="Email"></ty-input>
<ty-button id="submit" flavor="primary">Submit</ty-button>

<script>
  const email = document.getElementById('email')
  const submit = document.getElementById('submit')

  email.addEventListener('change', (e) => {
    console.log('email:', e.detail.value)
  })

  submit.addEventListener('click', () => {
    if (email.value) {
      // submit form
    }
  })
</script>
```

Three things to remember:

1. **Event payload lives on `event.detail`**, not `event` directly. Access values via `event.detail.value`.
2. **Properties vs attributes** — set primitives via attributes, set complex values (arrays, objects, functions) via JS properties:
   ```js
   el.setAttribute('label', 'Email')         // string attribute
   el.disabled = true                         // boolean property
   el.value = ['a', 'b', 'c']                 // array property (multiselect)
   ```
3. **Wait for definition before scripting** if you call methods immediately:
   ```js
   await customElements.whenDefined('ty-modal')
   document.querySelector('ty-modal').show()
   ```

## Reorderable lists (ty-sortable)

`ty-sortable` never moves its children. A drop (or a keyboard move) fires `ty-sortable-change` on the destination list, and the list holds the result on screen until your code puts the items in the new order. Key each item with `data-key` (or `id`):

```html
<ty-sortable id="todo" group="board" label="To do">
  <div data-key="a">
    <button type="button" data-handle aria-label="Move Design review">
      <ty-icon name="grip-vertical"></ty-icon>
    </button>
    Design review
  </div>
</ty-sortable>
<ty-sortable id="done" group="board" label="Done"></ty-sortable>

<script>
  document.addEventListener('ty-sortable-change', async (e) => {
    const { value, fromContainer, toContainer } = e.detail
    const lists = [fromContainer, toContainer]
    lists.forEach((l) => l.setAttribute('aria-busy', 'true'))
    try {
      await save(value)
      // value.order: the new key order of each touched list, by list id
      for (const [id, keys] of Object.entries(value.order)) {
        const list = document.getElementById(id)
        list.replaceChildren(...keys.map((k) => document.querySelector(`[data-key="${k}"]`)))
      }
    } finally {
      lists.forEach((l) => l.removeAttribute('aria-busy'))  // order unchanged: the item snaps back
    }
  })
</script>
```

- `value` is `{ key, group, source, from, to, order }`; `from` / `to` are `{ list, index, prev, next }`. For fractional ranking, save a rank between `value.to.prev` and `value.to.next` instead of the whole order.
- `aria-busy="true"` while saving makes a refused save snap back as soon as it is removed. Without it, call `toContainer.settle('rejected')`, or `e.preventDefault()` to reject at once. With no busy signal and no render, the hold ends after `hold-timeout` (5000 ms).
- 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.
- `list.move('a', { to: 'done', index: 0 })` moves without a pointer and resolves `'accepted'`, `'rejected'`, `'reconciled'` or `'unknown'`. Full API: [TY_GUIDE.md](../TY_GUIDE.md#ty-sortable).

## Bundler notes

### Vite

Works out of the box. Subpath imports, CSS imports, and `import()` splits all behave correctly:

```js
// vite.config.js — no special config required
export default {
  // ...
}
```

For Vue 3 inside Vite, see [VUE_TY_GUIDE.md](./VUE_TY_GUIDE.md).

### Webpack 5

Honors `sideEffects` and subpath exports. If you've manually overridden `sideEffects: false` for the project, you need to allow Tyrell's modules:

```js
// webpack.config.js
module.exports = {
  module: {
    rules: [{
      test: /\.js$/,
      // do NOT mark tyrell-components as side-effect-free
      sideEffects: (resourcePath) => !resourcePath.includes('tyrell-components'),
    }]
  }
}
```

### Rollup

Use `@rollup/plugin-node-resolve` with `exportConditions: ['import']`. `sideEffects` is honored automatically.

### esbuild / Bun

Both honor `exports` and `sideEffects`. No configuration needed.

### Parcel

Works automatically. Parcel respects `sideEffects` and resolves subpath exports.

## SSR and the registration boundary

`customElements.define` requires a browser. On Node.js, `customElements` is undefined. Server-side rendering tools must either:

- **Skip the registration import on the server**, importing it only in the client boundary, or
- **Render `<ty-*>` tags as opaque strings on the server** and let registration hydrate them on the client.

Most frameworks already handle this correctly when you import inside a client-only context. Specifics:

- **Next.js (App Router)** — Add `'use client'` to any file that imports `tyrell-components/...`, or perform the import inside a `useEffect` for purely client-side registration. See REACT_TY_GUIDE.md § Next.js Integration.
- **Nuxt 3** — Wrap registration in `if (process.client)` or place imports inside `<ClientOnly>` boundaries / `onMounted` hooks.
- **SvelteKit** — Use `import { browser } from '$app/environment'` and guard with `if (browser)`, or place imports inside `onMount`.
- **Astro** — Use `client:load` / `client:idle` directives on islands that contain `<ty-*>` elements; do not import `tyrell-components` from `.astro` files.
- **Remix** — Import inside `useEffect` or wrap with `ClientOnly` from `remix-utils`.

What you should **not** do is render `<ty-*>` tags on the server expecting them to "work" — they'll render as inert HTML until registration runs on the client. That's usually fine (graceful upgrade), but means initial paint shows unstyled content. Either:

- Accept the brief flash (acceptable for most apps), or
- Wrap critical UI with a skeleton until `customElements.whenDefined()` resolves, or
- Use Declarative Shadow DOM for SSR-friendly initial markup (advanced; not currently supported by Tyrell out of the box).

## Bundle size — what to expect

Approximate sizes for the most common configurations:

| Configuration | Minified |
|---|---:|
| Single primitive (`button`, `input`, `tag`) | 3–8 KB |
| Dropdown + option | ~15 KB |
| Modal + popup + tooltip | ~20 KB |
| Calendar + date-picker | ~25 KB |
| All components (full bundle) | ~150–200 KB |
| Per-icon SVG | 300–600 bytes |
| All lucide icons (mistake) | ~600 KB |

Components are bounded — even importing all 23 caps at ~200 KB. Icons are unbounded if you namespace-import a family. **The icon import pattern matters more than the component import pattern.**

## Code-splitting patterns

### Per-route splits

```js
// Defer calendar to the page that uses it
const DatePickerPage = () => import('./pages/date-picker.js')
const router = {
  '/booking': DatePickerPage,
}
```

The dynamic `import()` triggers the route's components to register on demand.

### Component-level splits

```js
async function showModal() {
  // Modal not registered yet
  if (!customElements.get('ty-modal')) {
    await import('tyrell-components/modal')
  }
  document.querySelector('ty-modal').show()
}
```

### Icon-bundle splits

For very icon-heavy apps, split icon registration by feature:

```js
// chart-icons.js
import { registerIcons } from 'tyrell-components/icons/registry'
import { trendingUp, trendingDown, barChart } from 'tyrell-components/icons/lucide'
export function registerChartIcons() {
  registerIcons({ trendingUp, trendingDown, barChart })
}

// chart.js
import { registerChartIcons } from './chart-icons.js'
registerChartIcons()
```

Combined with route-level splits, only the route that renders the chart pays the cost.

## Performance — startup ordering

If you load Tyrell via NPM and have hundreds of `<ty-*>` elements in initial HTML:

```js
// main.js — register first, paint second
import 'tyrell-components/css/tyrell.css'
import 'tyrell-components/css/tyrell-theme.css'
import 'tyrell-components'

import { registerIcons } from 'tyrell-components/icons/registry'
import { check, x } from 'tyrell-components/icons/lucide'
registerIcons({ check, x })

// Then mount your app
mountApp()
```

Registering before mounting avoids a flash of unregistered elements. With code splitting, accept the flash for offscreen content but prefetch eagerly for above-the-fold UI.

## TypeScript

The package ships `.d.ts` files for the component classes:

```ts
import type { TyButton } from 'tyrell-components/button'

const btn = document.querySelector('ty-button') as TyButton
btn.disabled = true
```

For framework-specific JSX types, see the framework guides. Plain TypeScript with `lib.dom.d.ts` does not know about `<ty-button>` — you'll need either the React wrapper types, the Vue/Svelte template type registration, or a manual `HTMLElementTagNameMap` augmentation.

## Quick reference — what to import where

| Goal | Import |
|---|---|
| Register everything | `import 'tyrell-components'` |
| Register one component | `import 'tyrell-components/button'` |
| Multiple components | One import line per component |
| Stylesheet — structure (bundler) | `import 'tyrell-components/css/tyrell.css'` |
| Stylesheet — colors (bundler) | `import 'tyrell-components/css/tyrell-theme.css'` |
| Icon registry function | `import { registerIcons } from 'tyrell-components/icons/registry'` |
| Specific icons | `import { check, heart } from 'tyrell-components/icons/lucide'` |
| Component class (typing) | `import type { TyButton } from 'tyrell-components/button'` |

## See also

- [TY_GUIDE.md](../TY_GUIDE.md) — universal HTML/JS API reference
- [CSS_GUIDE.md](../CSS_GUIDE.md) — design system (colors, surfaces, text)
- [REACT_TY_GUIDE.md](./REACT_TY_GUIDE.md) — React + `tyrell-react`
- [VUE_TY_GUIDE.md](./VUE_TY_GUIDE.md) — Vue 3 / Nuxt
- [SVELTE_TY_GUIDE.md](./SVELTE_TY_GUIDE.md) — Svelte 5 / SvelteKit
- [TYCOMPONENT_GUIDE.md](./TYCOMPONENT_GUIDE.md) — building custom components on `TyComponent`
