# LO-TEK in React

The rulebook for LO-TEK in a React app.

React differs from all the other environments in one thing, and it matters
enough to have its own file: React rewrites the attribute names. `class` is
`className` and `for` is `htmlFor`, and if you use the builder functions from
the main entry, React prints "Invalid DOM property" in the console for every
element. That is why the package has a React entry of its own.

This is @lo-tek/interfaces 0.36.0. The file is generated by the package and
follows its version, so it can never say anything other than the code next to
it.

## Short version

1. **Import the stylesheets in `main.tsx`**, `tokens.css` first. Without them,
   the components look unstyled. The answer is then to add the import, never
   to write your own CSS to make them look right.
2. **Use only the classes and elements in the tables below.** `lt-modal`,
   `lt-datepicker` and `data-variant="outlined"` exist in other design
   systems, not in LO-TEK. If you are unsure whether something exists, it is
   listed here or it does not exist.
3. **No hard-coded colours or pixels.** `var(--lt-color-…)` and
   `var(--lt-spacing-…)`.
4. **`defineLt*()` runs at the top of `main.tsx`,** not in a `useEffect`, and
   a boolean attribute on a web component is set as
   `open={isOpen || undefined}`. The two other ways of writing it are each
   wrong in one of the React versions.
5. **The types are your check.** `lt.button({ variant })` from
   `@lo-tek/interfaces/react` turns a variant that does not exist into a
   compile error, and `@lo-tek/interfaces/react-jsx`, imported once in a
   `.d.ts` file, does the same for the attributes on the web components. Run
   `tsc`. A hand-written `className` or `data-variant` is seen by neither of
   them, nor by `npx @lo-tek/interfaces check`, which reads `class`, not
   `className`, so use the builder functions. HTML and templates are checked
   with `npx @lo-tek/interfaces check <file>`.

## 1. The stylesheets

`tokens.css` defines all the variables, and all the other stylesheets build on
it. It must be loaded, and comes first out of habit: the order between it and
the others does not matter. After that, one per component you use:

```tsx
// main.tsx, at the top
import "@lo-tek/interfaces/tokens.css"
import "@lo-tek/interfaces/field.css"
import "@lo-tek/interfaces/button.css"
```

The name of each stylesheet is in the tables below.

## 2. What exists

35 CSS components and 9 web components, and this is the whole list. The
classes are `lt-` + kebab-case. Variants are always `data-*` attributes, never
classes of their own: `data-variant="secondary"`, not `lt-button--secondary`.
The default variant has no attribute.

### CSS components (no JavaScript)

| Class | Stylesheet | Attributes |
| --- | --- | --- |
| `lt-accordion`<br>`lt-accordion__content` | `@lo-tek/interfaces/accordion.css` | `data-variant`: plain |
| `lt-alert`<br>`lt-alert__title` | `@lo-tek/interfaces/alert.css` | `data-color`: info, success, warning, danger |
| `lt-avatar`<br>`lt-avatar-stack` | `@lo-tek/interfaces/avatar.css` | `data-variant`: square<br>`data-size`: small, large |
| `lt-badge` | `@lo-tek/interfaces/badge.css` | `data-color`: success, warning, danger, neutral |
| `lt-breadcrumbs` | `@lo-tek/interfaces/breadcrumbs.css` | none |
| `lt-button` | `@lo-tek/interfaces/button.css` | `data-variant`: secondary, ghost, danger |
| `lt-card`<br>`lt-card__title` | `@lo-tek/interfaces/card.css` | `data-variant`: filled<br>`data-interactive` (flag) |
| `lt-checkbox`<br>`lt-checkbox-row` | `@lo-tek/interfaces/checkbox.css` | `data-state`: invalid, success |
| `lt-divider` | `@lo-tek/interfaces/divider.css` | `data-variant`: subtle, strong |
| `lt-error-text` | `@lo-tek/interfaces/error-text.css` | `data-variant`: warning |
| `lt-fieldset`<br>`lt-legend` | `@lo-tek/interfaces/fieldset.css` | `data-state`: invalid, success<br>`data-required`: symbol, text<br>`data-optional` (flag) |
| `lt-file-upload`<br>`lt-file-upload-list` | `@lo-tek/interfaces/file-upload.css` | `data-state`: invalid, success |
| `lt-heading` | `@lo-tek/interfaces/heading.css` | `data-size`: xs, s, m, xl, mega |
| `lt-help-text` | `@lo-tek/interfaces/help-text.css` | `data-variant`: strong, success, warning |
| `lt-icon` | `@lo-tek/interfaces/icon.css` | none |
| `lt-input` | `@lo-tek/interfaces/input.css` | `data-state`: invalid, success<br>`data-variant`: date, datetime-local, time |
| `lt-label` | `@lo-tek/interfaces/label.css` | `data-required`: symbol, text<br>`data-optional` (flag) |
| `lt-link` | `@lo-tek/interfaces/link.css` | none |
| `lt-list` | `@lo-tek/interfaces/list.css` | `data-variant`: plain, divided |
| `lt-pagination`<br>`lt-pagination__gap` | `@lo-tek/interfaces/pagination.css` | none |
| `lt-paragraph` | `@lo-tek/interfaces/paragraph.css` | `data-variant`: lead<br>`data-size`: small, large |
| `lt-progress` | `@lo-tek/interfaces/progress.css` | `data-color`: success, warning, danger |
| `lt-radio`<br>`lt-radio-row` | `@lo-tek/interfaces/radio.css` | `data-state`: invalid, success |
| `lt-search`<br>`lt-search-row` | `@lo-tek/interfaces/search.css` | `data-state`: invalid, success |
| `lt-select` | `@lo-tek/interfaces/select.css` | `data-state`: invalid, success<br>`data-picker`: styled |
| `lt-skeleton` | `@lo-tek/interfaces/skeleton.css` | `data-variant`: text, circle |
| `lt-skip-link` | `@lo-tek/interfaces/skip-link.css` | none |
| `lt-spinner` | `@lo-tek/interfaces/spinner.css` | `data-size`: small, large |
| `lt-sr-only` | `@lo-tek/interfaces/sr-only.css` | none |
| `lt-switch`<br>`lt-switch-row` | `@lo-tek/interfaces/switch.css` | none |
| `lt-table`<br>`lt-table__sort`<br>`lt-table-scroll` | `@lo-tek/interfaces/table.css` | `data-variant`: striped<br>`data-hoverable` (flag) |
| `lt-tag` | `@lo-tek/interfaces/tag.css` | `data-variant`: filled<br>`data-selectable` (flag) |
| `lt-textarea` | `@lo-tek/interfaces/textarea.css` | `data-state`: invalid, success |
| `lt-toggle-group`<br>`lt-toggle-group__option` | `@lo-tek/interfaces/toggle-group.css` | none |
| `lt-tooltip`<br>`lt-tooltip__bubble` | `@lo-tek/interfaces/tooltip.css` | none |

There is also `lt-theme-control`, a class on a radio button that lets the user
choose a theme. It is in `tokens.css`, and is described under Tokens.

## 3. Tokens

One layer. A colour is a cell in a matrix of **family**, that is, what it
means, and **role**, that is, what it does, and the name is
`--lt-color-<family>-<role>`. Every family has every role, so
`--lt-color-danger-border` and `--lt-color-success-border` both exist. The
roles are the same whatever the family: `surface` is a tinted surface, `fill`
a filled one, `content` the text on top of `fill`, `border` a border, and
`text` the family's colour as text. Border and text each have a weaker and a
stronger step next to them.

```
Families: `accent`, `visited`, `brand1`, `brand2`, `brand3`, `neutral`, `danger`, `warning`, `success`.

Roles: `surface`, `border-subtle`, `border`, `border-strong`, `fill`, `text`, `text-strong`, `text-subtle`, `content`.

Outside the matrix: `--lt-color-disabled-surface`, `--lt-color-disabled-text`, `--lt-color-neutral-canvas`, `--lt-color-neutral-raised`, `--lt-color-overlay`, `--lt-focus-ring`, `--lt-icon-calendar`, `--lt-icon-check`, `--lt-icon-clock`, `--lt-icon-dash`, `--lt-icon-search`, `--lt-shadow-overlay`.
```

Spacing: `--lt-spacing-0-5`, `--lt-spacing-1`, `--lt-spacing-10`,
`--lt-spacing-12`, `--lt-spacing-16`, `--lt-spacing-2`, `--lt-spacing-3`,
`--lt-spacing-4`, `--lt-spacing-5`, `--lt-spacing-6`, `--lt-spacing-7`,
`--lt-spacing-8`, `--lt-spacing-px`.

Font: `--lt-font-size-l`, `--lt-font-size-m`, `--lt-font-size-mega`,
`--lt-font-size-reference`, `--lt-font-size-s`, `--lt-font-size-xl`,
`--lt-font-size-xs`, `--lt-font-size-xxl`, `--lt-font-size-xxs`,
`--lt-font-weight-bold`, `--lt-font-weight-medium`,
`--lt-font-weight-regular`, `--lt-font-weight-semibold`.

Line height: `--lt-line-height-article`, `--lt-line-height-compact`,
`--lt-line-height-default`, `--lt-line-height-heading`.

`disabled` and `neutral` are not the same. `disabled` is for controls that are
turned off, and is exempt from the contrast requirement in WCAG 1.4.3.
`neutral` is for subdued information the user actually has to read or press,
and holds 4.5:1. Never use the `disabled` colours to subdue something that is
meant to be read.

### Light and dark

Without you doing anything, the colours follow the device's setting. A page
that wants to decide for itself sets `data-theme="light"` or
`data-theme="dark"` on `<html>`.

The attribute is a **theme boundary** and works on any element, not only on
the root. One theme can sit inside another, both ways.

This is what an embedded component should use. When you put LO-TEK into a page
you do not control, set the attribute on the component's own root element:

```tsx
<div data-theme="light">
  <button {...lt.button()}>Save</button>
</div>
```

The component is then light whatever the device is set to, and the host is
left alone.

**The host's CSS stops at the boundary.** The host often has rules without a
layer, such as `button { background: none; border: none }` or a normalize, and
they beat `@layer lotek`. In that case, set `data-lt-boundary` on the same
root element:

```tsx
<div data-lt-boundary data-theme="light">
  <button {...lt.button()}>Save</button>
</div>
```

Below the root element the browser ignores CSS without a layer, within the
specificity below, and LO-TEK's layer applies again. The rule is in
`lotek.css` and in `@lo-tek/interfaces/boundary.css`. Fonts and other
inherited properties still come from the host, and the `--lt-*` variables
work. Three things follow from it:

- Your own CSS inside the boundary must be in a layer after `lotek`. CSS
  without a layer disappears there in the same way as the host's.
- Elements without a LO-TEK class lose the host's CSS without a layer. A layer
  the host has declared before `lotek`, such as Tailwind's Preflight in
  `base`, still applies where LO-TEK sets nothing.
- The boundary has the specificity (0,2,0). A rule from the host with the same
  specificity wins if it is loaded after the boundary, and one with more
  always wins. So do `!important` and layers the host has declared after
  `lotek`.

LO-TEK does **not** set `color-scheme` on `:root`. The property controls the
browser's own surfaces, that is, scrollbars, dropdowns and calendar panels,
and it is inherited. A child can opt out with `color-scheme: normal`, but that
is a counter-rule the host never asked to have to write: with the value on the
root, it applied to the whole document, including where the package is only a
guest. If the whole page should follow the system, write
`color-scheme: light dark` on `<html>` yourself, in the same way as you set
the layer order yourself. The exception is the theme picker below: when you
use it, each option sets `color-scheme` itself.

### Letting the user choose a theme

`lt-theme-control` on a radio button makes `value` a theme choice. It is plain
CSS, without a line of JavaScript:

```tsx
<fieldset className="lt-toggle-group">
  <legend className="lt-sr-only">Theme</legend>
  <label className="lt-toggle-group__option">
    <input className="lt-theme-control" type="radio" name="theme"
           value="auto" defaultChecked /> Follow the system
  </label>
  <label className="lt-toggle-group__option">
    <input className="lt-theme-control" type="radio" name="theme"
           value="light" /> Light
  </label>
  <label className="lt-toggle-group__option">
    <input className="lt-theme-control" type="radio" name="theme"
           value="dark" /> Dark
  </label>
</fieldset>
```

The choice controls two things. LO-TEK's colours come from the tokens, and the
browser's **own** surfaces from `color-scheme`: `light` gives `light`, `dark`
gives `dark`, and `auto` gives `light dark`. `light dark` is not a theme, but
the statement that the page works in both, so the browser can choose by the
system.

"Follow the system" has no theme block, and that is on purpose: a value
without a block matches nothing, and then the media query applies again.

Do not write `color-scheme` yourself when the picker is in use. Such a rule
outside a layer beats `@layer lotek` and locks the browser's surfaces to the
system while the user has chosen something else.

`light` and `dark` win over `data-theme` on `<html>`, so the server can send
the stored choice while a click still takes effect before the response is
back. `auto` does not: it means "no override from me", so if the server has
written `data-theme`, the server's value stands. For "follow the system" to
work at once, whatever stores the choice must also remove the attribute.

Two things it does not do. It **stores nothing**: submit the group in a form
and store the choice in a cookie the server reads, or in `localStorage`. And
it must be in the **same tree as `<html>`**, since `:has()` does not see out
of its own tree; a control inside a shadow root does not set the theme on the
page.

## 4. Web components

Three rules apply to all of them:

1. **`defineLt*()` runs once** at the top of the module, before `createRoot`,
   not in a `useEffect`. The import has no side effect on its own; it is the
   `define` call that registers the element.
2. **Boolean attributes are true as long as they are present.**
   `hidden="false"`, `disabled="false"` and `open="false"` turn it *on*. To
   turn any of them off, remove the attribute entirely.
3. **You write the markup, the component adds the behaviour.** `<lt-field>`
   does not create your label or your control. You write `for` on the label
   and `id` on the control, or wrap the control in a `<label>`, so the field
   has a name without JavaScript too. The component wires the help text and
   the error text with `aria-describedby` and `aria-invalid`, and never writes
   an id on the control: an id the server did not send makes an update from
   the server replace the field, with the focus and what the user has typed.
   The field is invalid when the error text is there without `hidden`.

| Element | Category | Stylesheet | Registration | Attributes | Events | Classes inside |
| --- | --- | --- | --- | --- | --- | --- |
| `<lt-field>` | frame | `@lo-tek/interfaces/field.css` | `defineLtField()` from `@lo-tek/interfaces/field` | `disabled` (flag)<br>`optional` (flag)<br>`described-by` (text) | none | none |
| `<lt-tabs>` | frame | `@lo-tek/interfaces/tabs.css` | `defineLtTabs()` from `@lo-tek/interfaces/tabs` | `server-controlled` (flag)<br>`activation`: manual, automatic | `tab-select` (index) | `lt-tabs__list`<br>`lt-tabs__panel` |
| `<lt-error-summary>` | frame | `@lo-tek/interfaces/error-summary.css` | `defineLtErrorSummary()` from `@lo-tek/interfaces/error-summary` | `data-autofocus`: false, true<br>`hidden` (flag) | none | `lt-error-summary`<br>`lt-error-summary__title` |
| `<lt-popover>` | frame | `@lo-tek/interfaces/popover.css` | `defineLtPopover()` from `@lo-tek/interfaces/popover` | `open` (flag)<br>`placement`: bottom-start, bottom-end, top-start, top-end<br>`server-controlled` (flag) | `popover-toggle` (open) | `lt-popover` |
| `<lt-suggestion>` | frame | `@lo-tek/interfaces/suggestion.css` | `defineLtSuggestion()` from `@lo-tek/interfaces/suggestion` | `prefiltered` (flag)<br>`count-none` (text)<br>`count-zero` (text)<br>`count-one` (text)<br>`count-two` (text)<br>`count-few` (text)<br>`count-many` (text)<br>`count-other` (text)<br>`server-controlled` (flag) | `suggestion-select` (value, label) | `lt-suggestion__list`<br>`lt-suggestion__option`<br>`lt-suggestion__value`<br>`lt-suggestion__empty` |
| `<lt-dialog>` | frame | `@lo-tek/interfaces/dialog.css` | `defineLtDialog()` from `@lo-tek/interfaces/dialog` | `open` (flag)<br>`server-controlled` (flag) | `dialog-toggle` (open, returnValue) | `lt-dialog` (`data-color`: brand, info, success, warning, danger)<br>`lt-dialog__body`<br>`lt-dialog__title`<br>`lt-dialog__footer`<br>`lt-dialog__header`<br>`lt-dialog__subtitle` |
| `<lt-toast>` | standalone | `@lo-tek/interfaces/toast.css` | `defineLtToast()` from `@lo-tek/interfaces/toast` | `duration` (number)<br>`label` (text)<br>`close-label` (text) | `toast-dismiss` | `lt-toast`<br>`lt-toast__message`<br>`lt-toast__close` |
| `<lt-session-timeout>` | frame | `@lo-tek/interfaces/session-timeout.css` | `defineLtSessionTimeout()` from `@lo-tek/interfaces/session-timeout` | `warn-at` (number)<br>`expires-at` (number)<br>`activity-interval` (number) | `session-warn`<br>`session-extend`<br>`session-logout`<br>`session-expired`<br>`session-activity` | `lt-session-timeout`<br>`lt-session-timeout__dialog`<br>`lt-session-timeout__title`<br>`lt-session-timeout__text`<br>`lt-session-timeout__count`<br>`lt-session-timeout__actions` |
| `<lt-connection-status>` | standalone | `@lo-tek/interfaces/connection-status.css` | `defineLtConnectionStatus()` from `@lo-tek/interfaces/connection-status` | `offline-text` (text)<br>`online-text` (text) | `connection-lost`<br>`connection-restored` | `lt-connection-status`<br>`lt-connection-status__bar` |

None of them uses shadow DOM. The content is in plain DOM, so `querySelector`,
`FormData` and ordinary CSS work straight into it.

## 5. Registration, types and use

```tsx
// main.tsx, runs once when the app starts
import "@lo-tek/interfaces/tokens.css"
import "@lo-tek/interfaces/field.css"
import "@lo-tek/interfaces/button.css"
import { defineLt } from "@lo-tek/interfaces/register"

defineLt()
```

The call is at the top of the module, not in a `useEffect`. An effect runs
after the first paint, so the elements are plain `HTMLElement`s when React
renders them, and a call to `show()` or `reportFailure()` before the effect
fails with "is not a function". The function does nothing on a server, so it
can sit in a root module that runs in both places. If you use only one
component, it has its own function, such as `defineLtTabs()` in
`@lo-tek/interfaces/tabs`.

```ts
// src/lotek.d.ts, gives the web components types in JSX
import "@lo-tek/interfaces/react-jsx"
```

A field is written with `lt.field()`. The wiring is then in the markup React
renders itself, on the server as in the browser. `<lt-field>` writes the
wiring on the elements before React hydrates, and with server rendering React
reports mismatches on the label, the field and the error text. Without a
server it works, but `lt.field()` is the way in both.

```tsx
// ContactForm.tsx
import { lt } from "@lo-tek/interfaces/react"
import { useId, useState } from "react"

export function ContactForm() {
  const [name, setName] = useState("")
  const [touched, setTouched] = useState(false)

  const invalid = touched && name.trim() === ""
  const field = lt.field({
    id: useId(),
    required: "symbol",
    error: true,
    invalid,
  })

  return (
    <form onSubmit={(e) => e.preventDefault()}>
      <label {...field.label}>Full name</label>
      <input
        {...lt.input({ type: "text" })}
        {...field.control}
        name="name"
        required
        value={name}
        onChange={(e) => setName(e.target.value)}
        onBlur={() => setTouched(true)}
      />
      <p {...lt.errorText()} {...field.error}>Enter your name.</p>

      <button {...lt.button()} type="submit">Send</button>
    </form>
  )
}
```

The id comes from `useId()`, so the server and the browser create the same
one.

`lt` is imported from `@lo-tek/interfaces/react`, never from the main entry:
the React entry gives `className` and `htmlFor`, the main entry gives `class`
and `for`. The 46 builder functions are in both:

`lt.accordion()`, `lt.alert()`, `lt.avatar()`, `lt.badge()`,
`lt.breadcrumbs()`, `lt.button()`, `lt.card()`, `lt.checkbox()`,
`lt.connectionStatus()`, `lt.dialog()`, `lt.divider()`, `lt.errorSummary()`,
`lt.errorText()`, `lt.field()`, `lt.fieldset()`, `lt.fileUpload()`,
`lt.heading()`, `lt.helpText()`, `lt.icon()`, `lt.input()`, `lt.label()`,
`lt.legend()`, `lt.link()`, `lt.list()`, `lt.pagination()`, `lt.paragraph()`,
`lt.popover()`, `lt.progress()`, `lt.radio()`, `lt.search()`, `lt.select()`,
`lt.sessionTimeout()`, `lt.skeleton()`, `lt.skipLink()`, `lt.spinner()`,
`lt.srOnly()`, `lt.suggestion()`, `lt.switch()`, `lt.table()`,
`lt.tableSort()`, `lt.tabs()`, `lt.tag()`, `lt.textarea()`, `lt.toast()`,
`lt.toggleGroup()`, `lt.tooltip()`

## 6. Only `open={isOpen || undefined}` works

This applies to every boolean attribute on a web component, such as `open` on
`<lt-dialog>` and `<lt-popover>`. React treats web components differently
between versions, and only this pattern is right in both:

| How it is written | React 18 (sets attribute) | React 19 (sets property) |
| --- | --- | --- |
| `open=""` | works | never open |
| `open={isOpen}` | always open | works |
| `open={isOpen \|\| undefined}` | works | works |

React 18 stringifies `false` to the attribute `open="false"`. The attribute is
then present, and so it is true. React 19 sets the property to `""`, and the
component reads the empty string as false.

If you import `@lo-tek/interfaces/react-jsx`, the first two forms become
compile errors.

The builder functions pass `true` or nothing, so
`{...lt.dialog({ titleId, open: isOpen }).host}` is already right.

## 7. The types

Without `@lo-tek/interfaces/react-jsx` TypeScript does not know `<lt-field>`
at all, and you get
`Property 'lt-field' does not exist on type 'JSX.IntrinsicElements'`. With it
you get autocompletion and errors on the attributes:

```tsx
<lt-field describedBy="terms" />         // error: the attribute is described-by
<lt-toast closeLabel="Close" />          // error: the attribute is close-label
<lt-connection-status offline="Down" />  // error: unknown attribute
```

The types work by the package extending React's `JSX.IntrinsicElements`. If
the project has two installations of `@types/react`, which easily happens in a
monorepo, the package extends one while your code uses the other, and the
elements stay unknown. Run `npm ls @types/react` if something looks odd.

## Known pitfalls

| Symptom | Cause |
| --- | --- |
| The styles are missing | `tokens.css` is not loaded. The order between it and the component's stylesheet does not matter |
| An `<lt-toast>` or `<lt-connection-status>` shows nothing, an `<lt-session-timeout>` never warns, or another component does nothing | The `define` function has not run. `<lt-toast>` and `<lt-connection-status>` create their content themselves and are empty without it, and `<lt-session-timeout>` does not count the time. The markup in the others comes from you and is there regardless, except that `<lt-tabs>` shows only one panel, the one the URL points to or the first, and `<lt-suggestion>` hides the list until they are registered |
| A component speaks English on a page in another language | The text in the markup comes from you, and is written with the app's own translation setup. The few default texts the package has are replaced with `label` and `close-label` on `<lt-toast>`, `offline-text` and `online-text` on `<lt-connection-status>`, `count-none`, `count-one` and `count-other` on `<lt-suggestion>`, and `--lt-label-required-text`, `--lt-label-optional-text` and `--lt-label-required-symbol` in CSS. Numbers and durations follow `lang` on `<html>`. See https://lo-tek.sobernetics.no/translation/ |
| The error text never shows, and the field counts as valid | `hidden="false"` is set on the error text, and it hides it all the same. The attribute must be removed, not set to `false` |
| The component does nothing, and nothing says so | The registration runs only on the server, where it does nothing. It must also run in the browser |
| "Invalid DOM property `class`" | `lt` is imported from the main entry. Use `@lo-tek/interfaces/react` |
| `Property 'lt-field' does not exist` | `@lo-tek/interfaces/react-jsx` is not imported in a `.d.ts` file |

## When CSS is not enough

The components are customised with tokens and `--lt-` variables. If that is
not enough, `npx @lo-tek/interfaces takeover <component>` copies the source
code of one component into the project, so the code is yours to change. A
complete colour theme from your brand colours is made with
`npx @lo-tek/interfaces theme`.

All of this, with live examples: https://lo-tek.sobernetics.no/
