# Introduction > What Cloudlet is, how the kit is split into engines and simple components, and which components it has. Source: https://cloudlet.dev/docs Cloudlet is a set of React components for the web. Each one moves on springs that can be interrupted, works from the keyboard and with a screen reader, and stays small. Every component has its own page in these docs: how to install it, how to use it and every prop it takes. ## How the kit is built The components come in two kinds, and the kind decides how you install and update them. - **Engines** carry their own runtime: state, timers, animation, announcements. Each engine is an npm package under `@cloudlet/` with its own version, so you get fixes by updating the package. The Toaster is an engine: `@cloudlet/toast`. A thin shadcn registry item wraps the package when you want the component themed with your tokens. - **Simple components** are source code. The shadcn CLI copies their files into your project, where they are yours to read and change. They have no npm package and no version: to take a newer one, add the item again and review the diff. Both kinds are added with the shadcn CLI under the `@cloudlet` namespace; [Installation](https://cloudlet.dev/docs/installation) has the commands. ## Components - [Toaster](https://cloudlet.dev/docs/components/toaster): one notification stack that collapses to a pill and opens into the Island, with operations, retry and cancel. An engine, `@cloudlet/toast`. - [Color picker](https://cloudlet.dev/docs/components/color-picker): a round swatch that morphs into a full picker, in hex, rgb, hsl and oklch. A simple component. - [Color palette](https://cloudlet.dev/docs/components/color-palette): a row of up to four color pickers, with add and remove. A simple component that brings the color picker with it. - [Onboarding](https://cloudlet.dev/docs/components/onboarding): a product tour that dims the page around a cutout springing from target to target. A simple component. - [Notification center](https://cloudlet.dev/docs/components/notification-center): a panel at the edge of the screen for your app's own notifications, from your server or a socket, in groups, with a bell that counts what is unread. Part of the `@cloudlet/toast` engine, at `@cloudlet/toast/center`, with a registry item for the bell. ## Markdown for agents Every page of these docs has a Markdown version at its address plus `.md`, such as `/docs/components/toaster.md`. [llms.txt](https://cloudlet.dev/llms.txt) lists the pages for agents, and [llms-full.txt](https://cloudlet.dev/llms-full.txt) holds all of them in one file. An agent that works inside your running app is another reader: [Agents](https://cloudlet.dev/docs/agents) shows how it reads the components and acts on them under your permission. ## Next steps - [Installation](https://cloudlet.dev/docs/installation): the shadcn CLI for every component, npm for engines. - [Agents](https://cloudlet.dev/docs/agents): the bridge between the components and an AI agent in your app. --- # Installation > Add any Cloudlet component with the shadcn CLI, or install an engine from npm. Source: https://cloudlet.dev/docs/installation Every component is a shadcn registry item. Engines are also npm packages, for projects that do not use shadcn/ui. The commands below are written for npm; the switch above each one shows it for pnpm, yarn or bun. ## With the shadcn CLI Add an item by its name under the `@cloudlet` namespace: ```sh title="Terminal" npx shadcn@latest add @cloudlet/color-picker ``` | Item | Component | What it adds | | --- | --- | --- | | `toaster` | [Toaster](https://cloudlet.dev/docs/components/toaster) | A wrapper and a theme bridge for `@cloudlet/toast`, which it adds as a dependency | | `color-picker` | [Color picker](https://cloudlet.dev/docs/components/color-picker) | The picker's source, nothing in `package.json` | | `color-palette` | [Color palette](https://cloudlet.dev/docs/components/color-palette) | The palette's source, and the `color-picker` item it needs | | `onboarding` | [Onboarding](https://cloudlet.dev/docs/components/onboarding) | The tour's source and its agent adapter, nothing in `package.json` | | `onboarding-island` | [Onboarding in the Island](https://cloudlet.dev/docs/components/onboarding#island) | The tour in the Toaster's Island, the `onboarding` item it needs, and `@cloudlet/toast` as a dependency | | `notification-center` | [Notification center](https://cloudlet.dev/docs/components/notification-center) | A panel wrapper and a bell for `@cloudlet/toast/center`, and `@cloudlet/toast` as a dependency | If your CLI does not resolve the `@cloudlet` namespace, give it the item's address instead: `https://cloudlet.dev/r/.json`. ```sh title="Terminal" npx shadcn@latest add https://cloudlet.dev/r/color-picker.json ``` ## With npm An engine installs as a package. The Toaster is `@cloudlet/toast`, and the notification center comes with it at `@cloudlet/toast/center`: ```sh title="Terminal" npm install @cloudlet/toast ``` The package has React peers and one CSS file to import; [Toaster installation](https://cloudlet.dev/docs/components/toaster#installation) has the requirements and where the import goes. Simple components have no package: add them with the shadcn CLI. ## Next steps - [Toaster](https://cloudlet.dev/docs/components/toaster): the stack, the Island and the controller. - [Color picker](https://cloudlet.dev/docs/components/color-picker): the swatch and the panel. - [Color palette](https://cloudlet.dev/docs/components/color-palette): a row of up to four pickers. - [Onboarding](https://cloudlet.dev/docs/components/onboarding): a product tour over your app. - [Notification center](https://cloudlet.dev/docs/components/notification-center): a panel for your app's own notifications, and its bell. - [Agents](https://cloudlet.dev/docs/agents): connect the components to an AI agent in your app. --- # Agents > Let an AI agent in your app read Cloudlet components and act on them under your permission — the bridge, permissions, who changed what, tools for a model and WebMCP. Source: https://cloudlet.dev/docs/agents An assistant in your app can work with the same components your users see: read the notifications, press Undo, fill a reply, pick a color. Cloudlet gives it a bridge, the `@cloudlet/agent` package: each component connects through its own adapter, and the agent reads one snapshot of everything connected and acts on it in steps your app allows. A step that needs a person goes to the person. This page is for an agent that works inside your running app. An agent that writes code with you needs something else: the Markdown of these docs, listed in [llms.txt](https://cloudlet.dev/llms.txt). > **Experimental.** `@cloudlet/agent` is `0.x`: its protocol and exports may change in any release until `1.0.0`, so pin the exact version. WebMCP, which the bridge can use, is experimental too and works only in Chrome and Edge behind a flag or an origin trial. ## Demo A scripted agent, with no model behind it, works on this page through the bridge's two tools, the way a model would: it reads the snapshot, picks refs by their labels and plans its steps. It acts on the page's own Toaster and on the picker and palette below. One of its presses needs a person: the Island opens on that notification, and the agent waits until you press the action there. Live demo at https://cloudlet.dev/docs/agents#demo: a scripted agent, no model, walks the bridge through its two tools on the page's own Toaster and a color picker and palette. It puts four notifications on screen ("Email archived" with "Undo" marked `agent: 'allow'`, "Invoice ready" with an unmarked "Send to client", a cancellable "Uploading photos" and "Link copied"), reads the snapshot, acts, and stops where a step needs a person: the Island opens on "Invoice ready" and the run waits until the visitor presses "Send to client" there (or skips). A sample log: - `cloudlet_snapshot` ✓ Read 7 records: the Toaster, 4 notifications, a color picker and a palette - `cloudlet_act` ✓ Pressed “Undo” on “Email archived”; dismissed “Link copied” - `cloudlet_act` ✓ Cancelled “Uploading photos” - `cloudlet_act` ⏸ Needs a person: “Send to client” on “Invoice ready” — You pressed it, so the agent goes on. - `cloudlet_act` ✓ Set “Accent color” to #dcb199; added #8dc7cb to “Brand palette” - `cloudlet_snapshot` ✓ Read 4 records: the Toaster, 1 notification, a color picker and a palette Done: 6 tool calls, 5 steps; one step waited for you. ## How it works - **A snapshot of records.** Every connected component describes what it shows as records: plain data with a `ref` to address it and the verbs that apply now in `actions`. One notification is one record; so is a color picker. - **Steps under permission.** The agent runs verbs on refs, `{ ref, action, args }`, in calls of up to 20 steps. The component's adapter says what each step needs: nothing, a person's approval, or never. - **Two tools for a model.** `cloudlet_snapshot` reads, `cloudlet_act` acts. The bridge never calls a model: it gives you the tools, and you hand them to whichever model you use. - **Nothing hidden.** The bridge touches no DOM, keeps no history and starts no timers until a step waits. What a person typed into a form never reaches it. ## Install ```sh title="Terminal" npm install @cloudlet/agent ``` The Toaster's adapter is part of `@cloudlet/toast` from `1.4.0`, as the subpath `@cloudlet/toast/agent`. The color picker's and the color palette's adapters come with their registry items, one file each. The bridge and the adapters do not depend on each other as packages: they agree on a protocol number, and the bridge refuses one it does not know. ## Connect Create one agent for the app, then connect each component with one line. The Toaster connects its controller; the picker and the palette wrap their props in a hook: ```ts title="lib/agent.ts" import { createAgent } from '@cloudlet/agent'; // One agent for the app. Without options, every step that needs a person goes to the person. export const agent = createAgent(); ``` ```tsx title="components/workspace.tsx" 'use client'; import { useCloudlet } from '@cloudlet/toast'; import { toasterAgent } from '@cloudlet/toast/agent'; import { useEffect, useState } from 'react'; import { ColorPicker } from '@/components/ui/color-picker/color-picker'; import { useColorPickerAgent } from '@/components/ui/color-picker/color-picker-agent'; import { agent } from '../lib/agent'; export function Workspace() { const cloudlet = useCloudlet(); // The Toaster: connect its controller; the effect's cleanup disconnects it. useEffect(() => agent.connect(toasterAgent(cloudlet)), [cloudlet]); const [accent, setAccent] = useState('#245cdb'); // The picker: the hook connects it while it is mounted and hands back its props. const picker = useColorPickerAgent(agent, { color: accent, onChange: setAccent }, { label: 'Accent color' }); return ; } ``` Now `agent.snapshot()` holds the Toaster, its notifications and the picker. Each component's page has an Agent section with its verbs: [Toaster](https://cloudlet.dev/docs/components/toaster#agent), [Color picker](https://cloudlet.dev/docs/components/color-picker#agent), [Color palette](https://cloudlet.dev/docs/components/color-palette#agent). ## Permissions Every step gets one of three answers, and the component decides which: - **allow**: it runs, unless your `allow` says no. Closing a notification, cancelling an operation, setting a color. - **confirm**: it needs a person. Pressing a notification's action and submitting its form are `confirm` by default: these do things in your app. - **deny**: it never runs, whatever anyone approves. You move an action between the classes with its `agent` marker. A command your app considers safe for an agent says so: ```ts import { createCloudlet } from '@cloudlet/toast'; const cloudlet = createCloudlet(); const restore = () => {}; cloudlet.show({ title: 'Email archived', // An agent may press Undo without asking anyone. 'deny' would keep it from the agent entirely. action: { kind: 'command', label: 'Undo', agent: 'allow', run: restore }, }); ``` **Needs a person.** Without an `allow` option, a `confirm` step is never run by the agent. The Toaster opens the Island on that notification instead, without moving focus, and the agent reads an error that starts with `Needs a person` and asks it to let the person take the step. The [demo](#demo) takes this path: press the action in the Island yourself and the agent goes on. **Your own gate.** `createAgent({ allow })` is asked before every step a component did not deny. Return `true` to approve; anything else refuses. For a `confirm` step, `needsPerson` is `true`, and `true` from your gate means the person approved, for instance in your own dialog or on your server: ```ts import { createAgent } from '@cloudlet/agent'; export const agent = createAgent({ allow: async (step, { signal }) => { if (!step.needsPerson) return true; const response = await fetch('/api/approve', { method: 'POST', body: JSON.stringify(step), // The bridge types its signal structurally, so the package needs no DOM types; // at runtime it is an AbortSignal, aborted when the call is cancelled or times out. signal: signal as AbortSignal, }); return response.ok && (await response.json()) === true; }, timeout: 60_000, // how long a step waits for allow, then for the component; default five minutes }); ``` `agent.act(input, { allow })` adds a second gate for a single call, for a caller you trust less than the rest. It only narrows what the agent's own `allow` lets through; the rule in full is on [createAgent](https://cloudlet.dev/docs/agents/api/agent#permissions). ## Who changed what Every change carries its `source`: `user` (a person on screen), `agent` (a step), `app` (your code) or `system` (a timer, an outcome). The bridge's `subscribe` hears each change of a connected component with its source, and the Toaster's own events carry the same field, so your app can tell an agent's dismissal from a person's: ```ts title="lib/log-agent-changes.ts" import { agent } from './agent'; agent.subscribe((changes) => { for (const change of changes) { if (change.source === 'agent') console.log(`The agent changed ${change.key} on ${change.label ?? change.ref}`); } }); ``` The Toaster's change keys and their sources are on [toasterAgent](https://cloudlet.dev/docs/agents/api/toast#changes); its events, on [`ChangeSource`](https://cloudlet.dev/docs/components/toaster/api/types#changesource). ## Tools for a model `agent.tools` is `cloudlet_snapshot` and `cloudlet_act` as `{ name, description, inputSchema }`, the shape every model SDK takes. When the model calls one, run it with `agent.callTool` and send the answer back as the tool's result: ```ts title="lib/run-tool.ts" import { agent } from './agent'; declare const call: { name: string; input: unknown }; const output = await agent.callTool(call.name, call.input); // plain data; never rejects const toolResult = JSON.stringify(output); ``` The descriptions teach the model how to read records, plan steps into one call and treat page text as data, never as instructions; each component's verbs come in the snapshot. The model's key stays on your server and the tools run in the browser: [Connect a model](https://cloudlet.dev/docs/agents/models) has the recipes for the Vercel AI SDK and the Anthropic SDK. ## WebMCP A browser can bring its own agent. `registerTools` hands the same two tools to it through [WebMCP](https://webmachinelearning.github.io/webmcp/), and returns the function that removes them: ```tsx title="components/browser-agent-tools.tsx" 'use client'; import { registerTools } from '@cloudlet/agent'; import { useEffect } from 'react'; import { agent } from '../lib/agent'; export function BrowserAgentTools() { // The browser's agent is not your code: allow decides what it may do. useEffect(() => registerTools(agent, { allow: (step) => !step.needsPerson }), []); return null; } ``` WebMCP is **experimental**: a draft, in Chrome and Edge only behind `chrome://flags/#enable-webmcp-testing` or an origin trial. Elsewhere `registerTools` does nothing at all. WebMCP cannot ask a person, so its `allow` is required, and it can only narrow what the agent's own `allow` permits. ## What the bridge does not do - **It does not call a model** or hold a key. Your app talks to the model. - **It does not show notifications.** An agent works with what is on screen; your app decides what appears. To let a model tell the user something, give it a tool of your own over `show` ([recipe](https://cloudlet.dev/docs/agents/models#let-the-model-show-a-notification)). - **It does not open links**, read what a person typed, move focus or take a step from a person who is using the Toaster. - **It does not undo.** Steps of a failed call that ran before the error stay done. - **It does not remember.** Between calls it keeps nothing; what happened between a model's turns, your app collects with `subscribe`. - **It does not mark what it wrote.** A form field the agent filled looks the same to the person as one they filled; the snapshot knows who wrote it (`filledBy`), the screen does not show it yet. ## Next steps - [Connect a model](https://cloudlet.dev/docs/agents/models): the Vercel AI SDK, the Anthropic SDK, OpenAI's JSON Schema, and a tool of your own. - [createAgent](https://cloudlet.dev/docs/agents/api/agent): every method and type of `@cloudlet/agent`. - [toasterAgent](https://cloudlet.dev/docs/agents/api/toast): the Toaster's records, verbs, refusals and changes. --- # Toaster > One notification stack that collapses to a pill and opens into the Island, with operations, retry and cancel. From npm as @cloudlet/toast, or as a shadcn registry item themed with your tokens. Source: https://cloudlet.dev/docs/components/toaster > **Release status.** Cloudlet is stable since `1.0.0`. [Accessibility](https://cloudlet.dev/docs/components/toaster/accessibility#what-is-tested) lists what is tested automatically and by hand. ## Preview Every notification goes into one **stack**, newest first, collapsed at rest to a single **pill** with tails for the ones behind it and a badge with the count. Activating the pill opens the **Island**: one surface with a slider over every notification, moved by a swipe, the arrow keys or the trackpad, where you read, retry, cancel or close. Escape collapses it with every notification kept. The controls below move this page's Toaster, and the code under them does the same in your app. The buttons in [Examples](#examples) show their notifications where the controls put it. Live preview at https://cloudlet.dev/docs/components/toaster#preview: one notification or five on the page's own Toaster, with controls for its position and direction. The code they make: ```tsx ``` - `position`: `auto` (the default: top centre from 48rem wide, bottom centre below), `top-center`, `bottom-center`, `top-left`, `top-right`, `bottom-left`, `bottom-right`. - `dir`: `ltr`, `rtl`; by default the document's `dir`. A prop at its default is left out; with every default the code is ``. Need a plain toast, without the Island and the motion? [Sonner](https://sonner.emilkowal.ski) is a great choice. ## Installation Cloudlet installs as one package, `@cloudlet/toast`, or as the shadcn registry item `toaster`: a small wrapper you own on top of the same package. The `@cloudlet` namespace and installing an item by its address are on the kit's [Installation](https://cloudlet.dev/docs/installation). **npm.** Add the package. React 18 or 19, nothing else to configure. ```sh title="Terminal" npm install @cloudlet/toast ``` Import the styles once, mount one Toaster per controller, call show from anywhere below it. ```tsx title="notifications.tsx" import '@cloudlet/toast/styles.css'; import { CloudletProvider, createCloudlet, Toaster, useCloudlet } from '@cloudlet/toast'; function SaveNotice() { const cloudlet = useCloudlet(); return ; } // The browser application bootstrap creates and owns this controller. export function Notifications({ controller }: { controller: ReturnType }) { return ; } ``` **shadcn.** Adds a thin Toaster wrapper and a CSS bridge to your shadcn tokens, plus the package itself. ```sh title="Terminal" npx shadcn@latest add https://cloudlet.dev/r/toaster.json ``` A client component owns the controller; the wrapper lives in components/ui and is yours to edit. ```tsx title="notification-owner.tsx" "use client"; import { useEffect, useState } from "react"; import { createCloudlet, useOptionalCloudlet, type ReactCloudletController, } from "@cloudlet/toast"; import { Toaster } from "@/components/ui/toaster"; function SaveButton() { const controller = useOptionalCloudlet(); return ( ); } export function NotificationOwner() { const [controller, setController] = useState(null); useEffect(() => { const instance = createCloudlet(); setController(instance); return () => instance.dispose(); }, []); // null on the server and in the first client render: the button renders, the Toaster waits. return ; } ``` ### Requirements - **React and React DOM** `^18.2.0 || ^19.0.0` are peer dependencies. Use a matching pair: the same version of `react` and `react-dom`. - **ESM only.** The package ships ES modules with TypeScript declarations; there is no CommonJS or UMD build. Deep imports into its internals are closed on purpose: everything public comes from `@cloudlet/toast`. - **No runtime dependencies.** The springs and tweens that move the stack and the Island are Cloudlet's own. - **No Tailwind or shadcn/ui requirement.** The npm package styles itself with plain CSS and custom properties; the shadcn item only bridges them to your tokens. - **Browsers.** Chromium and Edge 111, Firefox 114, Safari and iOS 16.4 or newer. The automated suite runs on current versions, and the minimum versions are checked by hand ([What is tested](https://cloudlet.dev/docs/components/toaster/accessibility#what-is-tested)). - **TypeScript.** The declarations work with `strict` and `exactOptionalPropertyTypes`; with the latter, leave an optional field out rather than passing `undefined`. ### Import the styles Cloudlet's CSS is one explicit file. Import it once, where your application imports its global CSS: the client entry of a single-page app, or the root layout of a Next.js App Router project. ```tsx title="app/layout.tsx" import '@cloudlet/toast/styles.css'; ``` In the Next.js Pages Router, global CSS must come from the custom App, so the import goes into `pages/_app.tsx`. The stylesheet does not need a build plugin; under a strict Content Security Policy keep it external, as described in [Content Security Policy](https://cloudlet.dev/docs/components/toaster/csp). ### The shadcn registry item The `toaster` item copies two files into your project and adds `@cloudlet/toast` as a dependency: - **`components/ui/toaster.tsx`**: a thin `"use client"` adapter that renders the Provider and the Toaster for a controller you pass in. Every public Toaster option passes through unchanged. - **`components/ui/toaster.css`**: a theme bridge that maps your shadcn tokens (`--popover`, `--popover-foreground`, `--muted-foreground`, `--border`, `--ring`, `--accent`, `--font-sans`) to Cloudlet's tokens. Both files are yours to edit. The notification runtime itself stays in the package: the item copies no controller, renderer or animation code. The wrapper deliberately does not create a controller: a client component owns it, as `notification-owner.tsx` in the shadcn tab above does, for the reasons in [SSR & Next.js](https://cloudlet.dev/docs/components/toaster/ssr#nextjs-app-router). A few details of the bridge: - The wrapper imports `@cloudlet/toast/styles.css` and then `./toaster.css`; keep that order. In the Pages Router, move both imports into `pages/_app.tsx` in the same order and remove them from the wrapper. - Define light tokens on `:root` and dark tokens on your `.dark` root, then pass the matching `theme="light"` or `theme="dark"` to the Toaster so the native `color-scheme` agrees. - The tokens must be inherited by the portal container. A wrapper element around your React tree does not theme the default portal on `document.body`. ## Usage Create one controller where your application starts, and render the Toaster inside its Provider. In the Next.js App Router a client component creates the controller instead: [SSR & Next.js](https://cloudlet.dev/docs/components/toaster/ssr#nextjs-app-router) has the setup. ```tsx title="main.tsx" import '@cloudlet/toast/styles.css'; import { createRoot } from 'react-dom/client'; import { CloudletProvider, createCloudlet, Toaster } from '@cloudlet/toast'; import { App } from './app'; // Once, when the browser application starts. const cloudlet = createCloudlet(); createRoot(document.getElementById('root')!).render( , ); ``` Any component under the Provider shows a notification: ```tsx title="app.tsx" import { useCloudlet } from '@cloudlet/toast'; export function App() { const cloudlet = useCloudlet(); return ; } ``` Every call returns a value you can act on rather than a promise that is silently dropped: `show` tells you whether a record was created, deduplicated or rejected and why, and `dismiss` and `update` report a stale handle instead of doing nothing ([Show a notification](https://cloudlet.dev/docs/components/toaster/notifications#show-a-notification)). ### Controller, Provider, Toaster Cloudlet splits into a core that knows nothing about the DOM and a React shell that renders it. - **`createCloudlet()`** returns a **controller**: the owner of notifications, their time, operations and announcements. Creating it allocates no timers and touches no DOM. - **`CloudletProvider`** hands the controller to a React tree. It does not render anything itself. - **`useCloudlet()`** returns the controller to any component under the Provider, so a save button can call `show` without prop drilling. - **`Toaster`** renders the stack and the Island for the controller it finds in context, in a portal after mount. Unmounting it pauses visible time and keeps every record; mounting it again resumes the same queue. ### What stays with your application Cloudlet owns the stack, its time and its accessibility. A few things stay yours by design: - **The controller's lifetime.** One controller per browser session or server request, disposed only when it ends: see [One controller per session or request](https://cloudlet.dev/docs/components/toaster/ssr#one-controller-per-session-or-request) and [When to dispose](https://cloudlet.dev/docs/components/toaster/ssr#when-to-dispose). - **Important data.** A notification is a notice, not a record: anything the user must not lose also lives in your main interface. - **Words.** Every label, announcement and fallback message is a string or a formatter you can replace ([Labels & announcements](https://cloudlet.dev/docs/components/toaster/api/labels)), so the Toaster speaks your product's language. - **Styling.** Cloudlet ships CSS tokens for colour, radius and spacing and adds your class names per part ([Styling](https://cloudlet.dev/docs/components/toaster/styling)); it does not require Tailwind or shadcn/ui. ## Examples ### Kinds Five kinds of weather. Success and info drift off after six seconds; the rest stay until you close them. More in [Notifications & time](https://cloudlet.dev/docs/components/toaster/notifications#kinds). Snippets assume `const cloudlet = useCloudlet();`. ```tsx cloudlet.show({ title: 'Synced to the cloud', kind: 'success' }); ``` ```tsx cloudlet.show({ title: 'Sync got lost in the fog', kind: 'error' }); ``` ```tsx cloudlet.show({ title: 'Light breeze from the west', kind: 'info' }); ``` ```tsx cloudlet.show({ title: 'Clouds are gathering', kind: 'warning' }); ``` ```tsx cloudlet.show({ title: 'Gathering clouds…', kind: 'loading' }); ``` ### Content A title, a line of description, rich text or an icon of your own. More in [Notifications & time](https://cloudlet.dev/docs/components/toaster/notifications#content). ```tsx cloudlet.show({ title: 'A small cloud drifted by' }); ``` ```tsx cloudlet.show({ title: 'Forecast updated', description: { kind: 'text', text: 'Sunny above the clouds, light drizzle below.' }, }); ``` ```tsx cloudlet.show({ title: 'Cruising altitude reached', description: { kind: 'rich', content: <>Above the clouds at 10,000 m, the sky is perfectly clear., announcement: 'Above the clouds at 10,000 m, the sky is perfectly clear.', }, }); ``` ```tsx cloudlet.show({ title: 'Spotted a cloud shaped like a cat', icon: ( ), }); ``` ### Actions A command, a real link, and a command that fails once and offers a retry. More in [Operations & cancellation](https://cloudlet.dev/docs/components/toaster/operations#actions). ```tsx cloudlet.show({ title: 'Photo moved to the archive', action: { kind: 'command', label: 'Undo', run: () => { cloudlet.show({ title: 'Photo is back in the sky', kind: 'success' }); }, }, }); ``` ```tsx cloudlet.show({ title: 'These clouds are open source', action: { kind: 'link', label: 'GitHub', href: 'https://github.com/Meerzus/cloudlet', target: '_blank', rel: 'noreferrer' }, }); ``` ```tsx let tries = 0; cloudlet.show({ title: 'Album ready to share', action: { kind: 'command', label: 'Share', errorMessage: () => 'A gust blew it away. Try again?', run: async () => { await new Promise((resolve) => setTimeout(resolve, 800)); tries += 1; if (tries === 1) throw new Error('Gust of wind'); cloudlet.show({ title: 'Album shared with the sky', kind: 'success' }); }, }, }); ``` ### Forms A field right in the Island: a quick reply, a note with a check, and a send that fails once. More in [Forms](https://cloudlet.dev/docs/components/toaster/forms). - `form-reply` (Reply): code in [Forms › A form action](https://cloudlet.dev/docs/components/toaster/forms#a-form-action). - `form-note` (Note): code in [Forms › Checks before sending](https://cloudlet.dev/docs/components/toaster/forms#checks-before-sending). - `form-retry` (Fails once): code in [Forms › Sending](https://cloudlet.dev/docs/components/toaster/forms#sending). ### Promises track() follows an operation from pending to its result; update() changes a card in place. More in [Operations & cancellation](https://cloudlet.dev/docs/components/toaster/operations). ```tsx cloudlet.track(new Promise((resolve) => setTimeout(resolve, 1500)), { pending: { title: 'Condensing water vapour…' }, success: { title: 'A fresh cloud formed' }, error: { title: 'The cloud evaporated' }, }); ``` ```tsx cloudlet.track(async ({ attempt }) => { await new Promise((resolve) => setTimeout(resolve, 1200)); if (attempt === 1) throw new Error('No signal above the clouds'); }, { pending: { title: 'Reaching the sky…' }, success: { title: 'Back in the sky' }, error: { title: "Couldn't reach the sky", description: { kind: 'text', text: 'Thick clouds in the way. The second try gets through.' }, }, }); ``` - `promise-progress` (Progress): code in [Operations & cancellation › Progress](https://cloudlet.dev/docs/components/toaster/operations#progress). - `track-cancel` (Cancel): code in [Operations & cancellation › Cancellation](https://cloudlet.dev/docs/components/toaster/operations#cancellation). ```tsx const packing = cloudlet.show({ title: 'Packing the clouds…', kind: 'loading' }); setTimeout(() => { if (packing.status === 'created') { cloudlet.update(packing.handle, { title: 'Clouds packed', kind: 'success' }); } }, 1500); ``` ### Attention Whether a notification opens the Island on its own: auto, open or stack. More in [Notifications & time](https://cloudlet.dev/docs/components/toaster/notifications#attention). - `attention-auto` (auto): code in [Notifications & time › Attention](https://cloudlet.dev/docs/components/toaster/notifications#attention). - `attention-upgrade` (open): code in [Notifications & time › Attention](https://cloudlet.dev/docs/components/toaster/notifications#attention). - `attention-stack` (stack): code in [Notifications & time › Attention](https://cloudlet.dev/docs/components/toaster/notifications#attention). ### Stack Newest on top, one pill at rest. Push it past 100 and the badge counts what was missed. More in [Notifications & time](https://cloudlet.dev/docs/components/toaster/notifications#the-stack-and-the-island). - `burst` (Burst ×5): code in [Notifications & time › The stack and the Island](https://cloudlet.dev/docs/components/toaster/notifications#the-stack-and-the-island). - `overflow` (Overflow): code in [Notifications & time › Capacity and overflow](https://cloudlet.dev/docs/components/toaster/notifications#capacity-and-overflow). - `dismiss-all` (Dismiss all): code in [Notifications & time › Capacity and overflow](https://cloudlet.dev/docs/components/toaster/notifications#capacity-and-overflow). ## Agent An agent in your app can read the stack and act on it through the [agent bridge](https://cloudlet.dev/docs/agents), experimental for now. The adapter ships in the package as `@cloudlet/toast/agent`; connect the controller with one line: ```tsx title="toaster-agent.tsx" 'use client'; import { createAgent } from '@cloudlet/agent'; import { useCloudlet } from '@cloudlet/toast'; import { toasterAgent } from '@cloudlet/toast/agent'; import { useEffect } from 'react'; const agent = createAgent(); export function ConnectToasterAgent() { const cloudlet = useCloudlet(); useEffect(() => agent.connect(toasterAgent(cloudlet)), [cloudlet]); return null; } ``` The snapshot then holds the Toaster (`open`, `close`, `clear`, `acknowledge`) and each notification (`dismiss`, `show`, `press`, `fill`, `submit`, `cancel`, `retry`, by state). Pressing an action and submitting a form need a person unless the action says otherwise with its `agent` marker: `'allow'` lets an agent press it, `'deny'` never. A step that needs a person opens the Island on its notification for them. Links are never opened, and what a person typed never reaches the agent. Every event and `CloseNotice` names who caused it in `source`. Records, verbs and messages: [toasterAgent](https://cloudlet.dev/docs/agents/api/toast). ## API Reference | Export | What it is | Reference | | --- | --- | --- | | `createCloudlet` | Creates a controller, the object that owns every notification, its time and its operations. | [createCloudlet](https://cloudlet.dev/docs/components/toaster/api/create-cloudlet) | | `CloudletProvider` | Hands a controller to a React tree; renders nothing itself. | [Toaster props](https://cloudlet.dev/docs/components/toaster/api/toaster#cloudletprovider) | | `useCloudlet` | Returns the controller of the nearest Provider. | [Toaster props](https://cloudlet.dev/docs/components/toaster/api/toaster#usecloudlet) | | `Toaster` | Renders the stack and the Island of that controller, in a portal after mount. | [Toaster props](https://cloudlet.dev/docs/components/toaster/api/toaster#props) | The controller's methods are on [Controller](https://cloudlet.dev/docs/components/toaster/api/controller), the other public types on [Types](https://cloudlet.dev/docs/components/toaster/api/types). --- # Color picker > A round swatch that morphs into a full color picker. Installed as source with the shadcn CLI. Source: https://cloudlet.dev/docs/components/color-picker `ColorPicker` is a swatch that opens into the picker; `ColorPickerPanel` is the same picker in the flow of the page, for forms and sidebars. Both edit a color given as a CSS string and give back a string in the format you allow. ## Preview Live preview at https://cloudlet.dev/docs/components/color-picker#preview: the picker as a swatch or as an inline panel, the value its `onChange` gives, and controls for the component, the output format and opacity. The code they make: ```tsx "use client"; import { useState } from "react"; import { ColorPickerPanel } from "@/components/ui/color-picker/color-picker"; export function AccentColor() { const [color, setColor] = useState("oklch(51.9% 0.203 263.2)"); return ; } ``` - Component: `ColorPicker` (the swatch that opens the picker) or `ColorPickerPanel` (the picker inline). - `defaultFormat`: `hex` (the default), `rgb`, `hsl`, `oklch`; the starting color is written in it. - `alpha`: off by default; on, the picker shows the opacity slider. A prop at its default is left out; with every default the code is ``. ## Installation The color picker is a shadcn registry item, not an npm package: the CLI copies its source into your project, where it is yours to change. ```sh title="Terminal" npx shadcn@latest add https://cloudlet.dev/r/color-picker.json ``` It adds six files under your `ui` and `lib` aliases and nothing to `package.json`: | File | What it holds | | --- | --- | | `components/ui/color-picker/color-picker.tsx` | `ColorPicker`, `ColorPickerPanel` and their types | | `components/ui/color-picker/color-picker.css` | The styles, imported by the component itself | | `components/ui/color-picker/color.ts` | Parsing, conversions and the canonical output | | `components/ui/color-picker/morph.ts` | The springs of the swatch-to-panel morph | | `components/ui/color-picker/color-picker-agent.ts` | `useColorPickerAgent`, which connects the picker to the Cloudlet agent bridge; nothing runs until you import it | | `lib/spring.ts` | The spring easing both use | The stylesheet reads the shadcn tokens `--background`, `--foreground`, `--border`, `--ring`, `--primary` with `--primary-foreground`, `--radius` and, if your theme has it, `--muted`. It resets its own buttons, so it does not rely on Tailwind's preflight. ## Usage Pass `color` and `onChange` and the picker is controlled, like an input. `onChange` receives the value in the current format on every change, and once more when the reader switches the format, so your state, the field and a hidden input always agree. ```tsx title="accent-field.tsx" "use client"; import { useState } from "react"; import { ColorPicker } from "@/components/ui/color-picker/color-picker"; export function AccentField() { const [accent, setAccent] = useState("#245cdb"); return ; } ``` Leave `color` out and give `defaultColor` to let the picker own its value. With `name`, a hidden input carries the value in a native form, so a server action or a plain `
` receives it: ```tsx title="theme-form.tsx" import { ColorPickerPanel } from "@/components/ui/color-picker/color-picker"; export function ThemeForm({ action }: { action: (data: FormData) => void }) { return ( ); } ``` ### Styling The corners follow your `--radius` the way shadcn's own components do: the panel a step above it, the value field and the format switch at it, the area and the buttons a step below; the swatch, the sliders and their handles stay round. The checked format is a `--primary` pill with `--primary-foreground` text, like a primary button, and the copy check turns `--primary`. A theme without these tokens gets the picker's own look: 1rem corners, a background pill and the foreground. Everything is plain CSS in `color-picker.css`; change it there, or override a class in your own stylesheet: ```css title="globals.css" .color-picker-panel { width: 18rem; border-radius: 1rem; } ``` ### Placement and limits The panel opens down and to the right of the swatch and flips up and/or left when it would cross the edge of the viewport. A swatch in the middle of a narrow screen has room on neither side: there the panel also moves along the edge until it is inside, 8 px from it, and its own swatch moves back by as much, so the panel still grows out of the swatch you pressed. It is not portalled, so it inherits the theme of its subtree and works inside an iframe — and an ancestor with `overflow: hidden` clips it. Give that container `overflow: visible`, or place the picker outside it. > **Not inside a paragraph.** The picker's root is a `
`, so it cannot sit inside a `

`: the browser would move it out and React reports a hydration error. Put it in a `

` instead. ### Reduced motion Under `prefers-reduced-motion: reduce` the swatch opens and closes in a single frame, without the morph, and the format switch and the copy check stop animating. An app with its own setting can ask for the same with `data-reduced-motion` on any ancestor: ```tsx title="settings.tsx" import type { ReactNode } from "react"; export function MotionSetting({ reduce, children }: { reduce: boolean; children: ReactNode }) { return
{children}
; } ``` ## Examples ### Inline panel `ColorPickerPanel` is the picker without the swatch, always open. ```tsx title="panel.tsx" "use client"; import { useState } from "react"; import { ColorPickerPanel } from "@/components/ui/color-picker/color-picker"; export function InlinePanel() { const [color, setColor] = useState("#245cdb"); return ; } ``` ### One format A single entry in `formats` fixes the output and hides the format switch. ```tsx title="one-format.tsx" import { ColorPicker } from "@/components/ui/color-picker/color-picker"; export function HexOnly() { return ; } ``` ### Opacity `alpha` adds the opacity slider; the value carries opacity only below 1. ```tsx title="opacity.tsx" import { ColorPickerPanel } from "@/components/ui/color-picker/color-picker"; export function WithOpacity() { return ; } ``` ### Format in your state `format` with `onFormatChange` keeps the reader's choice of a format where your app can save it. ```tsx title="format.tsx" "use client"; import { useState } from "react"; import { ColorPickerPanel, type ColorFormat } from "@/components/ui/color-picker/color-picker"; export function SavedFormat() { const [color, setColor] = useState("oklch(51.9% 0.203 263.2)"); const [format, setFormat] = useState("oklch"); return (

Saved format: {format}

); } ``` ### Swatch from a CSS variable `swatch` paints the button with any CSS color, here the variable the picker's value is written to. ```tsx title="swatch.tsx" "use client"; import { useState, type CSSProperties } from "react"; import { ColorPicker } from "@/components/ui/color-picker/color-picker"; export function AccentVariable() { const [accent, setAccent] = useState("#245cdb"); return (
); } ``` ### Translated labels A full `labels` object: every name and announcement in Spanish. ```tsx title="labels.tsx" import { ColorPicker, type ColorPickerLabels } from "@/components/ui/color-picker/color-picker"; const labels: ColorPickerLabels = { open: "Elegir color", panel: "Selector de color", close: "Cerrar", area: "Saturación y brillo", saturation: "Saturación", brightness: "Brillo", hue: "Tono", alpha: "Opacidad", value: "Valor del color", format: "Formato", eyedropper: "Tomar de la pantalla", copy: "Copiar", copied: "Copiado", }; export function SpanishPicker() { return ; } ``` ## Agent `color-picker-agent.ts` connects the picker to the [agent bridge](https://cloudlet.dev/docs/agents), experimental for now. `useColorPickerAgent(agent, props, options)` takes the picker's props and returns them wrapped; spread them on `ColorPicker` or `ColorPickerPanel`: ```tsx title="accent-agent.tsx" "use client"; import { createAgent } from "@cloudlet/agent"; import { useState } from "react"; import { ColorPicker } from "@/components/ui/color-picker/color-picker"; import { useColorPickerAgent } from "@/components/ui/color-picker/color-picker-agent"; const agent = createAgent(); export function AccentAgent() { const [accent, setAccent] = useState("#245cdb"); const picker = useColorPickerAgent(agent, { color: accent, onChange: setAccent }, { name: "accent", label: "Accent color" }); return ; } ``` The picker is one `ColorPickerEntry` in the snapshot: `ref` (its name), `component: 'color-picker'`, `label`, `value` as the field shows it, `format`, `formats` and `alpha`. Its one verb is `set [color]`: hex, `rgb()`, `hsl()` or `oklch()`, written in the picker's format, without opacity unless `alpha` is on. It runs unless the bridge's `allow` says no, and answers with the color the picker shows. `ColorPickerAgentOptions` are `name` (default `color-picker`; a second picker on one agent needs its own) and `label` (default `labels.open`). `COLOR_PICKER_VERBS` is the verb's text for a model. With `agent` null or undefined the props come back as they are. Each change reaches `agent.subscribe` under the key `color`, with its source. - **The answer is what the picker shows.** A step reads the picker after React commits the app's update. An app that sets the value later, after a server answers or in a transition, reads as not taking it: `The app did not take "#ff0000": "Accent color" is still "#245cdb".` Other refusals: a color it cannot read (`… is not a color "Accent color" can read. Use hex, rgb(), hsl() or oklch().`) and wrong arguments (`"set" on "accent" takes a color.`). - **One author per commit.** The color adapters on one agent share who started a change: `user` through the picker, `agent` through a step, `app` otherwise. A value your app passes on in a later commit, from an effect, is `app`. React 19 may merge a deferred update of your app into the next synchronous commit; then that value is named after the person's or the step's change in the same commit. - **Format changed by the app.** After your app itself changes a controlled `format`, the snapshot's `value` can differ from the field in the last digit until the next change. - **Connecting later.** An uncontrolled picker whose `agent` goes from null to a bridge starts again from `defaultColor`. The file also exports what the palette's adapter shares with it, which you do not need to call: copies of the bridge's protocol types (`AgentEntryShape`, `AgentSignalShape`, `AgentValueShape`, `AgentPermissionShape`, `AgentStepCallShape`, `AgentStepNamesShape`, `AgentStepCheckShape`, `AgentRunContextShape`, `AgentRunOutcomeShape`, `AgentSummonOutcomeShape`, `AgentChangeShape`, `AgentVerbsShape`, `AgentComponentShape`, `AgentConnectorShape`, `ChangeSourceShape`), so the file needs no `@cloudlet/agent` import, and the helpers `colorTexts`, `writeColor`, `commitNow`, `useChangeAuthor` with `ChangeAuthor`, and `useAgentPort` with `AgentPortMethods`. ## API Reference ### Props `ColorPickerProps` for `ColorPicker`, `ColorPickerPanelProps` for `ColorPickerPanel`; every prop is optional. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `color` | `string` | — | The color to show (controlled): hex, `rgb()`, `hsl()` or `oklch()`. A value that does not parse, such as `var(--accent)`, keeps the last valid color. | | `defaultColor` | `string` | `#ffffff` | The initial color when the picker owns its value. | | `onChange` | `(value: string) => void` | — | Called with the value in `format` on every change and when the format switches. | | `format` | `ColorFormat` | — | The output format (controlled); pair it with `onFormatChange`. Changing it from your code does not call `onChange`, see [Formats](#formats). | | `defaultFormat` | `ColorFormat` | the first of `formats` | The initial format when the picker owns it. | | `onFormatChange` | `(format: ColorFormat) => void` | — | Called when the reader picks another format. | | `formats` | `readonly ColorFormat[]` | all four | The formats the switch offers, in order. A single entry hides the switch. | | `alpha` | `boolean` | `false` | Shows the opacity slider and the checkerboard. Without it, alpha is dropped from input and output. | | `name` | `string` | — | Renders `` with this name and the current value. | | `labels` | `Partial` | `DEFAULT_LABELS` | Names and announcements; anything left out keeps its English default. | | `swatch` | `string` | the current value | `ColorPicker` only: any CSS color for the swatch button, such as a `var()` the picker cannot parse. | | `className` | `string` | — | `ColorPickerPanel` only: added to the panel. | ### Formats `ColorFormat` is `'hex' | 'rgb' | 'hsl' | 'oklch'`. The picker reads `#rgb`, `#rgba`, `#rrggbb` and `#rrggbbaa`, `rgb()` and `rgba()` in the old and the new syntax, `hsl()` and `hsla()`, and `oklch()` with lightness as a percentage or a fraction (`none` counts as 0). It writes one canonical form per format: lowercase hex, space-separated channels, oklch lightness, chroma and hue rounded to at most one, three and one decimals, and opacity only below 1. For `#ff8000`: | Format | Output | With opacity below 1 | | --- | --- | --- | | `hex` | `#ff8000` | `#ff800080` | | `rgb` | `rgb(255 128 0)` | `rgb(255 128 0 / 0.5)` | | `hsl` | `hsl(30 100% 50%)` | `hsl(30 100% 50% / 0.5)` | | `oklch` | `oklch(73.2% 0.186 53)` | `oklch(73.2% 0.186 53 / 0.5)` | When the reader switches the format, `onChange` gets the same color in the new one. When your code changes `format`, it does not: the field and the hidden input show the new format at once, and `onChange` reports it from the next change of the color. If you store the value and switch the format from outside, rewrite the stored value yourself. The area edits saturation and brightness in sRGB. An `oklch()` color outside sRGB shows as given on the swatch; the first move of a handle keeps its lightness and hue and lowers the chroma until it fits. ### Eyedropper and copy The eyedropper button appears only where the browser has the EyeDropper API, Chromium browsers today; elsewhere it is not rendered rather than shown disabled. Cancelling the eyedropper changes nothing. The copy button writes the value to the clipboard, turns into a check for a moment and announces `labels.copied`; a blocked clipboard leaves everything as it was. ### Keyboard and screen readers | Part | Role | Keys | | --- | --- | --- | | Swatch | button, `aria-expanded` | Enter or Space opens the picker | | Picker | dialog named by `labels.panel` | focus starts in the area; Escape closes and returns focus to the swatch; a press outside, or Tab out of the panel, closes without moving focus | | Area | slider, "Saturation 40%, Brightness 80%" | ← → saturation, ↑ ↓ brightness, by 1%; with Shift by 10% | | Hue, opacity | sliders, "Hue 48°", "Opacity 50%" | ← → by 1° or 1%, Shift by 10, Home and End to the ends | | Value field | text field named by `labels.value` | typing applies every color that parses; Escape reverts, a second Escape closes | | Format switch | radio group | arrows move between formats | Tab moves through the swatch that closes the panel, the value field, the area, the sliders, the format switch, the eyedropper and copy, in that order; past copy, focus leaves the picker and the panel closes, so it never covers what Tab reaches next. `ColorPickerPanel` has no closing swatch and starts at the value field. In forced-colors mode the handles, the area and the switch draw borders in system colors, so every part stays findable without gradients. The sliders are thin to look at but take a press anywhere in the gaps around them: up to the area's edge, down to the row of the format switch and the tools, and halfway to the other slider when there are two, so each is at least 24 px tall to press and a press meant for one never moves its neighbour or the area. ### Labels Every name and spoken word comes from `labels`; pass the ones you translate and the rest keep these defaults (`DEFAULT_LABELS`): | Key | Default | Where | | --- | --- | --- | | `open` | `Pick color` | the swatch button | | `panel` | `Color picker` | the dialog | | `close` | `Close` | the swatch inside the panel | | `area` | `Saturation and brightness` | the area's name | | `saturation`, `brightness` | `Saturation`, `Brightness` | the area's value, "Saturation 40%, Brightness 80%" | | `hue` | `Hue` | the hue slider's name and value, "Hue 48°" | | `alpha` | `Opacity` | the opacity slider's name and value, "Opacity 50%" | | `value` | `Color value` | the value field | | `format` | `Format` | the format switch | | `eyedropper` | `Pick from screen` | the eyedropper button | | `copy`, `copied` | `Copy`, `Copied` | the copy button and its announcement | --- # Color palette > A row of up to four color pickers with add and remove. Installed as source with the shadcn CLI. Source: https://cloudlet.dev/docs/components/color-palette `ColorPalette` keeps a set of one to four colors in a row of swatches. Every swatch is a [`ColorPicker`](https://cloudlet.dev/docs/components/color-picker); a button adds a color, Delete or a small × removes one. It edits an array of CSS strings the way the picker edits one. ## Preview Live preview at https://cloudlet.dev/docs/components/color-palette#preview: a palette of three colors, the array its `onChange` gives, and controls for the most colors it holds, the output format and opacity. The code they make: ```tsx "use client"; import { useState } from "react"; import { ColorPalette } from "@/components/ui/color-palette/color-palette"; export function BrandColors() { const [colors, setColors] = useState([ "oklch(51.9% 0.203 263.2)", "oklch(81.7% 0.14 80.1)", "oklch(60.1% 0.089 208.9)", ]); return ; } ``` - `max`: `2`, `3`, `4` (the default); the add button is gone at this count. - `defaultFormat`: `hex` (the default), `rgb`, `hsl`, `oklch`; every color is written in it. - `alpha`: off by default; on, every picker shows the opacity slider. A prop at its default is left out; with every default the code is ``. ## Installation The palette is its own registry item. It lists the color picker as a registry dependency, so the CLI adds [the picker's files](https://cloudlet.dev/docs/components/color-picker#installation) too if your project does not have them yet: ```sh title="Terminal" npx shadcn@latest add https://cloudlet.dev/r/color-palette.json ``` | File | What it holds | | --- | --- | | `components/ui/color-palette/color-palette.tsx` | `ColorPalette`, its props and labels | | `components/ui/color-palette/color-palette.css` | The styles, imported by the component itself | | `components/ui/color-palette/color-palette-agent.ts` | `useColorPaletteAgent`, which connects the palette to the Cloudlet agent bridge; nothing runs until you import it | ## Usage Pass `colors` and `onChange` to control it. `onChange` receives every color in the current format, in the reader's order, after any change, addition or removal; switching the format in one picker switches it for the whole palette and re-emits all of them. Its second argument, a `ColorPaletteChange`, says which color it was: `{ type: "set" | "add" | "remove", index }`, or `{ type: "format" }` when every color was rewritten; a plain setter can ignore it. With `name`, the palette renders one hidden input per color, so `FormData.getAll()` gives back the array: ```tsx title="brand-palette.tsx" "use client"; import { useState } from "react"; import { ColorPalette } from "@/components/ui/color-palette/color-palette"; export function BrandPalette() { const [colors, setColors] = useState(["#245cdb", "#f2b84b"]); return (
console.log(data.getAll("brand"))}> ); } ``` Each swatch belongs to its color, not to its place. When your code removes, inserts or reorders colors itself, the other swatches keep theirs: a picker the reader has open stays on the color it was opened for, and the picker of a removed color closes with it. The palette tells colors apart by their value, whatever format each is written in (`rgb(255 0 0)` and `#ff0000` are one color), so of two identical colors it cannot know which one your code removed; either way the row shows the same colors. A new color starts from the last one, turned around the OKLCH hue wheel by a full turn divided by `max` (a square of four at the default), and its picker opens at once. A grey has no hue to turn, so the new color steps in lightness instead. On touch screens, which have no hover, the × stays in view on every swatch. Under `prefers-reduced-motion: reduce` or inside `data-reduced-motion`, swatches appear and go without their springs. ## Examples ### In a form `name` on a palette that owns its colors: Save shows what `FormData.getAll()` receives. ```tsx title="form.tsx" "use client"; import { useState } from "react"; import { ColorPalette } from "@/components/ui/color-palette/color-palette"; export function BrandForm() { const [sent, setSent] = useState([]); return (
setSent(data.getAll("brand").map(String))}> {sent.join(", ")} ); } ``` ### Colors in OKLCH `defaultColors` in any syntax the picker reads, and `defaultFormat` for what the palette gives back. ```tsx title="oklch.tsx" import { ColorPalette } from "@/components/ui/color-palette/color-palette"; export function OklchPalette() { return ; } ``` ### Opacity `alpha` adds the opacity slider to every picker. ```tsx title="opacity.tsx" import { ColorPalette } from "@/components/ui/color-palette/color-palette"; export function TranslucentPalette() { return ; } ``` ## Agent `color-palette-agent.ts` connects the palette to the [agent bridge](https://cloudlet.dev/docs/agents), experimental for now. `useColorPaletteAgent(agent, props, options)` wraps the palette's props: ```tsx title="brand-agent.tsx" "use client"; import { createAgent } from "@cloudlet/agent"; import { useState } from "react"; import { ColorPalette } from "@/components/ui/color-palette/color-palette"; import { useColorPaletteAgent } from "@/components/ui/color-palette/color-palette-agent"; const agent = createAgent(); export function BrandAgent() { const [colors, setColors] = useState(["#245cdb", "#ff9500"]); const palette = useColorPaletteAgent(agent, { colors, onChange: setColors }, { name: "brand", label: "Brand palette" }); return ; } ``` The palette is one `ColorPaletteEntry`: `label`, `colors` as it shows them, `max`, `format`, `formats` and `alpha`. Its verbs, a `ColorPaletteAction`, are `set [index, color]`, `add [color]` while there are fewer than `max`, and `remove [index]` while more than one is left; indexes count from 0, and each answers with the colors after it. `ColorPaletteAgentOptions` are `name` (default `color-palette`) and `label` (default `labels.group`); `COLOR_PALETTE_VERBS` is the verbs' text for a model. Each change reaches `agent.subscribe` under the key `colors`, and a step hands your `onChange` the same `ColorPaletteChange` as the reader's edits. Refusals name the palette: `There is no color 5 in "Brand palette": it has colors 0–1.`, `… already holds 4 colors, its most.`, `… holds only one color, its least. Set it instead.` The answer, the author of a change and the format follow the same rules as the [picker's adapter](https://cloudlet.dev/docs/components/color-picker#agent), with whom the palette shares one author on the same agent. ## API Reference ### Props `ColorPaletteProps`; every prop is optional. `ColorFormat` and the syntaxes a color may be written in are the picker's: [Formats](https://cloudlet.dev/docs/components/color-picker#formats). | Prop | Type | Default | Description | | --- | --- | --- | --- | | `colors` | `readonly string[]` | — | The colors (controlled): one to `max` strings in hex, `rgb()`, `hsl()` or `oklch()`. An empty array shows one default color. | | `defaultColors` | `readonly string[]` | — | The initial colors when the palette owns them. | | `onChange` | `(colors: string[], change: ColorPaletteChange) => void` | — | Called with every color in `format` on any change, addition or removal; `change` names the color, see [Usage](#usage). | | `max` | `number` | `4` | The most colors the palette holds; the add button is gone at this count. | | `format` | `ColorFormat` | — | The output format of every color (controlled); pair it with `onFormatChange`. | | `defaultFormat` | `ColorFormat` | the first of `formats` | The initial format when the palette owns it. | | `onFormatChange` | `(format: ColorFormat) => void` | — | Called when the reader picks another format in any picker. | | `formats` | `readonly ColorFormat[]` | all four | The formats every picker offers. A single entry hides the switch. | | `alpha` | `boolean` | `false` | Shows the opacity slider in every picker. | | `name` | `string` | — | Renders one `` per color under this name. | | `labels` | `Partial` | `DEFAULT_PALETTE_LABELS` | Names and announcements; anything left out keeps its English default. | | `className` | `string` | — | Added to the palette's row. | ### Keyboard The palette is one Tab stop: ← and → move between the swatches and the add button, Home and End jump to the ends, Enter or Space opens the focused swatch's picker, and Delete or Backspace removes its color while more than one is left. After a removal, focus moves to the neighbouring swatch and a screen reader hears `labels.removed`; after an addition, focus is already in the new color's picker. Each swatch says its place and value, "Color 2 of 3, #2f8f9d". In forced-colors mode the swatches, the add button and the × draw borders in system colors. With a picker open, the keys are [the picker's](https://cloudlet.dev/docs/components/color-picker#keyboard-and-screen-readers). ### Labels | Key | Default | Where | | --- | --- | --- | | `group` | `Palette` | the group's name | | `color` | `Color {n} of {total}` | each swatch's name, before its value | | `add` | `Add color` | the add button | | `remove` | `Remove color` | the × on a swatch | | `removed` | `Color removed` | the announcement after a removal | | `picker` | `{}` | [`labels`](https://cloudlet.dev/docs/components/color-picker#labels) of every swatch's picker (its `open` is ignored: the swatch is named by `color`) | --- # Onboarding > A product tour that dims the page around a cutout springing from target to target, and a get-started checklist built from the same steps. Installed as source with the shadcn CLI. Source: https://cloudlet.dev/docs/components/onboarding `Onboarding` walks a person through your app one step at a time: the page dims around a cutout that springs from one element to the next, and a dark pill beside it carries the step's text with Back, Next, Done and Skip. `OnboardingChecklist` turns the same steps into a get-started list in a corner of the screen ([Checklist](#checklist)); `OnboardingIsland` shows them in the Island of your Toaster while the page stays bright ([Island](#island)). ## Preview Live preview at https://cloudlet.dev/docs/components/onboarding#preview: a small app (a header with New project, a search field and Settings) and a Start tour button; the tour walks its header in three steps and ends on a step without a target, in the centre. Controls set the overlay and how the first step goes on. The code they make: ```tsx "use client"; import { useState } from "react"; import { Onboarding, type OnboardingStep } from "@/components/ui/onboarding/onboarding"; const steps: OnboardingStep[] = [ { id: "new-project", target: "#tour-new-project", title: "Create a project", body: "Every project starts here.", advanceOn: "click" }, { id: "search", target: "#tour-search", title: "Find anything", body: "Search projects, people and settings." }, { id: "settings", target: "#tour-settings", title: "Make it yours", body: "Theme, notifications and your team." }, { id: "done", title: "All set", body: "Start the tour again any time." }, ]; export function ProductTour() { const [open, setOpen] = useState(false); return ( <> ); } ``` - `overlay`: `dim` (the default) darkens the page around the cutout; `none` leaves it bright and pressable, with a ring on the target. - First step: Next (the default) or `advanceOn: "click"`, where the pill has no Next and a press on New project goes on. With every default the tour is ``. ## Installation A shadcn registry item: the CLI copies the source into your project, where it is yours to change. Nothing is added to `package.json`. ```sh title="Terminal" npx shadcn@latest add https://cloudlet.dev/r/onboarding.json ``` | File | What it holds | | --- | --- | | `components/ui/onboarding/onboarding.tsx` | `Onboarding`, its props, steps and labels | | `components/ui/onboarding/engine.ts` | The steps without a face: the current step, its waits, the memory and how the tour finished | | `components/ui/onboarding/onboarding.css` | The styles, imported by the component itself | | `components/ui/onboarding/geometry.ts` | The cutout's outline, the pill's placement and finding a step's target | | `components/ui/onboarding/spring-channel.ts` | The interruptible spring every moving value runs on | | `components/ui/onboarding/storage.ts` | The `storageKey` record in localStorage | | `components/ui/onboarding/checklist.tsx` | `OnboardingChecklist`, its props and labels | | `components/ui/onboarding/checklist.css` | The checklist's styles, imported by it | | `components/ui/onboarding/onboarding-agent.ts` | `useOnboardingAgent`, the agent bridge for the tour; nothing runs until you import it | | `components/ui/onboarding/checklist-agent.ts` | `useOnboardingChecklistAgent`, the same for the checklist | | `lib/spring.ts` | The spring math, shared with the color picker | ## Usage Describe the steps as data and control `open`. Each step has an `id`, a `title`, an optional `body` and a `target`. ```tsx title="product-tour.tsx" "use client"; import { useState } from "react"; import { Onboarding, type OnboardingStep } from "@/components/ui/onboarding/onboarding"; const steps: OnboardingStep[] = [ { id: "new", target: "#new-project", title: "Create a project", body: "Every project starts here." }, { id: "search", target: "#search", title: "Find anything", placement: "bottom" }, { id: "done", title: "All set", body: "Start the tour again from Help." }, ]; export function ProductTour() { const [open, setOpen] = useState(false); return ( <> console.log(reason, step)} /> ); } ``` Done finishes the tour as `completed`, Skip and Esc as `skipped`; `onFinish` and `onOpenChange(false)` hear it. Closing through `open={false}` calls neither: your app already knows. ### Steps without a target A step without a `target` stands in the centre of the screen. ```tsx title="centered.tsx" "use client"; import { useRef, useState } from "react"; import { Onboarding, type OnboardingStep } from "@/components/ui/onboarding/onboarding"; export function CenteredSteps() { const [open, setOpen] = useState(false); const [finish, setFinish] = useState(""); const chart = useRef(null); const steps: OnboardingStep[] = [ { id: "intro", title: "What is new", body: "A step without a target stands in the centre of the screen." }, { id: "chart", target: chart, title: "Weekly chart", body: "Steps with a target point at it.", placement: "bottom" }, { id: "outro", title: "That is all", body: "Done finishes the tour." }, ]; return (
{[40, 65, 30, 80, 55, 90, 70].map((height, day) => ( ))}
{finish} setFinish(`${reason} at ${step}`)} />
); } ``` ### Targets A `target` takes whichever form your app already has. `{ id }` needs no `#` or escaping, `{ testId }` is found by `data-testid` or the attribute `testIdAttribute` names (`"data-cy"`); a target the page replaces is found again. ```tsx title="targets.ts" import type { OnboardingStep } from "@/components/ui/onboarding/onboarding"; export const steps: OnboardingStep[] = [ { id: "selector", target: "#new-project", title: "A CSS selector" }, { id: "id", target: { id: "new-project" }, title: "An element's id, as it is" }, { id: "test-id", target: { testId: "search" }, title: "The test id your tests already use" }, { id: "element", target: document.body, title: "An element you hold" }, // A ref ({ current }) or a function that returns the element work too. ]; ``` ### Without dimming `overlay="none"` leaves the page bright and pressable and rings the target. Press the buttons while the tour is open. ```tsx title="no-overlay.tsx" "use client"; import { useRef, useState } from "react"; import { Onboarding, type OnboardingStep } from "@/components/ui/onboarding/onboarding"; export function RingTour() { const [open, setOpen] = useState(false); const [presses, setPresses] = useState(0); const format = useRef(null); const share = useRef(null); const steps: OnboardingStep[] = [ { id: "format", target: format, title: "Format", body: "The page stays bright and every button keeps working." }, { id: "share", target: share, title: "Share", body: "Press it while the tour is open." }, ]; return (
Presses: {presses}
); } ``` ### Controlled step `step` and `onStepChange` in your state: the buttons open the tour at any step, and the state follows Next and Back. ```tsx title="controlled.tsx" "use client"; import { useRef, useState } from "react"; import { Onboarding, type OnboardingStep } from "@/components/ui/onboarding/onboarding"; export function ControlledStep() { const [open, setOpen] = useState(false); const [step, setStep] = useState("inbox"); const inbox = useRef(null); const drafts = useRef(null); const sent = useRef(null); const steps: OnboardingStep[] = [ { id: "inbox", target: inbox, title: "Inbox", body: "New mail lands here.", placement: "right" }, { id: "drafts", target: drafts, title: "Drafts", body: "Unsent mail waits here.", placement: "right" }, { id: "sent", target: sent, title: "Sent", body: "Everything you sent.", placement: "right" }, ]; const start = (id: string) => { setStep(id); setOpen(true); }; return (
  • Inbox
  • Drafts
  • Sent
{steps.map((item) => ( ))}
step: {step}
); } ``` ### Acting on the target `advanceOn` moves the tour on when the person does what the step is about: `"click"` on a press on the target, `{ event, when }` on any other event there. Next still works beside it; `requireAction: true` takes Next away, so only the action goes on. ```tsx title="action-steps.ts" import type { OnboardingStep } from "@/components/ui/onboarding/onboarding"; export const steps: OnboardingStep[] = [ // Press New project, or Next. { id: "create", target: "#new-project", title: "Create a project", advanceOn: "click" }, // Only by typing a name: no Next. { id: "name", target: "#project-name", title: "Name it", advanceOn: { event: "input", when: (event) => (event.target as HTMLInputElement).value.length >= 3 }, requireAction: true, }, // Your app calls target.dispatchEvent(new CustomEvent("project-created", { bubbles: true })). { id: "publish", target: "#publish", title: "Publish it", advanceOn: { event: "project-created" }, requireAction: true }, ]; ``` ### Menu `before` gets the page ready for a step: here it opens the menu, and the cutout lands on Export once it is on the page. The first step goes on with a press on File, or with Next. ```tsx title="menu.tsx" "use client"; import { useRef, useState } from "react"; import { Onboarding, type OnboardingStep } from "@/components/ui/onboarding/onboarding"; export function MenuTour() { const [open, setOpen] = useState(false); const [menu, setMenu] = useState(false); const trigger = useRef(null); const exportItem = useRef(null); const steps: OnboardingStep[] = [ { id: "file", target: trigger, title: "The File menu", body: "Press File to open it.", advanceOn: "click", // Back from the next step closes the menu again. before: () => setMenu(false), }, { id: "export", target: exportItem, title: "Export", body: "Saves the project as a file.", placement: "right", // However the tour gets here, the menu is open; the step waits until the item is on the page. before: () => setMenu(true), }, ]; const close = (next: boolean) => { setOpen(next); if (!next) setMenu(false); }; return (
{menu ? (
) : null}
); } ``` ### Waiting for a target A step whose target is not on the page yet waits for it, up to its `timeout` (5 s), then shows in the centre. Here the report appears after 1.5 s; Archive never does. The line under the buttons is `onWaitChange`. ```tsx title="waiting.tsx" "use client"; import { useRef, useState } from "react"; import { Onboarding, type OnboardingStep, type OnboardingWait } from "@/components/ui/onboarding/onboarding"; export function WaitingTour() { const [open, setOpen] = useState(false); const [report, setReport] = useState(false); const [wait, setWait] = useState(null); const upload = useRef(null); const reportCard = useRef(null); const steps: OnboardingStep[] = [ { id: "upload", target: upload, title: "Upload", body: "Add a file to build a report.", // Back to this step hides the report, so Next shows the wait again. before: () => setReport(false), }, { id: "report", target: reportCard, title: "Your report", body: "It appears a moment after the upload.", // The report "loads" 1.5 s after the step becomes current; the step waits for it. before: ({ signal }) => { const timer = setTimeout(() => setReport(true), 1500); signal.addEventListener("abort", () => clearTimeout(timer)); }, }, { id: "archive", target: "#docs-waiting-archive", title: "Archive", body: "Its target never appears: after 2 s the step shows in the centre, with Next.", advanceOn: "click", timeout: 2000, }, { id: "done", title: "All set", body: "A step without a target never waits." }, ]; const close = (next: boolean) => { setOpen(next); if (!next) setReport(false); }; return (
{report ? (
Report · 12 rows
) : ( "No report yet" )}
{wait ? `waiting for ${wait.for} of “${wait.step}”` : "not waiting"}
); } ``` ### Drag and drop `areas` cuts drop zones out of the dimming beside the target and keeps them live, and the cutout follows the card while it is dragged. Drag the card to Done: the board's own `card-dropped` event moves the step on. ```tsx title="drag.tsx" "use client"; import { useRef, useState, type KeyboardEvent, type PointerEvent } from "react"; import { Onboarding, type OnboardingStep } from "@/components/ui/onboarding/onboarding"; const steps: OnboardingStep[] = [ { id: "drag", // The card is drawn anew in the column it lands in: `{ id }` finds it wherever it is. target: { id: "docs-drag-card" }, // The drop zone is cut out of the dimming too, and stays live. areas: [{ testId: "docs-drag-done" }], title: "Drag the card to Done", body: "Hold it and move it across: the cutout follows it, and the step goes on when it lands. Next works too.", advanceOn: { event: "card-dropped" }, }, { id: "landed", target: { testId: "docs-drag-done" }, title: "Done", body: "The step went on by an event of the board, dispatched when the card landed." }, ]; type Column = "todo" | "done"; export function DragTour() { const [open, setOpen] = useState(false); const [column, setColumn] = useState("todo"); const [offset, setOffset] = useState<{ x: number; y: number } | null>(null); const from = useRef({ x: 0, y: 0 }); const done = useRef(null); // The drop of the board: the card moves to the column and, landing in Done, tells the tour. const land = (to: Column) => { setColumn(to); if (to === "done") done.current?.dispatchEvent(new CustomEvent("card-dropped", { bubbles: true })); }; const onPointerDown = (event: PointerEvent) => { if (event.button !== 0) return; event.currentTarget.setPointerCapture(event.pointerId); from.current = { x: event.clientX, y: event.clientY }; setOffset({ x: 0, y: 0 }); }; const onPointerMove = (event: PointerEvent) => { if (offset === null) return; setOffset({ x: event.clientX - from.current.x, y: event.clientY - from.current.y }); }; const onPointerUp = (event: PointerEvent) => { if (offset === null) return; setOffset(null); const zone = done.current?.getBoundingClientRect(); const over = zone !== undefined && event.clientX >= zone.left && event.clientX <= zone.right && event.clientY >= zone.top && event.clientY <= zone.bottom; const to: Column = over ? "done" : "todo"; if (to !== column) land(to); }; // From the keyboard, Enter or Space sends the card to the other column. const onKeyDown = (event: KeyboardEvent) => { if (event.key !== "Enter" && event.key !== " ") return; event.preventDefault(); land(column === "todo" ? "done" : "todo"); }; const card = (
setOffset(null)} onKeyDown={onKeyDown} > Write the docs
); return (
To do {column === "todo" ? card : null}
Done {column === "done" ? card : null}
); } ``` ### Tours across pages Change the page in a step's `before` with your router; the next step waits for its target there. Mount the tour above the routes, such as in `app/layout.tsx`. ```tsx title="app/tour.tsx" "use client"; import { useRouter } from "next/navigation"; import { useState, type ReactNode } from "react"; import { Onboarding, type OnboardingStep } from "@/components/ui/onboarding/onboarding"; export function Tour({ children }: { children: ReactNode }) { const router = useRouter(); const [open, setOpen] = useState(false); const steps: OnboardingStep[] = [ { id: "projects", target: "#new-project", title: "Your projects", before: () => router.push("/") }, { id: "billing", target: "#billing", title: "Billing", before: () => router.push("/settings/billing") }, ]; return ( <> {children} ); } ``` ### Show once With `storageKey`, a `defaultOpen` tour that was completed or skipped stays closed on the next visit; an explicit `open` still shows it. Load the page mounts the tour again; Reset deletes the record. ```tsx title="show-once.tsx" "use client"; import { useRef, useState } from "react"; import { Onboarding, type OnboardingStep } from "@/components/ui/onboarding/onboarding"; const KEY = "docs-welcome-tour"; function readRecord() { try { return localStorage.getItem(KEY) ?? "no record"; } catch { return "no storage"; } } function WelcomeTour({ onChange }: { onChange: () => void }) { const help = useRef(null); const steps: OnboardingStep[] = [ { id: "welcome", title: "Welcome", body: "This tour opens by itself once." }, { id: "help", target: help, title: "Help", body: "Finish or skip it, then load the page again." }, ]; return ( <> ); } export function ShowOnce() { const [visit, setVisit] = useState(0); const [record, setRecord] = useState(""); const reset = () => { try { localStorage.removeItem(KEY); } catch {} setRecord(readRecord()); }; return (
{visit > 0 ? setRecord(readRecord())} /> : null} {record}
); } ``` ### Remind `remind` brings a `defaultOpen` tour with `storageKey` back every `every` (`'6h'`) for `for` (`'7d'`), never in the middle of typing or over a dialog. After one completion it offers Don't show again. Here +6 h moves the clock forward. ```tsx title="remind.tsx" "use client"; import { useEffect, useRef, useState } from "react"; import { Onboarding, type OnboardingStep } from "@/components/ui/onboarding/onboarding"; const KEY = "docs-remind-tour"; const HOUR = 60 * 60 * 1000; const EVERY = 6 * HOUR; const FOR = 7 * 24 * HOUR; const TIMES = ["firstShownAt", "lastShownAt", "finishedAt", "completedAt", "dismissedAt"] as const; type TourRecord = { [K in (typeof TIMES)[number]]?: number }; function load(): TourRecord | null | undefined { try { const raw = localStorage.getItem(KEY); return raw ? (JSON.parse(raw) as TourRecord) : null; } catch { return undefined; } } function inHours(ms: number) { const h = Math.ceil(ms / HOUR); return h >= 24 ? `${Math.floor(h / 24)} d ${h % 24} h` : `${h} h`; } /** The record and when the tour opens on its own next: `every` after the last show, within `for` of the first. */ function describe() { const record = load(); if (record === undefined) return "no storage"; if (record === null) return "Next show: on the next load\nno record"; const now = Date.now(); const first = record.firstShownAt ?? now; const next = (record.lastShownAt ?? record.finishedAt ?? first) + EVERY; const end = first + FOR; const when = record.dismissedAt !== undefined ? "No more shows: Don’t show again is checked" : now >= end || next >= end ? "No more shows: the seven days are over" : next <= now ? "Next show: on the next load" : `Next show: in ${inHours(next - now)}`; return `${when}\n${JSON.stringify(record)}`; } function RemindTour() { const help = useRef(null); const steps: OnboardingStep[] = [ { id: "welcome", title: "Welcome", body: "This tour comes back every six hours for a week." }, { id: "help", target: help, title: "Help", body: "Finish it once, and the next shows offer Don’t show again." }, ]; return ( <> ); } export function Remind() { const [visit, setVisit] = useState(0); const [state, setState] = useState(""); // The tour writes its record as it shows, finishes and as the checkbox changes; read it again often. useEffect(() => { setState(describe()); const timer = setInterval(() => setState(describe()), 500); return () => clearInterval(timer); }, []); // Every time in the record six hours earlier: the clock of the example goes forward. const forward = () => { const record = load(); if (!record) return; const moved: { [key: string]: unknown } = { ...record }; for (const field of TIMES) { const at = record[field]; if (at !== undefined) moved[field] = at - EVERY; } try { localStorage.setItem(KEY, JSON.stringify(moved)); } catch {} setState(describe()); }; const reset = () => { try { localStorage.removeItem(KEY); } catch {} setState(describe()); }; const [when, record] = state.split("\n"); return (
{visit > 0 ? : null} {when} {record}
); } ``` ## Island `OnboardingIsland` shows the same steps in the Island of your [Toaster](https://cloudlet.dev/docs/components/toaster) instead of the dark pill. The page stays bright, scrolls and takes presses; a ring stands on the target and a thin thread runs from the Island to it. Start the tour, press Like, send a notification in the second step, then finish: the notification waits in the stack and opens once the tour gives the Island back. ```tsx title="island.tsx" "use client"; import { useRef, useState } from "react"; import { useOptionalCloudlet } from "@cloudlet/toast"; import { OnboardingIsland, type OnboardingStep } from "@/components/ui/onboarding-island/onboarding-island"; export function IslandTour() { // The tour takes the controller of the nearest CloudletProvider: here, the Toaster of this page. const cloudlet = useOptionalCloudlet(); const [open, setOpen] = useState(false); const [likes, setLikes] = useState(0); const like = useRef(null); const send = useRef(null); const steps: OnboardingStep[] = [ { id: "like", target: like, title: "Like it", body: "The page stays bright: press Like, or scroll, while the tour is open." }, { id: "send", target: send, title: "Send a notification", body: "It waits in the stack while the tour holds the Island." }, { id: "done", title: "All set", body: "Done gives the Island back, and the notification opens." }, ]; return (
); } ``` ### Installation A registry item of its own. It brings the `onboarding` item for the steps, and `@cloudlet/toast` into `package.json`. It needs a mounted `Toaster` of the package: the `toaster` item's or your own. ```sh title="Terminal" npx shadcn@latest add https://cloudlet.dev/r/onboarding-island.json ``` | File | What it holds | | --- | --- | | `components/ui/onboarding-island/onboarding-island.tsx` | `OnboardingIsland`, its props and labels | | `components/ui/onboarding-island/onboarding-island.css` | The ring and the thread, imported by the component itself | | `components/ui/onboarding-island/thread.ts` | The thread's path and its bend towards the pointer | | `components/ui/onboarding-island/onboarding-island-agent.ts` | `useOnboardingIslandAgent`, the agent bridge for this tour; nothing runs until you import it | ### Usage Render the tour inside the `CloudletProvider` of your Toaster, or pass its `controller`. It takes every prop of `Onboarding` except `overlay`; the steps, their waits, `storageKey` and `remind` work the same. ```tsx title="island-tour.tsx" "use client"; import { useState } from "react"; import { OnboardingIsland, type OnboardingStep } from "@/components/ui/onboarding-island/onboarding-island"; const steps: OnboardingStep[] = [ { id: "new", target: "#new-project", title: "Create a project", body: "Every project starts here." }, { id: "done", title: "All set", body: "Start the tour again from Help." }, ]; export function IslandTour() { const [open, setOpen] = useState(false); return ( <> ); } ``` **Notifications wait.** While the tour holds the Island, notifications still arrive into the stack and its badge counts them, but none opens the Island, even with `attention: 'open'`; their timers run as usual, so one that should outlive the tour takes `duration: null` or an action. Screen readers still hear them. **Focus.** A tour opened right after a press (a Start tour button) moves focus into the Island, on Next; one that opens on its own (`defaultOpen`, `remind`) or by an agent leaves focus where it is and is announced. The Island is a landmark named by `labels.tour`: Tab and F6 reach it, ← → go back and on and Esc skips while focus is in it, and focus returns where it was when the tour ends. **The end.** Done says "You're all set" (`labels.complete`) for about 1.3 s, 0.6 s under reduced motion, before the Island folds back; Skip and Esc fold it at once. **Styling.** The ring and the thread take the Toaster's accent, which the component copies into `--onboarding-island-accent` on their layer, `.onboarding-island`; set `--onboarding-island-ring`, `--onboarding-island-thread` or `--onboarding-island-thread-opacity` (0.6) through `className` to change them. The Island itself follows the Toaster's theme and its own reduced-motion setting. Your own content in the Island, without a tour, goes through [`@cloudlet/toast/guide`](https://cloudlet.dev/docs/components/toaster/guide). ## Checklist `OnboardingChecklist` takes the same steps as tasks: a pill in the corner grows into a list, and the person does the tasks in any order. A press on a task shows it with a ring on its target; doing it there marks it done, and the list comes back with the next task ready, so Enter goes on. A step's `task` is its line in the list. ```tsx title="checklist.tsx" "use client"; import { useEffect, useRef, useState } from "react"; import { OnboardingChecklist } from "@/components/ui/onboarding/checklist"; import type { OnboardingStep } from "@/components/ui/onboarding/onboarding"; const KEY = "docs-get-started"; function readRecord() { try { return localStorage.getItem(KEY) ?? "no record"; } catch { return "no storage"; } } export function Checklist() { const project = useRef(null); const invite = useRef(null); const theme = useRef(null); const [open, setOpen] = useState(false); const [mount, setMount] = useState(0); const [record, setRecord] = useState(""); const [projects, setProjects] = useState(0); // The checklist writes its record after it renders the change. const refresh = () => setTimeout(() => setRecord(readRecord()), 0); useEffect(() => setRecord(readRecord()), []); const steps: OnboardingStep[] = [ { id: "project", target: project, task: "Create a project", title: "New project", body: "Press New project." }, { id: "invite", target: invite, task: "Invite a teammate", title: "Invite", body: "Press Invite." }, { id: "theme", target: theme, task: "Pick a theme", title: "Theme", body: "Press Theme." }, { id: "shortcuts", task: "Learn the shortcuts", title: "Shortcuts", body: "Press ? anywhere to see them." }, ]; const reset = () => { try { localStorage.removeItem(KEY); } catch {} setOpen(false); setMount((n) => n + 1); setRecord(readRecord()); }; return (
{record}
); } ``` **What marks a task done:** acting on its target during its show (a press, or the step's `advanceOn`), Done on a task without a target or with `requireAction: false`, or your app through a controlled `done`. **After a task.** `afterTask="list"` (the default) opens the list again when a show ends if it was open as the show started, with the next task marked and focused; `afterTask="pill"` stays folded. The panel folds only for a show or by the person's hand, and with `storageKey` stays as they left it across reloads. **Memory and finishing.** `storageKey` keeps the tasks done, the panel and how it finished: after All set or Dismiss a `defaultOpen` checklist stays closed, and an explicit `open` brings it back with its progress. Give it its own key, not the tour's. ```json title="localStorage" { "version": 1, "done": ["new", "invite"], "expanded": true, "outcome": "completed", "finishedAt": 1764400042000 } ``` **Corner.** `position` picks the corner. It knows nothing about the Toaster: when they share a corner, or on a phone, lift it through a class of yours. ```css title="globals.css" @media (max-width: 639px) { .onboarding-checklist.get-started[data-position^="bottom"] { bottom: calc(6.5rem + env(safe-area-inset-bottom, 0px)); } } ``` ## Styling The pill and the checklist are dark in both themes and read `--onboarding-*` variables on `.onboarding` (the tour's layer) and `.onboarding-checklist`: `background`, `foreground`, `muted`, `outline`, `button`, `primary`, `primary-foreground`, `focus`, `radius`, `max-width`, `shadow`, `dim`, `edge`, `ring`, `area-edge`, `area-ring`, `z-index`, `font-family`, `mono`; the checklist adds `--onboarding-checklist-track`, `accent`, `next`, `offset`, `width`, `radius` and `z-index`. ```css title="globals.css" .onboarding { --onboarding-radius: 1.25rem; --onboarding-dim: rgb(0 0 0 / 0.6); } ``` The tour's layer is in the browser's top layer (`popover="manual"`), above any `z-index`; it carries `data-pending` while a step waits and `data-dragging` during a drag. A tour over your app's own modal `` is not supported yet. ## Reduced motion Under `prefers-reduced-motion: reduce`, `reducedMotion`, or `data-reduced-motion` on `` or ``, steps and the checklist appear in place with a short fade instead of flying and growing. ## Agent `onboarding-agent.ts` connects the tour to the [agent bridge](https://cloudlet.dev/docs/agents), experimental for now. `useOnboardingAgent(agent, props, options)` takes the tour's props and returns them wrapped: ```tsx title="tour-agent.tsx" "use client"; import { createAgent } from "@cloudlet/agent"; import { useState } from "react"; import { Onboarding, type OnboardingStep } from "@/components/ui/onboarding/onboarding"; import { useOnboardingAgent } from "@/components/ui/onboarding/onboarding-agent"; const agent = createAgent(); const steps: OnboardingStep[] = [ { id: "new", target: "#new-project", title: "Create a project", body: "Press New project to go on.", advanceOn: "click", requireAction: true }, { id: "search", target: "#search", title: "Find anything" }, ]; export function TourAgent() { const [open, setOpen] = useState(false); const tour = useOnboardingAgent(agent, { steps, open, onOpenChange: setOpen, storageKey: "tour" }, { label: "Product tour" }); return ; } ``` The tour is one `OnboardingEntry` in the snapshot — `ref`, `component: 'onboarding'`, `label`, `open`, `step`, `steps` (each an `OnboardingEntryStep` with `id`, `title`, `body` and `waitsForPerson`), `waiting` and `remind` — readable while the tour is closed. Its verbs, an `OnboardingAction`, are `start [id?]`, `next`, `back`, `go [id]` and `close`; each answers with `{ open, step }`. - **The person's steps stay theirs.** `waitsForPerson` is true for a step with `requireAction` and a target; no verb moves past it. - **Waiting.** `waiting` is an `OnboardingEntryWaiting` (`step`, `for`, `target` as it reads: `id "billing"`, `test id "billing" ([data-testid])`) while the step waits; `next` is refused meanwhile. - **Changes** reach `agent.subscribe` under `open` and `step` with their author: `user`, `agent`, `app`, or `system` for a reminder. Closing carries `completed` or `skipped`. - **Reminders.** `remind` is `null` or an `OnboardingEntryRemind` (`nextAt`, `endsAt`, `dismissed`); `close` only puts the tour off, and only the person checks Don't show again. ### Checklist and the agent `useOnboardingChecklistAgent(agent, props, options)` from `checklist-agent.ts` does the same for the checklist: ```tsx title="get-started-agent.tsx" "use client"; import { createAgent } from "@cloudlet/agent"; import { OnboardingChecklist } from "@/components/ui/onboarding/checklist"; import { useOnboardingChecklistAgent } from "@/components/ui/onboarding/checklist-agent"; import type { OnboardingStep } from "@/components/ui/onboarding/onboarding"; const agent = createAgent(); const steps: OnboardingStep[] = [ { id: "new", target: "#new-project", task: "Create a project", title: "New project" }, { id: "shortcuts", task: "Learn the shortcuts", title: "Shortcuts", body: "Press ? anywhere to see them." }, ]; export function GetStartedAgent() { const checklist = useOnboardingChecklistAgent(agent, { steps, defaultOpen: true, storageKey: "get-started" }, { label: "Get started" }); return ; } ``` The checklist is one `OnboardingChecklistEntry` — `ref`, `component: 'onboarding-checklist'`, `label`, `open`, `expanded`, `active`, `done`, `total` and `tasks` (each an `OnboardingChecklistEntryTask` with `id`, `task`, `title`, `body` and `done`). Its verbs, an `OnboardingChecklistAction`, are `expand`, `collapse`, `show [id]` and `hide`; each answers with `{ expanded, active, done }`. No verb marks a task done, opens or dismisses the checklist: an agent can lead the person to a task, not do it for them. Changes carry their author as in the tour; the list opened again after a show goes with whoever ended it. ### Island and the agent `useOnboardingIslandAgent(agent, props, options)` from `onboarding-island-agent.ts` connects an `OnboardingIsland` the same way: the same `OnboardingEntry`, verbs and rules, its `label` taken from `labels.tour` unless `options.label` names it. ```tsx title="island-tour-agent.tsx" "use client"; import { createAgent } from "@cloudlet/agent"; import { useState } from "react"; import { OnboardingIsland, type OnboardingStep } from "@/components/ui/onboarding-island/onboarding-island"; import { useOnboardingIslandAgent } from "@/components/ui/onboarding-island/onboarding-island-agent"; const agent = createAgent(); const steps: OnboardingStep[] = [ { id: "new", target: "#new-project", title: "Create a project" }, { id: "search", target: "#search", title: "Find anything" }, ]; export function IslandTourAgent() { const [open, setOpen] = useState(false); const tour = useOnboardingIslandAgent(agent, { steps, open, onOpenChange: setOpen }); return ; } ``` **The Island is taken.** Only the tour's record describes the step. With `toasterAgent` of the same controller on the agent, the Toaster's record says just that the Island is held, `guest: { ref }` with the tour's `ref` (the adapter passes it as `guestRef`; the Island keeps `labels.tour` as its name for screen readers), and its `open` and `show` are refused with "A tour is in progress in the Island" until the tour ends. `OnboardingAgentOptions` and `OnboardingChecklistAgentOptions` take `name` (default `onboarding` and `checklist`) and `label` (default `Tour` and `Checklist`); `ONBOARDING_VERBS` and `ONBOARDING_CHECKLIST_VERBS` are the verbs' text for a model. The adapters carry copies of the bridge's protocol types, so they need no `@cloudlet/agent` import: `AgentEntryShape`, `AgentSignalShape`, `AgentValueShape`, `AgentPermissionShape`, `AgentStepCallShape`, `AgentStepNamesShape`, `AgentStepCheckShape`, `AgentRunContextShape`, `AgentRunOutcomeShape`, `AgentSummonOutcomeShape`, `AgentChangeShape`, `AgentVerbsShape`, `AgentComponentShape` and `AgentConnectorShape`. The tour's and the checklist's adapters share the author of a change through `commitNow`, `useChangeAuthor` with `ChangeAuthor` and `ChangeSourceShape`, and `useAgentPort` with `AgentPortMethods`, which you do not need to call. ## API Reference ### Props `OnboardingProps`; only `steps` is required. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `steps` | `readonly OnboardingStep[]` | — | The steps in order; every `id` unique. | | `open` | `boolean` | — | Whether the tour is shown (controlled); always shows it, whatever the record of `storageKey` says. | | `defaultOpen` | `boolean` | `false` | Opens the tour by itself after mount when it owns `open`, unless `storageKey` says it was finished; with `remind`, when a reminder is due. | | `onOpenChange` | `(open: boolean) => void` | — | Called when the person closes the tour (Done, Skip, Esc), and with `true` when a reminder opens it after mount; not when your app closes it through `open`. | | `step` | `string` | — | Id of the current step (controlled). | | `defaultStep` | `string` | the first step | The step an uncontrolled tour starts on, and returns to when it opens again. | | `onStepChange` | `(id: string) => void` | — | Called with the new step's id on Next, Back, the keys or a press on an `advanceOn` target. | | `onWaitChange` | `(wait: OnboardingWait \| null) => void` | — | The current step starts or stops waiting: `{ step, for: "before" \| "target" }` when it begins and when `for` changes, `null` once it shows or the tour closes; not on unmount. | | `onFinish` | `(finish: OnboardingFinish) => void` | — | How the person closed the tour: `{ reason: "completed" \| "skipped", step }`. | | `storageKey` | `string` | — | The localStorage key of the tour's record ([Show once](#show-once), [Remind](#remind)). | | `remind` | `OnboardingRemind` | — | `{ every?, for? }`: a `defaultOpen` tour with `storageKey` opens on its own again ([Remind schedule](#remind-schedule)). | | `overlay` | `"dim" \| "none"` | `"dim"` | `dim` darkens the page around the cutout and catches presses beside the target; `none` rings the target and leaves the page pressable. | | `exit` | `"collapse" \| "complete"` | `"collapse"` | How the tour leaves when your app closes it through `open`: `collapse` folds it back into the element it opened from, like Skip; `complete` opens the cutout past the screen, like Done. | | `labels` | `Partial` | `DEFAULT_LABELS` | Button texts and announcements; anything left out keeps its English default. | | `reducedMotion` | `boolean` | `false` | Moves without flight, as under the system's reduced motion. | | `testIdAttribute` | `string` | `"data-testid"` | The attribute a `{ testId }` target is found by, such as `"data-cy"` or `"data-test"`. | | `className` | `string` | — | Added to the tour's layer; set `--onboarding-*` variables through it. | The tour renders nothing on the server and decides after mount. A tour of one step has no count and no Back. In development the console warns about a target that can never point at anything, a step whose target was not found, a `remind` it cannot read or without `storageKey`, and a `before` or `when` that throws. ### Steps `OnboardingStep`: | Field | Type | Description | | --- | --- | --- | | `id` | `string` | Unique in the list; `step`, `defaultStep` and `onStepChange` speak in ids. | | `target` | `OnboardingTarget` | `string` (a selector), `{ id: string }` (by `getElementById`), `{ testId: string }` (by `testIdAttribute`, escaped for you), an `Element`, `RefObject` or `() => Element \| null`. Without one the pill stands in the centre. A target the page replaces is found again by the same `target`. | | `title` | `string` | The pill's heading and the dialog's name. | | `body` | `string` | The step's text and the dialog's description. | | `placement` | `OnboardingPlacement` | `"auto"` (default), `"top"`, `"bottom"`, `"left"` or `"right"`: the side of the target for the pill; it flips when that side has no room. | | `advanceOn` | `"click" \| OnboardingAdvance` | The step also goes on when the person presses its target, or on `{ event, when? }`: when `event` happens on the target or one of its `areas`, or bubbles up to it, and `when`, if given, returns `true`. It goes on after your own handlers have run; a `stopPropagation()` inside the target hides the event. Next and → still go on, unless the step has `requireAction`. | | `requireAction` | `boolean` | The step goes on only by the person's action on its target: no Next, → does nothing, the agent's `next` is refused. Without `advanceOn` a press on the target goes on. A step without a target, or with one that never shows, keeps Next. Default `false` in the tour, `true` for a task with a target in the checklist. | | `areas` | `readonly OnboardingTarget[]` | More elements cut out of the dimming and kept live beside the target, such as drop zones; followed as they move, in the Tab round, and listened on by `advanceOn`. With `overlay="dim"` the rest of the page stays blocked. | | `timeout` | `number` | How long, in ms from the moment the step became current, it waits for `before` and its target: `5000` by default, `0` not to wait, `Infinity` as long as it is current. Past it the step shows in the centre and a step with `requireAction` gets Next back; a target that shows up later is still taken at the next press, key or transition on the page. | | `task` | `string` | The step's short line in a checklist; without it the checklist shows `title`. The tour does not read it. | | `before` | `(context: OnboardingBeforeContext) => void \| Promise` | Gets the page ready each time the step becomes current, however it got there; a returned promise is waited for within `timeout`. `context.signal` aborts when the step stops being current, the tour closes or unmounts, or `timeout` runs out. A step that should close a menu again closes it in the `before` of the step before it. | During a drag — a pointer pressed and moved, an HTML drag, or a library such as dnd-kit — the tour follows the target every frame, the pill holds still and lets drops through, and Esc and the arrows belong to the drag. ### Remind schedule `OnboardingRemind` is `{ every?: OnboardingDuration; for?: OnboardingDuration }`, `'6h'` and `'7d'` by default; `for` counts from the first show, `every` from the last. `OnboardingDuration` is ``number | `${number}${"s" | "m" | "h" | "d" | "w"}` ``: milliseconds, or a number and a unit (`'90s'`, `'1.5d'`). - It checks at mount and when the person comes back to the tab, never on a timer; while focus is in a field or a modal dialog is open, it waits until they leave it. - Skip and Esc put it off until `every` has passed again; completing it does not stop the reminders, only Don't show again and the end of `for` do. - With a controlled `open`, `remind` only offers the checkbox and keeps the record. Opening on its own after mount calls `onOpenChange(true)`. - `useOnboardingReminder({ enabled, storageKey, remind, onDue })` is the hook the tour runs itself; `OnboardingReminderOptions` take `enabled` and `onDue({ initial })`. The record stays version 1 when a reminder writes it: ```json title="localStorage" { "version": 1, "firstShownAt": 1764400000000, "lastShownAt": 1764421600000, "outcome": "skipped", "finishedAt": 1764421610000, "completedAt": 1764400042000, "dismissedAt": 1764421605000 } ``` `completedAt` is the first completion, `dismissedAt` is set while Don't show again is checked. To start everyone over, put a version in the key: `storageKey="welcome-v2"`. ### Keyboard and screen readers Opening moves focus into the pill, from the element that had it, and closing returns focus there. → and ← go to the next and the previous step, → on the last step finishes the tour, and Esc skips it. The keys are left alone while focus is in a field, a widget that takes arrows or something draggable, during a drag, or when your page has handled the key. Tab goes round the pill's buttons, the target and the step's areas. The pill is a non-modal `role="dialog"` named by the step's title and described by its text. A live region speaks each step a moment after it shows, "Step 2 of 5. Create a project. Every project starts here."; while a step waits the pill is `aria-busy="true"` and the region says "Loading…". The checklist's pill is a button with `aria-expanded`, named by its progress, "Get started, 2 of 5 done"; Enter opens the panel, a region with the tasks, Collapse and Dismiss. A done task stays with `aria-disabled`. Esc and Collapse fold the panel and return focus to the pill; after a task's show focus lands on the next task, or on the pill with `afterTask="pill"`. A live region speaks "Create a project: done. 2 of 5." and "All set". ### Labels `OnboardingLabels`; `{n}` is the step's place and `{total}` the number of steps. | Key | Default | Where | | --- | --- | --- | | `next` | `Next` | the button to the next step | | `done` | `Done` | the button on the last step, instead of Next | | `back` | `Back` | the button to the previous step, disabled on the first | | `skip` | `Skip` | the button that closes the tour as skipped | | `counter` | `{n}/{total}` | the count in the pill | | `position` | `Step {n} of {total}` | spoken before the step's title and text | | `waiting` | `Loading…` | spoken in place of the step's text while the step waits | | `dontShowAgain` | `Don't show again` | the checkbox of a `remind` tour after its first completion | ### Island props `OnboardingIslandProps`: every prop of `OnboardingProps` except `overlay`, with these differences; only `steps` is required. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `controller` | `ReactCloudletController \| null` | the nearest `CloudletProvider`'s | The controller whose `Toaster` carries the tour. Without one, or without a mounted Toaster, the tour shows nothing until they come, and development says so. | | `exit` | `"collapse" \| "complete"` | `"collapse"` | How the tour leaves when your app closes it through `open`: `collapse` folds the Island back at once, like Skip; `complete` says "You're all set" first, like Done. | | `labels` | `Partial` | `ISLAND_LABELS` | The tour's labels plus `tour` and `complete`. | | `guestRef` | `string` | `labels.tour` | The name agents read for the tour in the Toaster's record, `guest: { ref }`. `useOnboardingIslandAgent` sets it to the tour record's `ref`; screen readers keep naming the Island by `labels.tour`. | | `reducedMotion` | `boolean` | `false` | The ring and the thread move without flight or bend. The Island follows the Toaster's own setting. | | `className` | `string` | — | Added to the layer of the ring and the thread; set `--onboarding-island-*` through it. | `OnboardingIsland` re-exports the step types, `OnboardingStep`, `OnboardingTarget`, `OnboardingPlacement`, `OnboardingAdvance`, `OnboardingBeforeContext`, `OnboardingWait` and `OnboardingFinish`, so a tour in the Island imports nothing from `onboarding.tsx`. In the Island, Don't show again is a quiet button rather than a checkbox: it finishes the tour as skipped and stops the reminders. ### Island labels `OnboardingIslandLabels`: the keys of `OnboardingLabels` and two of its own. | Key | Default | Where | | --- | --- | --- | | `tour` | `Product tour` | the Island's name for screen readers while the tour holds it, and the tour's name for agents | | `complete` | `You're all set` | what the Island says for a moment after Done | ### Checklist props `OnboardingChecklistProps`; only `steps` is required. `open`, `expanded`, `active` and `done` are each controlled or not. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `steps` | `readonly OnboardingStep[]` | — | The tasks: the tour's steps, shown by `task` (else `title`). | | `open` | `boolean` | — | Whether the checklist is on the screen (controlled); shows it even when it finished. | | `defaultOpen` | `boolean` | `false` | Shows it after mount when it owns `open`, unless `storageKey` says it finished. | | `onOpenChange` | `(open: boolean) => void` | — | Called with `false` when it leaves on its own: Dismiss, or every task done; not when your app closes it. | | `expanded` | `boolean` | — | Whether the panel with the list is open rather than the pill (controlled). | | `defaultExpanded` | `boolean` | `false` | Whether the panel starts open; each new show starts so. With `storageKey`, the way the person last left it wins. | | `onExpandedChange` | `(expanded: boolean) => void` | — | The person opened or folded the panel (the pill, Collapse, Esc), a task's show folded it or `afterTask` opened it again, or the All set beat did. | | `afterTask` | `OnboardingChecklistAfterTask` | `"list"` | When a task's show ends: `"list"` opens the panel again if it was open as the show started, with the next task marked and focused; `"pill"` stays folded. | | `active` | `string \| null` | — | Id of the task shown now (controlled); a task that is done or not in the list does not show. | | `onActiveChange` | `(active: string \| null) => void` | — | The id when the person presses a task that is not done; `null` when its show ends. | | `done` | `readonly string[]` | — | Ids of the tasks done (controlled); ids the list does not have are not counted. | | `defaultDone` | `readonly string[]` | `[]` | Tasks done at first when it owns `done`; the `storageKey` record wins when there is one. | | `onDoneChange` | `(done: readonly string[]) => void` | — | The new list when a task gets done in its show. | | `onFinish` | `(finish: OnboardingChecklistFinish) => void` | — | `{ reason: "completed" \| "dismissed" }` after the All set beat or Dismiss; not when your app closes it. | | `storageKey` | `string` | — | The localStorage key of the checklist's own record, not the tour's. | | `position` | `OnboardingChecklistPosition` | `"bottom-right"` | `"bottom-right"`, `"bottom-left"`, `"top-right"` or `"top-left"`, `--onboarding-checklist-offset` (12px) from the edges plus the safe area. | | `overlay` | `"dim" \| "none"` | `"none"` | How a task's show points at its target: `none` rings it, `dim` darkens the page around it. | | `labels` | `Partial` | `DEFAULT_CHECKLIST_LABELS` | Texts and announcements; anything left out keeps its English default. | | `reducedMotion` | `boolean` | `false` | Moves without growth, as under the system's reduced motion. | | `testIdAttribute` | `string` | `"data-testid"` | The attribute a `{ testId }` target is found by, as in the tour. | | `className` | `string` | — | Added to the checklist's layer and to its task's show; set `--onboarding-*` and `--onboarding-checklist-*` through it. A Tailwind utility here needs `!`. | A task's show is the tour's `Onboarding` of that one step, so its `placement`, `before` and `timeout` work as in the tour; Close, Esc and a press on the pill end it without marking the task. A task whose target was not found shows in the centre with Close alone and is not marked, and acting on a target while its task is not shown marks nothing. `OnboardingChecklistFinish` is `{ reason: OnboardingChecklistOutcome }`, where `OnboardingChecklistOutcome` is `"completed" | "dismissed"`, the same word the record keeps as `outcome`. The record is `{ version: 1, done: string[], expanded?, outcome?, finishedAt? }`; ids the steps no longer have are ignored and new tasks start not done. The checklist reuses helpers that `onboarding.tsx` exports and you do not need to call: `MOTION`, `useControllable`, `prefersStill`, `snapshot`, `useTargetWarnings` and the `OnboardingTargetFound` context. ### Checklist labels `OnboardingChecklistLabels`; `{n}` is the number of tasks done, `{total}` the number of tasks and `{task}` a task's line. | Key | Default | Where | | --- | --- | --- | | `title` | `Get started` | the pill's caption and the panel's heading | | `counter` | `{n}/{total}` | the count in the pill | | `progress` | `{n} of {total}` | the count beside the heading, and in the pill's name | | `collapse` | `Collapse` | the button that folds the panel | | `dismiss` | `Dismiss` | the button that puts the checklist away | | `allSet` | `All set` | the pill's caption once every task is done, also spoken | | `done` | `done` | spoken after a done task's name, and in the pill's name | | `close` | `Close` | the button that ends a task's show without marking it | | `taskDone` | `{task}: done. {n} of {total}.` | spoken when a task gets done | --- # Notification center > A panel at the edge of the screen for your app's own notifications, from your server, a socket or local state, in groups that expand into stacks, with a bell that counts what is unread. Part of @cloudlet/toast, with a shadcn registry item for the bell. Source: https://cloudlet.dev/docs/components/notification-center `NotificationCenter` shows your app's own array of notifications in a panel at the edge of the screen. It never changes the array: clearing, actions and reading call your callbacks, you update the array, and the panel animates the difference. ## Preview Live preview at https://cloudlet.dev/docs/components/notification-center#preview: a bell button with a badge of unread notifications, and three buttons that change the Preview's own list, as an app changes its own. Send a notification adds one unread notification with a Remind me action, as a socket message would; Send a group adds three with one `group`, a stack in the panel that expands; Load from the server adds two older ones a moment later, as a REST answer would. The panel's clear buttons, swipes and Clear all call `onDismiss` and `onClear`, which take the notifications out of the list, and the unread ones the open panel shows go to `onRead`, which marks them read. Controls set the panel's side and backdrop. The code they make: ```tsx ``` - `side`: `right` (the default), `left`; physical, so the panel stays at that edge in RTL too. - `backdrop`: `blur` (the default: the page blurred under the panel), `tint` (a tone, no blur), `none` (nothing under the panel). A prop at its default is left out; with every default the code has only the list and its callbacks. ## Installation The center ships in `@cloudlet/toast` 1.5.0 or newer, at its own entry `@cloudlet/toast/center`; it needs no Toaster. ### From npm ```sh title="Terminal" npm install @cloudlet/toast ``` Import `NotificationCenter` and `useNotificationCenter` from `@cloudlet/toast/center`, and the styles from `@cloudlet/toast/styles.css` ([Import the styles](https://cloudlet.dev/docs/components/toaster#import-the-styles)). ### The shadcn registry item ```sh title="Terminal" npx shadcn@latest add https://cloudlet.dev/r/notification-center.json ``` It copies three files and adds `@cloudlet/toast` as a dependency: - **`components/ui/notification-center.tsx`**: `NotificationCenter`, `NotificationCenterButton` (a bell with a badge of your count), and `useNotificationCenter` with the types. - **`components/ui/notification-center-button.tsx`**: the bell on its own, which the first file re-exports. - **`components/ui/notification-center.css`**: your shadcn tokens mapped onto the panel's, and the bell's styles. ## Usage Give the panel your array and update it in the callbacks. Each notification needs a stable `id` and a `time`; the panel shows the newest first. ```tsx title="components/notifications.tsx" 'use client'; import { useState } from 'react'; import { NotificationCenter, NotificationCenterButton, useNotificationCenter, type NotificationItem, } from '@/components/ui/notification-center'; export function Notifications({ initial }: { initial: NotificationItem[] }) { const center = useNotificationCenter(); const [notifications, setNotifications] = useState(initial); const remove = (ids: readonly string[]) => setNotifications((list) => list.filter((item) => !ids.includes(item.id))); const markRead = (ids: readonly string[]) => setNotifications((list) => list.map((item) => (ids.includes(item.id) ? { ...item, read: true } : item))); return ( <> item.read === false).length} /> remove([id])} onClear={remove} onRead={markRead} /> ); } ``` Without `onDismiss` and `onClear` there are no clear buttons and no swipes. A card you keep after `onDismiss`, while your server confirms, springs back and leaves once your array drops it. ### From a REST API Fetch the list, put it in state, and send your requests from the callbacks; the example updates the list optimistically. ```tsx title="rest.tsx" "use client"; import { useCallback, useEffect, useState } from "react"; import { NotificationCenter, NotificationCenterButton, useNotificationCenter, type NotificationItem, } from "@/components/ui/notification-center"; const MINUTE = 60_000; /** Stands in for `fetch("/api/notifications")`: your server answers with its list a moment later. */ function fetchNotifications(): Promise { const now = Date.now(); return new Promise((resolve) => setTimeout( () => resolve([ { id: "forecast-3", title: "Rain on the way", description: "Showers reach the coast around 4 pm.", kind: "info", time: now - 5 * MINUTE, read: false }, { id: "forecast-2", title: "Storm warning lifted", description: "The front moved out to sea.", kind: "success", time: now - 2 * 60 * MINUTE }, { id: "forecast-1", title: "Weekly outlook", description: "Mostly sunny, a cloud or two.", time: now - 3 * 24 * 60 * MINUTE }, ]), 600, ), ); } export function RestInbox({ theme }: { theme: "light" | "dark" }) { const center = useNotificationCenter(); const [notifications, setNotifications] = useState([]); const [loading, setLoading] = useState(false); const load = useCallback(async () => { setLoading(true); setNotifications(await fetchNotifications()); setLoading(false); }, []); useEffect(() => { void load(); }, [load]); // Optimistic: the list changes at once, and your DELETE request goes out next to it. const remove = (ids: readonly string[]) => setNotifications((list) => list.filter((item) => !ids.includes(item.id))); const markRead = (ids: readonly string[]) => setNotifications((list) => list.map((item) => (ids.includes(item.id) ? { ...item, read: true } : item))); return (
item.read === false).length} /> remove([id])} onClear={remove} onRead={markRead} theme={theme} />
); } ``` ### From a WebSocket Add each message to the same state. A notification that arrives while the panel is open grows in at the top. ```tsx title="socket.tsx" "use client"; import { useEffect, useState } from "react"; import { NotificationCenter, NotificationCenterButton, useNotificationCenter, type NotificationItem, } from "@/components/ui/notification-center"; const CLOUDS = ["Cumulus", "Cirrus", "Stratus", "Nimbus"]; /** Stands in for a WebSocket: a message every two seconds until the returned function closes it. */ function connect(onMessage: (item: NotificationItem) => void) { let count = 0; const timer = setInterval(() => { count += 1; const cloud = CLOUDS[count % CLOUDS.length]; onMessage({ id: `cloud-${Date.now()}`, title: `${cloud} overhead`, description: "Seen from the station.", time: Date.now(), read: false }); }, 2000); return () => clearInterval(timer); } export function LiveFeed({ theme }: { theme: "light" | "dark" }) { const center = useNotificationCenter(); const [notifications, setNotifications] = useState([]); const [live, setLive] = useState(false); // Each message joins the list; the open panel grows it in at the top. useEffect(() => (live ? connect((item) => setNotifications((list) => [item, ...list])) : undefined), [live]); const remove = (ids: readonly string[]) => setNotifications((list) => list.filter((item) => !ids.includes(item.id))); const markRead = (ids: readonly string[]) => setNotifications((list) => list.map((item) => (ids.includes(item.id) ? { ...item, read: true } : item))); return (
item.read === false).length} /> remove([id])} onClear={remove} onRead={markRead} theme={theme} />
); } ``` ### Groups Notifications with the same `group` stand as one stack that expands. Clear on a group and Clear all take two presses and pass the ids to `onClear`. ```tsx title="groups.tsx" "use client"; import { useState } from "react"; import { NotificationCenter, NotificationCenterButton, useNotificationCenter, type NotificationItem, } from "@/components/ui/notification-center"; const MINUTE = 60_000; function journal(now: number): NotificationItem[] { return [ { id: "deploy-3", title: "Deploy finished", description: "production · build 483 is live", kind: "success", group: "Deploys", time: now - MINUTE }, { id: "deploy-2", title: "Health checks passed", description: "12 of 12 instances", kind: "success", group: "Deploys", time: now - 2 * MINUTE }, { id: "deploy-1", title: "Deploy started", description: "production · build 483", kind: "info", group: "Deploys", time: now - 3 * MINUTE }, { id: "invoice", title: "Invoice paid", description: "November · 3 seats", time: now - 40 * MINUTE }, { id: "mail-2", title: "Anna replied", description: "See you at 7.", group: "Mail", time: now - 90 * MINUTE }, { id: "mail-1", title: "Mark mentioned you", description: "in the launch checklist", group: "Mail", time: now - 120 * MINUTE }, ]; } export function GroupedJournal({ theme }: { theme: "light" | "dark" }) { const center = useNotificationCenter(); const [notifications, setNotifications] = useState(() => journal(Date.now())); const deploy = () => setNotifications((list) => [ { id: `deploy-${Date.now()}`, title: "Rollback ready", description: "build 482 can go back live", kind: "warning", group: "Deploys", time: Date.now() }, ...list, ]); // Clear on a group and Clear all pass the ids they clear. const remove = (ids: readonly string[]) => setNotifications((list) => list.filter((item) => !ids.includes(item.id))); return (
remove([id])} onClear={remove} theme={theme} />
); } ``` ### Read state and badge `read: false` marks a notification unread. The open panel reports the unread ids it shows to `onRead`, once per opening; the badge is your own `count`. ```tsx title="read.tsx" "use client"; import { useState } from "react"; import { NotificationCenter, NotificationCenterButton, useNotificationCenter, type NotificationItem, } from "@/components/ui/notification-center"; const MINUTE = 60_000; function unreadNews(now: number): NotificationItem[] { return [ { id: "news-3", title: "Fog this morning", description: "It lifts by 10.", time: now - MINUTE, read: false }, { id: "news-2", title: "Pollen count high", description: "Birch, mostly.", kind: "warning", time: now - 20 * MINUTE, read: false }, { id: "news-1", title: "New station online", description: "Readings every minute.", kind: "success", time: now - 4 * 60 * MINUTE }, ]; } export function ReadState({ theme }: { theme: "light" | "dark" }) { const center = useNotificationCenter(); const [notifications, setNotifications] = useState(() => unreadNews(Date.now())); // The badge is your count: here, what is still `read: false`. const unread = notifications.filter((item) => item.read === false).length; // Called with the unread ids the panel showed: your PATCH request goes out here. const markRead = (ids: readonly string[]) => setNotifications((list) => list.map((item) => (ids.includes(item.id) ? { ...item, read: true } : item))); return (
{unread} unread
); } ``` ### Custom cards `renderNotification` draws a card from the default parts ([`NotificationParts`](#notificationparts)); the panel keeps the card's motion, swipe and keyboard order. `actions` call `onAction(id, actionId)`. ```tsx title="render.tsx" "use client"; import { useState } from "react"; import { NotificationCenter, NotificationCenterButton, useNotificationCenter, type NotificationItem, } from "@/components/ui/notification-center"; type Message = { author: string; tone: string }; const MINUTE = 60_000; function messages(now: number): NotificationItem[] { return [ { id: "m-2", title: "Anna", description: "The radar shows a gap at 5. Walk then?", time: now - 2 * MINUTE, data: { author: "Anna", tone: "bg-pink-200" }, actions: [{ id: "reply", label: "Reply" }] }, { id: "m-1", title: "Oleg", description: "Uploaded the cloud photos.", time: now - 30 * MINUTE, data: { author: "Oleg", tone: "bg-teal-200" } }, ]; } export function MessageCards({ theme }: { theme: "light" | "dark" }) { const center = useNotificationCenter(); const [notifications, setNotifications] = useState(() => messages(Date.now())); const [replied, setReplied] = useState(""); const remove = (ids: readonly string[]) => setNotifications((list) => list.filter((item) => !ids.includes(item.id))); return (
{replied && `Replying to ${replied}`} remove([id])} onClear={remove} onAction={(id) => { setReplied((notifications.find((item) => item.id === id)?.data as Message).author); center.setOpen(false); }} // The center keeps the card, its motion and swipe; this draws what is inside it from the default parts. renderNotification={(item, parts) => { const message = item.data as Message; return (
{parts.title} {parts.description} {parts.actions}
{parts.time}
); }} theme={theme} />
); } ``` ### Controlled open `useNotificationCenter({ open, onOpenChange })` lets your state decide. Without a button, give the same props to `NotificationCenter` and leave out `center`. ```tsx title="controlled.tsx" "use client"; import { useState } from "react"; import { NotificationCenter, NotificationCenterButton, useNotificationCenter, type NotificationItem, } from "@/components/ui/notification-center"; const ALERT: NotificationItem = { id: "frost", title: "Frost tonight", description: "Cover the seedlings before 9 pm.", kind: "warning", time: Date.now(), actions: [{ id: "done", label: "Done" }], }; export function ControlledCenter({ theme }: { theme: "light" | "dark" }) { // Your state decides: the bell, Escape, a press outside and the close button ask through onOpenChange. const [open, setOpen] = useState(false); const center = useNotificationCenter({ open, onOpenChange: setOpen }); const [notifications, setNotifications] = useState([ALERT]); return (
{open ? "Open" : "Closed"} { // Done closes the center from your code and takes the alert out. setOpen(false); setNotifications([]); }} theme={theme} />
); } ``` ### Your own button Spread `triggerProps` on any button; several buttons can share one center, and focus returns to the one that opened it. ```tsx title="components/inbox.tsx" 'use client'; import { NotificationCenter, useNotificationCenter, type NotificationItem } from '@cloudlet/toast/center'; export function Inbox({ notifications, onClear }: { notifications: NotificationItem[]; onClear: (ids: readonly string[]) => void }) { const center = useNotificationCenter(); const unread = notifications.filter((item) => item.read === false).length; return ( <> ); } ``` ### Swipes A card swiped away from the edge asks `onDismiss` past 40 % of its width or after a flick of at least 60 px; a swipe towards the edge closes the drawer. Speed is measured over the last 100 ms, so a burst of trackpad events is no flick. ### Backdrop [`backdrop`](#notificationcenter-props) is `blur` (default; one layer in Safari, the tone of `tint` below 48rem), `tint` (a tone, no blur, cheaper on heavy pages) or `none`. Reduced motion turns the drawer into a fade and turns swipes off; reduced transparency draws `tint` in place of `blur`. ### SSR and Next.js `NotificationCenter` renders nothing on the server and in the first client render, so hydration never mismatches; the hook renders the same on both sides. ### Content Security Policy The panel writes its motion as CSSOM rules in its own `