npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@dreamtree-org/twreact-ui

v2.2.9

Published

A comprehensive React + Tailwind components library for building modern web apps

Readme

Dreamtree UI

A comprehensive React + Tailwind CSS components library for building modern web applications. Built with accessibility, customization, and developer experience in mind.

npm version License: MIT Website

About the Company

Dreamtree UI is built and maintained under Dreamtree-Org — a team crafting thoughtful, developer-first software for the modern web. We believe great products start with a great foundation, and that's exactly what this design system aims to be: a polished, open, and dependable building block for teams everywhere.

🌐 Website: www.dreamtreeglobal.com

Author & Maintainer

Partha Preetham Krishna — Dreamtree-Org 📧 [email protected]

Have an idea, a bug, or just want to say hi? Reach out anytime — feedback from developers like you is what keeps this design system growing.

💚 Sponsor & Support

Dreamtree UI is free and open source, built in the open and powered entirely by passion and late nights. Every feature you rely on — every accessible button, dark-mode-ready table, and tree-shakeable export — represents hours of careful craft so that your product can ship faster and feel better.

If this design system has saved you time, sparked an idea, or made your app a little more beautiful, please consider supporting its continued development. Your sponsorship keeps the updates coming, the bugs squashed, and the docs sharp — for the whole community. Even the smallest contribution is a huge encouragement. 🙏

☕ Make a one-tap donation via UPI

📷 Scan the QR with any UPI app (Google Pay, PhonePe, Paytm, BHIM, …) to pay instantly:

UPI ID: dhrugantha.llp@kotak  •  Payee: Dreamtree-Org

📱 On mobile, you can also tap the button below — it opens your UPI app directly. On desktop, scan the QR above or copy the UPI ID into your payment app.

Pay via UPI

🤝 Become a Sponsor

Want to back the project long-term or as a company? You can sponsor the package directly:

Every star ⭐, share, and contribution helps more than you know. Thank you for being part of the journey!

Features

  • 🎨 Modern Design: Clean, professional components with Tailwind CSS
  • 🌙 Dark Mode: Built-in dark/light mode support
  • ♿ Accessible: ARIA compliant with keyboard navigation
  • 📱 Responsive: Mobile-first design approach
  • 🎯 TypeScript Ready: Full TypeScript support
  • 🧩 Composable: Flexible APIs with props, slots, and render functions
  • 🎨 Customizable: Easy theming with Tailwind config
  • 📦 Tree Shakeable: Import only what you need
  • 🤖 AI-native: a companion MCP server serves live prop contracts to coding agents

Installation

npm install @dreamtree-org/twreact-ui
# or
yarn add @dreamtree-org/twreact-ui

Upgrading from 1.x

2.0.0 removes the 1.x deprecated colour props and renames the icon props to the shared leftIcon / rightIcon. A codemod handles most of it:

npm install @dreamtree-org/twreact-ui@^2.0.0
npx jscodeshift -t node_modules/@dreamtree-org/twreact-ui/codemods/v2.cjs src/
  • Input: icon + iconPosition became leftIcon / rightIcon. A controlled Input's clear button now calls only onClear, so clear value there.
  • Tabs.Tab: iconLeft / iconRight became leftIcon / rightIcon.
  • ProgressBar: the HEX color / bgColor / valueColor props are gone; use variant.
  • Checkbox / Switch / Rate: borderColor, activeColor / inactiveColor and the blue / indigo / purple presets are gone.

doc/MIGRATION-2.0.md has before/after code for each change and lists what the codemod leaves to you.

Import the stylesheet once (app entry or root layout):

import '@dreamtree-org/twreact-ui/dist/index.css';

Bundle size and tree-shaking

Import from the package root. Bundlers (Vite, webpack 5, esbuild, Rollup, Next.js) resolve it to a per-module ES build (dist/esm/, via the module field and the module export condition), and the package declares "sideEffects": ["**/*.css"], so only the components you import end up in your bundle. import { Button } from '@dreamtree-org/twreact-ui' costs about 8 KB gzip, down from about 100 KB. require(), Jest and plain Node keep getting the CommonJS build (dist/index.js).

There are no per-component subpaths such as @dreamtree-org/twreact-ui/button. The root import already tree-shakes. The only subpaths are the two optional entry points below, which exist because they need an extra dependency. Existing file paths (dist/index.css, dist/tokens/*, tokens/*, dist/index.esm.js, package.json, …) still resolve through the exports map.

Next.js App Router

Every module that uses React starts with 'use client', so Server Components can import components directly. You no longer need a "use client" wrapper file that re-exports the library:

// app/page.tsx — a Server Component
import { Button, cn } from '@dreamtree-org/twreact-ui';

export default function Page() {
  return <Button className={cn('mt-4')}>Save</Button>;
}

cn, Helpers and Emitter carry no directive, so they also run on the server. Two React Server Component rules still apply. You cannot pass functions (onClick, render, …) from a Server Component to these Client Components. You also cannot dot into a client export, so <Card.Header>, <Tabs.List> and <Dialog.Footer> must be used inside a 'use client' file. In Vite, Rollup can log Module level directives cause errors when bundled, "use client" … was ignored. This message is harmless. To hide it, filter MODULE_LEVEL_DIRECTIVE in build.rollupOptions.onwarn.

Optional entry points: charts, rich text and motion

Charts and the rich-text editor wrap third-party libraries, so they live on their own entry points and use optional peer dependencies. The motion (scroll-storytelling) components need no dependency at all but are kept off the root so app bundles never carry them. If you never import these entry points you install nothing extra, and nothing changes in your bundle — the root @dreamtree-org/twreact-ui import never touches them.

| Entry point | Exports | Install first | |---|---|---| | @dreamtree-org/twreact-ui/charts | LineChart, BarChart, AreaChart, DonutChart, Sparkline, ScatterChart | npm install recharts (recharts 2.15+ or 3.x; React 18 apps also npm install react-is@18) | | @dreamtree-org/twreact-ui/rich-text | RichTextEditor | npm install @tiptap/react @tiptap/pm @tiptap/starter-kit (Tiptap 3) | | @dreamtree-org/twreact-ui/motion | ScrollStage, Reveal, RevealGroup, LogoMarquee, CountUp, StatStrip, StackedCards, DeviceFrame, DeviceMorphHero, BentoExpandGrid, TestimonialSpotlight, PhotoCollage, RotatingBadge, SmoothScrollProvider, useScrollProgress, useSmoothScroll | Nothing. Optional: npm install lenis for SmoothScrollProvider |

import { LineChart, DonutChart } from '@dreamtree-org/twreact-ui/charts';
import { RichTextEditor } from '@dreamtree-org/twreact-ui/rich-text';
import { StackedCards, LogoMarquee } from '@dreamtree-org/twreact-ui/motion';

All three ship ESM (with 'use client'), CommonJS and TypeScript declarations, and resolve under every TypeScript moduleResolution (bundler, node16/nodenext and legacy node). Their styles are already in dist/index.css. Rich-text output is HTML from the user — sanitize it on the server before you store or render it (see doc/RichTextEditor.md).

Quick Start

import { Button, Input, Card } from '@dreamtree-org/twreact-ui';

function App() {
  return (
    <div className="p-4">
      <Card>
        <Card.Header>
          <Card.Title>Welcome to Dreamtree UI</Card.Title>
        </Card.Header>
        <Card.Content>
          <Input placeholder="Enter your name" />
          <Button className="mt-4">Get Started</Button>
        </Card.Content>
      </Card>
    </div>
  );
}

AI agents (MCP server)

If you build UI with an AI coding agent (Claude Code, Cursor, …), wire up the Model Context Protocol server bundled in this package. It gives the agent live, queryable access to the library — list_components, get_component (authoritative props/variants/sizes/examples per component), search_components, the per-component docs as resources, and a compose_ui prompt — so it stops guessing prop names.

Add it to your MCP client config (no extra install — it ships with the library):

{
  "mcpServers": {
    "dreamtree-ui": {
      "command": "npx",
      "args": ["-y", "@dreamtree-org/twreact-ui", "mcp"]
    }
  }
}

The catalog is a build-time snapshot baked into the package, so the server is self-contained (no source or network needed at runtime) and always matches the library version you installed.

The MCP server also serves the skill below as the dreamtree://skill resource, so MCP clients get it with zero install.

AI assistant skill (file install)

If your assistant reads a project skill / rules file rather than MCP, install the bundled skill into your repo with one command:

npx @dreamtree-org/twreact-ui init --ai claude
#                                    ^ claude | cursor | copilot | generic

| Provider | Installs to | | --------- | ----------- | | claude | .claude/skills/dreamtree-ui/SKILL.md | | cursor | .cursor/rules/dreamtree-ui.mdc | | copilot | .github/copilot-instructions.md | | generic | ai-skills/dreamtree-ui.md |

The skill primes the assistant on this library's components, the shared variant/size/theming vocabulary, and the provider wiring. Add --out <path> to choose a destination or --force to overwrite. Re-run after upgrading the library to refresh it.

Components

Core Components

Button

Versatile button component with multiple variants and states.

Props:

  • variant: 'primary' | 'secondary' | 'outline' | 'ghost' | 'destructive' | 'success' | 'warning' | 'link' (default: 'primary'). link is a text link (no background or padding, underline on hover, 44px on touch); colour it with tone
  • tone: 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'info' — text colour of variant="link" (default: 'primary')
  • size: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' (default: 'md') — heights h-7 / h-8 / h-10 / h-12 / h-14 / h-16
  • disabled: boolean
  • loading: boolean
  • leftIcon: ReactNode
  • rightIcon: ReactNode
  • fullWidth: boolean
  • as: ElementType — render as a link or router Link with the Button's look (a bare href renders an <a>)
  • href: string
  • className: string
<Button variant="primary" size="lg" loading>
  Loading...
</Button>
<Button href="tel:+919800000000" variant="outline">Call</Button>
<Button as={Link} to="/move-in">Move in</Button>

Input

Enhanced text input with validation states, icons, and clear functionality.

Props:

  • type: 'text' | 'password' | 'email' | 'search' | 'number' | 'tel' | 'url'
  • size: 'sm' | 'md' | 'lg' (default: 'md')
  • label: string
  • placeholder: string
  • error: string
  • success: string
  • helperText: ReactNode — hint below the input, linked via aria-describedby; replaced by error / success while shown
  • disabled: boolean
  • required: boolean
  • clearable: boolean
  • leftIcon: ReactNode — icon before the value (2.0: was icon)
  • rightIcon: ReactNode — icon after the value (2.0: was icon + iconPosition="right")
  • showCount: boolean
  • maxLength: number
  • readOnly: boolean
  • onClear: () => void — called by the clear button. A controlled Input clears its own value here (2.0: no synthetic onChange)
<Input
  type="email"
  label="Email Address"
  placeholder="Enter your email"
  error="Please enter a valid email"
  clearable
  required
/>

Select

Advanced select component with search, multi-select, and grouping support.

Props:

  • options: Array<{value: any, label: string, disabled?: boolean, group?: string}> (with grouped: also [{ label, options }] groups)
  • value: any | Array
  • onChange: (value: any) => void
  • placeholder: string (default: 'Select an option...') — shown muted (text-muted) with data-empty on the trigger while nothing is selected
  • label: string — associated with the trigger (accessible name = label + value)
  • error: string
  • helperText: ReactNode — hint below the control; replaced by error while shown
  • disabled: boolean
  • required: boolean
  • multiSelect: boolean
  • searchable: boolean
  • grouped: boolean — groups objects or flat options with a group key; malformed input is skipped (console warning), never thrown
  • creatable: boolean
  • onCreateOption: (value: string) => void
  • onSearch: (term: string) => void
  • loading: boolean
  • selectAllOption: boolean
  • closeOnSelect: boolean
  • maxTagCount: number (default: 3)
  • allowClear: boolean (default: false; set it when the field may be emptied)
  • size: 'sm' | 'md' | 'lg' (default: 'md') — md grows to the 44px touch target on coarse pointers; lg is 44px everywhere
<Select
  options={[
    { value: 'us', label: 'United States' },
    { value: 'ca', label: 'Canada' }
  ]}
  multiSelect
  searchable
  placeholder="Choose countries"
/>

Form

Declarative form builder with validation support.

Props:

  • fields: Array
  • onSubmit: (data: any) => void
  • defaultValues: object
  • validationSchema: any
  • submitText: string (default: 'Submit')
  • resetText: string (default: 'Reset')
  • showReset: boolean (default: true)

Field types: text, email, password, number, tel, url, select, date, textarea, checkbox, radio, file, switch, color (mounts ColorPicker; accepts swatches / showAlpha), custom. Every field accepts helperText (hint under the field; the validation error replaces it while shown).

const formFields = [
  {
    type: 'text',
    name: 'firstName',
    label: 'First Name',
    required: true,
    placeholder: 'Enter your first name'
  },
  {
    type: 'email',
    name: 'email',
    label: 'Email',
    required: true
  }
];

<Form
  fields={formFields}
  onSubmit={(data) => console.log(data)}
  submitText="Create Account"
/>

Table

Feature-rich data table with sorting, filtering, pagination, conditional row actions, and expandable row details.

Props:

  • data: Array
  • columns: Array — label is text or a node (e.g. an aligned or icon header); filter placeholders and validation messages fall back to key when it is not text
  • sortable: boolean (default: true)
  • filterable: boolean — per-column filter inputs; filter client-side data as you type (not in serverSide mode)
  • globalSearch: boolean — search box; filters client-side data with or without filterable (skips searchable: false columns)
  • selectable: boolean
  • pagination: boolean
  • pageSize: number (default: 25)
  • onSort: (key: string, direction: 'asc' | 'desc') => void
  • onFilter: (filters: object) => void
  • onSelectionChange: (selectedRows: object[]) => void
  • onRowClick: (row: object, index: number) => void
  • onPageChange: (page: number) => void — also called when the table clamps a page that no longer exists after the data shrinks
  • hasDetails: boolean | ((row, index) => boolean)
  • DetailsComponent: ReactComponent
  • withAction: boolean (default: true)
  • onAction: ({ action, row }) => void
  • actions: Array | ((row, index) => Array)
  • replaceDefaultActions: boolean (default: false)
  • interactive: boolean (default: false) — enable inline cell editing (double-click cell or press 'e' key on focused cell to enter edit mode, Tab/Shift+Tab to switch cells, Enter to save modified changes, Escape to stop editing)
  • editKeyBinding: string | function (default: "e") — key binding for entering edit mode on active cell
  • newRowPosition: 'bottom' | 'top' (default: 'bottom') — position to insert new empty rows
  • addRowRef: ReactRef — external ref for triggering new row insertion from external buttons
  • onSave: ({ updatedRows, newRows, allData, tableData }) => void | Promise<allData | { data: allData } | void>
  • onEdit: ({ rowKey, colKey, newValue, row, action, isNew }) => void
  • showSerial: boolean (default: true)
  • paginationPosition: 'top' | 'bottom' | 'both' (default: 'both') — which pager renders with pagination: the toolbar's compact pager, the footer, or both. 'bottom' keeps the toolbar (search, reload, page size) without the second pager
  • showToolbar: boolean (default: true) — false hides the toolbar (reload, page size, result count, pager header) and the column picker; interactive save controls still render
  • showColumnPicker: boolean (default: true) — hide just the column-picker button and its column
  • wrapCells: boolean (default: false) — let every cell wrap; a column's own wrap wins
  • mobileMaxFields: number — cap the fields shown on each mobile card (column order, after hideOnMobile)
  • serverSide / totalRecords: in server-side mode the "start - end of total" counter reads totalRecords

Column extras: searchable: false keeps a column out of the global search (ids, codes), wrap: true lets its text wrap instead of staying on one line, and hideOnMobile: true leaves it off the mobile card view (desktop is unaffected).

An Action is { name, label, icon, render?, onClick?, hidden?, disabled?, inline? }. label, icon, hidden and disabled each accept a value or a (row, index) => value producer, so actions can vary per row. inline: true renders the action as an icon button in the row itself instead of inside the kebab menu; when no menu actions remain for a row, the kebab is not rendered.

Supplied actions are merged onto the built-in Edit/Delete/View set by name — { name: 'edit', onClick } patches just that handler and keeps the default label and icon, and { name: 'delete', hidden: true } removes a default. Entries with an unrecognised name are appended. Pass replaceDefaultActions to skip merging and use only your own set. See doc/Table.md for the full contract.

const columns = [
  { key: 'name', label: 'Name', sortable: true },
  { key: 'email', label: 'Email', sortable: true },
  { key: 'role', label: 'Role' }
];

<Table
  columns={columns}
  data={users}
  sortable
  filterable
  pagination
  pageSize={10}
/>

DatePicker

Calendar-based date selection with keyboard navigation.

Props:

  • value: Date | string
  • onChange: (date: Date | null) => void
  • placeholder: string (default: 'Select date...') — shown muted (text-muted) with data-empty on the trigger while empty (same for DateRangePicker)
  • label: string
  • error: string
  • helperText: ReactNode — hint below the trigger; replaced by error while shown
  • disabled: boolean
  • required: boolean
  • minDate: Date | string
  • maxDate: Date | string
  • weekStartsOn: 0 | 1 (default: 0)
  • portal: boolean
  • displayFormat: string (default: 'MMM dd, yyyy')
  • locale: Locale
  • showClear: boolean (default: true)
  • closeOnSelect: boolean (default: true)
<DatePicker
  label="Birth Date"
  minDate={new Date('1900-01-01')}
  maxDate={new Date()}
  placeholder="Select your birth date"
/>

Navigation Components

Sidebar

Collapsible sidebar navigation with nested items.

Props:

  • items: Array
  • collapsed: boolean (default: false)
  • collapsible: boolean (default: true) — false removes the md+ collapse/expand toggle; the phone drawer keeps its 44px "Close navigation" button
  • onToggle: () => void
  • logo: ReactNode
  • user: {name: string, email: string, avatar?: string, menuItems?: Array}
  • onUserClick: (user: object) => void
  • linkAs: ElementType (default: "a") — e.g. Next.js Link
  • expandedIds / defaultExpandedIds: string[] — open groups (controlled / uncontrolled); onExpandedChange: (ids: string[]) => void
  • footer: ReactNode | ({ collapsed, isMobile, closeMobile }) => ReactNode — pinned region above the user block
  • stickyOffset: number | string — height of a top bar above the sidebar (sticks below it, fits the viewport); containerClassName for the outer sticky wrapper
  • isMobileOpen / setIsMobileOpen: mobile drawer — inert while closed; focus-trapped, Escape-to-close and focus-restoring while open

Every item renders as an <a>. Give an item an href and it becomes a real link, so Ctrl/Cmd-click or middle-click opens it in a new tab. Parents with an href navigate and expand; their chevron toggles without navigating. The group holding an active: true item (any depth) opens on load. Items take badge (+ accessible badgeLabel) and top-level group (section heading, a divider when collapsed — same as AppShell). With onUserClick the user block is a real <button>.

const sidebarItems = [
  {
    id: 'dashboard',
    label: 'Dashboard',
    href: '/dashboard',
    icon: <Home className="h-4 w-4" />,
    active: true
  },
  {
    id: 'users',
    label: 'Users',
    href: '/users',
    icon: <Users className="h-4 w-4" />,
    children: [
      { id: 'all-users', label: 'All Users', href: '/users' },
      { id: 'new-user', label: 'Add New User', href: '/users/new' }
    ]
  }
];

<Sidebar
  items={sidebarItems}
  logo={<div className="text-xl font-bold">Dreamtree</div>}
  user={{ name: 'John Doe', email: '[email protected]' }}
/>

Navbar

Top navigation bar with user menu and notifications.

Props:

  • logo: ReactNode (truncates on narrow screens)
  • center: ReactNode — centre slot (e.g. a search field); shrinks first so the bar fits a 390px phone
  • items: Array
  • user: {name: string, email: string, avatar?: string, menuItems?: Array} — without avatar, the menu shows name initials; below sm the logout icon moves into the user menu as "Sign out"
  • notifications: Array
  • searchable: boolean
  • onSearch: (term: string) => void
  • onNotificationClick: (notifications: Array) => void
  • onUserClick: (user: object) => void
  • leftIcon: ReactNode | false
  • onLeftIconClick: (event) => void
  • leftIconLabel: string (default: "Go back") — the left button's accessible name, e.g. "Open navigation" when it opens a Sidebar drawer
  • leftIconProps: ButtonHTMLAttributes — spread onto the left button (e.g. aria-expanded, aria-controls); className merges last
  • rightMenuContent: ReactNode | (props) => ReactNode — replaces the notifications menu; an element renders as is, a function receives { notifications, ...navbarProps }
<Navbar
  logo={<div className="text-xl font-bold">Dreamtree</div>}
  items={navItems}
  user={user}
  notifications={notifications}
  searchable
  onSearch={(term) => console.log(term)}
/>

FootNav

Fixed bottom tab bar for phones (md:hidden). Uses the semantic bg-surface / border-line tokens, so it follows dark mode.

Props:

  • items: Array<{ id, label, icon, onClick?, active?, badge?, variant?, 'aria-'?, 'data-'? }>
  • className: string

variant: 'action' renders the item as a raised circular primary button (FAB), e.g. a centre "+" that opens a sheet. aria-* and data-* item keys reach the button, so an item can carry aria-haspopup="dialog" and aria-expanded. The active item gets a tinted primary background, text-primary-700 and aria-current="page" (inactive tabs are neutral text-muted). Badges sit on their own item's icon. Items share the width and labels truncate, so five tabs fit a 375px screen.

<FootNav
  items={[
    { id: 'home', label: 'Home', icon: <Home />, active: true, onClick: () => navigate('/') },
    { id: 'inbox', label: 'Inbox', icon: <Inbox />, badge: 3, onClick: () => navigate('/inbox') },
  ]}
/>

Breadcrumbs

Breadcrumb trail with an optional Home link.

Props:

  • items: Array<{ id?, label, href?, icon?, onClick? }> — id is optional (used as the React key when present)
  • separator: ReactNode
  • showHome: boolean (default: true)
  • homeIcon: ReactNode
  • onHomeClick: () => void
<Breadcrumbs items={[{ label: 'Projects', href: '/projects' }, { label: 'Alpha' }]} />

Feedback Components

Alert

Status messages and notifications with different variants.

Props:

  • variant: 'success' | 'error' | 'warning' | 'info' (default: 'info')
  • title: string
  • children: ReactNode
  • dismissible: boolean
  • onDismiss: () => void
<Alert variant="success" title="Success!" dismissible>
  Your changes have been saved successfully.
</Alert>

Toast

Notification messages with different types, actions, bottom progress bar, and positioning.

Props:

  • id: string
  • title: string
  • message: string
  • description: string
  • type: 'success' | 'error' | 'warning' | 'info' | 'default' (default: 'info')
  • duration: number (default: 5000)
  • statusIcon: ReactNode
  • actions: Array<{ label: string, onClick?: (e: Event) => void, variant?: 'primary' | 'secondary', dismiss?: boolean }>
  • footerNote: ReactNode
  • showFooterNote: boolean (default: false)
  • onClose: (id: string) => void
  • position: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left' | 'top-center' | 'bottom-center'

App-level provider (recommended). Wrap the app once in ToastProvider; every useToast() below it shares one queue and the provider renders it — no per-screen ToastContainer:

import { ToastProvider, useToast } from '@dreamtree-org/twreact-ui';

<ToastProvider position="top-right">
  <App />
</ToastProvider>;

function SaveButton() {
  const { toast } = useToast();
  return <button onClick={() => toast.success('Saved')}>Save</button>;
}

Standalone (no provider). Outside a provider each useToast() owns its own queue; render it with ToastContainer. Under a provider, a ToastContainer handed the provider's own toasts renders nothing, so it never double-renders while you migrate.

import { useToast, ToastContainer } from '@dreamtree-org/twreact-ui';

function App() {
  const { toast, toasts, removeToast } = useToast();

  const showSuccess = () => {
    toast.success('Changes saved', 'Task has been updated with the recent changes.', {
      duration: 4000,
      showFooterNote: true,
      actions: [
        { label: 'Undo', onClick: () => console.log('Undo clicked') },
      ],
    });
  };

  return (
    <div>
      <button onClick={showSuccess}>Show Notification</button>
      <ToastContainer toasts={toasts} onRemove={removeToast} />
    </div>
  );
}

Utility Components

Card

Content containers with header, body, and footer sections.

Props:

  • children: ReactNode
  • hover: boolean
  • className: string
<Card hover>
  <Card.Header>
    <Card.Title>Card Title</Card.Title>
    <Card.Description>Card description</Card.Description>
  </Card.Header>
  <Card.Content>
    Card content goes here
  </Card.Content>
  <Card.Footer>
    <Button>Action</Button>
  </Card.Footer>
</Card>

Avatar

User profile images with fallbacks and status indicators.

Props:

  • src: string
  • alt: string
  • name: string
  • size: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' (default: 'md')
  • shape: 'circle' | 'square' | 'rounded' (default: 'circle')
  • status: 'online' | 'offline' | 'away' | 'busy'
<Avatar
  src="https://example.com/avatar.jpg"
  name="John Doe"
  size="lg"
  status="online"
/>

AvatarGroup

Overlapping stack of avatars with a "+N" overflow tile.

Props:

  • max: number. Avatars past max collapse into a "+N" tile
  • size: Avatar size passed to every child that doesn't set its own (default: 'md')
<AvatarGroup max={3} size="sm">
  <Avatar name="Ana" />
  <Avatar name="Ben" />
  <Avatar name="Cy" />
  <Avatar name="Dee" />
</AvatarGroup>

Badge

Status indicators and labels with different variants.

Props:

  • children: ReactNode
  • variant: 'default' | 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'info' | 'outline' (default: 'default')
  • size: 'sm' | 'md' | 'lg' (default: 'md')
  • rounded: boolean (default: true)
  • dot: boolean. A status dot before the label (default: false)
  • icon: ReactNode. A leading icon
  • max: number. A number child above max shows ${max}+
<Badge variant="success" size="sm">
  Active
</Badge>

Tabs

Tabbed content organization with different styles.

Props:

  • items: Array<{id: string, label: string, content: ReactNode, icon?: ReactNode, badge?: string}>
  • defaultActiveTab: string
  • orientation: 'horizontal' | 'vertical' (default: 'horizontal')
  • variant: 'default' | 'pills' | 'underline' (default: 'default')
  • onTabChange: (tabId: string) => void
const tabItems = [
  {
    id: 'overview',
    label: 'Overview',
    content: <div>Overview content</div>
  },
  {
    id: 'settings',
    label: 'Settings',
    content: <div>Settings content</div>
  }
];

<Tabs items={tabItems} variant="pills" />

Overlays, inputs and lists

Interaction primitives that products used to compose by hand. All are forwardRef, accept className + ...rest, are keyboard-operable with explicit ARIA, dark-mode aware and respect prefers-reduced-motion.

| Component | Group | Use for | |---|---|---| | Drawer | Feedback | Side/edge sheet (placement right/left/top/bottom, size sm–full) — record peeks and editors. placement="bottom" is a phone bottom sheet (grab handle, swipeToClose, rounded top, safe-area padding). Same isOpen/onClose contract as Dialog; focus trap, Escape/backdrop close, focus restore, scroll lock; Drawer.Header/Body/Footer | | Sheet | Feedback | Phone-native sheet (placement bottom/top/left/right): snapPoints (viewport fractions, activeSnap/defaultSnap/onSnapChange), drag-to-dismiss with rubber band and flick, keyboard-aware via visualViewport, opt-in scaleBackground. open (or isOpen) + onClose(reason); focus trap, Escape/backdrop close, focus restore, scroll lock; Sheet.Header/Body/Footer. Use for phone sheets; keep Drawer for record peeks | | Popover | Core | Anchored, click-triggered panel with interactive content (unlike Tooltip). Controlled/uncontrolled open, placement with flip, Escape/outside-click close, aria-expanded/aria-controls/aria-haspopup="dialog" | | Textarea | Core | Multi-line input mirroring Input: label, error, helperText, required, showCount/maxLength, autoResize/maxRows | | Slider | Core | Single value or [low, high] range; min/max/step, arrows/PageUp/PageDown/Home/End, role="slider" with full aria-value* | | Sortable | Utility | Drag-to-reorder list (pointer events, no extra dependency) + keyboard reordering (Space, arrows, Space/Escape) with live announcements; items, onReorder, renderItem, getKey | | SortableGroup | Utility | Moves items between Sortable lists (each with an id): pointer drag or cross-axis arrow keys, onMove({ item, from, to }), and canDrop(item, target, from) which marks and announces a refused list before the drop | | Tour | Feedback | Step-based onboarding: spotlight on each target (selector or ref), Back/Next/Skip/Finish, open/onClose/onFinish, scrolls targets into view | | ActionSheet | Feedback | iOS action sheet on Sheet: actions=[{ key?, label, icon?, tone?: 'default' | 'destructive', disabled?, onSelect }], optional title/message, a separate Cancel button, onClose(reason) | | SegmentedControl | Core | Radiogroup view toggle (list/board, day/week): options, value/defaultValue + onChange, size, fullWidth, name for forms; arrow keys move the selection. Use Tabs variant="segmented" when the choice switches panels | | SwipeableListItem | Core | Mail-style swipe-to-reveal row: leadingActions/trailingActions, fullSwipe commits the outer action, controlled open; a "More actions" button reaches every action without gestures. Table cards take swipeActions | | SearchField | Core | iOS-style search input: clear button, phone Cancel, onValueChange/onSearch; results/renderResults show in a Sheet on phones and a popover elsewhere (presentation) | | QuantityStepper | Core | − / value / + spinbutton for cart lines and buy boxes: value/defaultValue + onChange(number), min/max/step, size, loading, label/hideLabel, formatValue; arrows/PageUp/PageDown/Home/End, 44px buttons on touch | | OptionCard / OptionCardGroup | Core | Selectable choice tiles (title, description, media, badge) for template, block and starter-kit pickers. The group (value/onChange, columns 1–4, multiple) is a radiogroup (checkbox group with multiple) with arrow-key focus; a standalone card is a toggle (aria-pressed) | | ImageGallery | Utility | Product photos: layout thumbs-below / thumbs-side / mosaic, ratio, controlled index / onIndexChange, swipe, arrow keys, click-to-zoom, a Dialog lightbox, counter badge, placeholder for missing images | | PullToRefresh | Utility | Touch pull-to-refresh around a scroller: onRefresh returns a promise, threshold, maxPull, disabled, scrollRef | | BottomActionBar | Block | Sticky bottom bar for a form's primary action: pb-safe, rides above the on-screen keyboard (keyboardAware), stackOnMobile; add <BottomActionBar.Spacer /> at the end of the page |

import { Drawer, Sheet, Popover, Textarea, Slider, Sortable, SortableGroup, Tour, Button } from '@dreamtree-org/twreact-ui';

<Drawer isOpen={open} onClose={() => setOpen(false)} title="Edit task" footer={<Button onClick={save}>Save</Button>}>
  <Textarea label="Description" autoResize showCount maxLength={500} />
</Drawer>

<Sheet open={filtersOpen} onClose={() => setFiltersOpen(false)} title="Filters" snapPoints={[0.5, 1]}>
  <Sheet.Body>…</Sheet.Body>
  <Sheet.Footer><Button onClick={apply}>Apply</Button></Sheet.Footer>
</Sheet>

<Popover trigger={<Button variant="outline">Filters</Button>} title="Filters">
  <Slider label="Budget" defaultValue={[2000, 8000]} min={0} max={10000} step={500} showValue />
</Popover>

<Sortable aria-label="Backlog" items={tasks} onReorder={setTasks} renderItem={(t) => t.title} />

<SortableGroup onMove={({ item, from, to }) => moveTask(item, from, to)} canDrop={(task, target) => canEnter(task, target.listId)}>
  <Sortable id="backlog" aria-label="Backlog" items={backlog} onReorder={setBacklog} />
  <Sortable id="sprint" aria-label="Sprint" items={sprint} onReorder={setSprint} />
</SortableGroup>

<Tour open={tourOpen} steps={[{ title: 'Welcome' }, { target: '[data-tour="new-task"]', title: 'Capture work' }]} onClose={() => setTourOpen(false)} />

Charts (optional entry point)

Import from @dreamtree-org/twreact-ui/charts after npm install recharts. A data-first API over recharts: pass rows as data, the x-axis key as index and the series keys as categories. Colours are design tokens ('primary', 'success-600', …) resolved from the --dt-* variables, so charts follow your theme and dark mode. Every chart is responsive, forwardRef + className + ...rest, a named role="img" (title / description) with a visually-hidden data table for screen readers (accessibleTable), shows emptyState for empty data, and disables animation under prefers-reduced-motion.

| Component | Use for | |---|---| | LineChart | Trends over time (curveType, showDots, connectNulls) | | BarChart | Comparisons — grouped, stacked or horizontal | | AreaChart | Volume over time, optionally stacked | | DonutChart | Part-to-whole (variant="donut" or "pie", centerLabel) | | Sparkline | Word-sized trend for stat cards and table cells | | ScatterChart | Two numeric axes, one point per entity: x + y keys, optional index (entity name) and category (series), xAxisLabel / yAxisLabel; single points sit on padded axes |

Shared props: valueFormatter, height, showLegend, showTooltip, showXAxis, showYAxis, showGrid, colors, animate.

import { LineChart, DonutChart, Sparkline, ScatterChart } from '@dreamtree-org/twreact-ui/charts';

<LineChart
  data={[{ month: 'Jan', revenue: 4200 }, { month: 'Feb', revenue: 5100 }]}
  index="month"
  categories={['revenue']}
  valueFormatter={(v) => `$${v.toLocaleString()}`}
  title="Revenue, Jan–Feb"
/>
<DonutChart data={byStatus} index="status" category="tasks" centerLabel="63 tasks" title="Tasks by status" />
<Sparkline data={weekly} category="signups" color="success" title="Signups, last 4 weeks" />
<ScatterChart data={projects} x="health" y="variance" index="project" category="department" title="Health vs budget variance" />

Rich text (optional entry point)

RichTextEditor — import from @dreamtree-org/twreact-ui/rich-text after npm install @tiptap/react @tiptap/pm @tiptap/starter-kit. A Tiptap (StarterKit) field with the same label / error / helperText / required wiring as Input; controlled (value + onChange(html)) or uncontrolled (defaultValue), outputFormat="json" for Tiptap JSON, disabled / readOnly, minHeight / maxHeight, and a toolbar (bold, italic, strike, code, headings, lists, quote, link, undo/redo) that is a role="toolbar" of real buttons with aria-pressed and arrow-key roving focus. The ref is an imperative handle (editor, focus(), getHTML(), getJSON(), setContent(), clear()). SSR-safe: the editor mounts on the client.

import { RichTextEditor } from '@dreamtree-org/twreact-ui/rich-text';

<RichTextEditor label="Description" placeholder="Describe the task…" value={html} onChange={setHtml} maxHeight={320} />

The HTML comes from the user. Sanitize it on the server (e.g. DOMPurify / sanitize-html) before storing or rendering it; this library ships no sanitizer.

Motion: scroll storytelling (optional entry point)

Import from @dreamtree-org/twreact-ui/motion — landing-page sections that tell a story as the page scrolls (overview: doc/Motion.md). One shared requestAnimationFrame + IntersectionObserver engine drives them by writing CSS variables (--dt-p, 0–1), so React does not re-render per frame and only on-screen sections do any work. No animation library is bundled; the entry is gated at 12 KB gzipped (npm run motion:size).

| Component | Use for | |---|---| | ScrollStage | A pinned scene: content sticks while the page scrolls length vh (default 300, 150 below md); progress in --dt-p, children(progress) and onProgress | | useScrollProgress | The hook under it: useScrollProgress(ref, { mode: 'view' \| 'pin', start, end, onChange }) → { get, subscribe } | | Reveal / RevealGroup | Entrances on scroll (fade-up, fade, scale, clip, split-words), with delay / stagger | | LogoMarquee | Endless client strip (speed px/s, rows, fadeEdges); the loop copy is aria-hidden | | CountUp / StatStrip | Numbers that count up on view (en-IN grouping by default); the server renders the real value | | StackedCards | Sticky cards that stack, shrink and dim, with an alternating tilt | | DeviceFrame | CSS-only phone / tablet / laptop / browser mock-up | | DeviceMorphHero | Full-bleed media that shrinks into a device, which slides aside as the copy fades in | | BentoExpandGrid | Photo grid whose hovered or focused tile grows; a snap scroller on phones | | TestimonialSpotlight | Quotes beside a logo tile grid; tab-list dots, pausable autoplay | | PhotoCollage / RotatingBadge | Overlapping photos with parallax and stat chips; a turning circular text badge | | SmoothScrollProvider / useSmoothScroll | Opt-in Lenis smooth scroll (npm install lenis, pass lenis={Lenis}); scrollTo works either way |

import { DeviceMorphHero, LogoMarquee, StatStrip, StackedCards } from '@dreamtree-org/twreact-ui/motion';

<DeviceMorphHero media={{ video: '/intro.mp4', poster: '/intro.jpg', alt: 'Product tour' }} device="phone" content={<HeroCopy />} />
<LogoMarquee items={['Schoo360', 'TradeOS', { src: '/acme.svg', alt: 'Acme' }]} speed={40} />
<StatStrip items={[{ value: 500, suffix: '+', label: 'Projects' }, { value: 14, label: 'Years' }]} />
<StackedCards items={pillars} stickyTop={80} tilt={1} scaleBack={0.95} />

Server rendering and reduced motion. The server renders every component in its final state — real numbers, visible text, the device beside the copy — and motion only starts after hydration. With prefers-reduced-motion: reduce, pins become normal flow, counters show the final number, marquees become a static wrapped row, and tilt and parallax drop to 0. Content already on screen at load is never hidden by Reveal. Scroll defaults come from the new scroll tokens (scroll.stickyTop 80px, scroll.sceneLength 300vh, scroll.sceneLengthMobile 150vh).

Page blocks

Page-level patterns extracted from the Dreamtree products. Build pages from these before composing layouts by hand.

| Block | Use for | |---|---| | AppShell | Product shell: sidebar, top bar, mobile drawer (nav, linkAs); control the drawer with navOpen / onNavOpenChange, drop the desktop top bar with topbarFrom="below-lg" | | PageHeader | The page's h1, subtitle, one primary action, back link | | StatCard | KPI tile with icon, tone and change; children render under the value (a ProgressBar, a link), tinted colours the whole card by tone | | ProductCard | Storefront product tile: cover (second image or zoom on hover), badges, price with struck-through compareAtPrice and auto discount, one stretched link (href/to/as), actions, compare toggle (selectable) | | StatusPill | Domain status → tone and human label (never a raw enum) | | EmptyState / ErrorState / LoadingState | The three states every data card needs | | ConfirmDialog | Confirmation step — replaces window.confirm() |

import { PageHeader, StatCard, StatusPill, EmptyState, Button } from '@dreamtree-org/twreact-ui';

<PageHeader title="Compliance calendar" actions={<Button>Add obligation</Button>} />
<StatCard label="Due this week" value={18} icon={<CalendarDays className="h-6 w-6" />} />
<StatusPill status="docs_missing" map={{ docs_missing: { label: 'Missing documents', tone: 'warning' } }} />

Component types now carry their props (<Button variant="bogus" /> is a type error).

Hooks

useApi

Thin axios wrapper. Returns { data, error, loading, lastRequest, fetchData, fetchApi, fetchApiWith }.

  • fetchApi(key, data?, needLoading?) calls apiMap[key](data) with one argument.
  • fetchApiWith(key, args, { needLoading }?) spreads args into the map entry — use it for entries like (id, body) => ({...}).
const { fetchApi, fetchApiWith } = useApi({
  BASE_URL: 'https://api.example.com',
  apiMap: {
    getUser: (id) => ({ url: `/users/${id}`, method: 'GET' }),
    updateUser: (id, body) => ({ url: `/users/${id}`, method: 'PUT', data: body }),
  },
});

fetchApi('getUser', 7);
fetchApiWith('updateUser', [7, { name: 'Ada' }]);
  • onUnauthorized(error, { apiKey, url, method }) runs once per failing request that isUnauthorized(error) matches (default: HTTP 401), before the promise rejects; the promise still rejects. Use it to clear the session and redirect to sign-in — see the "redirect only once" recipe in the doc.

See doc/useApi.md.

useHaptics

Thin navigator.vibrate wrapper. Returns { trigger, supported, reducedMotion }; trigger('selection' | 'success' | 'warning' | 'error' | ms | number[]) does nothing where vibration is unsupported (iOS Safari) or reduced motion is on. Switch, Checkbox, ConfirmDialog and Sheet take an opt-in haptics prop that uses it.

Theming

Every colour in the compiled CSS is a CSS variable (--dt-primary-600, --dt-surface, …) generated from tokens/tokens.json (W3C Design Tokens format). The defaults equal the classic palette, so nothing changes until you override a variable.

Your brand lives in your repo. Keep it in dreamtree.brand.json at the repo root (colour scales, roles, font, logo, and optional landing-page colours) and build the CSS from it. No Tailwind config is needed, and it works with the precompiled CSS:

npx @dreamtree-org/twreact-ui brand init --id acme --name "Acme"      # starter file
npx @dreamtree-org/twreact-ui brand build --out app/brand.css          # only the --dt-* variables you override
npx @dreamtree-org/twreact-ui brand build --out app/brand.css --check  # in CI: fails if the CSS is stale
@import "@dreamtree-org/twreact-ui/dist/index.css";
@import "./brand.css";

The file is checked against tokens/brand.schema.json (add "$schema": "https://unpkg.com/@dreamtree-org/twreact-ui/tokens/brand.schema.json" for editor help). brand validate lists every problem with its fix, and --scope ".my-app" limits the brand to part of a page. twreact-ui ships only default; the practicepro and studio brands are deprecated copies until 1.5.0.

Use the same tokens in your own classes:

// Tailwind 3 — tailwind.config.js
module.exports = {
  presets: [require('@dreamtree-org/twreact-ui/dist/tokens/tailwind3-preset.cjs')],
  content: ['./src/**/*.{js,jsx,ts,tsx}', './node_modules/@dreamtree-org/twreact-ui/dist/**/*.{js,mjs}'],
};
/* Tailwind 4 — globals.css */
@layer theme, base, twreact, components, utilities;
@import "@dreamtree-org/twreact-ui/dist/index.css" layer(twreact);
@import "tailwindcss";
@import "@dreamtree-org/twreact-ui/dist/tokens/theme.css";
/* Generate twreact-ui's classes in your utilities layer too. Without it, an app class such as `hidden`
   lands in a higher layer than twreact's `lg:flex` and responsive components (AppShell) break. */
@source "../node_modules/@dreamtree-org/twreact-ui/dist/index.esm.js";

The palettes are primary, secondary, success, warning, error, info and gray (steps 50–950), so bg-info-50 / text-info-600 work out of the box; info is for informational and scheduled states that are not the brand accent. This adds semantic utilities next to the palettes: bg-surface, bg-background, text-foreground, text-muted, border-line, bg-shell, text-primary-foreground (text, bg-primary-foreground/12 tiles and ring-primary-foreground on a bg-primary-600–900 band; a brand with a light primary gets dark text), text-micro, rounded-control and rounded-card. Non-colour scales come from the same file: type roles (text-page-title, text-section-title, text-body, text-caption, text-kpi), rounded-sheet / rounded-pill, font-mono, elevation (shadow-xs … shadow-xl, shadow-overlay; deeper in dark mode via --dt-shadow-strength), z-layers (z-sticky, z-dropdown, z-overlay, z-modal, z-popover, z-toast, z-tooltip) and motion (duration-fast|base|slow, ease-standard|emphasized|spring-out). The Tailwind 3 preset and Tailwind 4 theme include them. Add a brand by creating tokens/brands/<name>.json; it overrides only the steps and roles you list.

Design rules: DESIGN.md is the rule set for product screens and AI agents: tokens only, blocks first, loading, empty and error states, 390 px, no native dialogs. It is generated from the tokens (npm run build:tokens).

Colours come from tokens. ProgressBar, Checkbox, Switch, Rate and Skeleton use token classes, so a brand file recolours them. 2.0.0 removed their raw-colour escape hatches: ProgressBar's HEX color / bgColor / valueColor (use variant), Checkbox's borderColor, Rate's activeColor / inactiveColor, and the blue / indigo / purple presets on Checkbox and Switch. See doc/MIGRATION-2.0.md.

SSR: Tabs, Tooltip and Switch generate ids with React.useId(), so server-rendered pages (Next.js) hydrate without mismatches. The /charts components do the same for their SVG ids, and they render token colours and reduced-motion state the way the server did until hydration finishes.

Mobile and touch

The stylesheet ships a phone baseline: no tap highlight, no iOS zoom when a field is focused (text fields are 16px on touch screens; add dt-keep-font-size to opt one out), color-scheme that follows the theme, and no rubber-band overscroll on body (add dt-overscroll-auto to <html> to keep pull-to-refresh). Pad edge bars with pt-safe / pb-safe / px-safe / inset-safe — they need <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> — and size full-height layouts with min-h-dvh instead of 100vh. Touch targets grow to 44px on coarse pointers.

Touch-friendly components (1.6–1.8).

  • Controls: Input/Textarea take size, Input adds floatingLabel and otp, and sets mobile keyboard hints for tel/email/url/search.
  • Buttons: square size="icon" sizes, press feedback, and a loading state that keeps the button's width.
  • FootNav: a native tab bar with safe area, links (href + linkAs), hideOnScroll and FootNav.Spacer.
  • Tabs: scroll with snap, plus a segmented variant and swipeable.
  • Navigation: Pagination goes compact on phones, Stepper can stack (orientation="auto"), and Breadcrumbs collapses (maxItems).
  • Carousel: a native scroll-snap swiper.
  • Sortable: drags after a long-press on touch.
  • FileUpload: shows "Choose file" / "Take photo" buttons on touch (capture).
  • Charts: take aspectRatio and pin the tooltip on tap.

Adaptive overlays. On phones (coarse pointer, under 640px), Select, DatePicker, DateRangePicker, ThreeDotPopover, the Table row menu, Dialog, ConfirmDialog, Popover and Tour open as a bottom Sheet (or an action sheet, or a docked card) by default. Each takes presentation="auto" | "popover" | "sheet"; use "popover" to keep the desktop behaviour. Tooltip opens on long-press on touch screens.

Native feel and PWA guide. doc/MobileNativeFeel.md walks through the rest of the setup for phones and installed apps: the viewport meta, per-theme theme-color kept in sync with ThemeProvider, a display: "standalone" web manifest, dvh layouts, the AppShell + FootNav + Sheet recipe, when to override presentation, safe areas, opt-in haptics, and a real-device testing checklist for iOS Safari and Android Chrome.

Dark Mode

Enable dark mode with the built-in theme provider:

import { ThemeProvider } from '@dreamtree-org/twreact-ui';

function App() {
  return (
    <ThemeProvider defaultTheme="dark">
      {/* Your app content */}
    </ThemeProvider>
  );
}

ThemeProvider sets data-theme, the .dark class and color-scheme on <html>, so dark: utilities work whether your tailwind.config.js uses darkMode: 'class' or a [data-theme="dark"] selector.

Surfaces such as Card, Sidebar, Navbar, Table, FootNav, Dropdown, the Select / DatePicker / DateRangePicker triggers and menus, Accordion, Popover, Tour, Drawer, Pagination, LocationPicker, Form's textarea / file button, the chart tooltip and RichTextEditor use the semantic bg-surface / bg-background / border-line / text-foreground / text-muted tokens, which switch under .dark (or [data-theme="dark"]). Re-theme them by overriding the --dt-surface, --dt-background, --dt-line, … variables.

Accessibility fixes (1.4.x): Radio groups keep a single selection when uncontrolled, Rate and DatePicker use one tab stop with arrow-key focus, Dialog/Sidebar/AppShell drawers share one focus trap and scroll lock, Toast announces via role="status", Alert's dismiss button is labelled, and Input shows a visible focus ring in its default state. No props changed.

Examples

Complete Form Example

import { Form, Button, Card } from '@dreamtree-org/twreact-ui';

const formFields = [
  {
    type: 'text',
    name: 'firstName',
    label: 'First Name',
    required: true,
    placeholder: 'Enter your first name'
  },
  {
    type: 'email',
    name: 'email',
    label: 'Email',
    required: true,
    placeholder: 'Enter your email'
  },
  {
    type: 'select',
    name: 'country',
    label: 'Country',
    options: [
      { value: 'us', label: 'United States' },
      { value: 'ca', label: 'Canada' }
    ]
  }
];

function ContactForm() {
  const handleSubmit = (data) => {
    console.log('Form data:', data);
  };

  return (
    <Card>
      <Card.Header>
        <Card.Title>Contact Information</Card.Title>
        <Card.Description>Please fill out the form below</Card.Description>
      </Card.Header>
      <Card.Content>
    <Form
      fields={formFields}
      onSubmit={handleSubmit}
      submitText="Send Message"
    />
      </Card.Content>
    </Card>
  );
}

Data Table with Actions

import { Table } from '@dreamtree-org/twreact-ui';

const columns = [
  { key: 'name', label: 'Name', sortable: true },
  { key: 'email', label: 'Email', sortable: true },
  { key: 'status', label: 'Status' }
];

const data = [
  { 
    id: 1, 
    name: 'John Doe', 
    email: '[email protected]', 
    status: 'Active' 
  },
  { 
    id: 2, 
    name: 'Jane Smith', 
    email: '[email protected]', 
    status: 'Inactive' 
  }
];

// Entries are merged onto the built-in Edit/Delete/View set by `name`.
const actions = [
  // patches the built-in `edit` — keeps its default label and icon
  {
    name: 'edit',
    onClick: ({ action, row }) => console.log('Edit', row)
  },
  // rendered as an icon button in the row, and only for Active users
  {
    name: 'deactivate',
    label: 'Deactivate',
    inline: true,
    hidden: (row) => row.status !== 'Active',
    onClick: ({ action, row }) => console.log('Deactivate', row)
  },
  // drop a built-in you don't want
  {
    name: 'delete',
    hidden: true
  }
];

function UserTable() {
  return (
    <Table
      columns={columns}
      data={data}
      sortable
      filterable
      pagination
      pageSize={10}
      actions={actions}
    />
  );
}

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support


Made with ❤️ by Partha Preetham Krishna under Dreamtree-Org · www.dreamtreeglobal.com