# Overview
What TILE is, the core and component packages, and where to start.
TILE is a design system for React apps. It gives you accessible, themed UI components in `@dxos/react-ui`, and in
`@dxos/ui-theme` the tokens and build plugin behind them. A **token** is a named color or size that the components
read in place of a fixed value. TILE needs neither [ECHO](/docs/echo/overview/), DXOS's database, nor
[PLEX](/docs/plex/overview/), its plugin framework, so you can use it in any React app.
Each demo below is a TILE component package running in this page, on sample data and with no database. You can drag
the cards, edit the cells and move the boxes. The demos follow the page's light or dark mode, and each card's header
opens the component's API page.
## Core and component packages
TILE comes as a core and the component packages built on it:
| Package | What it holds |
| ------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `@dxos/react-ui` | The components, such as buttons, inputs, overlays, menus, layout, status and icons, and the theme provider |
| `@dxos/ui-theme` | The color and size tokens, the cascade layers, and the Vite plugin that generates the styles |
| The other `@dxos/react-ui-*` packages | Lists, forms, menus, editors, tables and more, built on the core |
The API section documents the core first. Each component package then has a group of its own, with one page per
component, such as [Board](/docs/tile/api/react-ui-mosaic/board/) in `@dxos/react-ui-mosaic`.
[Composer](/composer), DXOS's local-first workspace, and its plugins draw their UI with TILE.
[TILE in a PLEX plugin](/docs/tile/guides/tile-in-a-plex-plugin/) says what changes when your components run inside
a plugin.
## How these pages are organized
- **Start here** has two more pages. [Why TILE?](/docs/tile/why-tile/) makes the case for the design, and
[Build with a coding agent](/docs/tile/build-with-a-coding-agent/) gives your agent the skills DXOS uses.
- **Learning path** builds a contacts screen step by step, starting at
[The TILE component](/docs/tile/learn/the-tile-component/). Its [Installation](/docs/tile/learn/installation/) page
adds TILE to a Vite app.
- **Core concepts** describe one idea each: [Theme and tokens](/docs/tile/concepts/theme-and-tokens/),
[Composite components](/docs/tile/concepts/composite-components/), [Layout](/docs/tile/concepts/layout/),
[Density and sizes](/docs/tile/concepts/density-and-sizes/),
[Focus and keyboard](/docs/tile/concepts/focus-and-keyboard/) and
[Translations and icons](/docs/tile/concepts/translations-and-icons/).
- **API** opens each page with the component running.
- **Guides** cover one job each: [Custom themes and dark mode](/docs/tile/guides/custom-themes/),
[TILE in a PLEX plugin](/docs/tile/guides/tile-in-a-plex-plugin/) and
[Testing and stories](/docs/tile/guides/testing-and-stories/).
- **Resources** has the [Glossary](/docs/tile/resources/glossary/), the generated
[API reference](/docs/tile/resources/api-reference/) and [llms.txt](/docs/tile/resources/llms-txt/) for agents.
---
# Why TILE?
Why UI written by many hands still looks and behaves like one app.
An app grows screens written by different people, at different times. Without a shared system, each screen picks its
own grays, paddings and focus styles. Keyboard behavior drifts from one menu to the next, and the app looks like a
collage.
TILE is the shared system. It gives you tokens that name roles instead of colors, components that bring their keyboard
and ARIA behavior with them, and one size scale. [Composer](/composer), DXOS's local-first workspace, loads plugins
from many authors who never talk to each other, and it draws every one of them with TILE.
## Tokens instead of colors
When you style a screen by hand, you pick each color yourself, and you pick a second one for dark mode. The next
author picks a slightly different gray.
With TILE, a plugin never names a raw color. It names a role, such as `bg-card-surface` for a card, `text-fg-muted`
for secondary text or `border-separator` for a rule. A **token** is the color behind a role, which the theme defines
once.
Each token has a light value and a dark value, so a screen that names roles follows light and dark mode with no code
of its own. When the theme gives a token a new value, every screen that names it changes too.
[Theme and tokens](/docs/tile/concepts/theme-and-tokens/) lists the roles and how their names are built.
## Components that bring their behavior
A menu has to open on Enter, move with the arrow keys, close on Escape and return focus to its trigger. A dialog has to
keep focus inside it. These rules are easy to get almost right.
TILE's components are built on [Ark UI](https://ark-ui.com), whose components run [zag](https://zagjs.com) state
machines. The machine owns the keyboard behavior and the ARIA roles, so they come with the component, and a plugin
cannot leave them out.
[Composite components](/docs/tile/concepts/composite-components/) shows how you put a component together from its
parts. [Focus and keyboard](/docs/tile/concepts/focus-and-keyboard/) says what each kind of control does with the
keys.
## One size scale
When each component sets its own height and padding, you adjust them one by one until a row lines up.
In TILE, every control reads its height, text size and icon size from one scale, `xs` to `xl`. A toolbar, the input in
it and the rows of a menu all take their height from that scale, so they line up without per-component padding.
[Density and sizes](/docs/tile/concepts/density-and-sizes/) shows how a size set on one element reaches the controls
inside it.
## No ECHO or PLEX required
`@dxos/react-ui` depends on neither ECHO, DXOS's database, nor PLEX, its plugin framework. You can use it in any React
app that adds TILE's Vite plugin and its stylesheets. [Installation](/docs/tile/learn/installation/) sets that up
from scratch.
---
# Build with a coding agent
Point Claude Code, Codex or Cursor at the skills DXOS uses to build with TILE.
DXOS builds the UI of [Composer](/composer), its local-first workspace, with coding agents. It keeps what they need
to know about TILE in two skills, and this page gives your agent the same two.
A **skill** is a folder with a `SKILL.md` file that tells an agent how to do one kind of work. Claude Code, Codex and
Cursor all read them.
| Skill | What it covers |
| --- | --- |
| [`composer-ui`](https://github.com/dxos/dxos/tree/main/.agents/skills/composer-ui) | How to use the components, from tokens and layout to lists, forms, toolbars, translations and stories |
| [`composite-components`](https://github.com/dxos/dxos/tree/main/.agents/skills/composite-components) | How to write a component of your own as a namespace of parts, the way TILE's are written |
`composer-ui` is written for Composer plugins. However, most of it applies to any app that uses TILE.
## Add the skills to your project
Copy each skill's folder into the folder your agent loads project skills from:
| Agent | Skills folder |
| --- | --- |
| Claude Code | `.claude/skills/` |
| Codex | `.agents/skills/` |
| Cursor | `.cursor/skills/` |
Then ask your agent for what you want built. It reads a skill when the work matches the skill's description.
## Give it the docs
[`/tile/llms-full.txt`](/tile/llms-full.txt) holds every TILE page as Markdown, code samples included. Ask your agent
to read it when it needs more than the skills say. [llms.txt](/docs/tile/resources/llms-txt/) also lists
`/tile/llms.txt`, an index of the pages with a summary of each.
To learn TILE by hand instead, start with [The TILE component](/docs/tile/learn/the-tile-component/). It opens a
learning path that builds one screen, a page at a time.
---
# The TILE component
What a TILE component is, and the contacts screen the learning path builds, running.
In this learning path we build one screen: a list of contacts beside the selected person's details, with a toolbar to
add, edit and delete them. This page explains what a TILE component is, and shows the screen finished.
## What a TILE component is
A component library often gives you one `Dialog` component, and you shape it with props. A TILE component is a
namespace of parts instead:
- A **part** is one element of the component, such as `Dialog.Trigger`, `Dialog.Content` or `Dialog.Title`.
- A **namespace** is the object that holds a component's parts, such as `Dialog`. You import each namespace from its
own entry point of `@dxos/react-ui`, such as `@dxos/react-ui/Dialog`.
`Dialog.Root` holds the state, and each other part renders one element. You put the parts together in JSX, in the
shape you want, and leave out the ones you don't need:
```ts
import * as Button from '@dxos/react-ui/Button';
import * as Dialog from '@dxos/react-ui/Dialog';
import * as Field from '@dxos/react-ui/Field';
import * as Input from '@dxos/react-ui/Input';
export const EditDialog = () => (
Edit contactEdit contact
Changes are saved when you press Save.
NameCancelSave
);
```
`Dialog.Trigger` wraps the button that opens the dialog. Each button in the footer sits in a `Dialog.CloseTrigger`,
so Cancel and Save both close it.
Every part takes its look from the **theme**, which is TILE's stylesheets and the tokens they are built from. A
**token** is a named color or size. A part writes its props, such as `variant='primary'`, onto its element as
attributes, and the stylesheets style them with tokens.
The same component therefore follows light and dark mode, and matches the rest of the app. To adjust one part, pass
`classNames`. `Theme.Provider` wraps the app and gives the parts their built-in strings and their icons.
The parts also handle the keyboard, focus and ARIA attributes. A dialog traps focus and closes on Escape without code
of yours.
[Composite components](/docs/tile/concepts/composite-components/) covers parts and the state machines behind them.
[Theme and tokens](/docs/tile/concepts/theme-and-tokens/) covers the tokens and `classNames`.
## The finished screen
This is the screen at the end of the path, before its last page moves the contacts into
[ECHO](/docs/echo/overview/), DXOS's database. Select a contact, edit it, delete it or add one:
Each page of the path builds one piece of it. From Lay out a screen on, each page keeps its version of the screen in a
folder of its own:
| Page | Folder | What it adds |
| --- | --- | --- |
| [Installation](/docs/tile/learn/installation/) | `src/` | A Vite app with TILE's theme, icons and dark mode, and its first buttons |
| [Lay out a screen](/docs/tile/learn/lay-out-a-screen/) | `src/layout/` | The list beside the detail, with a toolbar |
| [Inputs and actions](/docs/tile/learn/inputs-and-actions/) | `src/inputs/` | An editor for the selected contact |
| [Overlays](/docs/tile/learn/overlays/) | `src/overlays/` | An edit dialog, a delete confirmation, a tooltip and a toast |
| [Icons and translations](/docs/tile/learn/icons-and-translations/) | `src/icons/` | Icons, an Add button, and the screen's strings in a resource |
| [Connect to ECHO](/docs/tile/learn/connect-to-echo/) | `src/echo/` | The contacts as ECHO objects that sync, and a form built from their schema |
Every page before Connect to ECHO keeps the contacts in React state, so the only new thing on each page is TILE.
---
# Installation
Start the contacts screen, a Vite app with TILE's packages, theme, icons and dark mode.
By the end of this page the contacts screen is a Vite app with TILE's theme. It shows its first two buttons, in light
or dark mode to match the system. TILE needs neither ECHO, DXOS's database, nor PLEX, its plugin framework, for this.
## Background
You need Node 20 or later. Every page of the path is the same app, so keep the project when you go on to the next one.
A component library usually ships a finished stylesheet. TILE generates its CSS when our app builds, so we install the
tools that build it beside the components. Step 1 installs seven packages, and sets the version of React:
- `@dxos/react-ui` holds the components. It needs React 19.3, which is why step 1 names a version of `react` and
`react-dom`.
- `@dxos/ui-theme`, its peer, holds the tokens and `ThemePlugin`, a Vite plugin that turns them into CSS. A **token**
is a named color or size that the components read. We set the plugin up in step 2.
- `effect` and `@effect/atom-react` are peers of `@dxos/react-ui` too, so we install them beside it.
- `@dxos/vite-plugin-icons` holds `IconsPlugin`, which gathers the icons the app draws into one file.
- `@phosphor-icons/core` holds the icons themselves, as SVG files that `IconsPlugin` reads.
- `tailwindcss` is the compiler that `ThemePlugin` runs.
Until the next npm release, we install the `@dxos` packages from pkg.pr.new, as the build of main that these pages
describe. The releases on npm are older and do not all run outside the DXOS repository. ECHO's
[Installation](/docs/echo/learn/installation/) installs its packages from the same build.
## Steps
1. **Make a Vite app.** Create a React and TypeScript project and install the packages:
```sh
npm create vite@latest contacts -- --template react-ts
cd contacts
npm install \
https://pkg.pr.new/dxos/dxos/@dxos/react-ui@20a14b9 \
https://pkg.pr.new/dxos/dxos/@dxos/ui-theme@20a14b9 \
effect@4.0.4 @effect/atom-react@4.0.4 react@~19.3.1 react-dom@~19.3.1
npm install --save-dev \
https://pkg.pr.new/dxos/dxos/@dxos/vite-plugin-icons@20a14b9 \
@phosphor-icons/core tailwindcss
```
Install any other `@dxos` package from the same build, with its name in place of `react-ui`.
2. **Configure Vite.** Replace `vite.config.ts`. Two plugins do the work:
- `ThemePlugin` generates the theme's CSS with Tailwind. Tailwind emits a token or a class only when a file it
scans names it, so `content` points it at the components' own stylesheets.
- `IconsPlugin` builds `/icons.svg`, a **sprite**, which is one file that holds every icon our code and the
components name.
```ts title="vite.config.ts"
import react from '@vitejs/plugin-react';
import { join } from 'node:path';
import { defineConfig } from 'vite';
import { ThemePlugin } from '@dxos/ui-theme/plugin';
import { IconsPlugin, iconSymbolPattern } from '@dxos/vite-plugin-icons';
const phosphor = join(import.meta.dirname, 'node_modules/@phosphor-icons/core/assets');
export default defineConfig({
plugins: [
ThemePlugin({ content: ['node_modules/@dxos/*/src/**/*.css'] }),
IconsPlugin({
symbolPattern: iconSymbolPattern({ sets: ['ph'] }),
assetPath: (_set, name, variant) =>
join(phosphor, variant, variant === 'regular' ? `${name}.svg` : `${name}-${variant}.svg`),
spriteFile: 'icons.svg',
contentPaths: [join(import.meta.dirname, 'src/**/*.{ts,tsx}')],
// Pre-bundled dependencies skip the plugin's transform, so their icons are found by scanning up front.
scanPaths: [join(import.meta.dirname, 'node_modules/@dxos/*/dist/**/*.mjs')],
}),
react(),
],
});
```
`ThemePlugin` also gives the app dark mode. The dark value of every token applies under a `dark` class on the root
element. The plugin adds a script to the page's `
` that sets the class from the system's setting before the
first paint, and sets it again when the setting changes.
To let the user choose the mode instead, see [Custom themes and dark mode](/docs/tile/guides/custom-themes/),
which sets the class from a stored choice.
3. **Render the app inside the theme.** Replace `src/main.tsx`. The new file imports two stylesheets before any
component:
- `@dxos-theme` is the virtual module that `ThemePlugin` serves.
- `@dxos/react-ui/theme.css` holds the components' own rules.
Then it renders the app inside `Theme.Provider`, which gives every component the strings its built-in labels read
and the icons it draws:
```ts
import React from 'react';
import { createRoot } from 'react-dom/client';
import * as Theme from '@dxos/react-ui/Theme';
import { translations } from '@dxos/react-ui/translations';
import { App } from './App.tsx';
import '@dxos-theme';
import React from 'react';
import { createRoot } from 'react-dom/client';
import '@dxos/react-ui/theme.css';
import * as Theme from '@dxos/react-ui/Theme';
import { translations } from '@dxos/react-ui/translations';
import { App } from './App.tsx';
createRoot(document.getElementById('root')!).render(
,
);
```
`resourceExtensions={translations}` passes react-ui's own strings, such as the "No items" of an empty list.
`tx` takes a theme function, and `Theme.defaultTx` is the one TILE exports.
4. **Add the first buttons.** Replace `src/App.tsx`. `Layout.Flex` lays the buttons out in a row with a gap from the
theme's scale, and `variant='primary'` marks the main action:
```ts
import React from 'react';
import * as Button from '@dxos/react-ui/Button';
import * as Layout from '@dxos/react-ui/Layout';
import React from 'react';
import * as Button from '@dxos/react-ui/Button';
import * as Layout from '@dxos/react-ui/Layout';
export const App = () => (
Import
);
```
Delete `src/App.css` and `src/index.css`, which Vite's template made. The theme replaces them.
## Try it
Run `npm run dev` and open the page. Switch your system between light and dark, and the buttons follow. This preview
follows the docs' own mode picker instead:
## What you can do now
You can render TILE components in a themed app that follows light and dark mode. Next,
[Lay out a screen](/docs/tile/learn/lay-out-a-screen/) builds the list and the detail beside it, in a folder of its
own, `src/layout/`.
---
# Lay out a screen
A list of contacts beside a detail column, under a toolbar.
By the end of this page the app shows a toolbar over two columns: the contacts on the left, and the selected contact's
details on the right.
## Background
Built by hand, this screen is nested flex and grid boxes, each with its own padding and gap. TILE lays out a screen
with a few components that own their spacing, so we rarely write padding or flex classes:
- `Panel` is a frame with a header, a body that takes the remaining height, and an optional footer. Use it as the
outer shell of a screen. Step 4 puts the screen in one.
- `Toolbar` is a row of controls and text. Use it in a panel's header.
- `Layout.Grid` places its children in tracks, and `Layout.Flex` places them in a row or a stack. Both take their
gaps from the theme's scale. Use `Layout.Grid` when one track has a fixed size, as the list's column does in step 4.
- `ScrollArea` scrolls its content with the theme's scrollbar. Use it around content that can grow taller than its
column, as the detail does in step 3.
[Layout](/docs/tile/concepts/layout/) explains how a panel passes its height down to the part that scrolls.
## Steps
1. **Add the data.** We keep the contacts in React state until the last page. Put their type and the starting list in
`src/contacts.ts`:
```ts
import type * as Select from '@dxos/react-ui/Select';
export type Contact = {
id: string;
name: string;
email: string;
role: string;
};
export const ROLES: Select.Option[] = [
{ value: 'viewer', label: 'Viewer' },
{ value: 'editor', label: 'Editor' },
{ value: 'admin', label: 'Admin' },
];
export const CONTACTS: Contact[] = [
{ id: 'ada', name: 'Ada Lovelace', email: 'ada@example.com', role: 'admin' },
{ id: 'grace', name: 'Grace Hopper', email: 'grace@example.com', role: 'editor' },
{ id: 'alan', name: 'Alan Turing', email: 'alan@example.com', role: 'viewer' },
{ id: 'katherine', name: 'Katherine Johnson', email: 'katherine@example.com', role: 'editor' },
];
```
`ROLES` has the shape a `Select` takes for its options. The next page uses it.
2. **List the contacts.** `Listbox` draws one row per item, with the label and a second line from `description`. It
handles selection, arrow keys and typeahead. `Listbox.Viewport` makes the list scroll inside its column. Add
`src/layout/ContactsScreen.tsx`:
```ts
import * as Listbox from '@dxos/react-ui/Listbox';
import { type Contact } from '../contacts.ts';
type ContactListProps = {
contacts: Contact[];
selected?: string;
onSelect: (id: string) => void;
};
/** One row per contact; the list scrolls inside its own viewport. */
export const ContactList = ({ contacts, selected, onSelect }: ContactListProps) => {
const items = contacts.map((contact) => ({
value: contact.id,
label: contact.name,
description: contact.email,
}));
return (
id && onSelect(id)}>
{items.map((item) => (
))}
);
};
```
`value` is a list, because a listbox can allow several selections, so `onValueChange` takes the first id.
3. **Show the selected contact.** `Typography.Text` with `tone='muted'` reads as secondary text. When no contact is
selected, `Status.Empty` shows an icon and a hint in the middle of the column:
```ts
import * as Layout from '@dxos/react-ui/Layout';
import * as ScrollArea from '@dxos/react-ui/ScrollArea';
import * as Status from '@dxos/react-ui/Status';
import * as Typography from '@dxos/react-ui/Typography';
import { type Contact } from '../contacts.ts';
/** The selected contact's fields, or a hint when nothing is selected. */
export const ContactDetail = ({ contact }: { contact?: Contact }) =>
contact ? (
{contact.name}
{contact.email}Role: {contact.role}
) : (
Choose a contact
);
```
Nothing on this page clears the selection, so we don't see the hint yet. It first shows in
[Icons and translations](/docs/tile/learn/icons-and-translations/), after a delete.
4. **Put them in a panel.** The toolbar goes in `Panel.Header`. `cols={['16rem', 'fill']}` gives the list a fixed
width and the detail the rest:
```ts
import { useState } from 'react';
import * as Layout from '@dxos/react-ui/Layout';
import * as Panel from '@dxos/react-ui/Panel';
import * as Toolbar from '@dxos/react-ui/Toolbar';
import { CONTACTS } from '../contacts.ts';
export const ContactsScreen = () => {
const [contacts] = useState(CONTACTS);
const [selected, setSelected] = useState(contacts[0].id);
const contact = contacts.find(({ id }) => id === selected);
return (
Contacts{contacts.length} contacts
);
};
```
`Panel.Body asChild` makes the grid itself the body, so the grid fills the height under the toolbar and no extra
element sits between them.
5. **Render the screen.** In `src/main.tsx`, render `` in place of ``, imported from
`./layout/ContactsScreen.tsx`. Give it the window's height in `index.html`, so the panel fills it:
```html title="index.html"
```
## Try it
Click a contact, or move through the list with the arrow keys.
## What you can do now
You can lay out a screen with a toolbar, a scrolling list and a detail column. Next,
[Inputs and actions](/docs/tile/learn/inputs-and-actions/) makes the detail editable.
---
# Inputs and actions
Edit a contact with inputs, a select and buttons.
By the end of this page the detail column is a form. You can change a contact's name, email or role, then save or
revert.
## Background
We build the form from three components:
- A `Field` holds one input. It ties the label to the control for screen readers, and lines up labels, help text and
errors. Use one around every input that has a label.
- `Input.Root` is a text input. Use its `type` for one kind of text, such as the `'email'` of step 1.
- `Select` opens a list of options, and the user picks one. Use it when the choices are fixed, as our three roles
are.
`Input.Root` and `Select` both work controlled, with a value and a change handler, the way React inputs do.
[Input](/docs/tile/api/input/) lists the other controls, such as checkboxes and switches, and
[Button](/docs/tile/api/button/) lists the button variants.
## Steps
1. **Write the editor.** The editor edits a copy of the contact, which it keeps in `draft`, so nothing changes until
Save. We disable Save until the draft differs from the contact, and while the name is empty. Add
`src/inputs/ContactEditor.tsx`:
```ts
import { useState } from 'react';
import * as Button from '@dxos/react-ui/Button';
import * as Field from '@dxos/react-ui/Field';
import * as Input from '@dxos/react-ui/Input';
import * as Layout from '@dxos/react-ui/Layout';
import * as Select from '@dxos/react-ui/Select';
import { ROLES } from '../contacts.ts';
/** Edits a copy of `contact`; nothing changes until Save. */
export const ContactEditor = ({ contact, onSave }: ContactEditorProps) => {
const [draft, setDraft] = useState(contact);
const changed = JSON.stringify(draft) !== JSON.stringify(contact);
return (
Name setDraft({ ...draft, name: event.target.value })} />
Email setDraft({ ...draft, email: event.target.value })}
/>
Role setDraft({ ...draft, role })}
>
{ROLES.map((item) => (
))}
setDraft(contact)}>
Revert
onSave(draft)}>
Save
);
};
```
`gap='form'` is the spacing the theme uses between fields. A `Select`'s value is a list, because a select can
allow several choices, so `onValueChange` takes its first item.
2. **Put the editor in the detail column.** The screen now holds the contacts with `setContacts`, and Save replaces
the one that changed. Add `src/inputs/ContactsScreen.tsx`, which reuses `ContactList` from the last page, and
render this `ContactsScreen` from `src/main.tsx`:
```ts
import { useState } from 'react';
import * as Layout from '@dxos/react-ui/Layout';
import * as Panel from '@dxos/react-ui/Panel';
import * as ScrollArea from '@dxos/react-ui/ScrollArea';
import * as Toolbar from '@dxos/react-ui/Toolbar';
import { type Contact, CONTACTS } from '../contacts.ts';
import { ContactList } from '../layout/ContactsScreen.tsx';
import { ContactEditor } from './ContactEditor.tsx';
export const ContactsScreen = () => {
const [contacts, setContacts] = useState(CONTACTS);
const [selected, setSelected] = useState(contacts[0].id);
const contact = contacts.find(({ id }) => id === selected);
const handleSave = (next: Contact) =>
setContacts((contacts) => contacts.map((contact) => (contact.id === next.id ? next : contact)));
return (
Contacts{contacts.length} contacts
{contact && }
);
};
```
`key={contact.id}` gives each contact its own editor. Without it, the editor would keep the last contact's draft
when we choose another.
## Try it
Change Ada's name, and Save and Revert become active. Save, and the list shows the new name.
## What you can do now
You can build a form from fields, inputs, a select and buttons, and keep its state in React. Next,
[Overlays](/docs/tile/learn/overlays/) moves the editor into a dialog.
---
# Overlays
An edit dialog, a delete confirmation, a tooltip and a toast.
By the end of this page the detail column shows the contact's fields as text again. The toolbar has Edit, which opens
the editor in a dialog, and Delete, which asks first. A toast says when a contact is saved.
## Background
Our screen needs four things to appear above the page: an editor, a question, a hint and a notice. Which component
draws each one? An **overlay** is a component that TILE draws above the page, and we use four of them:
- A `Dialog` is modal. The page behind it is inert until it closes. Use it for a task the user finishes or cancels
before going on, as step 1 does for the editor.
- A `Popover` opens beside its trigger and closes when the user clicks elsewhere. Use it for short content that
belongs to one control, as step 2 does for the delete question.
- A `Tooltip` shows a short hint on hover or focus. Use it to name a control or explain a value, as step 3 does for
the role. It never takes focus, so put nothing in it that the user has to click.
- A `Toast` reports something that happened and goes away by itself. Use it when the user does not have to answer,
as step 4 does for a save.
A dialog, a popover and a tooltip each have a `Trigger` that opens it and a `Content` that holds it. `asChild` on a
trigger makes our button the trigger. Without it, the trigger wraps our button in a button of its own.
A toast has neither. It is open while `open` on its `Toast.Root` is true.
[Dialog](/docs/tile/api/dialog/), [Popover](/docs/tile/api/popover/), [Tooltip](/docs/tile/api/tooltip/) and
[Toast](/docs/tile/api/toast/) list the parts of each. TILE has more overlays than these four, such as
[Menu](/docs/tile/api/menu/) for a list of actions and [AlertDialog](/docs/tile/api/alert-dialog/) for a question the
user must answer.
## Steps
1. **Move the editor into a dialog.** The dialog is controlled, so it can close itself when the editor saves. The
trigger is an icon-only button, which shows its label as a tooltip on its own. Add `src/overlays/ContactsScreen.tsx`:
```ts
import { useState } from 'react';
import * as Button from '@dxos/react-ui/Button';
import * as Dialog from '@dxos/react-ui/Dialog';
import { type Contact } from '../contacts.ts';
import { ContactEditor } from '../inputs/ContactEditor.tsx';
type EditDialogProps = {
label: string;
contact: Contact;
onSave: (contact: Contact) => void;
};
/** The editor from the last page, in a dialog that closes on Save. */
export const EditDialog = ({ label, contact, onSave }: EditDialogProps) => {
const [open, setOpen] = useState(false);
return (
setOpen(open)}>
{contact.name} {
onSave(next);
setOpen(false);
}}
/>
);
};
```
`onSave` saves the contact, then calls `setOpen(false)`. A dialog that holds its own state would stay open after
Save, because the editor's Save button is not a `Dialog.CloseTrigger`.
2. **Ask before deleting.** A popover is lighter than a dialog for a yes-or-no question. `Popover.CloseTrigger`
closes it without deleting:
```ts
import * as Button from '@dxos/react-ui/Button';
import * as Layout from '@dxos/react-ui/Layout';
import * as Popover from '@dxos/react-ui/Popover';
/** Asks before it deletes, in a popover beside the button. */
type DeletePopoverProps = {
label: string;
onDelete: () => void;
};
export const DeletePopover = ({ label, onDelete }: DeletePopoverProps) => (
Delete this contact?Keep
Delete
);
```
The destructive `Button.Root` calls `onDelete` and closes nothing itself. Step 4 clears the selection on a delete,
and the screen then stops rendering `DeletePopover`.
3. **Explain the role.** A tooltip can wrap any element, not only a button:
```ts
import * as Tooltip from '@dxos/react-ui/Tooltip';
import * as Typography from '@dxos/react-ui/Typography';
const ROLE_HELP: Record = {
viewer: 'Can read the contact book',
editor: 'Can change contacts',
admin: 'Can change contacts and who has access',
};
/** The role, with what it allows in a tooltip. */
export const Role = ({ role }: { role: string }) => (
{/* Focusable, so a keyboard user can open the tooltip too. */}
Role: {role}{ROLE_HELP[role]}
);
```
`ROLE_HELP` keeps its strings in the component for now. The next page moves them into a translation resource.
4. **Put them on the screen.** Edit and Delete go in the toolbar, after the gap that pushes them to the end.
`Toast.Provider` wraps the screen, and `Toast.Toaster` is where toasts appear. The toast is open while `saved`
holds a name.
Add the screen to the same file, and render it from `src/main.tsx`:
```ts
import { useState } from 'react';
import * as Layout from '@dxos/react-ui/Layout';
import * as Panel from '@dxos/react-ui/Panel';
import * as Toast from '@dxos/react-ui/Toast';
import * as Toolbar from '@dxos/react-ui/Toolbar';
import * as Typography from '@dxos/react-ui/Typography';
import { type Contact, CONTACTS } from '../contacts.ts';
import { ContactList } from '../layout/ContactsScreen.tsx';
export const ContactsScreen = () => {
const [contacts, setContacts] = useState(CONTACTS);
const [selected, setSelected] = useState(contacts[0].id);
const [saved, setSaved] = useState();
const contact = contacts.find(({ id }) => id === selected);
const handleSave = (next: Contact) => {
setContacts((contacts) => contacts.map((contact) => (contact.id === next.id ? next : contact)));
setSaved(next.name);
};
const handleDelete = (id: string) => {
setContacts((contacts) => contacts.filter((contact) => contact.id !== id));
setSelected(undefined);
};
return (
Contacts
{contact && }
{contact && handleDelete(contact.id)} />}
{contact && (
{contact.name}
{contact.email}
)}
!open && setSaved(undefined)}>
Contact saved{saved} was updated.
);
};
```
`Toast.Root` passes `onOpenChange` the boolean itself, where `Dialog.Root` passes an object that holds it. When
the toast times out, the handler clears `saved`, so the next save opens the toast again.
## Try it
Choose a contact and press Edit. Save a change, and the toast appears. Hover over the role, or tab to it, to see what
the role allows. Press Delete, then Keep or Delete.
## What you can do now
You can open dialogs and popovers from buttons, add tooltips to any element, and show toasts. Next,
[Icons and translations](/docs/tile/learn/icons-and-translations/) moves the screen's strings into a resource.
---
# Icons and translations
Icons beside each field, an Add button, and the screen's strings in a translation resource.
By the end of this page the screen's own strings come from a translation resource, and the count says "1 contact" or
"3 contacts" as it should. Icons mark the email and the role, and an Add button creates a contact.
## Background
Our first toolbar wrote its count as `{contacts.length} contacts`, which says "1 contacts" when one is left. A
translation resource holds both forms of the string and picks one from the number:
- A **translation resource** maps keys to strings for each language. It files them under a **translation
namespace**, a name that keeps one screen's keys apart from another's. Step 1 writes ours.
- `Hooks.useTranslation(ns)` returns `t`, which looks a key up in the user's language. If a key has `_one` and
`_other` forms, the `count` we pass chooses between them. Steps 2 and 3 call it.
An icon needs no import. We name it in full, as a string, such as `ph--envelope--regular` for
[Phosphor](https://phosphoricons.com)'s envelope in the regular weight. `IconsPlugin` finds the names in our code and
puts those icons in the sprite, the one file of icons it builds.
[Translations and icons](/docs/tile/concepts/translations-and-icons/) explains how resources merge, and what happens
to an icon whose name the build did not see.
## Steps
1. **Write the resource.** Use a namespace no other code uses, such as a reverse domain. `as const` lets TypeScript
check the keys we pass to `t`. Add `src/icons/translations.ts`:
```ts
import type * as Theme from '@dxos/react-ui/Theme';
export const ns = 'com.example.contacts';
export const translations = [
{
'en-US': {
[ns]: {
'title.label': 'Contacts',
'count.label_one': '{{count}} contact',
'count.label_other': '{{count}} contacts',
'add.label': 'Add contact',
'edit.label': 'Edit contact',
'delete.label': 'Delete contact',
'empty.message': 'Choose a contact',
'new-contact.name': 'New contact',
'role.viewer': 'Can read the contact book',
'role.editor': 'Can change contacts',
'role.admin': 'Can change contacts and who has access',
},
},
},
] as const satisfies Theme.Resource[];
```
`count.label_one` and `count.label_other` are two forms of one key, `count.label`.
2. **Mark the fields with icons.** `Icon.Icon` draws a sprite icon at the text's size. The role's tooltip text now
comes from the resource, keyed by the role. Add `src/icons/ContactsScreen.tsx`:
```ts
import * as Hooks from '@dxos/react-ui/Hooks';
import * as Icon from '@dxos/react-ui/Icon';
import * as Layout from '@dxos/react-ui/Layout';
import * as Status from '@dxos/react-ui/Status';
import * as Tooltip from '@dxos/react-ui/Tooltip';
import * as Typography from '@dxos/react-ui/Typography';
import { type Contact } from '../contacts.ts';
import { ns } from './translations.ts';
/** Each field beside an icon that says what it is. */
const ContactDetail = ({ contact }: { contact?: Contact }) => {
const { t } = Hooks.useTranslation(ns);
if (!contact) {
return {t('empty.message')};
}
return (
{contact.name}
{contact.email}
{/* Focusable, so a keyboard user can open the tooltip too. */}
{contact.role}{t(`role.${contact.role}`)}
);
};
```
Each `icon` prop is a whole name, which is how `IconsPlugin` finds it. A name put together at run time would not
be in the sprite.
3. **Use the strings.** The toolbar reads its text from `t`. Add is an icon button whose label is both its tooltip and
its name for screen readers. Edit and Delete take their labels as props, so we pass them in from `t` too.
Add this to the same file:
```ts
import { useState } from 'react';
import * as Button from '@dxos/react-ui/Button';
import * as Hooks from '@dxos/react-ui/Hooks';
import * as Layout from '@dxos/react-ui/Layout';
import * as Panel from '@dxos/react-ui/Panel';
import * as Toolbar from '@dxos/react-ui/Toolbar';
import { type Contact, CONTACTS } from '../contacts.ts';
import { ContactList } from '../layout/ContactsScreen.tsx';
import { DeletePopover, EditDialog } from '../overlays/ContactsScreen.tsx';
import { ns } from './translations.ts';
export const ContactsScreen = () => {
const { t } = Hooks.useTranslation(ns);
const [contacts, setContacts] = useState(CONTACTS);
const [selected, setSelected] = useState(contacts[0].id);
const contact = contacts.find(({ id }) => id === selected);
const handleAdd = () => {
const contact: Contact = {
id: crypto.randomUUID(),
name: t('new-contact.name'),
email: '',
role: 'viewer',
};
setContacts((contacts) => [...contacts, contact]);
setSelected(contact.id);
};
const handleSave = (next: Contact) =>
setContacts((contacts) => contacts.map((contact) => (contact.id === next.id ? next : contact)));
const handleDelete = (id: string) => {
setContacts((contacts) => contacts.filter((contact) => contact.id !== id));
setSelected(undefined);
};
return (
{t('title.label')}{t('count.label', { count: contacts.length })}
{contact && }
{contact && handleDelete(contact.id)} />}
);
};
```
`handleDelete` clears the selection, and `ContactDetail` then shows its hint. `EditDialog` and `DeletePopover` come
from the last page as they are, so the strings inside them are not in the resource yet. This screen also leaves
out the toast.
4. **Register the resource and render the screen.** `Theme.Provider` takes our resource beside react-ui's own. In
`src/main.tsx`, import react-ui's `translations` under the name `uiTranslations`, import ours and this page's
`ContactsScreen`, and replace the render:
```ts
import { createRoot } from 'react-dom/client';
import * as Theme from '@dxos/react-ui/Theme';
import { ContactsScreen } from './icons/ContactsScreen.tsx';
createRoot(document.getElementById('root')!).render(
,
);
```
A resource that is missing from `resourceExtensions` shows on screen as its keys, such as `add.label`.
## Try it
Delete contacts until one is left and watch the count. Press Add, then Edit to name the new contact.
## What you can do now
You can use icons by name and keep a screen's strings in a resource. Next,
[Connect to ECHO](/docs/tile/learn/connect-to-echo/) stores the contacts in a database that syncs.
---
# Connect to ECHO
Replace the screen's React state with ECHO's Person type, a live query and a schema form.
By the end of this page the contacts are objects in [ECHO](/docs/echo/overview/), DXOS's database. They are stored on
the device, and they sync to your other devices and to anyone you share the space with. The edit dialog is a form
built from their schema.
## Background
So far the contacts live in React state, which a reload resets and no other device sees. To move them into ECHO, we
change three things from the last page:
- An ECHO type replaces the `Contact` type. ECHO checks and syncs objects of a type it knows. Step 2 adds the type.
- `useQuery` replaces the `useState` that held the list. It returns the objects that match, and the component
renders again when one is added or removed, here or on another device. Step 7 makes the swap.
- `useObject` reads one object. A component that reads an object's fields this way renders again when that object
changes. Steps 4 and 5 use it.
We take the type from ECHO's own learning path. Its `Person` has a name, an email and an employer, and no role. The
role select, the role's tooltip and the `role.*` strings from the earlier pages therefore have no place on this
screen.
## Steps
1. **Install the React client and the form package.** `@dxos/react-client` holds the hooks, and
`@dxos/react-ui-form` holds the form. Until the next npm release, they come from the same build as the packages in
[Installation](/docs/tile/learn/installation/):
```sh
npm install \
https://pkg.pr.new/dxos/dxos/@dxos/react-client@20a14b9 \
https://pkg.pr.new/dxos/dxos/@dxos/react-ui-form@20a14b9
npm install --save-dev vite-plugin-wasm
```
Then add the bundler settings from step 2 of ECHO's [Installation](/docs/echo/learn/installation/) to
`vite.config.ts`, so the database's worker and WebAssembly load. Those settings use `vite-plugin-wasm`.
2. **Use ECHO's Person type.** This is the `Person` from ECHO's
[Defining types](/docs/echo/learn/defining-types/), with a name, an optional email and an optional employer. Add
`src/echo/schema.ts`. Put that page's `Organization` type in it first, because `employer` refers to it:
```ts
import * as Schema from 'effect/Schema';
import { Annotation, DXN, Format, Ref, Type } from '@dxos/echo';
export class Person extends Type.makeObject(DXN.make('com.example.type.person', '0.1.0'))(
Schema.Struct({
name: Schema.String,
email: Schema.optional(Format.Email),
employer: Schema.optional(Ref.Ref(Organization)),
}).pipe(Annotation.IconAnnotation.set({ icon: 'ph--user--regular', hue: 'cyan' })),
) {}
```
3. **Query the people.** The query selects every `Person`, sorted by name. Add `src/echo/ContactsScreen.tsx`:
```ts
import { Filter, Order, Query } from '@dxos/echo';
import { Person } from './schema.ts';
const people = Query.select(Filter.type(Person)).orderBy(Order.property('name', 'asc'));
```
`people` only describes the query. Nothing reads the database until step 7 passes it to `useQuery`.
4. **List them.** The list is the same `Listbox` as before. Each row reads its person with `useObject`, so a rename
shows in the list at once:
```ts
import { useObject } from '@dxos/react-client/echo';
import * as Listbox from '@dxos/react-ui/Listbox';
import { Person } from './schema.ts';
/** A row that re-renders when its person is renamed. */
const PersonRow = ({ person }: { person: Person }) => {
const [snapshot] = useObject(person);
return ;
};
type PeopleListProps = {
people: Person[];
selected?: string;
onSelect: (id: string) => void;
};
const PeopleList = ({ people, selected, onSelect }: PeopleListProps) => (
({ value: person.id, label: person.name }))}
value={selected ? [selected] : []}
onValueChange={([id]) => id && onSelect(id)}
>
{people.map((person) => (
))}
);
```
`useObject` returns a pair. `snapshot` is the first of the two, a copy of the person's fields as they are now.
The second is a function that changes the person.
5. **Show the selected person.** The detail reads the person the same way. It shows the name and the email, and no
role, because `Person` has none:
```ts
import { useObject } from '@dxos/react-client/echo';
import * as Icon from '@dxos/react-ui/Icon';
import * as Layout from '@dxos/react-ui/Layout';
import * as Typography from '@dxos/react-ui/Typography';
import { Person } from './schema.ts';
/** Re-renders when this person changes, here or on another peer. */
const PersonDetail = ({ person }: { person: Person }) => {
const [snapshot] = useObject(person);
return (
{snapshot.name}
{snapshot.email && (
{snapshot.email}
)}
);
};
```
6. **Edit with a schema form.** `ObjectForm` builds its fields from `Person`'s schema: a text field for the name, an
email field, and a picker of organizations for the employer. It writes each change to the object as it is made,
so the dialog needs no Save button. We no longer need the editor from
[Inputs and actions](/docs/tile/learn/inputs-and-actions/).
```ts
import { useObject } from '@dxos/react-client/echo';
import { ObjectForm } from '@dxos/react-ui-form';
import * as Button from '@dxos/react-ui/Button';
import * as Dialog from '@dxos/react-ui/Dialog';
import { Person } from './schema.ts';
/** A form built from `Person`'s schema; each change is written to the object as it is made. */
const EditDialog = ({ label, person }: { label: string; person: Person }) => {
const [snapshot] = useObject(person);
return (
{snapshot.name}
);
};
```
`Dialog.Root` takes no `open` now. With no Save to close the dialog, it can hold its own state.
[Form](/docs/tile/api/react-ui-form/form/) shows how to describe a form's fields and how to edit an ECHO object
with one.
7. **Write the screen.** Add puts a new object in the database with `db.add`, and Delete takes it out with
`db.remove`. Neither changes a list of our own. The query sees the change, and the list renders again.
```ts
import { useState } from 'react';
import { type Database, Obj } from '@dxos/echo';
import { useQuery } from '@dxos/react-client/echo';
import * as Button from '@dxos/react-ui/Button';
import * as Hooks from '@dxos/react-ui/Hooks';
import * as Layout from '@dxos/react-ui/Layout';
import * as Panel from '@dxos/react-ui/Panel';
import * as Status from '@dxos/react-ui/Status';
import * as Toolbar from '@dxos/react-ui/Toolbar';
import { ns } from '../icons/translations.ts';
import { DeletePopover } from '../overlays/ContactsScreen.tsx';
import { Person } from './schema.ts';
export const ContactsScreen = ({ db }: { db: Database.Database }) => {
const { t } = Hooks.useTranslation(ns);
const contacts = useQuery(db, people);
const [selected, setSelected] = useState();
const person = contacts.find(({ id }) => id === selected);
const handleAdd = () => {
const name: string = t('new-contact.name');
const person = db.add(Obj.make(Person, { name }));
setSelected(person.id);
};
const handleDelete = (person: Person) => {
db.remove(person);
setSelected(undefined);
};
return (
{t('title.label')}{t('count.label', { count: contacts.length })}
{person && }
{person && handleDelete(person)} />}
{person ? (
) : (
{t('empty.message')}
)}
);
};
```
`const contacts = useQuery(db, people)` is the line that replaces `useState(CONTACTS)`. One `useState` is left,
and it holds `selected`, the id of the chosen person, which `handleAdd` and `handleDelete` still set.
8. **Open a space.** A space is a database that its members share, and an identity owns the spaces it creates. The
first time the app runs, `setUp` creates an identity and then a space. `Contacts` shows the screen once the space
is there.
Add `src/echo/main.tsx`, starting with the same stylesheet imports as the first entry point,
`import '@dxos-theme';` and `import '@dxos/react-ui/theme.css';`:
```ts
import { type Client } from '@dxos/client';
import { useSpaces } from '@dxos/react-client/echo';
import { ContactsScreen } from './ContactsScreen.tsx';
/** Gives the app an identity the first time it runs, and a space to keep the contacts in. */
const setUp = async (client: Client) => {
if (!client.halo.identity.get()) {
await client.halo.createIdentity();
}
if (client.spaces.get().length === 0) {
await client.spaces.create({ name: 'Contacts' });
}
};
/** Shows the screen once the space is there. */
const Contacts = () => {
const [space] = useSpaces();
return space ? : null;
};
```
9. **Render it inside the client.** `ClientProvider` starts ECHO with the types the app uses, and runs `setUp`
once the client is ready. Its config is the one from ECHO's [Installation](/docs/echo/learn/installation/) page.
The config keeps the data across reloads, and reaches other devices through [EDGE](/docs/edge/overview/), the
always-online peer that DXOS runs.
The theme provider goes inside it, and now also registers `@dxos/react-ui-form`'s strings:
```ts
import { createRoot } from 'react-dom/client';
import { Config } from '@dxos/config';
import { ClientProvider } from '@dxos/react-client';
import * as Theme from '@dxos/react-ui/Theme';
import { Organization, Person } from './schema.ts';
/** Keeps the data across reloads and reaches other devices through EDGE, as the ECHO learning path's app does. */
const config = new Config({
runtime: {
client: {
storage: { persistent: true },
edgeFeatures: { signaling: true, subductionReplicator: true, feedReplicator: true },
},
services: {
edge: { url: 'https://dxos.network/' },
iceProviders: [{ urls: 'https://dxos.network/ice' }],
},
},
});
/** Runs the database in a worker, in the browser's private file system. */
const createOpfsWorker = () => new Worker(new URL('@dxos/client/opfs-worker', import.meta.url), { type: 'module' });
createRoot(document.getElementById('root')!).render(
,
);
```
Then point `index.html` at `src/echo/main.tsx`.
## Try it
Run the app and add a few contacts. Reload, and they are still there.
To see the contacts sync, a second browser profile has to join the space, and this screen has no way to invite one.
ECHO's [Sharing a space](/docs/echo/learn/sharing/) adds an invitation. With that in place, edits in one window
appear in the other.
## What you can do now
You can build a screen with TILE whose data lives in ECHO. From here:
- The API section covers each component package, such as [Listbox](/docs/tile/api/react-ui-list/listbox/),
[Form](/docs/tile/api/react-ui-form/form/), [ActionToolbar](/docs/tile/api/react-ui-menu/action-toolbar/) and
[Editor](/docs/tile/api/react-ui-editor/editor/).
- [TILE in a PLEX plugin](/docs/tile/guides/tile-in-a-plex-plugin/) shows how this screen would become a plugin for
[Composer](/composer), DXOS's local-first workspace.
---
# Theme and tokens
Semantic tokens, cascade layers, and `classNames` instead of `className`.
A token is a CSS custom property that holds one of TILE's colors or sizes. You style with tokens by role, never by
value, so one change to the theme reaches every component and every plugin.
## Model
A CSS variable lets you name a value once and use it in many rules. A token goes one step further. Its name says what
the value is for, such as a card's surface, not what the value is.
### Tiers
Color tokens come in three tiers. The table starts with the raw values, and each tier is built from the tiers above it
in the table:
| Tier | Example | Use |
| -------- | ---------------------------------------------------------------- | ------------------------------------------------------- |
| Scale | `--color-neutral-150`, `--color-blue-600` | Raw values. A component never uses one directly |
| Hue role | `--color-red-surface`, `--color-red-fg` | One set of roles per hue, for color that carries data |
| Semantic | `--color-card-surface`, `--color-fg-muted`, `--color-error-text` | Named surfaces and roles of the UI. Reach for this tier |
You use a token through a class. Every `--color-` token yields the Tailwind utilities `bg-`, `text-`
and `border-`. For example, `--color-card-surface` gives `bg-card-surface`.
### Names
A color token is named `{name}-{kind}[-{state}]`. The name says what the token is for, such as `card`, `accent` or
`error`. The kind says what the color paints, and it is one of five words:
- `surface` is a background.
- `fg` is text on that surface.
- `bg` is a solid fill, such as a primary button.
- `border` is a border on the surface.
- `text` is text on the page itself, with no surface.
A state such as `hover` comes last. For example, `accent-bg-hover` is the fill of a primary button while the pointer
is over it.
### Light and dark
A semantic token holds its light value and its dark value together, with CSS `light-dark()`. The theme sets
`color-scheme: dark` under the `dark` class, so the browser picks the dark value there.
### Status colors
Four names are status colors, and each is an alias of a hue: `info` is sky, `success` is emerald, `warning` is amber
and `error` is rose. Each has all five kinds, so `text-error-text` and `bg-warning-surface` both exist. A **valence**
is the status a component shows. A component's `valence` prop takes one of these four, or `neutral`, which carries no
status and uses the neutral hue.
### Surface levels
A **surface** is a background that content sits on. Surfaces form a ladder of six **levels**, from `sunken` up through
`chrome`, `base`, `raised` and `overlay` to `popup`. A higher surface is lighter in dark mode, so a menu reads as
sitting above a card, which sits above the page.
| Level | Named surfaces |
| --------- | ---------------------------------------------------- |
| `sunken` | `deck-surface` |
| `chrome` | `sidebar-surface`, `header-surface` |
| `base` | `base-surface` |
| `raised` | `card-surface`, `modal-surface` (dialogs) |
| `overlay` | None. Set this level on an element to lift it higher |
| `popup` | `popover-surface`, for menus, popovers and toasts |
The levels `overlay` and `popup` name backgrounds. An overlay, by contrast, is a component that TILE draws above the
page, such as a dialog or a menu, and it need not sit at the `overlay` level. A dialog draws on `modal-surface`, at
the `raised` level.
### Cascade layers
The theme puts its rules in named cascade layers, in this order: `properties`, `theme`, `dx-tokens`, `user-tokens`,
`base`, `tw-base`, `dx-base`, `components`, `tw-components`, `dx-components` and `utilities`. Your app's own styles
outside any layer win over all of them.
The theme declares its tokens in `theme`. In `dx-tokens` it sets its line widths and gutters, and the values that
change with a surface or with a density, which is how compact a region's controls are.
`user-tokens` comes after both, so a token value you set in that layer replaces the default.
[Custom themes and dark mode](/docs/tile/guides/custom-themes/) sets an accent color this way.
### Generated CSS
`ThemePlugin` generates the CSS when your app builds. It runs Tailwind over your sources and the components'
stylesheets, and a class that no scanned file names is not in the CSS. A class built from a string at run time, such
as `` `bg-${hue}-surface` ``, is never seen, so name classes in full.
## Behavior
**Overrides go through `classNames`.** A themed component takes a `classNames` prop, which is a string or an array of
strings, and merges it after its own classes. `className` is not among its props.
**Example** (Passing a width class to a button)
```tsx
Save
```
`w-full` is a layout hint, like a margin, and layout hints are what `classNames` is for. Pass color through tokens,
never as a raw value.
**Components read `--dx-*` variables.** These hold their sizes and states, such as `--dx-block-size` for a control's
height and `--dx-focus-ring-color` for its focus ring. If you set one on an element, it changes the components inside
it.
## Limits
- A guessed token name is not an error. `bg-input` or `text-primary` produce no CSS, and the element falls back to
inherited colors that may be unreadable in one mode. Check the name against the theme's CSS, or copy it from an
existing component.
- Hue-role and scale tokens do not follow the semantic ladder. A `bg-red-surface` stays red in both modes, so use it
only where the color carries meaning.
---
# Composite components
One namespace per component, and one part per element.
A composite component is a TILE component with more than one element, written as a namespace of parts. A dialog, for
example, is `Dialog.Root`, `Dialog.Trigger`, `Dialog.Content`, `Dialog.Title` and so on. You compose the parts in JSX,
in the shape you want.
## Model
If you have used Radix or Ark UI, you already know the shape. Those libraries split a component into parts that you
arrange yourself, where others give you one `Dialog` and a prop for each thing it can show. TILE does the same.
**One entry point, one namespace.** Each component is its own entry point of `@dxos/react-ui`. You import it as a
**namespace**, the object that holds its parts:
```ts
import * as Dialog from '@dxos/react-ui/Dialog';
import * as Input from '@dxos/react-ui/Input';
```
A few namespaces group related components. `Button` holds `Root`, `Group`, `Menu` and `Toggle`. `Input` holds `Root`,
`Checkbox`, `Switch`, `Textarea` and the other controls. `Layout` and `Status` each hold several small components,
which [Layout](/docs/tile/api/layout/) and [Status](/docs/tile/api/status/) list.
**Parts.** A **part** is one element of the component. `Root` holds the state, and renders either no element or the
outer one. The other parts each render one element and read the state from `Root` through React context.
A part you leave out renders nothing, so you decide what a component shows by the parts you write.
**Example** (Composing a dialog from its parts)
```ts
import * as Button from '@dxos/react-ui/Button';
import * as Dialog from '@dxos/react-ui/Dialog';
import * as Field from '@dxos/react-ui/Field';
import * as Input from '@dxos/react-ui/Input';
export const EditDialog = () => (
Edit contactEdit contact
Changes are saved when you press Save.
NameCancelSave
);
```
`Dialog.Root` takes no props here, so it holds the open state itself. `Dialog.Trigger` opens the dialog, and each
`Dialog.CloseTrigger` closes it.
**`asChild`.** A part with `asChild` renders no element of its own. It becomes a slot for its single child, and
passes its props, ref and handlers to that child. Use `asChild` when the child is already the element you want. In
the example above, `Dialog.Trigger asChild` makes the `Button.Root` the trigger, where the trigger would otherwise
wrap it in a second button.
**Behavior from state machines.** The parts are built on [Ark UI](https://ark-ui.com), whose components run
[zag](https://zagjs.com) state machines. The machine owns opening, closing, keyboard handling and the ARIA attributes,
and each part spreads the props the machine gives it.
## Behavior
- ARIA roles and state attributes on interactive parts come from the machine, so don't add them to such a part.
- An icon-only part still needs an accessible name, such as `aria-label` or a component's `label`.
- Layout primitives are different. `Layout.Grid` defaults to `role='none'`, so give it a role such as `list` when you
use it with `asChild` around a list.
- A component that can be controlled takes `open` and `onOpenChange`, or `value` and `onValueChange`. If you leave them
out, it works uncontrolled.
- Every part takes `classNames` for overrides. [Theme and tokens](/docs/tile/concepts/theme-and-tokens/) says what to
pass in it.
## Limits
- `asChild` needs exactly one child element that forwards its ref and spreads its props. A TILE component does both.
A plain function component that drops its props does not. In development, a part such as `Panel.Body` or
`Layout.Flex` logs a warning for a child like that.
- A part needs its `Root` above it. Outside one it has no state to read, and it fails.
---
# Layout
The Panel and ScrollArea container model, and the layout primitives.
TILE lays out a screen with a few components instead of hand-written flex and grid classes. A `Panel` is the shell of
a pane, `ScrollArea` makes its body scroll, and the layout primitives, such as `Flex`, `Grid` and `Container`, arrange
what is inside.
## Model
A pane with a fixed header and a scrolling body is easy to get wrong by hand. It takes a flex column, a
`min-height: 0` and an `overflow`, each on the right element, and if you miss one, the whole page scrolls where the
pane should. With TILE, you compose the pane from a panel and a scroll area instead.
**A panel has three rows.** `Panel.Root` is a grid whose rows are `Panel.Header`, `Panel.Body` and `Panel.Footer`. The
header and footer take the height of their content, and the body takes the rest.
Use a panel as the outer shell of a pane. It fills its parent, so its parent needs a height.
**The height chain.** The height chain is the run of elements from the panel down to the content that scrolls. For
the body to scroll, each of them must pass its height down.
`Panel.Body asChild` makes the `ScrollArea.Root` the body itself, and `ScrollArea.Viewport asChild` makes the content
the viewport. This way, no extra element breaks the chain.
**Example** (Building a panel with a scrolling body)
```ts
import * as Button from '@dxos/react-ui/Button';
import * as Icon from '@dxos/react-ui/Icon';
import * as Layout from '@dxos/react-ui/Layout';
import * as Panel from '@dxos/react-ui/Panel';
import * as ScrollArea from '@dxos/react-ui/ScrollArea';
import * as Toolbar from '@dxos/react-ui/Toolbar';
import * as Typography from '@dxos/react-ui/Typography';
export const ContactsPanel = () => (
Contacts
{CONTACTS.map((name) => (
{name}
))}
{CONTACTS.length} contacts
);
```
`ContactsPanel` puts four parts between the panel and its rows: the body, the scroll area's root, its viewport and a
`Layout.Container`. The two `asChild` lines fold them into two elements. Each row's icon sits in a `Layout.Block`, in
the rail that `gutter='rail'` leaves.
**Layout primitives.** A layout primitive is one of the six components in the `Layout` namespace, which place
content and own its spacing. `Flex`, `Grid` and `Container` take `asChild`, so you can lay out a semantic element such
as a `` or `
` without an extra wrapper. `Block`, `Columns` and `Separator` do not take it. The table says
what each one arranges and when to use it:
| Primitive | Arranges |
| ----------- | ---------------------------------------------------------------------------------------------- |
| `Flex` | Children along one axis. Use it for a row of controls or a stack of fields. Its props are `column`, `gap`, `align`, `justify`, `wrap`, `grow` and `center` |
| `Grid` | Children in tracks. Use it when columns must line up, or when one track has a fixed size. `cols={3}` gives equal columns, `cols={['min', 'fill']}` a label column and the rest, and `cols='subgrid'` the parent's tracks |
| `Container` | Content between two gutters, so rows line up with the panel's edges. Use it for the rows of a panel's body. `gutter='rail'` leaves room for an icon column |
| `Block` | One slot in the rail of a `Container`, sized so an icon and an icon button line up. Use it for the icon at the start or the end of a row |
| `Columns` | A horizontal run of as many columns as fit, which scrolls one column at a time. Use it for a drill-down, where each choice opens a column beside the last |
| `Separator` | A rule between groups. Use it to part two groups of rows or of controls |
A **gutter** is the space at the start and at the end of the rows of a `Layout.Container`.
**`gap` takes steps, not numbers.** `Flex` and `Grid` take `gap='xs'` through `'2xl'`, plus `'form'` and
`'form-section'` for the spacing between fields. Steps keep the spacing the same from one screen to the next. A
literal such as `gap-2`, passed in `classNames`, still applies, and that screen then drifts from the rest.
## Behavior
- Width and height use physical classes: `w-*`, `h-*`, `min-w-*` and `max-h-*`. A physical class names an axis of the
screen, which is the same in every language.
- Spacing that depends on the reading direction uses logical classes: `ps-*` and `pe-*` for padding, `ms-*` and
`me-*` for margin, and `start-*` and `end-*` for insets. A logical class names the start or the end of a line, so
it flips in a right-to-left language.
- By default, `Flex` sets no `align`, so children stretch as they do in plain CSS.
- `grow` on a `Flex` or `Grid` makes it take the slack of its parent and clip what overflows. A child that scrolls
needs that from its parent, as a link in the height chain.
## Limits
- If you put a wrapper `` between `Panel.Body` and the scrolling content, it breaks the height chain, and the
content grows instead of scrolling. Use `asChild` instead.
- Components such as forms and lists own their spacing. If you add padding around them, you double it.
---
# Density and sizes
One size scale, set on an element and inherited by everything inside it.
Every TILE control takes its height, text size, icon size and spacing from one scale with five steps: `xs`, `sm`, `md`,
`lg` and `xl`. When you set a size on an element, the controls inside it follow.
## Model
To make one toolbar compact by hand, you override the height and the padding of every control in it. With TILE, you
set the size once, on the toolbar, and the controls inside read it.
**Density** is how compact a region's controls are, and a **size** is the step of the scale that sets it. A smaller
size makes the controls shorter, with smaller text, smaller icons and narrower gaps.
**A size is an attribute.** A component that takes a `size` prop sets `data-size` on its element. The theme defines,
for each step, variables such as `--dx-block-size` (a control's height), `--dx-font-size`, `--dx-icon-size` and
`--dx-gap-size`. Every control reads these variables instead of fixed values.
**Sizes inherit.** A control without its own `size` uses the nearest one above it. `Panel.Root`, `Toolbar.Root`,
`Layout.Container`, a field header, a dialog and a button all take `size`. Outside any of them, controls use `md`.
**Example** (Setting a size on three toolbars)
```ts
import * as Button from '@dxos/react-ui/Button';
import * as Input from '@dxos/react-ui/Input';
import * as Layout from '@dxos/react-ui/Layout';
import * as Toolbar from '@dxos/react-ui/Toolbar';
export const Sizes = () => (
{(['sm', 'md', 'lg'] as const).map((size) => (
Save
))}
);
```
`Toolbar.Root` is the only component here that takes a `size`. The buttons and the input inside it name none, so
each row of controls follows its toolbar.
## Behavior
- An overlay takes the size of its trigger. For example, a popover opened from a `sm` toolbar is `sm` too, though the
popover renders in a portal outside the toolbar.
- A menu is the exception. It is `md` wherever it opens, and a submenu takes the size of the menu it opens from.
- An overlay's content can name its own `size` to break from its trigger. Use this for a dialog that should be `lg`
wherever it opens.
- Labels read one text step below the body at the same size, and helper text one step below that.
## Limits
- A fixed height or padding set with `classNames` does not follow the scale. Set a size instead.
- `data-size` takes effect only on TILE's own elements. If you set it on a plain ``, it changes nothing. Use a
`Layout.Container` with `size` instead.
---
# Focus and keyboard
The focus ring, arrow-key navigation, and focus inside overlays.
Every TILE control works from the keyboard, and shows where the focus is with the same ring. Most of this comes with
the components. This page says what you can expect and what you need to keep intact.
## Model
On the web, a `