# OVERVIEW --- # Getting Started ## Quickstart Running tight on schedule? No worries! Check out our quickstart example to get started with Ark Ripple in seconds. - [Next.js Template](https://stackblitz.com/edit/github-qcm2dskf) - [Solid Start Template](https://stackblitz.com/edit/github-1hgkbbln) - [Nuxt Template](https://stackblitz.com/edit/github-s3sg6syq) ## Setup Guide Before you start, ensure you have a proper project setup. If not, follow your preferred application framework setup guide and then return to this guide. Install the Ark UI dependency using your preferred package manager. ```bash npm install ark-ripple // or pnpm install ark-ripple // or yarn add ark-ripple // or bun add ark-ripple ``` In this guide, we will be adding a Slider component. Copy the following code to your project. Ark UI is a headless component library that doesn't include default styles. You can leverage the `data-scope` and `data-part` attributes to style your components with custom CSS. For example, to style a slider component, you can target its parts using these attributes: ```css /* Targets the */ [data-scope='slider'][data-part='root'] { display: flex; flex-direction: column; } ``` Check out the [Styling Components guide](/react/docs/guides/styling) to learn more about styling components in Ark Ripple. Congratulations! You've successfully set up and styled your components using Ark UI. If you run into any issues or have questions, open an issue on our [GitHub](https://github.com/anubra266/ark-ripple/issues/new) or reach out on [Discord](https://discord.gg/3kjgmUWj). Happy hacking! ✌️ # Changelog ## [Unreleased] ## [1.2.0] - 2025-09-04 ### Added - Added `get_component_props` tool to retrieve component props/properties for specific Ark UI components ## [1.1.2] - 2025-09-03 ### Fixed Add missing node shebang to the `stdio` script. ## [1.1.1] - 2025-09-01 ### Fixed Don't ship the `src` directory to the package. ## [1.1.0] - 2025-09-01 ### Added - Initial release of the official MCP server for Ark UI # GUIDES --- # Styling ## Overview Ark Ripple is a headless component library that works with any styling solution. It provides functional styles for elements like popovers for positioning, while leaving presentation styles up to you. Some components also expose CSS variables that can be used for styling or animations. ### Data Attributes Ark Ripple components use `data-scope` and `data-part` attributes to target specific elements within a component. Interactive components often include `data-*` attributes to indicate their state. For example, here's what an open accordion item looks like: ```html
``` For more details on each component's data attributes, refer to their respective documentation. ## Styling with CSS When styling components with CSS, you can target the data attributes assigned to each component part for easy customization. ### Styling a Part To style a specific component part, target its `data-scope` and `data-part` attributes: ```css [data-scope='accordion'][data-part='item'] { border-bottom: 1px solid #e5e5e5; } ``` ### Styling a State To style a component based on its state, use the `data-state` attribute: ```css [data-scope='accordion'][data-part='item'][data-state='open'] { background-color: #f5f5f5; } ``` > **Tip:** If you prefer using classes instead of data attributes, utilize the `class` or `className` prop to add custom > classes to Ark Ripple components. ### Class Names If you prefer using classes instead of data attributes, utilize `class` or `className` prop to add custom classes to Ark Ripple components. Pass a class: ```jsx {/* … */} ``` Then use in styles: ```css .AccordionItem { border-bottom: 1px solid #e5e5e5; &[data-state='open'] { background-color: #f5f5f5; } } ``` ## Styling with Tailwind CSS [Tailwind CSS](https://tailwindcss.com/) is a utility-first CSS framework providing a flexible way to style your components. ### Styling a Part To style a part, apply classes directly to the parts using either `class` or `className`, depending on the JavaScript framework. ```jsx {/* … */} ``` ### Styling a State Leverage Tailwind CSS's variant selector to style a component based on its data-state attribute. ```jsx {/* … */} ``` # Composition ## The asChild Prop In Ark Ripple, `asChild` lets you integrate custom components, ensuring consistent styling and behavior while promoting flexibility and reusability. All Ark components that render a DOM element accept `asChild`. Here's an example using `asChild` to integrate a custom `Button` component within a `Popover`: In this example, `asChild` allows the `Button` to be used as the trigger for the `Popover`, inheriting its behaviors from Popover.Trigger. ## The Ark Factory You can use the `ark` factory to create your own elements that work just like Ark Ripple components. This will produce the following HTML: ```html Ark UI ``` ## ID Composition When composing components that need to work together, share IDs between them using the `ids` prop for proper accessibility and interaction. ```ripple import { Avatar } from 'ark-ripple/avatar' import { Tooltip } from 'ark-ripple/tooltip' export component TooltipWithAvatar() { const id = ':ark-avatar' component asChild({ propsFn }){ {"SA"} } {"Abraham Aremu is online"} } ``` Both components share the same `id` through their `ids` props, creating proper accessibility bindings, `aria-*` attributes and interaction behavior. ## Limitations Certain components, such as `Checkbox.Root` or `RadioGroup.Item`, have specific requirements for their child elements. For instance, they may require a label element as a child. If you change the underlying element type, ensure it remains accessible and functional. # Component State Need to access a component's state? You have three options: | Approach | When to use it | | ------------------------------- | --------------------------------------------- | | `Component.Context` | Quick inline access via named children | | `use*Context` hooks | Build custom child components that read state | | `useComponent` + `RootProvider` | Control the component from outside | ## Context Components Use `Component.Context` to access state inline via named children. Here, `Avatar.Fallback` reads the `loaded` state to show different content: ## Context Hooks Every component exports a `use*Context` hook (like `useDialogContext` or `useMenuContext`). Call it from any child component to access state and methods—no render props needed. ```ripple import { Dialog, useDialogContext } from 'ark-ripple/dialog' component CustomCloseButton() { const dialog = useDialogContext() } export component Demo() { Open } ``` The hook returns the same API as `Component.Context`, just without the nesting. ## Provider Components Need to control a component from outside its tree? Use a `useComponent` hook (like `useDialog`) with `RootProvider`. > When you use `RootProvider`, skip the `Root` component—you don't need both. ## Choosing the Right Approach - **`Component.Context`** — Quick inline access for conditional rendering - **`use*Context` hooks** — Build reusable child components that need parent state - **`useComponent` + `RootProvider`** — Trigger actions from outside (like opening a dialog from a menu item) # Animation Adding animation to Ark Ripple Components is as straightforward as with any other component, but keep in mind some considerations when working with exit animations with JavaScript animation libraries. ## Animating with CSS The most straightforward method to animate your elements is using CSS. You can animate both the mounting and unmounting phases with CSS. The latter is achievable because Ark Ripple Components postpones the unmounting while your animation runs. Below is a simple example of creating a fade-in and fade-out animation using CSS keyframes: ```css @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } } ``` You can use these keyframes to animate any element during its lifecycle. For instance, to apply the `fadeIn` animation when your `Tooltip` enters the 'open' state, and `fadeOut` when it enters the 'closed' state, you could use the following styles: ```css [data-scope='tooltip'][data-part='content'][data-state='open'] { animation: fadeIn 300ms ease-out; } [data-scope='tooltip'][data-part='content'][data-state='closed'] { animation: fadeOut 300ms ease-in; } ``` ## Animating with JS Libraries There's plenty of versatility when it comes to animating your Ark Ripple Elements with JavaScript libraries. Various libraries such as GreenSock, anime.js, Framer Motion, and more can add a new level of interaction and feedback to your UI components. One significant advantage of using Ark Ripple Elements is the control you have over the unmounting phase of your components. This is primarily facilitated through the `present` prop. The `present` prop allows the component to stay mounted even after its enclosing condition has been falsified, allowing for exit animations to complete before the component is removed from the DOM. # Forms Ark Ripple provides the `Field` and `Fieldset` components for integrating with native `form` element or any form library. ## Field Context Form components in Ark Ripple automatically integrate with `Field` through context. When nested inside a `Field.Root`, they inherit `disabled`, `invalid`, `required`, and `readOnly` states automatically. ```ripple import { Field } from 'ark-ripple/field' import { NumberInput } from 'ark-ripple/number-input' component Demo() { // NumberInput will be disabled } ``` ### Accessible Labels When building accessible forms, you need to ensure that they are properly labeled and described. - `Field.Label`: Used to provide an accessible label the input. - `Field.HelperText`: Used to provide additional instructions about the input. These components are automatically linked to the input element via the `aria-describedby` attribute. > **Best practice**: Make sure that labels are visible (and not just used as placeholders) for screen readers to read > them. ```ripple import { Field } from 'ark-ripple/field' component Demo() {
{"Username"} {"This will be your public display name."}
} ``` ### Error Handling and Validation When the input is invalid, you can use the `Field.ErrorText` component to provide an error message for the input, and pass the `invalid` prop to the `Field.Root` component. > **Best practice**: Make sure to provide clear, specific error messages that are easy to understand and fix. ```ripple import { Field } from 'ark-ripple/field' component Demo() {
{"Username"} {"Username is required."}
} ``` ### Required Fields To indicate that a field is required, you can pass the `required` prop to the `Field.Root` component. Optionally, you can use the `Field.RequiredIndicator` component to indicate that the field is required. > **Best practice**: Don't rely solely on color to indicate required status ```ripple import { Field } from 'ark-ripple/field' export component Demo() {
{"Username"} {"(required)"} {"Username is required."}
} ``` To indicate that a field is optional, use the `fallback` prop on the `Field.RequiredIndicator` component. ```ripple {"(required)"} ``` ### Native Controls Field supports native HTML form controls including `input`, `textarea`, and `select`: ```ripple import { Field } from 'ark-ripple/field' export component Demo(){
// Input {"Email"} // Textarea {"Bio"} // Select {"Country"}
} ``` ### Form Reset When the `reset` event is triggered on a form, all Ark Ripple components automatically sync their internal state with the form's reset values. > **Note**: For this to work correctly, always include the `HiddenInput` component in your form controls. The hidden > input participates in the native form reset mechanism, and Ark Ripple listens for this to sync the component state. ```ripple import { Checkbox } from 'ark-ripple/checkbox' component Demo() {
{"I agree to the terms"} // Clicking reset will restore checkbox to defaultChecked state
} ``` ## Fieldset Context When you have multiple fields in a form or a component that renders multiple `input` elements, you can use the `Fieldset` component to group them together. Common use cases checkbox group, radio group, input + select composition, etc. ### Checkbox Group ```ripple import { Fieldset } from 'ark-ripple/fieldset' const items = [ { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Vue', value: 'vue' }, { label: 'Svelte', value: 'svelte' }, ] component Demo() { {"Frameworks"} for (const item of items; key item.value) { } {"Choose your preferred frameworks"} } ``` ### Radio Group ```ripple import { Fieldset } from 'ark-ripple/fieldset' import { RadioGroup } from 'ark-ripple/radio-group' const items = [ { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Vue', value: 'vue' }, { label: 'Svelte', value: 'svelte' }, ] component Demo() { {"Frameworks"} for (const item of items; key item.value) { } {"Choose your preferred framework"} } ``` # AI FOR AGENTS --- # LLMs.txt ## What is LLMs.txt? We support [LLMs.txt](https://llmstxt.org/) files for making the Ark Ripple documentation available to large language models (LLMs). This feature helps AI tools better understand our component library, its APIs, and usage patterns. ## Available Routes We provide several LLMs.txt routes to help AI tools access our documentation: - [llms.txt](https://ark-ui.rip/llms.txt) - Contains a structured overview of all components and their documentation links - [llms-full.txt](https://ark-ui.rip/llms-full.txt) - Provides comprehensive documentation including implementation details and examples ## Usage with AI Tools ### Cursor Use the `@Docs` feature in Cursor to include the LLMs.txt files in your project. This helps Cursor provide more accurate code suggestions and documentation for Ark Ripple components. [Read more about @Docs in Cursor](https://docs.cursor.com/context/@-symbols/@-docs) ### Windstatic Reference the LLMs.txt files using `@` or in your `.windsurfrules` files to enhance Windstatic's understanding of Ark Ripple components. [Read more about Windstatic Memories](https://docs.codeium.com/windsurf/memories#memories-and-rules) ### Other AI Tools Any AI tool that supports LLMs.txt can use these routes to better understand Ark Ripple. Simply point your tool to any of the routes above based on your framework of choice. # COLLECTIONS --- # List Collection A list collection is a collection that is based on an array of items. It is created by passing an array of items to the constructor. ```ts import { createListCollection } from 'ark-ripple/collection' const collection = createListCollection({ items: [ { label: 'Apple', value: 'apple' }, { label: 'Banana', value: 'banana' }, ], }) console.log(collection.items) // [{ label: 'Apple', value: 'apple' }, { label: 'Banana', value: 'banana' }] ``` ### Converting value to item Use the `find` or `findMany` method to convert a value to an item. ```ts const item = collection.find('banana') console.log(item) // { label: "Banana", value: "banana" } const items = collection.findMany(['apple', 'banana']) console.log(items) // [{ label: "Apple", value: "apple" }, { label: "Banana", value: "banana" }] ``` ### Value Traversal Use the `getNextValue` or `getPreviousValue` method to get the next or previous item based on a value. ```ts const nextValue = collection.getNextValue('apple') console.log(nextValue) // banana const previousItem = collection.getPreviousValue('banana') console.log(previousItem) // apple ``` Likewise, use the `firstValue` or `lastValue` computed properties to get the first or last item. ```ts console.log(collection.firstValue) // apple console.log(collection.lastValue) // banana ``` ### Check for value existence Use the `has` method to check if a value exists in the collection. ```ts const hasValue = collection.has('apple') console.log(hasValue) // true ``` ### Working with custom objects If you are working with custom objects, you can pass a function to the `itemToString` and `itemToValue` options to specify how to convert an item to a string and a value, respectively. > By default, we look for the `label` and `value` properties in the item. ```ts import { createListCollection } from 'ark-ripple/collection' const collection = createListCollection({ items: [ { id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 3, name: 'cherry' }, ], itemToString: (item) => item.name, itemToValue: (item) => item.id, }) ``` To mark an item as disabled, pass a function to the `isItemDisabled` option. > By default, we look for the `disabled` property in the item. ```ts import { createListCollection } from 'ark-ripple/collection' const collection = createListCollection({ items: [ { id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 3, name: 'cherry' }, ], isItemDisabled: (item) => item.id === 2, }) ``` ### Reorder items Use the `reorder` method to reorder items by passing the starting index and the ending index of the item to be moved. ```ts const fromIndex = 1 // Banana const toIndex = 0 // Apple collection.reorder(fromIndex, toIndex) console.log(collection.items) // [{ label: "Banana", value: "banana" }, { label: "Apple", value: "apple" }] ``` # Tree Collection A tree collection is designed to manage hierarchical data structures like file systems, navigation menus, or organization charts. It provides powerful methods for traversing, manipulating, and querying tree structures. ```ts import { createTreeCollection } from 'ark-ripple/collection' const treeData = { value: 'root', label: 'Root', children: [ { value: 'folder1', label: 'Folder 1', children: [ { value: 'file1', label: 'File 1.txt' }, { value: 'file2', label: 'File 2.txt' }, ], }, { value: 'folder2', label: 'Folder 2', children: [ { value: 'subfolder1', label: 'Subfolder 1', children: [{ value: 'file3', label: 'File 3.txt' }], }, ], }, ], } const tree = createTreeCollection({ rootNode: treeData }) ``` ### Navigation Methods The tree collection provides various methods to navigate through the hierarchical structure. #### Getting First and Last Nodes ```ts const firstNode = tree.getFirstNode() console.log(firstNode?.value) // "folder1" const lastNode = tree.getLastNode() console.log(lastNode?.value) // "folder2" ``` #### Sequential Navigation Navigate to the next or previous node in the tree traversal order: ```ts const nextNode = tree.getNextNode('file1') console.log(nextNode?.value) // "file2" const previousNode = tree.getPreviousNode('file2') console.log(previousNode?.value) // "file1" ``` ### Hierarchical Relationships #### Parent and Children Get parent and descendant nodes: ```ts // Get parent node const parentNode = tree.getParentNode('file1') console.log(parentNode?.value) // "folder1" // Get all ancestor nodes const ancestors = tree.getParentNodes('file3') console.log(ancestors.map((n) => n.value)) // ["folder2", "subfolder1"] // Get all descendant nodes const descendants = tree.getDescendantNodes('folder1') console.log(descendants.map((n) => n.value)) // ["file1", "file2"] // Get descendant values only const descendantValues = tree.getDescendantValues('folder2') console.log(descendantValues) // ["subfolder1", "file3"] ``` #### Sibling Navigation Navigate between sibling nodes: ```ts // Assuming we have the index path of "file1" const indexPath = tree.getIndexPath('file1') // [0, 0] const nextSibling = tree.getNextSibling(indexPath) console.log(nextSibling?.value) // "file2" const previousSibling = tree.getPreviousSibling(indexPath) console.log(previousSibling) // undefined (no previous sibling) // Get all siblings const siblings = tree.getSiblingNodes(indexPath) console.log(siblings.map((n) => n.value)) // ["file1", "file2"] ``` ### Index Path Operations Work with index paths to identify node positions: ```ts // Get index path for a value const indexPath = tree.getIndexPath('file3') console.log(indexPath) // [1, 0, 0] // Get value from index path const value = tree.getValue([1, 0, 0]) console.log(value) // "file3" // Get full value path (all ancestors + node) const valuePath = tree.getValuePath([1, 0, 0]) console.log(valuePath) // ["folder2", "subfolder1", "file3"] // Get node at specific index path const node = tree.at([1, 0]) console.log(node?.value) // "subfolder1" ``` ### Tree Queries #### Branch and Leaf Detection ```ts // Check if a node is a branch (has children) const folder1Node = tree.findNode('folder1') const isBranch = tree.isBranchNode(folder1Node!) console.log(isBranch) // true // Get all branch values const branchValues = tree.getBranchValues() console.log(branchValues) // ["folder1", "folder2", "subfolder1"] ``` #### Tree Traversal Visit all nodes with custom logic: ```ts tree.visit({ onEnter: (node, indexPath) => { console.log(`Visiting: ${node.value} at depth ${indexPath.length}`) // Skip certain branches if (node.value === 'folder2') { return 'skip' // Skip this branch and its children } }, }) ``` #### Filtering Create a new tree with filtered nodes: ```ts // Keep only nodes that match criteria const filteredTree = tree.filter((node, indexPath) => { return node.value.includes('file') // Only keep files }) console.log(filteredTree.getValues()) // ["file1", "file2", "file3"] ``` ### Tree Manipulation #### Adding Nodes ```ts const newFile = { value: 'newfile', label: 'New File.txt' } // Insert after a specific node const indexPath = tree.getIndexPath('file1') const updatedTree = tree.insertAfter(indexPath!, [newFile]) // Insert before a specific node const updatedTree2 = tree.insertBefore(indexPath!, [newFile]) ``` #### Removing Nodes ```ts const indexPath = tree.getIndexPath('file2') const updatedTree = tree.remove([indexPath!]) console.log(updatedTree.getValues()) // file2 is removed ``` #### Moving Nodes ```ts const fromIndexPaths = [tree.getIndexPath('file1')!] const toIndexPath = tree.getIndexPath('folder2')! const updatedTree = tree.move(fromIndexPaths, toIndexPath) // file1 is now moved under folder2 ``` #### Replacing Nodes ```ts const indexPath = tree.getIndexPath('file1')! const newNode = { value: 'replacedfile', label: 'Replaced File.txt' } const updatedTree = tree.replace(indexPath, newNode) ``` ### Utility Methods #### Flattening Convert the tree to a flat structure: ```ts const flatNodes = tree.flatten() console.log(flatNodes.map((n) => ({ value: n.value, depth: n._indexPath.length }))) // [{ value: "folder1", depth: 1 }, { value: "file1", depth: 2 }, ...] ``` #### Getting All Values ```ts const allValues = tree.getValues() console.log(allValues) // ["folder1", "file1", "file2", "folder2", "subfolder1", "file3"] ``` #### Depth Calculation ```ts const depth = tree.getDepth('file3') console.log(depth) // 3 (root -> folder2 -> subfolder1 -> file3) ``` ### Working with Custom Node Types You can customize how the tree collection interprets your data: ```ts interface CustomNode { id: string name: string items?: CustomNode[] isDisabled?: boolean } const customTree = createTreeCollection({ rootNode: { id: 'root', name: 'Root', items: [ { id: '1', name: 'Item 1', isDisabled: false }, { id: '2', name: 'Item 2', isDisabled: true }, ], }, nodeToValue: (node) => node.id, nodeToString: (node) => node.name, nodeToChildren: (node) => node.items, isNodeDisabled: (node) => node.isDisabled ?? false, }) ``` ### Creating Trees from File Paths Create a tree structure from file paths: ```ts import { createFileTreeCollection } from 'ark-ripple/collection' const paths = ['src/components/Button.tsx', 'src/components/Input.tsx', 'src/utils/helpers.ts', 'docs/README.md'] const fileTree = createFileTreeCollection(paths) console.log(fileTree.getBranchValues()) // ["src", "components", "utils", "docs"] ``` > **Good to know**: Tree collections are immutable - all modification methods return a new tree instance rather than > modifying the original. # Async List The `useAsyncList` hook manages asynchronous data operations for list collections. It provides a comprehensive solution for loading, filtering, sorting, and paginating data with built-in loading states, error handling, and request cancellation. ```tsx import { useAsyncList } from 'ark-ripple/collection' const list = useAsyncList({ async load({ signal }) { const response = await fetch('/api/users', { signal }) const users = await response.json() return { items: users } }, }) console.log(list.items) // User[] console.log(list.loading) // boolean console.log(list.error) // Error | null ``` ## Examples ### Loading Data Load data asynchronously from an API using the `load` function and update the list when the data is ready. **Example: async-list/reload** ```ripple import { useAsyncList } from 'ark-ripple/collection'; import { Loader } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/async-list.module.css'; interface Quote { id: number; quote: string; author: string; } export component Reload() { const list = useAsyncList( { autoReload: true, async load() { const response = await fetch( `https://dummyjson.com/quotes?limit=4&skip=${Math.floor(Math.random() * 50)}`, ); if (!response.ok) throw new Error('Failed to fetch quotes'); const data = await response.json(); return { items: data.quotes }; }, }, );
if (@list.error) {
{'Error: '} {@list.error.message}
}
for (const quote of @list.items; key quote.id) {
{'"'} {quote.quote} {'"'}
{'— '} {quote.author}
}
} ``` ### Infinite Loading Implement pagination by returning a cursor that indicates more data is available. **Example: async-list/infinite-loading** ```ripple import { useAsyncList } from 'ark-ripple/collection'; import { Loader } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/async-list.module.css'; const LIMIT = 4; interface Post { userId: number; id: number; title: string; body: string; } export component InfiniteLoading() { const list = useAsyncList( { autoReload: true, async load({ cursor }: { cursor?: number }) { const page = cursor || 1; const start = (page - 1) * LIMIT; const response = await fetch( `https://jsonplaceholder.typicode.com/posts?_start=${start}&_limit=${LIMIT}`, ); if (!response.ok) throw new Error('Failed to fetch posts'); const posts: Post[] = await response.json(); const hasNextPage = posts.length === LIMIT; return { items: posts, cursor: hasNextPage ? page + 1 : undefined, }; }, }, );
{'Loaded '} {@list.items.length} {' posts'} {@list.cursor ? ' (more available)' : null} if (@list.cursor) { }
if (@list.error) {
{'Error: '} {@list.error.message}
}
for (const post of @list.items; key post.id) {
{@list.items.indexOf(post) + 1} {'. '} {post.title}
{post.body}
}
} ``` ### Filtering Filter data based on user input with automatic debouncing and loading states. **Example: async-list/filter** ```ripple import { useAsyncList } from 'ark-ripple/collection'; import { Loader } from 'lucide-ripple'; import field from 'styles/field.module.css'; import styles from 'styles/async-list.module.css'; const LIMIT = 4; interface User { id: number; name: string; email: string; department: string; role: string; } const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const mockUsers: User[] = [ { id: 1, name: 'Alice Johnson', email: 'alice@example.com', department: 'Engineering', role: 'Senior Developer', }, { id: 2, name: 'Bob Smith', email: 'bob@example.com', department: 'Marketing', role: 'Marketing Manager', }, { id: 3, name: 'Carol Davis', email: 'carol@example.com', department: 'Engineering', role: 'Frontend Developer', }, { id: 4, name: 'David Wilson', email: 'david@example.com', department: 'Sales', role: 'Sales Representative', }, { id: 5, name: 'Eva Brown', email: 'eva@example.com', department: 'Engineering', role: 'DevOps Engineer', }, { id: 6, name: 'Frank Miller', email: 'frank@example.com', department: 'Support', role: 'Customer Success', }, { id: 7, name: 'Grace Lee', email: 'grace@example.com', department: 'Marketing', role: 'Content Creator', }, { id: 8, name: 'Henry Taylor', email: 'henry@example.com', department: 'Engineering', role: 'Backend Developer', }, { id: 9, name: 'Ivy Anderson', email: 'ivy@example.com', department: 'Sales', role: 'Account Manager', }, { id: 10, name: 'Jack Thompson', email: 'jack@example.com', department: 'Support', role: 'Technical Support', }, { id: 11, name: 'Kate Martinez', email: 'kate@example.com', department: 'Marketing', role: 'Brand Manager', }, { id: 12, name: 'Liam Garcia', email: 'liam@example.com', department: 'Engineering', role: 'Full Stack Developer', }, { id: 13, name: 'Mia Rodriguez', email: 'mia@example.com', department: 'Sales', role: 'Sales Director', }, { id: 14, name: 'Noah Lopez', email: 'noah@example.com', department: 'Support', role: 'Support Manager', }, { id: 15, name: 'Olivia White', email: 'olivia@example.com', department: 'Engineering', role: 'UI Designer', }, { id: 16, name: 'Paul Harris', email: 'paul@example.com', department: 'Marketing', role: 'Digital Marketer', }, { id: 17, name: 'Quinn Clark', email: 'quinn@example.com', department: 'Engineering', role: 'Mobile Developer', }, { id: 18, name: 'Ruby Lewis', email: 'ruby@example.com', department: 'Sales', role: 'Business Development', }, { id: 19, name: 'Sam Young', email: 'sam@example.com', department: 'Support', role: 'Documentation Specialist', }, { id: 20, name: 'Tina Walker', email: 'tina@example.com', department: 'Marketing', role: 'Social Media Manager', }, ]; export component Filter() { const list = useAsyncList( { initialItems: mockUsers.slice(0, LIMIT), async load({ filterText }: { filterText?: string }) { await delay(500); if (!filterText) return { items: mockUsers.slice(0, LIMIT) }; const filtered = mockUsers.filter( (user) => user.name.toLowerCase().includes(filterText.toLowerCase()) || user.email.toLowerCase().includes(filterText.toLowerCase()), ); return { items: filtered.slice(0, LIMIT) }; }, }, );
{ @list.setFilterText((e.target as HTMLInputElement).value); }} /> if (@list.loading) { {'Searching'} }
if (@list.error) {
{'Error: '} {@list.error.message}
}
for (const user of @list.items; key user.id) {
{user.name}
{user.email}
{user.department} {' • '} {user.role}
}
if (@list.items.length === 0 && !@list.loading) {
{'No results found'}
}
} ``` ### Sorting (Client-side) Sort data on the client side after loading from the server. **Example: async-list/sort-client-side** ```ripple import { useAsyncList } from 'ark-ripple/collection'; import { ArrowDown, ArrowUpDown, ArrowUp, Loader } from 'lucide-ripple'; import styles from 'styles/async-list.module.css'; interface User { id: number; name: string; username: string; email: string; phone: string; website: string; } const collator = new Intl.Collator(); const cols: { key: keyof User; label: string }[] = [ { key: 'name', label: 'Name' }, { key: 'username', label: 'Username' }, { key: 'email', label: 'Email' }, ]; export component SortClientSide() { const list = useAsyncList( { autoReload: true, load: async () => { const response = await fetch('https://jsonplaceholder.typicode.com/users?_limit=5'); const data = await response.json(); return { items: data }; }, sort({ items, descriptor }) { return { items: items.sort((a, b) => { const { column, direction } = descriptor; let cmp = collator.compare( String(a[column as keyof User]), String(b[column as keyof User]), ); if (direction === 'descending') { cmp *= -1; } return cmp; }), }; }, }, ); const handleSort = (column: keyof User) => { const currentSort = @list.sortDescriptor; let direction: 'ascending' | 'descending' = 'ascending'; if (currentSort?.column === column && currentSort.direction === 'ascending') { direction = 'descending'; } @list.sort({ column, direction }); };
if (@list.loading) {
{'Loading'}
} if (@list.error) {
{'Error: '} {@list.error.message}
}
{'Sorted by: '} {@list.sortDescriptor ? `${@list.sortDescriptor.column} (${@list.sortDescriptor.direction})` : 'none'}
for (const col of cols; key col.key) { } for (const user of @list.items; key user.id) { }
handleSort(col.key)}> {col.label} {' '} if (!@list.sortDescriptor || @list.sortDescriptor.column !== col.key) { } else if (@list.sortDescriptor.direction === 'ascending') { } else { }
{user.name} {user.username} {user.email}
} ``` ### Sorting (Server-side) Send sort parameters to the server and reload data when sorting changes. **Example: async-list/sort-server-side** ```ripple import { useAsyncList } from 'ark-ripple/collection'; import { ArrowDown, ArrowUpDown, ArrowUp, Loader } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/async-list.module.css'; interface Product { id: number; title: string; price: number; description: string; category: string; image: string; rating: { rate: number; count: number; }; } export component SortServerSide() { const list = useAsyncList( { autoReload: true, async load({ sortDescriptor }: { sortDescriptor?: { column: string; direction: string } }) { const url = new URL('https://fakestoreapi.com/products'); url.searchParams.set('limit', '5'); if (sortDescriptor) { const { direction } = sortDescriptor; url.searchParams.set('sort', direction === 'ascending' ? 'asc' : 'desc'); } const response = await fetch(url); const items = await response.json(); return { items }; }, }, ); const handleSort = (column: keyof Product) => { const currentSort = @list.sortDescriptor; let direction: 'ascending' | 'descending' = 'ascending'; if (currentSort?.column === column && currentSort.direction === 'ascending') { direction = 'descending'; } @list.sort({ column, direction }); };
if (@list.loading) { {'Loading'} }
if (@list.error) {
{'Error: '} {@list.error.message}
}
for (const product of @list.items; key product.id) {
{product.title}
{product.title}
{' ### Dependencies Automatically reload data when dependencies change, such as filter selections or external state. **Example: async-list/dependencies** ```ripple import { useAsyncList } from 'ark-ripple/collection'; import { Loader } from 'lucide-ripple'; import { track } from 'ripple'; import field from 'styles/field.module.css'; import styles from 'styles/async-list.module.css'; const LIMIT = 5; interface User { id: number; name: string; email: string; department: string; role: string; } const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const departments = ['Engineering', 'Marketing', 'Sales', 'Support']; const roles = [ 'Senior Developer', 'Marketing Manager', 'Frontend Developer', 'Sales Representative', 'DevOps Engineer', 'Customer Success', 'Content Creator', 'Backend Developer', 'Account Manager', 'Technical Support', 'Brand Manager', 'Full Stack Developer', 'Sales Director', 'Support Manager', 'UI Designer', 'Digital Marketer', 'Mobile Developer', 'Business Development', 'Documentation Specialist', 'Social Media Manager', ]; const mockUsers: User[] = [ { id: 1, name: 'Alice Johnson', email: 'alice@example.com', department: 'Engineering', role: 'Senior Developer', }, { id: 2, name: 'Bob Smith', email: 'bob@example.com', department: 'Marketing', role: 'Marketing Manager', }, { id: 3, name: 'Carol Davis', email: 'carol@example.com', department: 'Engineering', role: 'Frontend Developer', }, { id: 4, name: 'David Wilson', email: 'david@example.com', department: 'Sales', role: 'Sales Representative', }, { id: 5, name: 'Eva Brown', email: 'eva@example.com', department: 'Engineering', role: 'DevOps Engineer', }, { id: 6, name: 'Frank Miller', email: 'frank@example.com', department: 'Support', role: 'Customer Success', }, { id: 7, name: 'Grace Lee', email: 'grace@example.com', department: 'Marketing', role: 'Content Creator', }, { id: 8, name: 'Henry Taylor', email: 'henry@example.com', department: 'Engineering', role: 'Backend Developer', }, { id: 9, name: 'Ivy Anderson', email: 'ivy@example.com', department: 'Sales', role: 'Account Manager', }, { id: 10, name: 'Jack Thompson', email: 'jack@example.com', department: 'Support', role: 'Technical Support', }, { id: 11, name: 'Kate Martinez', email: 'kate@example.com', department: 'Marketing', role: 'Brand Manager', }, { id: 12, name: 'Liam Garcia', email: 'liam@example.com', department: 'Engineering', role: 'Full Stack Developer', }, { id: 13, name: 'Mia Rodriguez', email: 'mia@example.com', department: 'Sales', role: 'Sales Director', }, { id: 14, name: 'Noah Lopez', email: 'noah@example.com', department: 'Support', role: 'Support Manager', }, { id: 15, name: 'Olivia White', email: 'olivia@example.com', department: 'Engineering', role: 'UI Designer', }, { id: 16, name: 'Paul Harris', email: 'paul@example.com', department: 'Marketing', role: 'Digital Marketer', }, { id: 17, name: 'Quinn Clark', email: 'quinn@example.com', department: 'Engineering', role: 'Mobile Developer', }, { id: 18, name: 'Ruby Lewis', email: 'ruby@example.com', department: 'Sales', role: 'Business Development', }, { id: 19, name: 'Sam Young', email: 'sam@example.com', department: 'Support', role: 'Documentation Specialist', }, { id: 20, name: 'Tina Walker', email: 'tina@example.com', department: 'Marketing', role: 'Social Media Manager', }, ]; export component Dependencies() { let selectedDepartment = track(''); let selectedRole = track(''); const dependencies = track(() => [@selectedDepartment, @selectedRole]); const list = useAsyncList( { initialItems: mockUsers.slice(0, LIMIT), dependencies, async load({ filterText }: { filterText?: string }) { await delay(400); let items = mockUsers; if (@selectedDepartment) { items = items.filter((user) => user.department === @selectedDepartment); } if (@selectedRole) { items = items.filter((user) => user.role === @selectedRole); } if (filterText) { items = items.filter( (user) => user.name.toLowerCase().includes(filterText.toLowerCase()) || user.email.toLowerCase().includes(filterText.toLowerCase()), ); } return { items: items.slice(0, LIMIT) }; }, }, );
{ @list.setFilterText((e.target as HTMLInputElement).value); }} /> if (@list.loading) { {'Loading'} }
if (@list.error) {
{'Error: '} {@list.error.message}
}
{'Found '} {@list.items.length} {' users'}
for (const user of @list.items; key user.id) {
{user.name}
{user.email}
{user.department} {' • '} {user.role}
}
if (@list.items.length === 0 && !@list.loading) {
{'No users found with current filters'}
}
} ``` ## API Reference ### Props - **load** (`(params: LoadParams) => Promise>`) - Function to load data asynchronously - **sort** (`(params: SortParams) => Promise> | SortResult`) - Optional function for client-side sorting - **autoReload** (`boolean`, default: `false`) - Whether to automatically reload data on mount - **initialItems** (`T[]`, default: `[]`) - Initial items to display before first load - **dependencies** (`any[]`, default: `[]`) - Values that trigger a reload when changed - **initialFilterText** (`string`, default: `''`) - Initial filter text value - **initialSortDescriptor** (`SortDescriptor | null`) - Initial sort configuration ### Load Parameters The `load` function receives an object with the following properties: - **cursor** (`C | undefined`) - Current cursor for pagination - **filterText** (`string`) - Current filter text - **sortDescriptor** (`SortDescriptor | null`) - Current sort configuration - **signal** (`AbortSignal`) - AbortController signal for request cancellation ### Load Result The `load` function should return an object with: - **items** (`T[]`) - The loaded items - **cursor** (`C | undefined`) - Optional cursor for next page ### Sort Parameters The `sort` function receives an object with: - **items** (`T[]`) - Current items to sort - **descriptor** (`SortDescriptor`) - Sort configuration with `column` and `direction` ### Return Value The hook returns an object with the following properties and methods: #### State Properties - **items** (`T[]`) - Current list of items - **loading** (`boolean`) - Whether a load operation is in progress - **error** (`Error | null`) - Any error from the last operation - **cursor** (`C | undefined`) - Current cursor for pagination - **filterText** (`string`) - Current filter text - **sortDescriptor** (`SortDescriptor | null`) - Current sort configuration #### Methods - **reload** (`() => void`) - Reload data from the beginning - **loadMore** (`() => void`) - Load more items (when cursor is available) - **setFilterText** (`(text: string) => void`) - Set filter text and reload - **sort** (`(descriptor: SortDescriptor) => void`) - Apply sorting #### Types ```tsx interface SortDescriptor { column: string direction: 'ascending' | 'descending' } interface LoadParams { cursor?: C filterText: string sortDescriptor?: SortDescriptor | null signal: AbortSignal } interface LoadResult { items: T[] cursor?: C } ```} {product.price}
{product.category} {' • '} {product.rating.rate} {' ('} {product.rating.count} {' reviews)'}
}
} ``` ### Dependencies Automatically reload data when dependencies change, such as filter selections or external state. ```ripple import { useAsyncList } from 'ark-ripple/collection'; import { Loader } from 'lucide-ripple'; import { track } from 'ripple'; import field from 'styles/field.module.css'; import styles from 'styles/async-list.module.css'; const LIMIT = 5; interface User { id: number; name: string; email: string; department: string; role: string; } const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const departments = ['Engineering', 'Marketing', 'Sales', 'Support']; const roles = [ 'Senior Developer', 'Marketing Manager', 'Frontend Developer', 'Sales Representative', 'DevOps Engineer', 'Customer Success', 'Content Creator', 'Backend Developer', 'Account Manager', 'Technical Support', 'Brand Manager', 'Full Stack Developer', 'Sales Director', 'Support Manager', 'UI Designer', 'Digital Marketer', 'Mobile Developer', 'Business Development', 'Documentation Specialist', 'Social Media Manager', ]; const mockUsers: User[] = [ { id: 1, name: 'Alice Johnson', email: 'alice@example.com', department: 'Engineering', role: 'Senior Developer', }, { id: 2, name: 'Bob Smith', email: 'bob@example.com', department: 'Marketing', role: 'Marketing Manager', }, { id: 3, name: 'Carol Davis', email: 'carol@example.com', department: 'Engineering', role: 'Frontend Developer', }, { id: 4, name: 'David Wilson', email: 'david@example.com', department: 'Sales', role: 'Sales Representative', }, { id: 5, name: 'Eva Brown', email: 'eva@example.com', department: 'Engineering', role: 'DevOps Engineer', }, { id: 6, name: 'Frank Miller', email: 'frank@example.com', department: 'Support', role: 'Customer Success', }, { id: 7, name: 'Grace Lee', email: 'grace@example.com', department: 'Marketing', role: 'Content Creator', }, { id: 8, name: 'Henry Taylor', email: 'henry@example.com', department: 'Engineering', role: 'Backend Developer', }, { id: 9, name: 'Ivy Anderson', email: 'ivy@example.com', department: 'Sales', role: 'Account Manager', }, { id: 10, name: 'Jack Thompson', email: 'jack@example.com', department: 'Support', role: 'Technical Support', }, { id: 11, name: 'Kate Martinez', email: 'kate@example.com', department: 'Marketing', role: 'Brand Manager', }, { id: 12, name: 'Liam Garcia', email: 'liam@example.com', department: 'Engineering', role: 'Full Stack Developer', }, { id: 13, name: 'Mia Rodriguez', email: 'mia@example.com', department: 'Sales', role: 'Sales Director', }, { id: 14, name: 'Noah Lopez', email: 'noah@example.com', department: 'Support', role: 'Support Manager', }, { id: 15, name: 'Olivia White', email: 'olivia@example.com', department: 'Engineering', role: 'UI Designer', }, { id: 16, name: 'Paul Harris', email: 'paul@example.com', department: 'Marketing', role: 'Digital Marketer', }, { id: 17, name: 'Quinn Clark', email: 'quinn@example.com', department: 'Engineering', role: 'Mobile Developer', }, { id: 18, name: 'Ruby Lewis', email: 'ruby@example.com', department: 'Sales', role: 'Business Development', }, { id: 19, name: 'Sam Young', email: 'sam@example.com', department: 'Support', role: 'Documentation Specialist', }, { id: 20, name: 'Tina Walker', email: 'tina@example.com', department: 'Marketing', role: 'Social Media Manager', }, ]; export component Dependencies() { let selectedDepartment = track(''); let selectedRole = track(''); const dependencies = track(() => [@selectedDepartment, @selectedRole]); const list = useAsyncList( { initialItems: mockUsers.slice(0, LIMIT), dependencies, async load({ filterText }: { filterText?: string }) { await delay(400); let items = mockUsers; if (@selectedDepartment) { items = items.filter((user) => user.department === @selectedDepartment); } if (@selectedRole) { items = items.filter((user) => user.role === @selectedRole); } if (filterText) { items = items.filter( (user) => user.name.toLowerCase().includes(filterText.toLowerCase()) || user.email.toLowerCase().includes(filterText.toLowerCase()), ); } return { items: items.slice(0, LIMIT) }; }, }, );
{ @list.setFilterText((e.target as HTMLInputElement).value); }} /> if (@list.loading) { {'Loading'} }
if (@list.error) {
{'Error: '} {@list.error.message}
}
{'Found '} {@list.items.length} {' users'}
for (const user of @list.items; key user.id) {
{user.name}
{user.email}
{user.department} {' • '} {user.role}
}
if (@list.items.length === 0 && !@list.loading) {
{'No users found with current filters'}
}
} ``` ## API Reference ### Props - **load** (`(params: LoadParams) => Promise>`) - Function to load data asynchronously - **sort** (`(params: SortParams) => Promise> | SortResult`) - Optional function for client-side sorting - **autoReload** (`boolean`, default: `false`) - Whether to automatically reload data on mount - **initialItems** (`T[]`, default: `[]`) - Initial items to display before first load - **dependencies** (`any[]`, default: `[]`) - Values that trigger a reload when changed - **initialFilterText** (`string`, default: `''`) - Initial filter text value - **initialSortDescriptor** (`SortDescriptor | null`) - Initial sort configuration ### Load Parameters The `load` function receives an object with the following properties: - **cursor** (`C | undefined`) - Current cursor for pagination - **filterText** (`string`) - Current filter text - **sortDescriptor** (`SortDescriptor | null`) - Current sort configuration - **signal** (`AbortSignal`) - AbortController signal for request cancellation ### Load Result The `load` function should return an object with: - **items** (`T[]`) - The loaded items - **cursor** (`C | undefined`) - Optional cursor for next page ### Sort Parameters The `sort` function receives an object with: - **items** (`T[]`) - Current items to sort - **descriptor** (`SortDescriptor`) - Sort configuration with `column` and `direction` ### Return Value The hook returns an object with the following properties and methods: #### State Properties - **items** (`T[]`) - Current list of items - **loading** (`boolean`) - Whether a load operation is in progress - **error** (`Error | null`) - Any error from the last operation - **cursor** (`C | undefined`) - Current cursor for pagination - **filterText** (`string`) - Current filter text - **sortDescriptor** (`SortDescriptor | null`) - Current sort configuration #### Methods - **reload** (`() => void`) - Reload data from the beginning - **loadMore** (`() => void`) - Load more items (when cursor is available) - **setFilterText** (`(text: string) => void`) - Set filter text and reload - **sort** (`(descriptor: SortDescriptor) => void`) - Apply sorting #### Types ```tsx interface SortDescriptor { column: string direction: 'ascending' | 'descending' } interface LoadParams { cursor?: C filterText: string sortDescriptor?: SortDescriptor | null signal: AbortSignal } interface LoadResult { items: T[] cursor?: C } ``` # List Selection The `useListSelection` hook manages selection state in lists and collections. It supports single and multiple selection modes with operations like select, deselect, toggle, and clear. ```tsx import { createListCollection, useListSelection } from 'ark-ripple/collection' const collection = createListCollection({ items: [ { label: 'Apple', value: 'apple' }, { label: 'Banana', value: 'banana' }, { label: 'Cherry', value: 'cherry' }, ], }) const selection = useListSelection({ collection, selectionMode: 'single', deselectable: true, }) console.log(selection.selectedValues) // ['apple', 'banana', 'cherry'] ``` ## Examples ### Basic By default, the hook supports single selection mode that can be deselected. > Set `deselectable` to `false` to prevent deselecting the current selection. **Example: list-selection/basic** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import { createListCollection, useListSelection } from 'ark-ripple/collection'; import { Check } from 'lucide-ripple'; import styles from 'styles/list-selection.module.css'; import checkboxStyles from 'styles/checkbox.module.css'; const collection = createListCollection( { items: [ { label: 'React', value: 'react' }, { label: 'Vue', value: 'vue' }, { label: 'Angular', value: 'angular' }, { label: 'Svelte', value: 'svelte' }, ], }, ); export component Basic() { const selection = useListSelection({ collection });
{'Selected: '} {@selection.selectedValues.join(', ') || 'None'} for (const item of collection.items; key item.value) { @selection.select(item.value)} > {item.label} }
} ``` ### Multiple Selection Set `selectionMode` to `multiple` to allow multiple items to be selected. **Example: list-selection/multiple** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import { createListCollection, useListSelection } from 'ark-ripple/collection'; import { Check } from 'lucide-ripple'; import styles from 'styles/list-selection.module.css'; import checkboxStyles from 'styles/checkbox.module.css'; const collection = createListCollection( { items: [ { label: 'React', value: 'react' }, { label: 'Vue', value: 'vue' }, { label: 'Angular', value: 'angular' }, { label: 'Svelte', value: 'svelte' }, { label: 'Solid', value: 'solid' }, ], }, ); export component Multiple() { const selection = useListSelection({ collection, selectionMode: 'multiple' }); const handleSelectAll = () => { if (@selection.isAllSelected()) { @selection.clear(); } else { @selection.setSelectedValues(collection.getValues()); } };
{@selection.selectedValues.length} {' of '} {collection.items.length} {' selected'}
for (const item of collection.items; key item.value) { @selection.select(item.value)} > {item.label} }
} ``` ### Range Selection Here's an example of how to implement range selection that extends the selection from the first selected item to the clicked item. **Example: list-selection/range** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import { createListCollection, useListSelection } from 'ark-ripple/collection'; import { Check } from 'lucide-ripple'; import styles from 'styles/list-selection.module.css'; import checkboxStyles from 'styles/checkbox.module.css'; const collection = createListCollection( { items: [ { label: 'React', value: 'react' }, { label: 'Vue', value: 'vue' }, { label: 'Angular', value: 'angular' }, { label: 'Svelte', value: 'svelte' }, { label: 'Solid', value: 'solid' }, ], }, ); export component Range() { const selection = useListSelection({ collection, selectionMode: 'multiple' }); const handleItemClick = (value: string, event: MouseEvent) => { event.preventDefault(); const firstSelected = @selection.firstSelectedValue; if (event.shiftKey && firstSelected) { @selection.extend(firstSelected, value); } else if (event.ctrlKey || event.metaKey) { @selection.toggle(value); } else { @selection.replace(value); } };
{'Selected: '} {@selection.selectedValues.join(', ') || 'None'} for (const item of collection.items; key item.value) { handleItemClick(item.value, e)} > {item.label} }

{'Click to select • Shift+Click for range • Cmd/Ctrl+Click to toggle'}

} ``` ## API Reference ### Props - **collection** (`ListCollection`) - The collection to manage selection for - **selectionMode** (`'single' | 'multiple' | 'none'`, default: `'single'`) - The selection mode - **deselectable** (`boolean`, default: `true`) - Whether selected items can be deselected - **initialSelectedValues** (`string[]`, default: `[]`) - Initial selected values - **resetOnCollectionChange** (`boolean`, default: `false`) - Whether to reset selection when collection changes ### Return Value The hook returns an object with the following properties and methods: #### State Properties - **selectedValues** (`string[]`) - Array of currently selected values - **isEmpty** (`boolean`) - Whether no items are selected - **firstSelectedValue** (`string | null`) - The first selected value in collection order - **lastSelectedValue** (`string | null`) - The last selected value in collection order #### Query Methods - **isSelected** (`(value: string | null) => boolean`) - Check if a value is selected - **canSelect** (`(value: string) => boolean`) - Check if a value can be selected - **isAllSelected** (`() => boolean`) - Check if all items are selected - **isSomeSelected** (`() => boolean`) - Check if some items are selected #### Selection Methods - **select** (`(value: string, forceToggle?: boolean) => void`) - Select a value - **deselect** (`(value: string) => void`) - Deselect a value - **toggle** (`(value: string) => void`) - Toggle selection of a value - **replace** (`(value: string | null) => void`) - Replace selection with a single value - **extend** (`(anchorValue: string, targetValue: string) => void`) - Extend selection from anchor to target - **setSelectedValues** (`(values: string[]) => void`) - Set the selected values - **setSelection** (`(values: string[]) => void`) - Set the selection (alias for setSelectedValues) - **clear** (`() => void`) - Clear all selections - **resetSelection** (`() => void`) - Reset selection to initial state # COMPONENTS --- # Accordion ## Anatomy ```tsx ``` ## Examples ### Default Value Set the `defaultValue` prop to specify which item should be expanded by default. **Example: basic** ```ripple import { Accordion } from 'ark-ripple/accordion'; import { ChevronDown } from 'lucide-ripple'; import styles from 'styles/accordion.module.css'; export component Basic() { for (const item of items; key item.value) { {item.title}
{item.content}
}
} const items = [ { value: 'ark-ui', title: 'What is Ark UI?', content: 'A headless component library for building accessible web apps.', }, { value: 'getting-started', title: 'How to get started?', content: 'Install the package and import the components you need.', }, { value: 'maintainers', title: 'Who maintains this project?', content: 'Ark UI is maintained by the Chakra UI team.', }, ]; ``` ### Controlled Use the `value` and `onValueChange` props to control the expanded items. **Example: controlled** ```ripple import { Accordion } from 'ark-ripple/accordion'; import { track } from 'ripple'; import { ChevronDown } from 'lucide-ripple'; import styles from 'styles/accordion.module.css'; export component Controlled() { let value = track([]); { @value = details.value; }} > for (const item of items; key item.value) { {item.title}
{item.content}
}
} const items = [ { value: 'ark-ui', title: 'What is Ark UI?', content: 'A headless component library for building accessible web apps.', }, { value: 'getting-started', title: 'How to get started?', content: 'Install the package and import the components you need.', }, { value: 'maintainers', title: 'Who maintains this project?', content: 'Ark UI is maintained by the Chakra UI team.', }, ]; ``` ### Root Provider An alternative way to control the accordion is to use the `RootProvider` component and the `useAccordion` hook. This way you can access the state and methods from outside the component. **Example: root-provider** ```ripple import { Accordion } from 'ark-ripple/accordion'; import { useAccordion } from 'ark-ripple/accordion'; import { ChevronDown } from 'lucide-ripple'; import styles from 'styles/accordion.module.css'; export component RootProvider() { const accordion = useAccordion({ multiple: true, defaultValue: ['ark-ui'] });
{'Value: '} {JSON.stringify(@accordion.value)} for (const item of items; key item.value) { {item.title}
{item.content}
}
} const items = [ { value: 'ark-ui', title: 'What is Ark UI?', content: 'A headless component library for building accessible web apps.', }, { value: 'getting-started', title: 'How to get started?', content: 'Install the package and import the components you need.', }, { value: 'maintainers', title: 'Who maintains this project?', content: 'Ark UI is maintained by the Chakra UI team.', }, ]; ``` ### Collapsible Use the `collapsible` prop to allow the user to collapse all panels. **Example: collapsible** ```ripple import { Accordion } from 'ark-ripple/accordion'; import { ChevronDown } from 'lucide-ripple'; import styles from 'styles/accordion.module.css'; export component Collapsible() { for (const item of items; key item.value) { {item.title}
{item.content}
}
} const items = [ { value: 'ark-ui', title: 'What is Ark UI?', content: 'A headless component library for building accessible web apps.', }, { value: 'getting-started', title: 'How to get started?', content: 'Install the package and import the components you need.', }, { value: 'maintainers', title: 'Who maintains this project?', content: 'Ark UI is maintained by the Chakra UI team.', }, ]; ``` ### Multiple Use the `multiple` prop to allow multiple panels to be expanded simultaneously. **Example: multiple** ```ripple import { Accordion } from 'ark-ripple/accordion'; import { ChevronDown } from 'lucide-ripple'; import styles from 'styles/accordion.module.css'; export component Multiple() { for (const item of items; key item.value) { {item.title}
{item.content}
}
} const items = [ { value: 'ark-ui', title: 'What is Ark UI?', content: 'A headless component library for building accessible web apps.', }, { value: 'getting-started', title: 'How to get started?', content: 'Install the package and import the components you need.', }, { value: 'maintainers', title: 'Who maintains this project?', content: 'Ark UI is maintained by the Chakra UI team.', }, ]; ``` ### Horizontal By default, the Accordion is oriented vertically. Use the `orientation` prop to switch to a horizontal layout. **Example: horizontal** ```ripple import { Accordion } from 'ark-ripple/accordion'; import styles from 'styles/accordion.module.css'; export component Horizontal() { for (const item of items; key item.value) { {item.title}
{item.content}
}
} const items = [ { value: 'ark-ui', title: 'What is Ark UI?', content: 'A headless component library for building accessible web apps.', }, { value: 'getting-started', title: 'How to get started?', content: 'Install the package and import the components you need.', }, { value: 'maintainers', title: 'Who maintains this project?', content: 'Ark UI is maintained by the Chakra UI team.', }, ]; ``` ### Lazy Mount Use the `lazyMount` prop to defer rendering of accordion content until the item is expanded. Combine with `unmountOnExit` to unmount content when collapsed, freeing up resources. **Example: lazy-mount** ```ripple import { Accordion } from 'ark-ripple/accordion'; import { ChevronDown } from 'lucide-ripple'; import styles from 'styles/accordion.module.css'; export component LazyMount() { for (const item of items; key item.value) { {item.title}
{item.content}
}
} const items = [ { value: 'ark-ui', title: 'What is Ark UI?', content: 'A headless component library for building accessible web apps.', }, { value: 'getting-started', title: 'How to get started?', content: 'Install the package and import the components you need.', }, { value: 'maintainers', title: 'Who maintains this project?', content: 'Ark UI is maintained by the Chakra UI team.', }, ]; ``` ### Context Use `Accordion.Context` or `useAccordionContext` to access the accordion state. **Example: context** ```ripple import { Accordion } from 'ark-ripple/accordion'; import { ChevronDown } from 'lucide-ripple'; import styles from 'styles/accordion.module.css'; export component Context() { component children({ context }) {
{'context.value: '} {JSON.stringify(@context.value)}
{'context.focusedValue: '} {@context.focusedValue || 'null'}
}
for (const item of items; key item.value) { {item.title}
{item.content}
}
} const items = [ { value: 'ark-ui', title: 'What is Ark UI?', content: 'A headless component library for building accessible web apps.', }, { value: 'getting-started', title: 'How to get started?', content: 'Install the package and import the components you need.', }, { value: 'maintainers', title: 'Who maintains this project?', content: 'Ark UI is maintained by the Chakra UI team.', }, ]; ``` ### Item State Use `Accordion.ItemContext` or `useAccordionItemContext` to access the state of an accordion item. **Example: item-context** ```ripple import { Accordion } from 'ark-ripple/accordion'; import { ChevronDown } from 'lucide-ripple'; import styles from 'styles/accordion.module.css'; export component ItemContext() { for (const item of items; key item.value) { {item.title} component children({ context }) { if (@context.expanded) { {'Expanded'} } if (@context.focused) { {'Focused'} } }
{item.content}
}
} const items = [ { value: 'ark-ui', title: 'What is Ark UI?', content: 'A headless component library for building accessible web apps.', }, { value: 'getting-started', title: 'How to get started?', content: 'Install the package and import the components you need.', }, { value: 'maintainers', title: 'Who maintains this project?', content: 'Ark UI is maintained by the Chakra UI team.', }, ]; ``` ## Guides ### Content Animation Use the `--height` and/or `--width` CSS variables to animate the size of the content when it expands or closes: ```css @keyframes slideDown { from { opacity: 0.01; height: 0; } to { opacity: 1; height: var(--height); } } @keyframes slideUp { from { opacity: 1; height: var(--height); } to { opacity: 0.01; height: 0; } } [data-scope='accordion'][data-part='item-content'][data-state='open'] { animation: slideDown 250ms ease-in-out; } [data-scope='accordion'][data-part='item-content'][data-state='closed'] { animation: slideUp 200ms ease-in-out; } ``` ## API Reference ### Props **Component API Reference** **Root Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `collapsible` | `boolean` | No | Whether an accordion item can be closed after it has been expanded. | | `defaultValue` | `string[]` | No | The initial value of the expanded accordion items. Use when you don't need to control the value of the accordion. | | `disabled` | `boolean` | No | Whether the accordion items are disabled | | `id` | `string` | No | The unique identifier of the machine. | | `ids` | `Partial<{ root: string item: (value: string) => string itemContent: (value: string) => string itemTrigger: (value: string) => string }>` | No | The ids of the elements in the accordion. Useful for composition. | | `lazyMount` | `boolean` | No | Whether to enable lazy mounting | | `multiple` | `boolean` | No | Whether multiple accordion items can be expanded at the same time. | | `onFocusChange` | `(details: FocusChangeDetails) => void` | No | The callback fired when the focused accordion item changes. | | `onValueChange` | `(details: ValueChangeDetails) => void` | No | The callback fired when the state of expanded/collapsed accordion items changes. | | `orientation` | `'horizontal' | 'vertical'` | No | The orientation of the accordion items. | | `unmountOnExit` | `boolean` | No | Whether to unmount on exit. | | `value` | `string[]` | No | The controlled value of the expanded accordion items. | **Root Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | accordion | | `[data-part]` | root | | `[data-orientation]` | The orientation of the accordion | **ItemContent Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ItemContent Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | accordion | | `[data-part]` | item-content | | `[data-state]` | "open" | "closed" | | `[data-disabled]` | Present when disabled | | `[data-focus]` | Present when focused | | `[data-orientation]` | The orientation of the item | **ItemIndicator Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ItemIndicator Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | accordion | | `[data-part]` | item-indicator | | `[data-state]` | "open" | "closed" | | `[data-disabled]` | Present when disabled | | `[data-focus]` | Present when focused | | `[data-orientation]` | The orientation of the item | **Item Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `string` | Yes | The value of the accordion item. | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `disabled` | `boolean` | No | Whether the accordion item is disabled. | **Item Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | accordion | | `[data-part]` | item | | `[data-state]` | "open" | "closed" | | `[data-focus]` | Present when focused | | `[data-disabled]` | Present when disabled | | `[data-orientation]` | The orientation of the item | **ItemTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ItemTrigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | accordion | | `[data-part]` | item-trigger | | `[data-controls]` | | | `[data-orientation]` | The orientation of the item | | `[data-state]` | "open" | "closed" | **RootProvider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `UseAccordionReturn` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `lazyMount` | `boolean` | No | Whether to enable lazy mounting | | `unmountOnExit` | `boolean` | No | Whether to unmount on exit. | ### Context **API:** | Property | Type | Description | |----------|------|-------------| | `focusedValue` | `string` | The value of the focused accordion item. | | `value` | `string[]` | The value of the accordion | | `setValue` | `(value: string[]) => void` | Sets the value of the accordion | | `getItemState` | `(props: ItemProps) => ItemState` | Returns the state of an accordion item. | ## Accessibility This component complies with the [Accordion WAI-ARIA design pattern](https://www.w3.org/WAI/ARIA/apg/patterns/accordion/). ### Keyboard Support **`Space`** Description: When focus is on an trigger of a collapsed item, the item is expanded **`Enter`** Description: When focus is on an trigger of a collapsed section, expands the section. **`Tab`** Description: Moves focus to the next focusable element **`Shift + Tab`** Description: Moves focus to the previous focusable element **`ArrowDown`** Description: Moves focus to the next trigger **`ArrowUp`** Description: Moves focus to the previous trigger. **`Home`** Description: When focus is on an trigger, moves focus to the first trigger. **`End`** Description: When focus is on an trigger, moves focus to the last trigger. # Angle Slider ## Anatomy ```tsx ``` ## Examples ### Basic Here's a basic example of the Angle Slider component. **Example: basic** ```ripple import { AngleSlider } from 'ark-ripple/angle-slider'; import styles from 'styles/angle-slider.module.css'; const markers = [0, 45, 90, 135, 180, 225, 270, 315]; export component Basic() { {'Rotation'} for (const value of markers; key value) { } } ``` ### Controlled Use the `value` and `onValueChange` props to control the value of the Angle Slider. **Example: controlled** ```ripple import { AngleSlider } from 'ark-ripple/angle-slider'; import { track } from 'ripple'; import styles from 'styles/angle-slider.module.css'; const markers = [0, 45, 90, 135, 180, 225, 270, 315]; export component Controlled() { let value = track(45); { @value = e.value; }} > {'Rotation'} for (const marker of markers; key marker) { } } ``` ### Steps Use the `step` prop to set the discrete steps of the Angle Slider. **Example: step** ```ripple import { AngleSlider } from 'ark-ripple/angle-slider'; import styles from 'styles/angle-slider.module.css'; const markers = [0, 45, 90, 135, 180, 225, 270, 315]; export component Step() { {'15 Step'} for (const value of markers; key value) { } } ``` ## API Reference ### Props **Component API Reference** **Root Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `aria-label` | `string` | No | The accessible label for the slider thumb. | | `aria-labelledby` | `string` | No | The id of the element that labels the slider thumb. | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `defaultValue` | `number` | No | The initial value of the slider. Use when you don't need to control the value of the slider. | | `disabled` | `boolean` | No | Whether the slider is disabled. | | `id` | `string` | No | The unique identifier of the machine. | | `ids` | `Partial<{ root: string thumb: string hiddenInput: string control: string valueText: string label: string }>` | No | The ids of the elements in the machine. Useful for composition. | | `invalid` | `boolean` | No | Whether the slider is invalid. | | `name` | `string` | No | The name of the slider. Useful for form submission. | | `onValueChange` | `(details: ValueChangeDetails) => void` | No | The callback function for when the value changes. | | `onValueChangeEnd` | `(details: ValueChangeDetails) => void` | No | The callback function for when the value changes ends. | | `readOnly` | `boolean` | No | Whether the slider is read-only. | | `step` | `number` | No | The step value for the slider. | | `value` | `number` | No | The value of the slider. | **Root Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | angle-slider | | `[data-part]` | root | | `[data-disabled]` | Present when disabled | | `[data-invalid]` | Present when invalid | | `[data-readonly]` | Present when read-only | **Root CSS Variables:** | Variable | Description | |----------|-------------| | `--value` | The current value | | `--angle` | The angle in degrees | **Control Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Control Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | angle-slider | | `[data-part]` | control | | `[data-disabled]` | Present when disabled | | `[data-invalid]` | Present when invalid | | `[data-readonly]` | Present when read-only | **HiddenInput Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Label Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Label Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | angle-slider | | `[data-part]` | label | | `[data-disabled]` | Present when disabled | | `[data-invalid]` | Present when invalid | | `[data-readonly]` | Present when read-only | **MarkerGroup Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Marker Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `number` | Yes | The value of the marker | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Marker Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | angle-slider | | `[data-part]` | marker | | `[data-value]` | The value of the item | | `[data-state]` | | | `[data-disabled]` | Present when disabled | **Marker CSS Variables:** | Variable | Description | |----------|-------------| | `--marker-value` | The logical marker value (e.g. 0, 45, 90) | | `--marker-display-value` | The rotation angle for display (mirrored in RTL) | **RootProvider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `UseAngleSliderReturn` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Thumb Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Thumb Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | angle-slider | | `[data-part]` | thumb | | `[data-disabled]` | Present when disabled | | `[data-invalid]` | Present when invalid | | `[data-readonly]` | Present when read-only | **ValueText Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | ### Context **API:** | Property | Type | Description | |----------|------|-------------| | `value` | `number` | The current value of the angle slider | | `valueAsDegree` | `string` | The current value as a degree string | | `setValue` | `(value: number) => void` | Sets the value of the angle slider | | `dragging` | `boolean` | Whether the slider is being dragged. | # Avatar ## Anatomy ```tsx ``` ## Examples ### Basic Display a user's profile image with a fallback. **Example: basic** ```ripple import { Avatar } from 'ark-ripple/avatar'; import styles from 'styles/avatar.module.css'; export component Basic() { {'PA'} } ``` ### Events Use `onStatusChange` to listen for loading state changes. **Example: events** ```ripple import { Avatar } from 'ark-ripple/avatar'; import { track } from 'ripple'; import styles from 'styles/avatar.module.css'; export component Events() { let status = track('loading...');
{'Status: '} {@status} { @status = e.status; }} > {'PA'}
} ``` ### Root Provider An alternative way to control the avatar is to use the `RootProvider` component and the `useAvatar` hook. This way you can access the state and methods from outside the component. **Example: root-provider** ```ripple import { Avatar } from 'ark-ripple/avatar'; import { useAvatar } from 'ark-ripple/avatar'; import { track } from 'ripple'; import button from 'styles/button.module.css'; import styles from 'styles/avatar.module.css'; export component RootProvider() { let count = track(0); const avatar = useAvatar();
{'PA'}
} ``` ## API Reference ### Props **Component API Reference** **Root Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `ids` | `Partial<{ root: string; image: string; fallback: string }>` | No | The ids of the elements in the avatar. Useful for composition. | | `onStatusChange` | `(details: StatusChangeDetails) => void` | No | Functional called when the image loading status changes. | **Fallback Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Fallback Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | avatar | | `[data-part]` | fallback | | `[data-state]` | "hidden" | "visible" | **Image Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Image Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | avatar | | `[data-part]` | image | | `[data-state]` | "visible" | "hidden" | **RootProvider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `UseAvatarReturn` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | ### Context **API:** | Property | Type | Description | |----------|------|-------------| | `loaded` | `boolean` | Whether the image is loaded. | | `setSrc` | `(src: string) => void` | Function to set new src. | | `setLoaded` | `VoidFunction` | Function to set loaded state. | | `setError` | `VoidFunction` | Function to set error state. | # Carousel ## Anatomy ```tsx ``` ## Examples **Example: basic** ```ripple import { Carousel } from 'ark-ripple/carousel'; import styles from 'styles/carousel.module.css'; const images = [ { src: 'https://picsum.photos/seed/1/500/300', alt: 'Nature landscape', index: 0 }, { src: 'https://picsum.photos/seed/2/500/300', alt: 'City skyline', index: 1 }, { src: 'https://picsum.photos/seed/3/500/300', alt: 'Mountain view', index: 2 }, { src: 'https://picsum.photos/seed/4/500/300', alt: 'Ocean sunset', index: 3 }, { src: 'https://picsum.photos/seed/5/500/300', alt: 'Forest path', index: 4 }, ]; export component Basic() { {'←'} for (const image of images; key image.index) { {image.alt} } {'→'} for (const image of images; key image.index) { } } ``` ### Controlled To create a controlled Carousel component, you can manage the state of the carousel using the `page` prop and update it when the `onPageChange` event handler is called: **Example: controlled** ```ripple import { Carousel } from 'ark-ripple/carousel'; import { track } from 'ripple'; import styles from 'styles/carousel.module.css'; const images = [ { src: 'https://picsum.photos/seed/1/500/300', alt: 'Nature landscape', index: 0 }, { src: 'https://picsum.photos/seed/2/500/300', alt: 'City skyline', index: 1 }, { src: 'https://picsum.photos/seed/3/500/300', alt: 'Mountain view', index: 2 }, { src: 'https://picsum.photos/seed/4/500/300', alt: 'Ocean sunset', index: 3 }, { src: 'https://picsum.photos/seed/5/500/300', alt: 'Forest path', index: 4 }, ]; export component Controlled() { let page = track(0); { @page = e.page; }} > {'←'} for (const image of images; key image.index) { {image.alt} } {'→'} for (const image of images; key image.index) { } } ``` ### Root Provider An alternative way to control the carousel is to use the `RootProvider` component and the `useCarousel` hook. This way you can access the state and methods from outside the component. **Example: root-provider** ```ripple import { Carousel } from 'ark-ripple/carousel'; import { useCarousel } from 'ark-ripple/carousel'; import styles from 'styles/carousel.module.css'; const images = [ { src: 'https://picsum.photos/seed/1/500/300', alt: 'Nature landscape', index: 0 }, { src: 'https://picsum.photos/seed/2/500/300', alt: 'City skyline', index: 1 }, { src: 'https://picsum.photos/seed/3/500/300', alt: 'Mountain view', index: 2 }, { src: 'https://picsum.photos/seed/4/500/300', alt: 'Ocean sunset', index: 3 }, { src: 'https://picsum.photos/seed/5/500/300', alt: 'Forest path', index: 4 }, ]; export component RootProvider() { const carousel = useCarousel({ slideCount: images.length });
{'Page: '} {@carousel.page} {'←'} for (const image of images; key image.index) { {image.alt} } {'→'} for (const image of images; key image.index) { }
} ``` ### Autoplay Pass the `autoplay` and `loop` props to `Carousel.Root` to make the carousel play automatically. **Example: autoplay** ```ripple import { Carousel } from 'ark-ripple/carousel'; import styles from 'styles/carousel.module.css'; const images = [ { src: 'https://picsum.photos/seed/1/500/300', alt: 'Nature landscape', index: 0 }, { src: 'https://picsum.photos/seed/2/500/300', alt: 'City skyline', index: 1 }, { src: 'https://picsum.photos/seed/3/500/300', alt: 'Mountain view', index: 2 }, { src: 'https://picsum.photos/seed/4/500/300', alt: 'Ocean sunset', index: 3 }, { src: 'https://picsum.photos/seed/5/500/300', alt: 'Forest path', index: 4 }, ]; export component Autoplay() { for (const image of images; key image.index) { {image.alt} } {'‹'} {'⏸'} {'›'} } ``` ### Pause on Hover This feature isn't built-in, but you can use the `play()` and `pause()` methods from `Carousel.Context` to implement pause on hover. **Example: pause-on-hover** ```ripple import { Carousel } from 'ark-ripple/carousel'; import styles from 'styles/carousel.module.css'; const images = [ { src: 'https://picsum.photos/seed/1/500/300', alt: 'Nature landscape', index: 0 }, { src: 'https://picsum.photos/seed/2/500/300', alt: 'City skyline', index: 1 }, { src: 'https://picsum.photos/seed/3/500/300', alt: 'Mountain view', index: 2 }, { src: 'https://picsum.photos/seed/4/500/300', alt: 'Ocean sunset', index: 3 }, { src: 'https://picsum.photos/seed/5/500/300', alt: 'Forest path', index: 4 }, ]; export component PauseOnHover() { component children({ context }) { {'Autoplay is: '} {@context.isPlaying ? 'playing' : 'paused'} } component children({ context }) { { @context.pause(); }} onPointerLeave={() => { @context.play(); }} > for (const image of images; key image.index) { {image.alt} } } for (const image of images; key image.index) { } } ``` ### Thumbnail Indicators Replace default indicator dots with image thumbnails. Render each thumbnail inside `Carousel.Indicator` to create a visual preview of each slide: **Example: thumbnail-indicator** ```ripple import { Carousel } from 'ark-ripple/carousel'; import styles from 'styles/carousel.module.css'; const images = [ { src: 'https://picsum.photos/seed/1/500/300', alt: 'Nature landscape', index: 0 }, { src: 'https://picsum.photos/seed/2/500/300', alt: 'City skyline', index: 1 }, { src: 'https://picsum.photos/seed/3/500/300', alt: 'Mountain view', index: 2 }, { src: 'https://picsum.photos/seed/4/500/300', alt: 'Ocean sunset', index: 3 }, { src: 'https://picsum.photos/seed/5/500/300', alt: 'Forest path', index: 4 }, ]; export component ThumbnailIndicator() { {'←'} for (const image of images; key image.index) { {image.alt} } {'→'} for (const image of images; key image.index) { {image.alt} } } ``` ### Vertical Add the `orientation="vertical"` prop to `Carousel.Root` to switch the carousel to vertical scrolling. This can be helpful for displaying vertical galleries or content feeds. **Example: vertical** ```ripple import { Carousel } from 'ark-ripple/carousel'; import styles from 'styles/carousel.module.css'; const images = [ { src: 'https://picsum.photos/seed/1/500/300', alt: 'Nature landscape', index: 0 }, { src: 'https://picsum.photos/seed/2/500/300', alt: 'City skyline', index: 1 }, { src: 'https://picsum.photos/seed/3/500/300', alt: 'Mountain view', index: 2 }, { src: 'https://picsum.photos/seed/4/500/300', alt: 'Ocean sunset', index: 3 }, { src: 'https://picsum.photos/seed/5/500/300', alt: 'Forest path', index: 4 }, ]; export component Vertical() { for (const image of images; key image.index) { {image.alt} } {'↑'} for (const image of images; key image.index) { } {'↓'} } ``` ### Dynamic Manage slides dynamically by storing them in state and syncing the carousel page. Pass the `page` prop and `onPageChange` handler to `Carousel.Root`, and update `slideCount` when slides are added or removed. This demonstrates bidirectional state synchronization between your component state and the carousel. **Example: dynamic-slides** ```ripple import { Carousel } from 'ark-ripple/carousel'; import { track } from 'ripple'; import button from 'styles/button.module.css'; import styles from 'styles/carousel.module.css'; export component DynamicSlides() { let slides = track([0, 1, 2, 3, 4]); let page = track(0);
{ @page = e.page; }} > for (const index of @slides; key index) {
{'Slide '} {index + 1}
}
{'←'} for (const index of @slides; key index) { } {'→'}
} ``` ### Scroll to Slide Use `Carousel.Context` to access the carousel API and call `api.scrollToIndex(index)` to programmatically navigate to a specific slide. This is useful for creating custom navigation or jump-to-slide functionality. **Example: scroll-to** ```ripple import { Carousel } from 'ark-ripple/carousel'; import button from 'styles/button.module.css'; import styles from 'styles/carousel.module.css'; const slides = [0, 1, 2, 3, 4]; export component ScrollTo() { component children({ context }) { } for (const index of slides; key index) {
{'Slide '} {index + 1}
}
{'←'} {'→'} for (const index of slides; key index) { }
} ``` ### Slides Per Page Display multiple slides simultaneously by setting the `slidesPerPage` prop on `Carousel.Root`. Use `api.pageSnapPoints` from `Carousel.Context` to render the correct number of indicators based on pages rather than individual slides. Add the `spacing` prop to control the gap between slides. **Example: slides-per-page** ```ripple import { Carousel } from 'ark-ripple/carousel'; import styles from 'styles/carousel.module.css'; const slides = [0, 1, 2, 3, 4, 5]; const pageIndicators = [0, 1, 2]; export component SlidesPerPage() { {'←'} {'→'} for (const index of slides; key index) {
{'Slide '} {index + 1}
}
for (const index of pageIndicators; key index) { }
} ``` ### Spacing Control the gap between slides using the `spacing` prop on `Carousel.Root`. Combine it with `slidesPerPage` to create layouts that show partial previews of adjacent slides. **Example: spacing** ```ripple import { Carousel } from 'ark-ripple/carousel'; import styles from 'styles/carousel.module.css'; const slides = [0, 1, 2, 3, 4, 5]; export component Spacing() { {'spacing=\'48px\''} for (const index of slides; key index) {
{index + 1}
}
{'←'} component children({ context }) { for (const snapPoint of @context.pageSnapPoints; key snapPoint) { } } {'→'}
} ``` ### Variable Sizes To allow slides with different widths, set the `autoSize` prop on `Carousel.Root`. This lets each `Carousel.Item` define its own width, and the carousel will adjust automatically. You can also use the `snapAlign` prop on individual items to control where each one snaps into view. **Example: variable-size** ```ripple import { Carousel } from 'ark-ripple/carousel'; import styles from 'styles/carousel.module.css'; const items = [ { id: '1', width: '120px', label: 'Small', index: 0 }, { id: '2', width: '200px', label: 'Medium Size', index: 1 }, { id: '3', width: '80px', label: 'XS', index: 2 }, { id: '4', width: '250px', label: 'Large Content Here', index: 3 }, { id: '5', width: '150px', label: 'Regular', index: 4 }, ]; export component VariableSize() { {'←'} {'→'} for (const item of items; key item.id) {
{item.label}
}
component children({ context }) { for (const snapPoint of @context.pageSnapPoints; key snapPoint) { } }
} ``` ## API Reference ### Props **Component API Reference** **Root Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `slideCount` | `number` | Yes | The total number of slides. Useful for SSR to render the initial ating the snap points. | | `allowMouseDrag` | `boolean` | No | Whether to allow scrolling via dragging with mouse | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `autoplay` | `boolean | { delay: number }` | No | Whether to scroll automatically. The default delay is 4000ms. | | `autoSize` | `boolean` | No | Whether to enable variable width slides. | | `defaultPage` | `number` | No | The initial page to scroll to when rendered. Use when you don't need to control the page of the carousel. | | `ids` | `Partial<{ root: string item: (index: number) => string itemGroup: string nextTrigger: string prevTrigger: string indicatorGroup: string indicator: (index: number) => string }>` | No | The ids of the elements in the carousel. Useful for composition. | | `inViewThreshold` | `number | number[]` | No | The threshold for determining if an item is in view. | | `loop` | `boolean` | No | Whether the carousel should loop around. | | `onAutoplayStatusChange` | `(details: AutoplayStatusDetails) => void` | No | Function called when the autoplay status changes. | | `onDragStatusChange` | `(details: DragStatusDetails) => void` | No | Function called when the drag status changes. | | `onPageChange` | `(details: PageChangeDetails) => void` | No | Function called when the page changes. | | `orientation` | `'horizontal' | 'vertical'` | No | The orientation of the element. | | `padding` | `string` | No | Defines the extra space added around the scrollable area, enabling nearby items to remain partially in view. | | `page` | `number` | No | The controlled page of the carousel. | | `slidesPerMove` | `number | 'auto'` | No | The number of slides to scroll at a time. When set to `auto`, the number of slides to scroll is determined by the `slidesPerPage` property. | | `slidesPerPage` | `number` | No | The number of slides to show at a time. | | `snapType` | `'proximity' | 'mandatory'` | No | The snap type of the item. | | `spacing` | `string` | No | The amount of space between items. | | `translations` | `IntlTranslations` | No | The localized messages to use. | **Root Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | carousel | | `[data-part]` | root | | `[data-orientation]` | The orientation of the carousel | **Root CSS Variables:** | Variable | Description | |----------|-------------| | `--slides-per-page` | The number of slides visible per page | | `--slide-spacing` | The spacing between slides | | `--slide-item-size` | The calculated size of each slide item | **AutoplayIndicator Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `fallback` | `string | number | bigint | boolean | ReactElement> | Iterable | ReactPortal | Promise<...>` | No | The fallback content to render when autoplay is paused. | **AutoplayTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **AutoplayTrigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | carousel | | `[data-part]` | autoplay-trigger | | `[data-orientation]` | The orientation of the autoplaytrigger | | `[data-pressed]` | Present when pressed | **Control Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Control Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | carousel | | `[data-part]` | control | | `[data-orientation]` | The orientation of the control | **IndicatorGroup Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **IndicatorGroup Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | carousel | | `[data-part]` | indicator-group | | `[data-orientation]` | The orientation of the indicatorgroup | **Indicator Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `index` | `number` | Yes | The index of the indicator. | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `readOnly` | `boolean` | No | Whether the indicator is read only. | **Indicator Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | carousel | | `[data-part]` | indicator | | `[data-orientation]` | The orientation of the indicator | | `[data-index]` | The index of the item | | `[data-readonly]` | Present when read-only | | `[data-current]` | Present when current | **ItemGroup Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ItemGroup Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | carousel | | `[data-part]` | item-group | | `[data-orientation]` | The orientation of the item | | `[data-dragging]` | Present when in the dragging state | **Item Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `index` | `number` | Yes | The index of the item. | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `snapAlign` | `'center' | 'start' | 'end'` | No | The snap alignment of the item. | **Item Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | carousel | | `[data-part]` | item | | `[data-index]` | The index of the item | | `[data-inview]` | Present when in viewport | | `[data-orientation]` | The orientation of the item | **NextTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **NextTrigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | carousel | | `[data-part]` | next-trigger | | `[data-orientation]` | The orientation of the nexttrigger | **PrevTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **PrevTrigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | carousel | | `[data-part]` | prev-trigger | | `[data-orientation]` | The orientation of the prevtrigger | **ProgressText Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **RootProvider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `UseCarouselReturn` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | ### Context **API:** | Property | Type | Description | |----------|------|-------------| | `page` | `number` | The current index of the carousel | | `pageSnapPoints` | `number[]` | The current snap points of the carousel | | `isPlaying` | `boolean` | Whether the carousel is auto playing | | `isDragging` | `boolean` | Whether the carousel is being dragged. This only works when `draggable` is true. | | `canScrollNext` | `boolean` | Whether the carousel is can scroll to the next view | | `canScrollPrev` | `boolean` | Whether the carousel is can scroll to the previous view | | `scrollToIndex` | `(index: number, instant?: boolean) => void` | Function to scroll to a specific item index | | `scrollTo` | `(page: number, instant?: boolean) => void` | Function to scroll to a specific page | | `scrollNext` | `(instant?: boolean) => void` | Function to scroll to the next page | | `scrollPrev` | `(instant?: boolean) => void` | Function to scroll to the previous page | | `getProgress` | `() => number` | Returns the current scroll progress as a percentage | | `getProgressText` | `() => string` | Returns the progress text | | `play` | `VoidFunction` | Function to start/resume autoplay | | `pause` | `VoidFunction` | Function to pause autoplay | | `isInView` | `(index: number) => boolean` | Whether the item is in view | | `refresh` | `VoidFunction` | Function to re-compute the snap points and clamp the page | ## Accessibility Complies with the [Carousel WAI-ARIA design pattern](https://www.w3.org/WAI/ARIA/apg/patterns/carousel/). # Checkbox ## Anatomy ```tsx ``` ## Examples **Example: basic** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import { Check } from 'lucide-ripple'; import styles from 'styles/checkbox.module.css'; export component Basic() { {'Checkbox'} } ``` ### Default Checked Use the `defaultChecked` prop to set the initial checked state in an uncontrolled manner. The checkbox will manage its own state internally. **Example: default-checked** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import { Check } from 'lucide-ripple'; export component DefaultChecked() { {'Checkbox'} } ``` ### Controlled Use the `checked` and `onCheckedChange` props to programatically control the checkbox's state. **Example: controlled** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import { track } from 'ripple'; import { Check } from 'lucide-ripple'; export component Controlled() { let checked = track(true); { @checked = e.checked; }} > {'Checkbox'} } ``` ### Root Provider An alternative way to control the checkbox is to use the `RootProvider` component and the `useCheckbox` hook. This way you can access the state and methods from outside the component. **Example: root-provider** ```ripple import { Checkbox, useCheckbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import button from 'styles/button.module.css'; import { Check } from 'lucide-ripple'; export component RootProvider() { const checkbox = useCheckbox();
{'Checkbox'} if (@checkbox.checked) { } else { }
} ``` ### Disabled Use the `disabled` prop to make the checkbox non-interactive. **Example: disabled** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import { Check } from 'lucide-ripple'; export component Disabled() { {'Checkbox'} } ``` ### Indeterminate Use the `indeterminate` prop to create a checkbox in an indeterminate state (partially checked). **Example: indeterminate** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import { Check, Minus } from 'lucide-ripple'; export component Indeterminate() { {'Checkbox'} } ``` ### Field The checkbox integrates smoothly with the `Field` component to handle form state, helper text, and error text for proper accessibility. **Example: with-field** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import { Field } from 'ark-ripple/field'; import { Check, Minus } from 'lucide-ripple'; import styles from 'styles/checkbox.module.css'; import field from 'styles/field.module.css'; export component WithField() { {'Label'} {'Additional Info'} {'Error Info'} } ``` ### Form Pass the `name` and `value` props to the `Checkbox.Root` component to make the checkbox part of a form. The checkbox's value will be submitted with the form when the user submits it. **Example: with-form** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import button from 'styles/button.module.css'; import { Check } from 'lucide-ripple'; export component WithForm() {
{ e.preventDefault(); console.log('terms:', new FormData(e.currentTarget).get('terms')); }} > {'I agree to the terms and conditions'}
} ``` ### Context Access the checkbox's state and methods with `Checkbox.Context` or the `useCheckboxContext` hook. **Example: context** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import { Check } from 'lucide-ripple'; export component Context() { component children({ context }) { {'Checked: '} {String(@context.checked)} } } ``` ## Checkbox Group Use the `Checkbox.Group` component to manage a group of checkboxes. The `Checkbox.Group` component manages the state of the checkboxes and provides a way to access the checked values. ```tsx ``` **Example: group** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import { Check } from 'lucide-ripple'; export component Group() { for (const item of items; key item.value) { {item.label} } } const items = [ { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Vue', value: 'vue' }, ]; ``` ### Controlled Use the `value` and `onValueChange` props to programmatically control the checkbox group's state. This example demonstrates how to manage selected checkboxes in an array and display the current selection. **Example: group-controlled** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import { track } from 'ripple'; import { Check } from 'lucide-ripple'; export component GroupControlled() { let value = track(['react']);
{'value: '} {JSON.stringify(@value)} { @value = v; console.log(v); }} > for (const item of items; key item.value) { {item.label} }
} const items = [ { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Vue', value: 'vue' }, ]; ``` ### Root Provider Use the `useCheckboxGroup` hook to create the checkbox group store and pass it to the `Checkbox.GroupProvider` component. This provides maximum control over the group programmatically, similar to how `RootProvider` works for individual checkboxes. **Example: group-provider** ```ripple import { Checkbox, useCheckboxGroup } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import { Check } from 'lucide-ripple'; export component GroupProvider() { const group = useCheckboxGroup( { defaultValue: ['react'], name: 'framework', }, ); for (const item of items; key item.value) { {item.label} } } const items = [ { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Vue', value: 'vue' }, ]; ``` ### Invalid Use the `invalid` prop on `Checkbox.Group` to mark the entire group as invalid for validation purposes. This applies the invalid state to all checkboxes within the group. **Example: group-with-invalid** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import { Check } from 'lucide-ripple'; export component GroupWithInvalid() { for (const item of items; key item.value) { {item.label} } } const items = [ { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Vue', value: 'vue' }, ]; ``` ### Max Selected Use the `maxSelectedValues` prop to limit the number of checkboxes that can be selected at once. Once the maximum is reached, remaining checkboxes become disabled. **Example: group-with-max-selected** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import { Check } from 'lucide-ripple'; export component GroupWithMaxSelected() { for (const item of items; key item.value) { {item.label} } } const items = [ { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Vue', value: 'vue' }, { label: 'Svelte', value: 'svelte' }, ]; ``` ### Select All Implement a "select all" checkbox that controls all checkboxes within a group. The parent checkbox automatically shows an indeterminate state when some (but not all) items are selected, and becomes fully checked when all items are selected. **Example: group-with-select-all** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import { Check, Minus } from 'lucide-ripple'; import { track, trackSplit } from 'ripple'; import styles from 'styles/checkbox.module.css'; component CheckboxItem(props: Checkbox.RootProps & { children?: any }) { } export component GroupWithSelectAll() { let value = track([]); const handleSelectAll = (checked: boolean) => { @value = checked ? items.map((item) => item.value) : []; }; const allSelected = track(() => @value.length === items.length); const indeterminate = track(() => @value.length > 0 && @value.length < items.length);
{'Selected: '} {JSON.stringify(@value)} { handleSelectAll(!!e.checked); }} > {'JSX Frameworks'} { @value = v; }} > for (const item of items; key item.value) { {item.label} }
} const items = [ { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Vue', value: 'vue' }, ]; ``` ### Form Use the `Checkbox.Group` component within a form to handle multiple checkbox values with form submission. The `name` prop ensures all selected values are collected as an array when the form is submitted using `FormData.getAll()`. **Example: group-with-form** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import styles from 'styles/checkbox.module.css'; import button from 'styles/button.module.css'; import { Check } from 'lucide-ripple'; export component GroupWithForm() {
{ e.preventDefault(); console.log(new FormData(e.currentTarget).getAll('framework')); }} > for (const item of items; key item.value) { {item.label} }
} const items = [ { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Vue', value: 'vue' }, ]; ``` ### Fieldset Use the `Fieldset` component with `Checkbox.Group` to provide semantic grouping with legend, helper text, and error text support. **Example: group-with-fieldset** ```ripple import { Checkbox } from 'ark-ripple/checkbox'; import { Fieldset } from 'ark-ripple/fieldset'; import { Check } from 'lucide-ripple'; import styles from 'styles/checkbox.module.css'; import fieldset from 'styles/fieldset.module.css'; export component GroupWithFieldset() { {'Select frameworks'} {'Choose your preferred frameworks'} for (const item of items; key item.value) { {item.label} } } const items = [ { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Vue', value: 'vue' }, ]; ``` ## Guides ### asChild Behavior The `Checkbox.Root` element of the checkbox is a `label` element. This is because the checkbox is a form control and should be associated with a label to provide context and meaning to the user. Otherwise, the HTML and accessibility structure will be invalid. > If you need to use the `asChild` property, make sure that the `label` element is the direct child of the > `Checkbox.Root` component. ## API Reference ### Props **Component API Reference** **Root Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `checked` | `CheckedState` | No | The controlled checked state of the checkbox | | `defaultChecked` | `CheckedState` | No | The initial checked state of the checkbox when rendered. Use when you don't need to control the checked state of the checkbox. | | `disabled` | `boolean` | No | Whether the checkbox is disabled | | `form` | `string` | No | The id of the form that the checkbox belongs to. | | `id` | `string` | No | The unique identifier of the machine. | | `ids` | `Partial<{ root: string; hiddenInput: string; control: string; label: string }>` | No | The ids of the elements in the checkbox. Useful for composition. | | `invalid` | `boolean` | No | Whether the checkbox is invalid | | `name` | `string` | No | The name of the input field in a checkbox. Useful for form submission. | | `onCheckedChange` | `(details: CheckedChangeDetails) => void` | No | The callback invoked when the checked state changes. | | `readOnly` | `boolean` | No | Whether the checkbox is read-only | | `required` | `boolean` | No | Whether the checkbox is required | | `value` | `string` | No | The value of checkbox input. Useful for form submission. | **Root Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-active]` | Present when active or pressed | | `[data-focus]` | Present when focused | | `[data-focus-visible]` | Present when focused with keyboard | | `[data-readonly]` | Present when read-only | | `[data-hover]` | Present when hovered | | `[data-disabled]` | Present when disabled | | `[data-state]` | "indeterminate" | "checked" | "unchecked" | | `[data-invalid]` | Present when invalid | | `[data-required]` | Present when required | **Control Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Control Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-active]` | Present when active or pressed | | `[data-focus]` | Present when focused | | `[data-focus-visible]` | Present when focused with keyboard | | `[data-readonly]` | Present when read-only | | `[data-hover]` | Present when hovered | | `[data-disabled]` | Present when disabled | | `[data-state]` | "indeterminate" | "checked" | "unchecked" | | `[data-invalid]` | Present when invalid | | `[data-required]` | Present when required | **Group Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `defaultValue` | `string[]` | No | The initial value of `value` when uncontrolled | | `disabled` | `boolean` | No | If `true`, the checkbox group is disabled | | `invalid` | `boolean` | No | If `true`, the checkbox group is invalid | | `maxSelectedValues` | `number` | No | The maximum number of selected values | | `name` | `string` | No | The name of the input fields in the checkbox group (Useful for form submission). | | `onValueChange` | `(value: string[]) => void` | No | The callback to call when the value changes | | `readOnly` | `boolean` | No | If `true`, the checkbox group is read-only | | `value` | `string[]` | No | The controlled value of the checkbox group | **GroupProvider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `UseCheckboxGroupContext` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **HiddenInput Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Indicator Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `indeterminate` | `boolean` | No | | **Indicator Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-active]` | Present when active or pressed | | `[data-focus]` | Present when focused | | `[data-focus-visible]` | Present when focused with keyboard | | `[data-readonly]` | Present when read-only | | `[data-hover]` | Present when hovered | | `[data-disabled]` | Present when disabled | | `[data-state]` | "indeterminate" | "checked" | "unchecked" | | `[data-invalid]` | Present when invalid | | `[data-required]` | Present when required | **Label Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Label Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-active]` | Present when active or pressed | | `[data-focus]` | Present when focused | | `[data-focus-visible]` | Present when focused with keyboard | | `[data-readonly]` | Present when read-only | | `[data-hover]` | Present when hovered | | `[data-disabled]` | Present when disabled | | `[data-state]` | "indeterminate" | "checked" | "unchecked" | | `[data-invalid]` | Present when invalid | | `[data-required]` | Present when required | **RootProvider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `UseCheckboxReturn` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | ### Context **API:** | Property | Type | Description | |----------|------|-------------| | `checked` | `boolean` | Whether the checkbox is checked | | `disabled` | `boolean` | Whether the checkbox is disabled | | `indeterminate` | `boolean` | Whether the checkbox is indeterminate | | `focused` | `boolean` | Whether the checkbox is focused | | `checkedState` | `CheckedState` | The checked state of the checkbox | | `setChecked` | `(checked: CheckedState) => void` | Function to set the checked state of the checkbox | | `toggleChecked` | `VoidFunction` | Function to toggle the checked state of the checkbox | ## Accessibility Complies with the [Checkbox WAI-ARIA design pattern](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/). ### Keyboard Support **`Space`** Description: Toggle the checkbox # Clipboard ## Anatomy ```tsx ``` ## Examples **Example: basic** ```ripple import { Clipboard } from 'ark-ripple/clipboard'; import { Check, Copy } from 'lucide-ripple'; import styles from 'styles/clipboard.module.css'; export component Basic() { {'Copy this link'} } ``` ### Controlled Control the clipboard value externally by managing the state yourself and using `onValueChange` to handle updates. **Example: controlled** ```ripple import { Clipboard } from 'ark-ripple/clipboard'; import { track } from 'ripple'; import styles from 'styles/clipboard.module.css'; import button from 'styles/button.module.css'; import { Check, Copy } from 'lucide-ripple'; export component Controlled() { const url = track('https://ark-ui.rip');
{ @url = details.value; }} > {'Copy this link'}
} ``` ### Root Provider An alternative way to control the clipboard is to use the `RootProvider` component and the `useClipboard` hook. This way you can access the state and methods from outside the component. **Example: root-provider** ```ripple import { Clipboard, useClipboard } from 'ark-ripple/clipboard'; import styles from 'styles/clipboard.module.css'; import { Check, Copy } from 'lucide-ripple'; export component RootProvider() { const clipboard = useClipboard({ value: 'https://ark-ui.rip' });
{'value: '} {@clipboard.value} {', copied: '} {String(@clipboard.copied)} {'Copy this link'}
} ``` ### Context Access the clipboard's state with `Clipboard.Context` or the `useClipboardContext` hook. You get properties like `copied`, `value`, and `setValue`. > Alternatively, you can use the `useClipboardContext` hook to access the clipboard context. **Example: context** ```ripple import { Clipboard } from 'ark-ripple/clipboard'; import { Check, Copy } from 'lucide-ripple'; import styles from 'styles/clipboard.module.css'; import button from 'styles/button.module.css'; export component Context() { {'Copy this link'} component children({ context }) { } } ``` ### Copy Status Use the `onStatusChange` prop to listen for copy operations. It exposes a `copied` property that you can use to display a success message. **Example: copy-status** ```ripple import { Clipboard } from 'ark-ripple/clipboard'; import { track } from 'ripple'; import { Check, Copy } from 'lucide-ripple'; import styles from 'styles/clipboard.module.css'; export component CopyStatus() { const copyCount = track(0); { if (details.copied) { @copyCount = @copyCount + 1; } }} >

{'Copied '} {@copyCount} {' times'}

} ``` ### Timeout Configure the copy status timeout duration using the `timeout` prop. Default is 3000ms (3 seconds). **Example: timeout** ```ripple import { Clipboard } from 'ark-ripple/clipboard'; import { Check, Copy } from 'lucide-ripple'; import styles from 'styles/clipboard.module.css'; export component Timeout() { {'Copy this link (5 second timeout)'} } ``` ### Value Text Use `Clipboard.ValueText` to display the current clipboard value. **Example: value-text** ```ripple import { Clipboard } from 'ark-ripple/clipboard'; import { Check, Copy } from 'lucide-ripple'; import styles from 'styles/clipboard.module.css'; export component ValueText() { } ``` ## API Reference ### Props **Component API Reference** **Root Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `defaultValue` | `string` | No | The initial value to be copied to the clipboard when rendered. Use when you don't need to control the value of the clipboard. | | `id` | `string` | No | The unique identifier of the machine. | | `ids` | `Partial<{ root: string; input: string; label: string }>` | No | The ids of the elements in the clipboard. Useful for composition. | | `onStatusChange` | `(details: CopyStatusDetails) => void` | No | The function to be called when the value is copied to the clipboard | | `onValueChange` | `(details: ValueChangeDetails) => void` | No | The function to be called when the value changes | | `timeout` | `number` | No | The timeout for the copy operation | | `value` | `string` | No | The controlled value of the clipboard | **Root Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | clipboard | | `[data-part]` | root | | `[data-copied]` | Present when copied state is true | **Control Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Control Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | clipboard | | `[data-part]` | control | | `[data-copied]` | Present when copied state is true | **Indicator Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `copied` | `string | number | bigint | boolean | ReactElement> | Iterable | ReactPortal | Promise<...>` | No | | **Input Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Input Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | clipboard | | `[data-part]` | input | | `[data-copied]` | Present when copied state is true | | `[data-readonly]` | Present when read-only | **Label Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Label Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | clipboard | | `[data-part]` | label | | `[data-copied]` | Present when copied state is true | **RootProvider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `UseClipboardReturn` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Trigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Trigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | clipboard | | `[data-part]` | trigger | | `[data-copied]` | Present when copied state is true | **ValueText Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | ### Context **API:** | Property | Type | Description | |----------|------|-------------| | `copied` | `boolean` | Whether the value has been copied to the clipboard | | `value` | `string` | The value to be copied to the clipboard | | `setValue` | `(value: string) => void` | Set the value to be copied to the clipboard | | `copy` | `VoidFunction` | Copy the value to the clipboard | # Collapsible ## Anatomy ```tsx ``` ## Examples **Example: basic** ```ripple import { Collapsible } from 'ark-ripple/collapsible'; import { ChevronRight } from 'lucide-ripple'; import styles from 'styles/collapsible.module.css'; export component Basic() { {'What is Ark UI?'}
{'Ark UI is a headless component library for building accessible, high-quality UI components for React, Solid, Vue, and Svelte.'}
} ``` ### Disabled Use the `disabled` prop to disable the collapsible and prevent it from being toggled. **Example: disabled** ```ripple import { Collapsible } from 'ark-ripple/collapsible'; import { ChevronRight } from 'lucide-ripple'; import styles from 'styles/collapsible.module.css'; export component Disabled() { {'System Requirements'}
{'This section is currently unavailable.'}
} ``` ### Partial Collapse Use the `collapsedHeight` or `collapsedWidth` props to create a "show more/less" pattern. When set, the content maintains the specified dimensions when collapsed instead of collapsing to 0px. We expose the `--collapsed-height` or `--collapsed-width` variables to use in your CSS animations. **Example: partial-collapse** ```ripple import { Collapsible } from 'ark-ripple/collapsible'; import { ChevronRight } from 'lucide-ripple'; import styles from 'styles/collapsible.module.css'; export component PartialCollapse() { {'Read More'}

{'Ark UI is a headless component library for building accessible, high-quality UI components for React, Solid, Vue, and Svelte. It provides unstyled, fully accessible components that you can customize to match your design system.'}

{'Built on top of Zag.js state machines, Ark UI ensures consistent behavior across all frameworks while giving you complete control over styling. Each component follows WAI-ARIA patterns for accessibility out of the box.'}

{'Whether you\'re building a design system from scratch or need reliable primitives for your next project, Ark UI provides the foundation you need without imposing any visual constraints.'}

} ``` > Interactive elements (links, buttons, inputs) within the collapsed area automatically become `inert` to prevent > keyboard navigation to hidden content. ### Nested Collapsibles You can nest collapsibles within collapsibles to create hierarchical content structures. **Example: nested** ```ripple import { Collapsible } from 'ark-ripple/collapsible'; import { ChevronRight } from 'lucide-ripple'; import styles from 'styles/collapsible.module.css'; export component Nested() { {'Getting Started'}

{'Welcome to the Ark UI documentation. Here are some topics to explore:'}

{'Installation'}

{'Install Ark UI using your preferred package manager:'}

{'npm install ark-ripple'}
{'Styling'}

{'Ark UI components are unstyled by default. Use CSS modules, Tailwind, or any styling solution.'}

} ``` ### Lazy Mount Use `lazyMount` to delay mounting the content until first opened, and `unmountOnExit` to remove it from the DOM when collapsed. Combining both ensures the component is only in the DOM while expanded. **Example: lazy-mount** ```ripple import { Collapsible } from 'ark-ripple/collapsible'; import { ChevronRight } from 'lucide-ripple'; import styles from 'styles/collapsible.module.css'; export component LazyMount() { {'Session Details'}
{'This content is lazily mounted when first opened and removed from the DOM when collapsed.'}
} ``` ### Root Provider An alternative way to control the collapsible is to use the `RootProvider` component and the `useCollapsible` hook. This way you can access the state and methods from outside the component. **Example: root-provider** ```ripple import { Collapsible } from 'ark-ripple/collapsible'; import { useCollapsible } from 'ark-ripple/collapsible'; import { ChevronRight } from 'lucide-ripple'; import styles from 'styles/collapsible.module.css'; export component RootProvider() { const collapsible = useCollapsible();
{'collapsible: '} {String(@collapsible.open)} {', visible: '} {String(@collapsible.visible)} {'Toggle Panel'}
{'This panel can be toggled by the button above, which uses the useCollapsible hook for state management.'}
} ``` ## Guides ### Indicator Animation To rotate the indicator icon (such as a chevron) when the collapsible opens and closes, use CSS transforms with the `data-state` attribute: ```css [data-scope='collapsible'][data-part='indicator'] { transition: transform 200ms; &[data-state='open'] { transform: rotate(180deg); } } ``` ### Open vs Visible When using `useCollapsible` or `useCollapsibleContext`, you can access the `open` and `visible` state properties. They seem similar but serve different purposes: - **`open`**: Indicates the intended state of the collapsible. This is `true` when the collapsible should be expanded and `false` when it should be collapsed. This changes immediately when triggered. - **`visible`**: Indicates whether the content is currently visible in the DOM. This accounts for exit animations - the content remains `visible` while the closing animation plays, even though `open` is already `false`. Once the animation completes, `visible` becomes `false`. ### Content Animation Use the `--height` and/or `--width` CSS variables to animate the size of the content when it expands or closes. If you use `collapsedHeight` or `collapsedWidth`, update your CSS animations to use the `--collapsed-height` or `--collapsed-width` variables as the starting/ending point: ```css @keyframes expand { from { height: var(--collapsed-height, 0); } to { height: var(--height); } } @keyframes collapse { from { height: var(--height); } to { height: var(--collapsed-height, 0); } } [data-scope='collapsible'][data-part='content'] { &[data-state='open'] { animation: expand 250ms; } &[data-state='closed'] { animation: collapse 250ms; } } ``` ## API Reference ### Props **Component API Reference** **Root Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `collapsedHeight` | `string | number` | No | The height of the content when collapsed. | | `collapsedWidth` | `string | number` | No | The width of the content when collapsed. | | `defaultOpen` | `boolean` | No | The initial open state of the collapsible when rendered. Use when you don't need to control the open state of the collapsible. | | `disabled` | `boolean` | No | Whether the collapsible is disabled. | | `ids` | `Partial<{ root: string; content: string; trigger: string }>` | No | The ids of the elements in the collapsible. Useful for composition. | | `lazyMount` | `boolean` | No | Whether to enable lazy mounting | | `onExitComplete` | `VoidFunction` | No | The callback invoked when the exit animation completes. | | `onOpenChange` | `(details: OpenChangeDetails) => void` | No | The callback invoked when the open state changes. | | `open` | `boolean` | No | The controlled open state of the collapsible. | | `unmountOnExit` | `boolean` | No | Whether to unmount on exit. | **Root Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | collapsible | | `[data-part]` | root | | `[data-state]` | "open" | "closed" | **Content Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Content Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | collapsible | | `[data-part]` | content | | `[data-collapsible]` | | | `[data-state]` | "open" | "closed" | | `[data-disabled]` | Present when disabled | | `[data-has-collapsed-size]` | Present when the content has collapsed width or height | **Content CSS Variables:** | Variable | Description | |----------|-------------| | `--height` | The height of the element | | `--width` | The width of the element | | `--collapsed-height` | The height of the Content | | `--collapsed-width` | The width of the Content | **Indicator Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Indicator Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | collapsible | | `[data-part]` | indicator | | `[data-state]` | "open" | "closed" | | `[data-disabled]` | Present when disabled | **RootProvider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `UseCollapsibleReturn` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Trigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Trigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | collapsible | | `[data-part]` | trigger | | `[data-state]` | "open" | "closed" | | `[data-disabled]` | Present when disabled | ### Context **API:** | Property | Type | Description | |----------|------|-------------| | `open` | `boolean` | Whether the collapsible is open. | | `visible` | `boolean` | Whether the collapsible is visible (open or closing) | | `disabled` | `boolean` | Whether the collapsible is disabled | | `setOpen` | `(open: boolean) => void` | Function to open or close the collapsible. | | `measureSize` | `VoidFunction` | Function to measure the size of the content. | ## Accessibility ### Keyboard Support **`Space`** Description: Opens/closes the collapsible. **`Enter`** Description: Opens/closes the collapsible. # Color Picker ## Anatomy ```tsx ``` ## Examples **Example: basic** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import { Pipette } from 'lucide-ripple'; import styles from 'styles/color-picker.module.css'; export component Basic() { {'Color'}
} ``` ### Controlled Use the `value` and `onValueChange` props to programatically control the color picker's state. **Example: controlled** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import { Pipette } from 'lucide-ripple'; import { track } from 'ripple'; import styles from 'styles/color-picker.module.css'; export component Controlled() { let color = track(parseColor('hsl(20, 100%, 50%)'));
{'Selected color: '} {@color.toString('hex')} { @color = e.value; }} > {'Color'}
} ``` ### Open Controlled Control the open state of the color picker popover programmatically using the `open` and `onOpenChange` props. **Example: open-controlled** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import { Pipette } from 'lucide-ripple'; import { track } from 'ripple'; import styles from 'styles/color-picker.module.css'; import button from 'styles/button.module.css'; export component OpenControlled() { let open = track(false);
{ @open = e.open; }} defaultValue={parseColor('#eb5e41')} > {'Color'}
} ``` ### Root Provider An alternative way to control the color picker is to use the `RootProvider` component and the `useColorPicker` hook. This way you can access the state and methods from outside the component. **Example: root-provider** ```ripple import { ColorPicker, parseColor, useColorPicker } from 'ark-ripple/color-picker'; import { Check, Pipette } from 'lucide-ripple'; import styles from 'styles/color-picker.module.css'; const swatches = ['red', 'blue', 'green', 'orange']; export component RootProvider() { const colorPicker = useColorPicker({ defaultValue: parseColor('#eb5e41') });
{'Color: '} {@colorPicker.valueAsString} {'Color'}
for (const color of swatches; key color) { }
} ``` ### Disabled Use the `disabled` prop to disable the color picker. **Example: disabled** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import styles from 'styles/color-picker.module.css'; export component Disabled() { {'Color'}
} ``` ### Inline Render the color picker inline without a popover by using the `inline` prop. **Example: inline** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import { Check } from 'lucide-ripple'; import styles from 'styles/color-picker.module.css'; const swatches = ['red', 'blue', 'green', 'orange']; export component Inline() { for (const color of swatches; key color) { } } ``` ### Input Only A minimal color picker with just an input field, value swatch, and eye dropper trigger. **Example: input-only** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import { Pipette } from 'lucide-ripple'; import styles from 'styles/color-picker.module.css'; export component InputOnly() { {'Color'} } ``` ### Slider Only Display only the channel sliders for RGB color selection. **Example: slider-only** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import styles from 'styles/color-picker.module.css'; export component SliderOnly() {
{'R'}
{'G'}
{'B'}
} ``` ### Swatch Only A simple color picker with only preset color swatches. **Example: swatch-only** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import { Check } from 'lucide-ripple'; import styles from 'styles/color-picker.module.css'; const swatches = ['red', 'pink', 'orange', 'purple']; export component SwatchOnly() { {'Selected color: '} for (const color of swatches; key color) { } } ``` ### Swatches Include preset color swatches in the color picker content for quick color selection. **Example: swatches** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import { Check, Pipette } from 'lucide-ripple'; import styles from 'styles/color-picker.module.css'; const swatches = ['red', 'blue', 'green', 'orange']; export component Swatches() { {'Color'}
for (const color of swatches; key color) { }
} ``` ### Value Swatch Display the current color value as a swatch alongside the color area and sliders. **Example: value-swatch** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import styles from 'styles/color-picker.module.css'; export component ValueSwatch() {
} ``` ### Field The `Field` component helps manage form-related state and accessibility attributes of a color picker. It includes handling ARIA labels, helper text, and error text to ensure proper accessibility. **Example: with-field** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import { Field } from 'ark-ripple/field'; import styles from 'styles/color-picker.module.css'; import field from 'styles/field.module.css'; export component WithField() { {'Label'}
{'Additional Info'} {'Error Info'}
} ``` ### Form Usage Integrate the color picker with form libraries like React Hook Form using the `HiddenInput` component. **Example: form-usage** ```ripple import { ColorPicker, parseColor } from 'ark-ripple/color-picker'; import { Pipette } from 'lucide-ripple'; import styles from 'styles/color-picker.module.css'; import button from 'styles/button.module.css'; export component FormUsage() { const onSubmit = (e: Event) => { e.preventDefault(); const form = e.target as HTMLFormElement; alert(JSON.stringify(Object.fromEntries(new FormData(form)))); };
} ``` ## API Reference ### Props **Component API Reference** **Root Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `closeOnSelect` | `boolean` | No | Whether to close the color picker when a swatch is selected | | `defaultFormat` | `ColorFormat` | No | The initial color format when rendered. Use when you don't need to control the color format of the color picker. | | `defaultOpen` | `boolean` | No | The initial open state of the color picker when rendered. Use when you don't need to control the open state of the color picker. | | `defaultValue` | `Color` | No | The initial color value when rendered. Use when you don't need to control the color value of the color picker. | | `disabled` | `boolean` | No | Whether the color picker is disabled | | `format` | `ColorFormat` | No | The controlled color format to use | | `id` | `string` | No | The unique identifier of the machine. | | `ids` | `Partial<{ root: string; control: string; trigger: string; label: string; input: string; hiddenInput: string; content: string; area: string; areaGradient: string; positioner: string; formatSelect: string; areaThumb: string; channelInput: (id: string) => string; channelSliderTrack: (id: ColorChannel) => string; channe...` | No | The ids of the elements in the color picker. Useful for composition. | | `immediate` | `boolean` | No | Whether to synchronize the present change immediately or defer it to the next frame | | `initialFocusEl` | `() => HTMLElement | null` | No | The initial focus element when the color picker is opened. | | `inline` | `boolean` | No | Whether to render the color picker inline | | `invalid` | `boolean` | No | Whether the color picker is invalid | | `lazyMount` | `boolean` | No | Whether to enable lazy mounting | | `name` | `string` | No | The name for the form input | | `onExitComplete` | `VoidFunction` | No | Function called when the animation ends in the closed state | | `onFocusOutside` | `(event: FocusOutsideEvent) => void` | No | Function called when the focus is moved outside the component | | `onFormatChange` | `(details: FormatChangeDetails) => void` | No | Function called when the color format changes | | `onInteractOutside` | `(event: InteractOutsideEvent) => void` | No | Function called when an interaction happens outside the component | | `onOpenChange` | `(details: OpenChangeDetails) => void` | No | Handler that is called when the user opens or closes the color picker. | | `onPointerDownOutside` | `(event: PointerDownOutsideEvent) => void` | No | Function called when the pointer is pressed down outside the component | | `onValueChange` | `(details: ValueChangeDetails) => void` | No | Handler that is called when the value changes, as the user drags. | | `onValueChangeEnd` | `(details: ValueChangeDetails) => void` | No | Handler that is called when the user stops dragging. | | `open` | `boolean` | No | The controlled open state of the color picker | | `openAutoFocus` | `boolean` | No | Whether to auto focus the color picker when it is opened | | `positioning` | `PositioningOptions` | No | The positioning options for the color picker | | `present` | `boolean` | No | Whether the node is present (controlled by the user) | | `readOnly` | `boolean` | No | Whether the color picker is read-only | | `required` | `boolean` | No | Whether the color picker is required | | `skipAnimationOnMount` | `boolean` | No | Whether to allow the initial presence animation. | | `unmountOnExit` | `boolean` | No | Whether to unmount on exit. | | `value` | `Color` | No | The controlled color value of the color picker | **Root Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | root | | `[data-disabled]` | Present when disabled | | `[data-readonly]` | Present when read-only | | `[data-invalid]` | Present when invalid | **Root CSS Variables:** | Variable | Description | |----------|-------------| | `--value` | The current value | **AreaBackground Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **AreaBackground Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | area-background | | `[data-invalid]` | Present when invalid | | `[data-disabled]` | Present when disabled | | `[data-readonly]` | Present when read-only | **Area Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `xChannel` | `ColorChannel` | No | | | `yChannel` | `ColorChannel` | No | | **Area Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | area | | `[data-invalid]` | Present when invalid | | `[data-disabled]` | Present when disabled | | `[data-readonly]` | Present when read-only | **AreaThumb Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **AreaThumb Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | area-thumb | | `[data-disabled]` | Present when disabled | | `[data-invalid]` | Present when invalid | | `[data-readonly]` | Present when read-only | **AreaThumb CSS Variables:** | Variable | Description | |----------|-------------| | `--color` | The text color | **ChannelInput Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `channel` | `ExtendedColorChannel` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `orientation` | `Orientation` | No | | **ChannelInput Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | channel-input | | `[data-channel]` | The color channel of the channelinput | | `[data-disabled]` | Present when disabled | | `[data-invalid]` | Present when invalid | | `[data-readonly]` | Present when read-only | **ChannelSliderLabel Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ChannelSliderLabel Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | channel-slider-label | | `[data-channel]` | The color channel of the channelsliderlabel | **ChannelSlider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `channel` | `ColorChannel` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `orientation` | `Orientation` | No | | **ChannelSlider Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | channel-slider | | `[data-channel]` | The color channel of the channelslider | | `[data-orientation]` | The orientation of the channelslider | **ChannelSliderThumb Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ChannelSliderThumb Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | channel-slider-thumb | | `[data-channel]` | The color channel of the channelsliderthumb | | `[data-disabled]` | Present when disabled | | `[data-orientation]` | The orientation of the channelsliderthumb | **ChannelSliderTrack Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ChannelSliderTrack Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | channel-slider-track | | `[data-channel]` | The color channel of the channelslidertrack | | `[data-orientation]` | The orientation of the channelslidertrack | **ChannelSliderValueText Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ChannelSliderValueText Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | channel-slider-value-text | | `[data-channel]` | The color channel of the channelslidervaluetext | **Content Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Content Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | content | | `[data-placement]` | The placement of the content | | `[data-nested]` | popover | | `[data-has-nested]` | popover | | `[data-state]` | "open" | "closed" | **Content CSS Variables:** | Variable | Description | |----------|-------------| | `--layer-index` | The index of the dismissable in the layer stack | | `--nested-layer-count` | The number of nested color-pickers | **Control Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Control Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | control | | `[data-disabled]` | Present when disabled | | `[data-readonly]` | Present when read-only | | `[data-invalid]` | Present when invalid | | `[data-state]` | "open" | "closed" | | `[data-focus]` | Present when focused | **EyeDropperTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **EyeDropperTrigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | eye-dropper-trigger | | `[data-disabled]` | Present when disabled | | `[data-invalid]` | Present when invalid | | `[data-readonly]` | Present when read-only | **FormatSelect Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **FormatTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **HiddenInput Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Label Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Label Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | label | | `[data-disabled]` | Present when disabled | | `[data-readonly]` | Present when read-only | | `[data-invalid]` | Present when invalid | | `[data-required]` | Present when required | | `[data-focus]` | Present when focused | **Positioner Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Positioner CSS Variables:** | Variable | Description | |----------|-------------| | `--reference-width` | The width of the reference element | | `--reference-height` | The height of the root | | `--available-width` | The available width in viewport | | `--available-height` | The available height in viewport | | `--x` | The x position for transform | | `--y` | The y position for transform | | `--z-index` | The z-index value | | `--transform-origin` | The transform origin for animations | **RootProvider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `UseColorPickerReturn` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `immediate` | `boolean` | No | Whether to synchronize the present change immediately or defer it to the next frame | | `lazyMount` | `boolean` | No | Whether to enable lazy mounting | | `onExitComplete` | `VoidFunction` | No | Function called when the animation ends in the closed state | | `present` | `boolean` | No | Whether the node is present (controlled by the user) | | `skipAnimationOnMount` | `boolean` | No | Whether to allow the initial presence animation. | | `unmountOnExit` | `boolean` | No | Whether to unmount on exit. | **SwatchGroup Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **SwatchIndicator Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Swatch Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `string | Color` | Yes | The color value | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `respectAlpha` | `boolean` | No | Whether to include the alpha channel in the color | **Swatch Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | swatch | | `[data-state]` | "checked" | "unchecked" | | `[data-value]` | The value of the item | **Swatch CSS Variables:** | Variable | Description | |----------|-------------| | `--color` | The text color | **SwatchTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `string | Color` | Yes | The color value | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `disabled` | `boolean` | No | Whether the swatch trigger is disabled | **SwatchTrigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | swatch-trigger | | `[data-state]` | "checked" | "unchecked" | | `[data-value]` | The value of the item | | `[data-disabled]` | Present when disabled | **SwatchTrigger CSS Variables:** | Variable | Description | |----------|-------------| | `--color` | The text color | **TransparencyGrid Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `size` | `string` | No | | **TransparencyGrid CSS Variables:** | Variable | Description | |----------|-------------| | `--size` | The size (width and height) of the element | **Trigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Trigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | trigger | | `[data-disabled]` | Present when disabled | | `[data-readonly]` | Present when read-only | | `[data-invalid]` | Present when invalid | | `[data-placement]` | The placement of the trigger | | `[data-state]` | "open" | "closed" | | `[data-focus]` | Present when focused | **ValueSwatch Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `respectAlpha` | `boolean` | No | Whether to include the alpha channel in the color | **ValueText Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `format` | `ColorStringFormat` | No | | **ValueText Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | color-picker | | `[data-part]` | value-text | | `[data-disabled]` | Present when disabled | | `[data-focus]` | Present when focused | **View Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `format` | `ColorFormat` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | ### Context **API:** | Property | Type | Description | |----------|------|-------------| | `dragging` | `boolean` | Whether the color picker is being dragged | | `open` | `boolean` | Whether the color picker is open | | `inline` | `boolean` | Whether the color picker is rendered inline | | `value` | `Color` | The current color value (as a string) | | `valueAsString` | `string` | The current color value (as a Color object) | | `setValue` | `(value: string | Color) => void` | Function to set the color value | | `getChannelValue` | `(channel: ColorChannel) => string` | Function to set the color value | | `getChannelValueText` | `(channel: ColorChannel, locale: string) => string` | Function to get the formatted and localized value of a specific channel | | `setChannelValue` | `(channel: ColorChannel, value: number) => void` | Function to set the color value of a specific channel | | `format` | `ColorFormat` | The current color format | | `setFormat` | `(format: ColorFormat) => void` | Function to set the color format | | `alpha` | `number` | The alpha value of the color | | `setAlpha` | `(value: number) => void` | Function to set the color alpha | | `setOpen` | `(open: boolean) => void` | Function to open or close the color picker | ## Accessibility ### Keyboard Support **`Enter`** Description: When focus is on the trigger, opens the color picker
When focus is on a trigger of a swatch, selects the color (and closes the color picker)
When focus is on the input or channel inputs, selects the color
**`ArrowLeft`** Description: When focus is on the color area, decreases the hue value of the color
When focus is on the channel sliders, decreases the value of the channel
**`ArrowRight`** Description: When focus is on the color area, increases the hue value of the color
When focus is on the channel sliders, increases the value of the channel
**`ArrowUp`** Description: When focus is on the color area, increases the saturation value of the color
When focus is on the channel sliders, increases the value of the channel
**`ArrowDown`** Description: When focus is on the color area, decreases the saturation value of the color
When focus is on the channel sliders, decreases the value of the channel
**`Esc`** Description: Closes the color picker and moves focus to the trigger # Combobox ## Anatomy ```tsx ``` ## Examples **Example: basic** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown, X } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; export component Basic() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter } = useListCollection( { initialItems: [ { label: 'Apple', value: 'apple' }, { label: 'Banana', value: 'banana' }, { label: 'Orange', value: 'orange' }, { label: 'Mango', value: 'mango' }, { label: 'Pineapple', value: 'pineapple' }, { label: 'Strawberry', value: 'strawberry' }, ], filter: @filterApi.contains, }, ); { filter(details.inputValue); }} > {'Favorite Fruit'}
for (const item of @collection.items; key item.value) { {item.label} }
} ``` ### Auto Highlight Automatically highlight the first matching item as the user types by setting `inputBehavior="autohighlight"`. **Example: auto-highlight** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown, X } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; export component AutoHighlight() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter } = useListCollection( { initialItems: [ { label: 'Engineering', value: 'engineering' }, { label: 'Marketing', value: 'marketing' }, { label: 'Sales', value: 'sales' }, { label: 'Finance', value: 'finance' }, { label: 'Human Resources', value: 'hr' }, { label: 'Operations', value: 'operations' }, { label: 'Product', value: 'product' }, { label: 'Customer Success', value: 'customer-success' }, { label: 'Legal', value: 'legal' }, { label: 'Information Technology', value: 'information-technology' }, { label: 'Design', value: 'design' }, ], filter: @filterApi.contains, }, ); const handleInputChange = (details: Combobox.InputValueChangeDetails) => { filter(details.inputValue); }; {'Department'}
{'No results found'} for (const item of @collection.items; key item.value) { {item.label} }
} ``` ### Inline Autocomplete Complete the input value with the first matching item by setting `inputBehavior="autocomplete"`. Use with `startsWith` filter for best results. **Example: inline-autocomplete** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown, X } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; export component InlineAutocomplete() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter } = useListCollection( { initialItems: [ { label: 'Whale', value: 'whale' }, { label: 'Dolphin', value: 'dolphin' }, { label: 'Shark', value: 'shark' }, { label: 'Octopus', value: 'octopus' }, { label: 'Jellyfish', value: 'jellyfish' }, { label: 'Seahorse', value: 'seahorse' }, ], filter: @filterApi.startsWith, }, ); const handleInputChange = (details: Combobox.InputValueChangeDetails) => { filter(details.inputValue); }; {'Sea Creature'}
{'No results found'} for (const item of @collection.items; key item.value) { {item.label} }
} ``` ### Grouping To group related combobox items, use the `groupBy` prop on the collection and `collection.group()` to iterate the groups. **Example: grouping** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown, X } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; export component Grouping() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter } = useListCollection( { initialItems, filter: @filterApi.contains, groupBy: (item) => item.continent, }, ); const handleInputChange = (details: Combobox.InputValueChangeDetails) => { filter(details.inputValue); }; {'Country'}
for (const [continent, group] of @collection.group(); key continent) { {continent} for (const item of group; key item.value) { {item.label} } }
} const initialItems = [ { label: 'Canada', value: 'ca', continent: 'North America' }, { label: 'United States', value: 'us', continent: 'North America' }, { label: 'Mexico', value: 'mx', continent: 'North America' }, { label: 'United Kingdom', value: 'uk', continent: 'Europe' }, { label: 'Germany', value: 'de', continent: 'Europe' }, { label: 'France', value: 'fr', continent: 'Europe' }, { label: 'Japan', value: 'jp', continent: 'Asia' }, { label: 'South Korea', value: 'kr', continent: 'Asia' }, { label: 'China', value: 'cn', continent: 'Asia' }, ]; ``` ### Field The `Field` component helps manage form-related state and accessibility attributes of a combobox. It includes handling ARIA labels, helper text, and error text to ensure proper accessibility. **Example: with-field** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { Field } from 'ark-ripple/field'; import { useFilter } from 'ark-ripple/locale'; import { Check, ChevronsUpDown, X } from 'lucide-ripple'; import field from 'styles/field.module.css'; import styles from 'styles/combobox.module.css'; const initialItems = [ { label: 'Engineering', value: 'engineering' }, { label: 'Design', value: 'design' }, { label: 'Marketing', value: 'marketing' }, { label: 'Sales', value: 'sales' }, { label: 'Human Resources', value: 'hr' }, { label: 'Finance', value: 'finance' }, ]; export component WithField() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter } = useListCollection( { initialItems, filter: @filterApi.contains, }, ); const handleInputChange = (details: Combobox.InputValueChangeDetails) => { filter(details.inputValue); }; {'Department'}
for (const item of @collection.items; key item.value) { {item.label} }
{'Select your primary department'} {'Department is required'}
} ``` ### Context Access the combobox's state with `Combobox.Context` or the `useComboboxContext` hook—useful for displaying the selected value or building custom UI. **Example: context** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown, X } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; export component Context() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter } = useListCollection( { initialItems: [ { label: 'Small', value: 'sm' }, { label: 'Medium', value: 'md' }, { label: 'Large', value: 'lg' }, { label: 'Extra Large', value: 'xl' }, ], filter: @filterApi.contains, }, ); const handleInputChange = (details: Combobox.InputValueChangeDetails) => { filter(details.inputValue); }; component children({ context }) {

{'Selected: '} {@context.valueAsString || 'None'}

}
{'Size'}
for (const item of @collection.items; key item.value) { {item.label} }
} ``` ### Root Provider An alternative way to control the combobox is to use the `RootProvider` component and the `useCombobox` hook. This way you can access the state and methods from outside the component. **Example: root-provider** ```ripple import { Combobox, useCombobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown, X } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/combobox.module.css'; const initialItems = [ { label: 'Designer', value: 'designer' }, { label: 'Developer', value: 'developer' }, { label: 'Product Manager', value: 'pm' }, { label: 'Data Scientist', value: 'data-scientist' }, { label: 'DevOps Engineer', value: 'devops' }, { label: 'Marketing Lead', value: 'marketing' }, ]; export component RootProvider() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter } = useListCollection( { initialItems, filter: @filterApi.contains, }, ); const combobox = useCombobox( { collection, onInputValueChange: (details) => { filter(details.inputValue); }, }, );
{'Job Title'}
for (const item of @collection.items; key item.value) { {item.label} }
} ``` ### Links Use the `asChild` prop to render the combobox items as links. **Example: links** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; export component Links() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter } = useListCollection( { initialItems, filter: @filterApi.contains, }, ); const handleInputChange = (details: Combobox.InputValueChangeDetails) => { filter(details.inputValue); }; {'Developer Resources'}
for (const item of @collection.items; key item.value) { component asChild({ propsFn }) { {item.label} } }
} const initialItems = [ { label: 'GitHub', href: 'https://github.com', value: 'github' }, { label: 'Stack Overflow', href: 'https://stackoverflow.com', value: 'stackoverflow' }, { label: 'MDN Web Docs', href: 'https://developer.mozilla.org', value: 'mdn' }, { label: 'npm', href: 'https://www.npmjs.com', value: 'npm' }, { label: 'TypeScript', href: 'https://www.typescriptlang.org', value: 'typescript' }, { label: 'React', href: 'https://react.dev', value: 'react' }, ]; ``` ### Rehydrate When a combobox has a `defaultValue` or `value` but the `collection` is not loaded yet, you can rehydrate the value to populate the input. **Example: rehydrate-value** ```ripple import { Combobox, useCombobox, useComboboxContext, useListCollection } from 'ark-ripple/combobox'; import { Portal } from 'ark-ripple/portal'; import { Check } from 'lucide-ripple'; import { track, effect } from 'ripple'; import styles from 'styles/combobox.module.css'; import { useAsync } from './use-async'; export component RehydrateValue() { let inputValue = track(''); let { collection, set } = useListCollection( { initialItems: [], itemToString: (item) => item.name, itemToValue: (item) => item.name, }, ); const combobox = useCombobox( { collection, defaultValue: ['C-3PO'], placeholder: 'Example: Dexter', inputValue, onInputValueChange: (e) => { @inputValue = e.inputValue; }, }, ); let state = useAsync(async (signal) => { const response = await fetch(`https://swapi.py4e.com/api/people/?search=${@inputValue}`, { signal, }); const data = await response.json(); set(data.results); }); effect(() => { void @inputValue; void state.load(); }); let hydrated = false; effect(() => { if (@combobox.value.length && @combobox.collection.size && !hydrated) { @combobox.syncSelectedItems(); hydrated = true; } }); {'Search Star Wars Characters'} if (state.@loading) { {'Loading...'} } else if (state.@error) { {state.@error?.message} } else { for (const item of @collection.items; key item.name) { {item.name} {' - '} {item.height} {'cm / '} {item.mass} {'kg'} } } } interface Character { name: string; height: string; mass: string; created: string; edited: string; url: string; } ``` ### Highlight Text Highlight the matching search text in combobox items based on the user's input. **Example: highlight-matching-text** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { Highlight } from 'ark-ripple/highlight'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { ChevronsUpDown, X } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; export component HighlightMatchingText() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter } = useListCollection( { initialItems: [ { label: 'John Smith', value: 'john-smith' }, { label: 'Jane Doe', value: 'jane-doe' }, { label: 'Bob Johnson', value: 'bob-johnson' }, { label: 'Alice Williams', value: 'alice-williams' }, { label: 'Charlie Brown', value: 'charlie-brown' }, { label: 'Diana Ross', value: 'diana-ross' }, ], filter: @filterApi.contains, }, ); const handleInputChange = (details: Combobox.InputValueChangeDetails) => { filter(details.inputValue); }; {'Assignee'}
for (const item of @collection.items; key item.value) { component children({ context }) { } }
} ``` ### Dynamic Generate combobox items dynamically based on user input. This is useful for creating suggestions or autocomplete functionality. **Example: dynamic** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; const suggestList = ['gmail.com', 'yahoo.com', 'ark-ui.rip']; export component Dynamic() { let { collection, set } = useListCollection( { initialItems: [], }, ); const handleInputChange = (details: Combobox.InputValueChangeDetails) => { if (details.reason === 'input-change') { const items = suggestList.map((item) => `${details.inputValue}@${item}`); set(items); } }; {'Email'}
for (const item of @collection.items; key item) { {item} }
} ``` ### Creatable Allow users to create new options when their search doesn't match any existing items. This is useful for tags, categories, or other custom values. **Example: creatable** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown, X } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; interface Item { label: string; value: string; __new__?: boolean | undefined; } const NEW_OPTION_VALUE = '[[new]]'; const createNewOption = (value: string): Item => ({ label: value, value: NEW_OPTION_VALUE }); const isNewOptionValue = (value: string) => value === NEW_OPTION_VALUE; const replaceNewOptionValue = (values: string[], value: string) => values.map( (v) => (v === NEW_OPTION_VALUE ? value : v), ); const getNewOptionData = (inputValue: string): Item => ({ label: inputValue, value: inputValue, __new__: true, }); export component Creatable() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter, upsert, remove, update } = useListCollection( { initialItems: [ { label: 'Bug', value: 'bug' }, { label: 'Feature', value: 'feature' }, { label: 'Enhancement', value: 'enhancement' }, { label: 'Documentation', value: 'docs' }, ], filter: @filterApi.contains, }, ); const isValidNewOption = (inputValue: string) => { const exactOptionMatch = @collection.filter((item) => item.toLowerCase() === inputValue.toLowerCase()).size > 0; return !exactOptionMatch && inputValue.trim().length > 0; }; let selectedValue = track([]); let inputValue = track(''); { if (details.reason === 'input-change' || details.reason === 'item-select') { if (isValidNewOption(details.inputValue)) { upsert(NEW_OPTION_VALUE, createNewOption(details.inputValue)); } else if (details.inputValue.trim().length === 0) { remove(NEW_OPTION_VALUE); } filter(details.inputValue); } @inputValue = details.inputValue; }} onOpenChange={(details) => { if (details.reason === 'trigger-click') { filter(''); } }} onValueChange={(details) => { @selectedValue = replaceNewOptionValue(details.value, @inputValue); if (details.value.includes(NEW_OPTION_VALUE)) { update(NEW_OPTION_VALUE, getNewOptionData(@inputValue)); } }} > {'Label'}
for (const item of @collection.items; key item.value) { if (isNewOptionValue(item.value)) { {'+ Create "'} {item.label} {'"'} } else { {item.label} {item.__new__ ? ' (new)' : ''} } }
} ``` ### Multiple Selection Enable multiple selection by setting the `multiple` prop. Selected items can be displayed as tags above the input. **Example: multiple** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; export component Multiple() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter, remove } = useListCollection( { initialItems: [ { label: 'JavaScript', value: 'js' }, { label: 'TypeScript', value: 'ts' }, { label: 'Python', value: 'python' }, { label: 'Go', value: 'go' }, { label: 'Rust', value: 'rust' }, { label: 'Java', value: 'java' }, ], filter: @filterApi.contains, }, ); { filter(details.inputValue); }} onValueChange={(details) => { remove(...details.value); }} multiple > {'Skills'} component children({ context }) {
if (@context.selectedItems.length === 0) { {'None selected'} } for (const item of @context.selectedItems; key item.value) { {item.label} }
}
{'No skills found'} for (const item of @collection.items; key item.value) { {item.label} }
} ``` ### Async Search Load options asynchronously based on user input using the `useAsyncList` hook. This is useful for searching large datasets or fetching data from an API. **Example: async-search** ```ripple import { useAsyncList } from 'ark-ripple/collection'; import { Combobox, createListCollection } from 'ark-ripple/combobox'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown, Loader, X } from 'lucide-ripple'; import { track } from 'ripple'; import styles from 'styles/combobox.module.css'; interface Movie { id: string; title: string; year: number; director: string; genre: string; } export component AsyncSearch() { const list = useAsyncList( { async load({ filterText, signal }: { filterText?: string; signal?: AbortSignal }) { if (!filterText) return { items: [] }; await new Promise((resolve) => setTimeout(resolve, 300)); if (signal?.aborted) return { items: [] }; const items = allMovies.filter( (movie) => movie.title.toLowerCase().includes(filterText.toLowerCase()) || movie.director.toLowerCase().includes(filterText.toLowerCase()) || movie.genre.toLowerCase().includes(filterText.toLowerCase()), ); return { items }; }, }, ); const collection = track( () => createListCollection( { items: @list.items, itemToString: (item) => item.title, itemToValue: (item) => item.id, }, ), ); { if (details.reason === 'input-change') { @list.setFilterText(details.inputValue); } }} > {'Movie'}
if (@list.loading) {
{'Searching...'}
} else if (@list.error) {
{@list.error.message}
} else if (@list.items.length === 0) {
{@list.filterText ? 'No results found' : 'Start typing to search movies...'}
} else { for (const movie of @list.items; key movie.id) { {movie.title} {movie.year} {' · '} {movie.director} } }
} const allMovies: Movie[] = [ { id: 'inception', title: 'Inception', year: 2010, director: 'Christopher Nolan', genre: 'Sci-Fi', }, { id: 'the-dark-knight', title: 'The Dark Knight', year: 2008, director: 'Christopher Nolan', genre: 'Action', }, { id: 'pulp-fiction', title: 'Pulp Fiction', year: 1994, director: 'Quentin Tarantino', genre: 'Crime', }, { id: 'the-godfather', title: 'The Godfather', year: 1972, director: 'Francis Ford Coppola', genre: 'Crime', }, { id: 'forrest-gump', title: 'Forrest Gump', year: 1994, director: 'Robert Zemeckis', genre: 'Drama', }, { id: 'the-matrix', title: 'The Matrix', year: 1999, director: 'The Wachowskis', genre: 'Sci-Fi', }, { id: 'interstellar', title: 'Interstellar', year: 2014, director: 'Christopher Nolan', genre: 'Sci-Fi', }, { id: 'parasite', title: 'Parasite', year: 2019, director: 'Bong Joon-ho', genre: 'Thriller' }, { id: 'the-shawshank-redemption', title: 'The Shawshank Redemption', year: 1994, director: 'Frank Darabont', genre: 'Drama', }, { id: 'fight-club', title: 'Fight Club', year: 1999, director: 'David Fincher', genre: 'Drama' }, { id: 'goodfellas', title: 'Goodfellas', year: 1990, director: 'Martin Scorsese', genre: 'Crime', }, { id: 'the-silence-of-the-lambs', title: 'The Silence of the Lambs', year: 1991, director: 'Jonathan Demme', genre: 'Thriller', }, ]; ``` ### Virtualized For very large lists, use virtualization with `@tanstack/virtual` to render only the visible items. Pass the `scrollToIndexFn` prop to enable keyboard navigation within the virtualized list. **Example: virtualized** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; import { createVirtualizer } from '../../../utils/use-virtualizer.ripple'; import { flushSync, track } from 'ripple'; export component Virtualized() { let contentRef = track(null); const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter, reset } = useListCollection( { initialItems: countries, filter: @filterApi.startsWith, }, ); const virtualizer = createVirtualizer( { get count() { return @collection.size; }, getScrollElement: () => @contentRef, estimateSize: () => 32, overscan: 10, }, ); const handleScrollToIndex: Combobox.RootProps['scrollToIndexFn'] = (details) => { flushSync(() => { virtualizer.scrollToIndex(details.index, { align: 'center', behavior: 'auto' }); }); }; const handleInputChange = (details: Combobox.InputValueChangeDetails) => { filter(details.inputValue); }; {'Country'}
{ @contentRef = el; return () => { @contentRef = null; }; }} class={styles.Scroller} >
for (const virtualItem of virtualizer.getVirtualItems(); key ((@collection.items[virtualItem.index])).value) { let item = @collection.items[virtualItem.index]; {item.emoji} {item.label} }
} interface Country { value: string; label: string; emoji: string; } const countries: Country[] = [ { value: 'AD', label: 'Andorra', emoji: '🇦🇩' }, { value: 'AE', label: 'United Arab Emirates', emoji: '🇦🇪' }, { value: 'AF', label: 'Afghanistan', emoji: '🇦🇫' }, { value: 'AG', label: 'Antigua and Barbuda', emoji: '🇦🇬' }, { value: 'AI', label: 'Anguilla', emoji: '🇦🇮' }, { value: 'AL', label: 'Albania', emoji: '🇦🇱' }, { value: 'AM', label: 'Armenia', emoji: '🇦🇲' }, { value: 'AO', label: 'Angola', emoji: '🇦🇴' }, { value: 'AQ', label: 'Antarctica', emoji: '🇦🇶' }, { value: 'AR', label: 'Argentina', emoji: '🇦🇷' }, { value: 'AS', label: 'American Samoa', emoji: '🇦🇸' }, { value: 'AT', label: 'Austria', emoji: '🇦🇹' }, { value: 'AU', label: 'Australia', emoji: '🇦🇺' }, { value: 'AW', label: 'Aruba', emoji: '🇦🇼' }, { value: 'AX', label: 'Åland Islands', emoji: '🇦🇽' }, { value: 'AZ', label: 'Azerbaijan', emoji: '🇦🇿' }, { value: 'BA', label: 'Bosnia and Herzegovina', emoji: '🇧🇦' }, { value: 'BB', label: 'Barbados', emoji: '🇧🇧' }, { value: 'BD', label: 'Bangladesh', emoji: '🇧🇩' }, { value: 'BE', label: 'Belgium', emoji: '🇧🇪' }, { value: 'BF', label: 'Burkina Faso', emoji: '🇧🇫' }, { value: 'BG', label: 'Bulgaria', emoji: '🇧🇬' }, { value: 'BH', label: 'Bahrain', emoji: '🇧🇭' }, { value: 'BI', label: 'Burundi', emoji: '🇧🇮' }, { value: 'BJ', label: 'Benin', emoji: '🇧🇯' }, { value: 'BL', label: 'Saint Barthélemy', emoji: '🇧🇱' }, { value: 'BM', label: 'Bermuda', emoji: '🇧🇲' }, { value: 'BN', label: 'Brunei', emoji: '🇧🇳' }, { value: 'BO', label: 'Bolivia', emoji: '🇧🇴' }, { value: 'BR', label: 'Brazil', emoji: '🇧🇷' }, { value: 'BS', label: 'Bahamas', emoji: '🇧🇸' }, { value: 'BT', label: 'Bhutan', emoji: '🇧🇹' }, { value: 'BW', label: 'Botswana', emoji: '🇧🇼' }, { value: 'BY', label: 'Belarus', emoji: '🇧🇾' }, { value: 'BZ', label: 'Belize', emoji: '🇧🇿' }, { value: 'CA', label: 'Canada', emoji: '🇨🇦' }, { value: 'CD', label: 'Congo', emoji: '🇨🇩' }, { value: 'CF', label: 'Central African Republic', emoji: '🇨🇫' }, { value: 'CH', label: 'Switzerland', emoji: '🇨🇭' }, { value: 'CI', label: 'Côte d\'Ivoire', emoji: '🇨🇮' }, { value: 'CK', label: 'Cook Islands', emoji: '🇨🇰' }, { value: 'CL', label: 'Chile', emoji: '🇨🇱' }, { value: 'CM', label: 'Cameroon', emoji: '🇨🇲' }, { value: 'CN', label: 'China', emoji: '🇨🇳' }, { value: 'CO', label: 'Colombia', emoji: '🇨🇴' }, { value: 'CR', label: 'Costa Rica', emoji: '🇨🇷' }, { value: 'CU', label: 'Cuba', emoji: '🇨🇺' }, { value: 'CV', label: 'Cabo Verde', emoji: '🇨🇻' }, { value: 'CY', label: 'Cyprus', emoji: '🇨🇾' }, { value: 'CZ', label: 'Czech Republic', emoji: '🇨🇿' }, { value: 'DE', label: 'Germany', emoji: '🇩🇪' }, { value: 'DJ', label: 'Djibouti', emoji: '🇩🇯' }, { value: 'DK', label: 'Denmark', emoji: '🇩🇰' }, { value: 'DM', label: 'Dominica', emoji: '🇩🇲' }, { value: 'DO', label: 'Dominican Republic', emoji: '🇩🇴' }, { value: 'DZ', label: 'Algeria', emoji: '🇩🇿' }, { value: 'EC', label: 'Ecuador', emoji: '🇪🇨' }, { value: 'EE', label: 'Estonia', emoji: '🇪🇪' }, { value: 'EG', label: 'Egypt', emoji: '🇪🇬' }, { value: 'ER', label: 'Eritrea', emoji: '🇪🇷' }, { value: 'ES', label: 'Spain', emoji: '🇪🇸' }, { value: 'ET', label: 'Ethiopia', emoji: '🇪🇹' }, { value: 'FI', label: 'Finland', emoji: '🇫🇮' }, { value: 'FJ', label: 'Fiji', emoji: '🇫🇯' }, { value: 'FK', label: 'Falkland Islands', emoji: '🇫🇰' }, { value: 'FM', label: 'Micronesia', emoji: '🇫🇲' }, { value: 'FO', label: 'Faroe Islands', emoji: '🇫🇴' }, { value: 'FR', label: 'France', emoji: '🇫🇷' }, { value: 'GA', label: 'Gabon', emoji: '🇬🇦' }, { value: 'GB', label: 'United Kingdom', emoji: '🇬🇧' }, { value: 'GD', label: 'Grenada', emoji: '🇬🇩' }, { value: 'GE', label: 'Georgia', emoji: '🇬🇪' }, { value: 'GH', label: 'Ghana', emoji: '🇬🇭' }, { value: 'GI', label: 'Gibraltar', emoji: '🇬🇮' }, { value: 'GL', label: 'Greenland', emoji: '🇬🇱' }, { value: 'GM', label: 'Gambia', emoji: '🇬🇲' }, { value: 'GN', label: 'Guinea', emoji: '🇬🇳' }, { value: 'GQ', label: 'Equatorial Guinea', emoji: '🇬🇶' }, { value: 'GR', label: 'Greece', emoji: '🇬🇷' }, { value: 'GT', label: 'Guatemala', emoji: '🇬🇹' }, { value: 'GU', label: 'Guam', emoji: '🇬🇺' }, { value: 'GW', label: 'Guinea-Bissau', emoji: '🇬🇼' }, { value: 'GY', label: 'Guyana', emoji: '🇬🇾' }, { value: 'HK', label: 'Hong Kong', emoji: '🇭🇰' }, { value: 'HN', label: 'Honduras', emoji: '🇭🇳' }, { value: 'HR', label: 'Croatia', emoji: '🇭🇷' }, { value: 'HT', label: 'Haiti', emoji: '🇭🇹' }, { value: 'HU', label: 'Hungary', emoji: '🇭🇺' }, { value: 'ID', label: 'Indonesia', emoji: '🇮🇩' }, { value: 'IE', label: 'Ireland', emoji: '🇮🇪' }, { value: 'IL', label: 'Israel', emoji: '🇮🇱' }, { value: 'IM', label: 'Isle of Man', emoji: '🇮🇲' }, { value: 'IN', label: 'India', emoji: '🇮🇳' }, { value: 'IQ', label: 'Iraq', emoji: '🇮🇶' }, { value: 'IR', label: 'Iran', emoji: '🇮🇷' }, { value: 'IS', label: 'Iceland', emoji: '🇮🇸' }, { value: 'IT', label: 'Italy', emoji: '🇮🇹' }, { value: 'JE', label: 'Jersey', emoji: '🇯🇪' }, { value: 'JM', label: 'Jamaica', emoji: '🇯🇲' }, { value: 'JO', label: 'Jordan', emoji: '🇯🇴' }, { value: 'JP', label: 'Japan', emoji: '🇯🇵' }, { value: 'KE', label: 'Kenya', emoji: '🇰🇪' }, { value: 'KG', label: 'Kyrgyzstan', emoji: '🇰🇬' }, { value: 'KH', label: 'Cambodia', emoji: '🇰🇭' }, { value: 'KI', label: 'Kiribati', emoji: '🇰🇮' }, { value: 'KM', label: 'Comoros', emoji: '🇰🇲' }, { value: 'KN', label: 'Saint Kitts and Nevis', emoji: '🇰🇳' }, { value: 'KP', label: 'North Korea', emoji: '🇰🇵' }, { value: 'KR', label: 'South Korea', emoji: '🇰🇷' }, { value: 'KW', label: 'Kuwait', emoji: '🇰🇼' }, { value: 'KY', label: 'Cayman Islands', emoji: '🇰🇾' }, { value: 'KZ', label: 'Kazakhstan', emoji: '🇰🇿' }, { value: 'LA', label: 'Laos', emoji: '🇱🇦' }, { value: 'LB', label: 'Lebanon', emoji: '🇱🇧' }, { value: 'LC', label: 'Saint Lucia', emoji: '🇱🇨' }, { value: 'LI', label: 'Liechtenstein', emoji: '🇱🇮' }, { value: 'LK', label: 'Sri Lanka', emoji: '🇱🇰' }, { value: 'LR', label: 'Liberia', emoji: '🇱🇷' }, { value: 'LS', label: 'Lesotho', emoji: '🇱🇸' }, { value: 'LT', label: 'Lithuania', emoji: '🇱🇹' }, { value: 'LU', label: 'Luxembourg', emoji: '🇱🇺' }, { value: 'LV', label: 'Latvia', emoji: '🇱🇻' }, { value: 'LY', label: 'Libya', emoji: '🇱🇾' }, { value: 'MA', label: 'Morocco', emoji: '🇲🇦' }, { value: 'MC', label: 'Monaco', emoji: '🇲🇨' }, { value: 'MD', label: 'Moldova', emoji: '🇲🇩' }, { value: 'ME', label: 'Montenegro', emoji: '🇲🇪' }, { value: 'MG', label: 'Madagascar', emoji: '🇲🇬' }, { value: 'MH', label: 'Marshall Islands', emoji: '🇲🇭' }, { value: 'MK', label: 'North Macedonia', emoji: '🇲🇰' }, { value: 'ML', label: 'Mali', emoji: '🇲🇱' }, { value: 'MM', label: 'Myanmar', emoji: '🇲🇲' }, { value: 'MN', label: 'Mongolia', emoji: '🇲🇳' }, { value: 'MO', label: 'Macao', emoji: '🇲🇴' }, { value: 'MR', label: 'Mauritania', emoji: '🇲🇷' }, { value: 'MS', label: 'Montserrat', emoji: '🇲🇸' }, { value: 'MT', label: 'Malta', emoji: '🇲🇹' }, { value: 'MU', label: 'Mauritius', emoji: '🇲🇺' }, { value: 'MV', label: 'Maldives', emoji: '🇲🇻' }, { value: 'MW', label: 'Malawi', emoji: '🇲🇼' }, { value: 'MX', label: 'Mexico', emoji: '🇲🇽' }, { value: 'MY', label: 'Malaysia', emoji: '🇲🇾' }, { value: 'MZ', label: 'Mozambique', emoji: '🇲🇿' }, { value: 'NA', label: 'Namibia', emoji: '🇳🇦' }, { value: 'NC', label: 'New Caledonia', emoji: '🇳🇨' }, { value: 'NE', label: 'Niger', emoji: '🇳🇪' }, { value: 'NF', label: 'Norfolk Island', emoji: '🇳🇫' }, { value: 'NG', label: 'Nigeria', emoji: '🇳🇬' }, { value: 'NI', label: 'Nicaragua', emoji: '🇳🇮' }, { value: 'NL', label: 'Netherlands', emoji: '🇳🇱' }, { value: 'NO', label: 'Norway', emoji: '🇳🇴' }, { value: 'NP', label: 'Nepal', emoji: '🇳🇵' }, { value: 'NR', label: 'Nauru', emoji: '🇳🇷' }, { value: 'NU', label: 'Niue', emoji: '🇳🇺' }, { value: 'NZ', label: 'New Zealand', emoji: '🇳🇿' }, { value: 'OM', label: 'Oman', emoji: '🇴🇲' }, { value: 'PA', label: 'Panama', emoji: '🇵🇦' }, { value: 'PE', label: 'Peru', emoji: '🇵🇪' }, { value: 'PF', label: 'French Polynesia', emoji: '🇵🇫' }, { value: 'PG', label: 'Papua New Guinea', emoji: '🇵🇬' }, { value: 'PH', label: 'Philippines', emoji: '🇵🇭' }, { value: 'PK', label: 'Pakistan', emoji: '🇵🇰' }, { value: 'PL', label: 'Poland', emoji: '🇵🇱' }, { value: 'PR', label: 'Puerto Rico', emoji: '🇵🇷' }, { value: 'PS', label: 'Palestine', emoji: '🇵🇸' }, { value: 'PT', label: 'Portugal', emoji: '🇵🇹' }, { value: 'PW', label: 'Palau', emoji: '🇵🇼' }, { value: 'PY', label: 'Paraguay', emoji: '🇵🇾' }, { value: 'QA', label: 'Qatar', emoji: '🇶🇦' }, { value: 'RO', label: 'Romania', emoji: '🇷🇴' }, { value: 'RS', label: 'Serbia', emoji: '🇷🇸' }, { value: 'RU', label: 'Russia', emoji: '🇷🇺' }, { value: 'RW', label: 'Rwanda', emoji: '🇷🇼' }, { value: 'SA', label: 'Saudi Arabia', emoji: '🇸🇦' }, { value: 'SB', label: 'Solomon Islands', emoji: '🇸🇧' }, { value: 'SC', label: 'Seychelles', emoji: '🇸🇨' }, { value: 'SD', label: 'Sudan', emoji: '🇸🇩' }, { value: 'SE', label: 'Sweden', emoji: '🇸🇪' }, { value: 'SG', label: 'Singapore', emoji: '🇸🇬' }, { value: 'SI', label: 'Slovenia', emoji: '🇸🇮' }, { value: 'SK', label: 'Slovakia', emoji: '🇸🇰' }, { value: 'SL', label: 'Sierra Leone', emoji: '🇸🇱' }, { value: 'SM', label: 'San Marino', emoji: '🇸🇲' }, { value: 'SN', label: 'Senegal', emoji: '🇸🇳' }, { value: 'SO', label: 'Somalia', emoji: '🇸🇴' }, { value: 'SR', label: 'Suriname', emoji: '🇸🇷' }, { value: 'SS', label: 'South Sudan', emoji: '🇸🇸' }, { value: 'ST', label: 'Sao Tome and Principe', emoji: '🇸🇹' }, { value: 'SV', label: 'El Salvador', emoji: '🇸🇻' }, { value: 'SY', label: 'Syria', emoji: '🇸🇾' }, { value: 'SZ', label: 'Eswatini', emoji: '🇸🇿' }, { value: 'TC', label: 'Turks and Caicos Islands', emoji: '🇹🇨' }, { value: 'TD', label: 'Chad', emoji: '🇹🇩' }, { value: 'TG', label: 'Togo', emoji: '🇹🇬' }, { value: 'TH', label: 'Thailand', emoji: '🇹🇭' }, { value: 'TJ', label: 'Tajikistan', emoji: '🇹🇯' }, { value: 'TK', label: 'Tokelau', emoji: '🇹🇰' }, { value: 'TL', label: 'Timor-Leste', emoji: '🇹🇱' }, { value: 'TM', label: 'Turkmenistan', emoji: '🇹🇲' }, { value: 'TN', label: 'Tunisia', emoji: '🇹🇳' }, { value: 'TO', label: 'Tonga', emoji: '🇹🇴' }, { value: 'TR', label: 'Türkiye', emoji: '🇹🇷' }, { value: 'TT', label: 'Trinidad and Tobago', emoji: '🇹🇹' }, { value: 'TV', label: 'Tuvalu', emoji: '🇹🇻' }, { value: 'TW', label: 'Taiwan', emoji: '🇹🇼' }, { value: 'TZ', label: 'Tanzania', emoji: '🇹🇿' }, { value: 'UA', label: 'Ukraine', emoji: '🇺🇦' }, { value: 'UG', label: 'Uganda', emoji: '🇺🇬' }, { value: 'US', label: 'United States', emoji: '🇺🇸' }, { value: 'UY', label: 'Uruguay', emoji: '🇺🇾' }, { value: 'UZ', label: 'Uzbekistan', emoji: '🇺🇿' }, { value: 'VA', label: 'Vatican City', emoji: '🇻🇦' }, { value: 'VC', label: 'Saint Vincent and the Grenadines', emoji: '🇻🇨' }, { value: 'VE', label: 'Venezuela', emoji: '🇻🇪' }, { value: 'VG', label: 'British Virgin Islands', emoji: '🇻🇬' }, { value: 'VI', label: 'U.S. Virgin Islands', emoji: '🇻🇮' }, { value: 'VN', label: 'Vietnam', emoji: '🇻🇳' }, { value: 'VU', label: 'Vanuatu', emoji: '🇻🇺' }, { value: 'WF', label: 'Wallis and Futuna', emoji: '🇼🇫' }, { value: 'WS', label: 'Samoa', emoji: '🇼🇸' }, { value: 'YE', label: 'Yemen', emoji: '🇾🇪' }, { value: 'YT', label: 'Mayotte', emoji: '🇾🇹' }, { value: 'ZA', label: 'South Africa', emoji: '🇿🇦' }, { value: 'ZM', label: 'Zambia', emoji: '🇿🇲' }, { value: 'ZW', label: 'Zimbabwe', emoji: '🇿🇼' }, ]; ``` ### Custom Object Use the `itemToString` and `itemToValue` props to map custom objects to the required interface. **Example: custom-object** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown, X } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; export component CustomObject() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter } = useListCollection( { initialItems: [ { country: 'United States', code: 'US', flag: '🇺🇸' }, { country: 'Canada', code: 'CA', flag: '🇨🇦' }, { country: 'Australia', code: 'AU', flag: '🇦🇺' }, ], itemToString: (item) => item.country, itemToValue: (item) => item.code, filter: @filterApi.contains, }, ); const handleInputChange = (details: Combobox.InputValueChangeDetails) => { filter(details.inputValue); }; {'Country'}
for (const item of @collection.items; key item.code) { {item.flag} {' '} {item.country} }
} ``` ### Limit Results Use the `limit` property on `useListCollection` to limit the number of rendered items in the DOM. **Example: limit-results** ```ripple import { Combobox, useListCollection } from 'ark-ripple/combobox'; import { useFilter } from 'ark-ripple/locale'; import { Portal } from 'ark-ripple/portal'; import { Check, ChevronsUpDown } from 'lucide-ripple'; import styles from 'styles/combobox.module.css'; const cities = [ { label: 'New York', value: 'new-york' }, { label: 'Los Angeles', value: 'los-angeles' }, { label: 'Chicago', value: 'chicago' }, { label: 'Houston', value: 'houston' }, { label: 'Phoenix', value: 'phoenix' }, { label: 'Philadelphia', value: 'philadelphia' }, { label: 'San Antonio', value: 'san-antonio' }, { label: 'San Diego', value: 'san-diego' }, { label: 'Dallas', value: 'dallas' }, { label: 'San Jose', value: 'san-jose' }, { label: 'Austin', value: 'austin' }, { label: 'Jacksonville', value: 'jacksonville' }, { label: 'Fort Worth', value: 'fort-worth' }, { label: 'Columbus', value: 'columbus' }, { label: 'Charlotte', value: 'charlotte' }, { label: 'San Francisco', value: 'san-francisco' }, { label: 'Indianapolis', value: 'indianapolis' }, { label: 'Seattle', value: 'seattle' }, { label: 'Denver', value: 'denver' }, { label: 'Boston', value: 'boston' }, ]; export component LimitResults() { const filterApi = useFilter({ sensitivity: 'base' }); let { collection, filter } = useListCollection( { initialItems: cities, limit: 5, filter: @filterApi.contains, }, ); const handleInputChange = (details: Combobox.InputValueChangeDetails) => { filter(details.inputValue); }; {'City'}
for (const item of @collection.items; key item.value) { {item.label} }
} ``` ## Guides ### Router Links Customize the `navigate` prop on `Combobox.Root` to integrate with your router.: ```tsx import { Combobox } from 'ark-ripple/combobox' import { useNavigate } from '' function Demo() { const navigate = useNavigate() return ( { navigate({ to: e.node.href }) }} > {/* ... */} ) } ``` ### Custom Objects By default, the combobox collection expects an array of objects with `label` and `value` properties. In some cases, you may need to deal with custom objects. Use the `itemToString` and `itemToValue` props to map the custom object to the required interface. ```tsx const items = [ { country: 'United States', code: 'US', flag: '🇺🇸' }, { country: 'Canada', code: 'CA', flag: '🇨🇦' }, { country: 'Australia', code: 'AU', flag: '🇦🇺' }, // ... ] const { collection } = useListCollection({ initialItems: items, itemToString: (item) => item.country, itemToValue: (item) => item.code, }) ``` ### Large Datasets The recommended way of managing large lists is to use the `limit` property on the `useListCollection` hook. This will limit the number of rendered items in the DOM to improve performance. ```tsx {3} const { collection } = useListCollection({ initialItems: items, limit: 10, }) ``` ### Available Size The following css variables are exposed to the `Combobox.Positioner` which you can use to style the `Combobox.Content` ```css /* width of the combobox control */ --reference-width: ; /* width of the available viewport */ --available-width: ; /* height of the available viewport */ --available-height: ; ``` For example, if you want to make sure the maximum height doesn't exceed the available height, you can use the following: ```css [data-scope='combobox'][data-part='content'] { max-height: calc(var(--available-height) - 100px); } ``` ## API Reference ### Props **Component API Reference** **Root Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `collection` | `ListCollection` | Yes | The collection of items | | `allowCustomValue` | `boolean` | No | Whether to allow typing custom values in the input | | `alwaysSubmitOnEnter` | `boolean` | No | Whether to always submit on Enter key press, even if popup is open. Useful for single-field autocomplete forms where Enter should submit the form. | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `autoFocus` | `boolean` | No | Whether to autofocus the input on mount | | `closeOnSelect` | `boolean` | No | Whether to close the combobox when an item is selected. | | `composite` | `boolean` | No | Whether the combobox is a composed with other composite widgets like tabs | | `defaultHighlightedValue` | `string` | No | The initial highlighted value of the combobox when rendered. Use when you don't need to control the highlighted value of the combobox. | | `defaultInputValue` | `string` | No | The initial value of the combobox's input when rendered. Use when you don't need to control the value of the combobox's input. | | `defaultOpen` | `boolean` | No | The initial open state of the combobox when rendered. Use when you don't need to control the open state of the combobox. | | `defaultValue` | `string[]` | No | The initial value of the combobox's selected items when rendered. Use when you don't need to control the value of the combobox's selected items. | | `disabled` | `boolean` | No | Whether the combobox is disabled | | `disableLayer` | `boolean` | No | Whether to disable registering this a dismissable layer | | `form` | `string` | No | The associate form of the combobox. | | `highlightedValue` | `string` | No | The controlled highlighted value of the combobox | | `id` | `string` | No | The unique identifier of the machine. | | `ids` | `Partial<{ root: string label: string control: string input: string content: string trigger: string clearTrigger: string item: (id: string, index?: number | undefined) => string positioner: string itemGroup: (id: string | number) => string itemGroupLabel: (id: string | number) => string }>` | No | The ids of the elements in the combobox. Useful for composition. | | `immediate` | `boolean` | No | Whether to synchronize the present change immediately or defer it to the next frame | | `inputBehavior` | `'none' | 'autohighlight' | 'autocomplete'` | No | Defines the auto-completion behavior of the combobox. - `autohighlight`: The first focused item is highlighted as the user types - `autocomplete`: Navigating the listbox with the arrow keys selects the item and the input is updated | | `inputValue` | `string` | No | The controlled value of the combobox's input | | `invalid` | `boolean` | No | Whether the combobox is invalid | | `lazyMount` | `boolean` | No | Whether to enable lazy mounting | | `loopFocus` | `boolean` | No | Whether to loop the keyboard navigation through the items | | `multiple` | `boolean` | No | Whether to allow multiple selection. **Good to know:** When `multiple` is `true`, the `selectionBehavior` is automatically set to `clear`. It is recommended to render the selected items in a separate container. | | `name` | `string` | No | The `name` attribute of the combobox's input. Useful for form submission | | `navigate` | `(details: NavigateDetails) => void` | No | Function to navigate to the selected item | | `onExitComplete` | `VoidFunction` | No | Function called when the animation ends in the closed state | | `onFocusOutside` | `(event: FocusOutsideEvent) => void` | No | Function called when the focus is moved outside the component | | `onHighlightChange` | `(details: HighlightChangeDetails) => void` | No | Function called when an item is highlighted using the pointer or keyboard navigation. | | `onInputValueChange` | `(details: InputValueChangeDetails) => void` | No | Function called when the input's value changes | | `onInteractOutside` | `(event: InteractOutsideEvent) => void` | No | Function called when an interaction happens outside the component | | `onOpenChange` | `(details: OpenChangeDetails) => void` | No | Function called when the popup is opened | | `onPointerDownOutside` | `(event: PointerDownOutsideEvent) => void` | No | Function called when the pointer is pressed down outside the component | | `onSelect` | `(details: SelectionDetails) => void` | No | Function called when an item is selected | | `onValueChange` | `(details: ValueChangeDetails) => void` | No | Function called when a new item is selected | | `open` | `boolean` | No | The controlled open state of the combobox | | `openOnChange` | `boolean | ((details: InputValueChangeDetails) => boolean)` | No | Whether to show the combobox when the input value changes | | `openOnClick` | `boolean` | No | Whether to open the combobox popup on initial click on the input | | `openOnKeyPress` | `boolean` | No | Whether to open the combobox on arrow key press | | `placeholder` | `string` | No | The placeholder text of the combobox's input | | `positioning` | `PositioningOptions` | No | The positioning options to dynamically position the menu | | `present` | `boolean` | No | Whether the node is present (controlled by the user) | | `readOnly` | `boolean` | No | Whether the combobox is readonly. This puts the combobox in a "non-editable" mode but the user can still interact with it | | `required` | `boolean` | No | Whether the combobox is required | | `scrollToIndexFn` | `(details: ScrollToIndexDetails) => void` | No | Function to scroll to a specific index | | `selectionBehavior` | `'clear' | 'replace' | 'preserve'` | No | The behavior of the combobox input when an item is selected - `replace`: The selected item string is set as the input value - `clear`: The input value is cleared - `preserve`: The input value is preserved | | `skipAnimationOnMount` | `boolean` | No | Whether to allow the initial presence animation. | | `translations` | `IntlTranslations` | No | Specifies the localized strings that identifies the accessibility elements and their states | | `unmountOnExit` | `boolean` | No | Whether to unmount on exit. | | `value` | `string[]` | No | The controlled value of the combobox's selected items | **Root Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | root | | `[data-invalid]` | Present when invalid | | `[data-readonly]` | Present when read-only | **ClearTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ClearTrigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | clear-trigger | | `[data-invalid]` | Present when invalid | **Content Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Content Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | content | | `[data-state]` | "open" | "closed" | | `[data-nested]` | listbox | | `[data-has-nested]` | listbox | | `[data-placement]` | The placement of the content | | `[data-empty]` | Present when the content is empty | **Content CSS Variables:** | Variable | Description | |----------|-------------| | `--layer-index` | The index of the dismissable in the layer stack | | `--nested-layer-count` | The number of nested comboboxs | **Control Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Control Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | control | | `[data-state]` | "open" | "closed" | | `[data-focus]` | Present when focused | | `[data-disabled]` | Present when disabled | | `[data-invalid]` | Present when invalid | **Empty Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Input Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Input Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | input | | `[data-invalid]` | Present when invalid | | `[data-autofocus]` | | | `[data-state]` | "open" | "closed" | **ItemGroupLabel Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ItemGroup Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ItemGroup Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | item-group | | `[data-empty]` | Present when the content is empty | **ItemIndicator Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ItemIndicator Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | item-indicator | | `[data-state]` | "checked" | "unchecked" | **Item Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `item` | `any` | No | The item to render | | `persistFocus` | `boolean` | No | Whether hovering outside should clear the highlighted state | **Item Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | item | | `[data-highlighted]` | Present when highlighted | | `[data-state]` | "checked" | "unchecked" | | `[data-disabled]` | Present when disabled | | `[data-value]` | The value of the item | **ItemText Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ItemText Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | item-text | | `[data-state]` | "checked" | "unchecked" | | `[data-disabled]` | Present when disabled | | `[data-highlighted]` | Present when highlighted | **Label Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Label Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | label | | `[data-readonly]` | Present when read-only | | `[data-disabled]` | Present when disabled | | `[data-invalid]` | Present when invalid | | `[data-required]` | Present when required | | `[data-focus]` | Present when focused | **List Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **List Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | list | | `[data-empty]` | Present when the content is empty | **Positioner Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Positioner CSS Variables:** | Variable | Description | |----------|-------------| | `--reference-width` | The width of the reference element | | `--reference-height` | The height of the root | | `--available-width` | The available width in viewport | | `--available-height` | The available height in viewport | | `--x` | The x position for transform | | `--y` | The y position for transform | | `--z-index` | The z-index value | | `--transform-origin` | The transform origin for animations | **RootProvider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `UseComboboxReturn` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `immediate` | `boolean` | No | Whether to synchronize the present change immediately or defer it to the next frame | | `lazyMount` | `boolean` | No | Whether to enable lazy mounting | | `onExitComplete` | `VoidFunction` | No | Function called when the animation ends in the closed state | | `present` | `boolean` | No | Whether the node is present (controlled by the user) | | `skipAnimationOnMount` | `boolean` | No | Whether to allow the initial presence animation. | | `unmountOnExit` | `boolean` | No | Whether to unmount on exit. | **Trigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `focusable` | `boolean` | No | Whether the trigger is focusable | **Trigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | combobox | | `[data-part]` | trigger | | `[data-state]` | "open" | "closed" | | `[data-invalid]` | Present when invalid | | `[data-focusable]` | | | `[data-readonly]` | Present when read-only | | `[data-disabled]` | Present when disabled | ### Context **API:** | Property | Type | Description | |----------|------|-------------| | `focused` | `boolean` | Whether the combobox is focused | | `open` | `boolean` | Whether the combobox is open | | `inputValue` | `string` | The value of the combobox input | | `highlightedValue` | `string` | The value of the highlighted item | | `highlightedItem` | `V` | The highlighted item | | `setHighlightValue` | `(value: string) => void` | The value of the combobox input | | `clearHighlightValue` | `VoidFunction` | Function to clear the highlighted value | | `syncSelectedItems` | `VoidFunction` | Function to sync the selected items with the value. Useful when `value` is updated from async sources. | | `selectedItems` | `V[]` | The selected items | | `hasSelectedItems` | `boolean` | Whether there's a selected item | | `value` | `string[]` | The selected item keys | | `valueAsString` | `string` | The string representation of the selected items | | `selectValue` | `(value: string) => void` | Function to select a value | | `setValue` | `(value: string[]) => void` | Function to set the value of the combobox | | `clearValue` | `(value?: string) => void` | Function to clear the value of the combobox | | `focus` | `VoidFunction` | Function to focus on the combobox input | | `setInputValue` | `(value: string, reason?: InputValueChangeReason) => void` | Function to set the input value of the combobox | | `getItemState` | `(props: ItemProps) => ItemState` | Returns the state of a combobox item | | `setOpen` | `(open: boolean, reason?: OpenChangeReason) => void` | Function to open or close the combobox | | `collection` | `ListCollection` | Function to toggle the combobox | | `reposition` | `(options?: Partial) => void` | Function to set the positioning options | | `multiple` | `boolean` | Whether the combobox allows multiple selections | | `disabled` | `boolean` | Whether the combobox is disabled | ## Accessibility Complies with the [Combobox WAI-ARIA design pattern](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/). ### Keyboard Support **`ArrowDown`** Description: When the combobox is closed, opens the listbox and highlights to the first option. When the combobox is open, moves focus to the next option. **`ArrowUp`** Description: When the combobox is closed, opens the listbox and highlights to the last option. When the combobox is open, moves focus to the previous option. **`Home`** Description: When the combobox is open, moves focus to the first option. **`End`** Description: When the combobox is open, moves focus to the last option. **`Escape`** Description: Closes the listbox. **`Enter`** Description: Selects the highlighted option and closes the combobox. **`Esc`** Description: Closes the combobox # Date Picker ## Anatomy ```tsx ``` ## Examples **Example: basic** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component Basic() { {'Label'} {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Default Value Use the `defaultValue` prop with `parseDate` to set the initial date value. **Example: default-value** ```ripple import { DatePicker, parseDate } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component DefaultValue() { {'Label'} {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Controlled Use the `value` and `onValueChange` props to control the date picker's value programmatically. **Example: controlled** ```ripple import { DatePicker, parseDate } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import { track } from 'ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component Controlled() { let value = track([parseDate('2022-01-01')]); { @value = e.value; }} > {'Label'} {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Root Provider An alternative way to control the date picker is to use the `RootProvider` component and the `useDatePicker` hook. This way you can access the state and methods from outside the component. **Example: root-provider** ```ripple import { DatePicker, useDatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component RootProvider() { const datePicker = useDatePicker();
{'Label'} {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid( { columns: 4 }, ); key years[0].value) { for (const year of years; key year.value) { {year.label} } } }
} ``` ### Default View Use the `defaultView` prop to set which view (day, month, or year) the calendar opens to initially. **Example: default-view** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component DefaultView() { {'Label'} {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Month and Year Select Use `MonthSelect` and `YearSelect` components to create a header with dropdown selects for quick month/year navigation, alongside the prev/next triggers. **Example: month-year-select** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component MonthYearSelect() { {'Label'} {'Clear'} component children({ context }) {
for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } }
} ``` ### Range To create a date picker that allows a range selection, you need to: - Set the `selectionMode` prop to `range`. - Render multiple inputs with the `index` prop set to `0` and `1`. **Example: range-selection** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component RangeSelection() { {'Label'} {'Clear'} {'Last 7 days'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Multiple Use the `selectionMode="multiple"` prop to allow selecting multiple dates. This example also shows how to display selected dates as removable tags. **Example: multi-selection** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { type DateValue } from '@internationalized/date'; import { Calendar, ChevronLeft, ChevronRight, X } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; const formatWithDay = (date: DateValue) => new Intl.DateTimeFormat('en', { dateStyle: 'medium', }).format(date.toDate('UTC')); export component MultiSelection() { {'Label'} component children({ context }) { for (const date of @context.value; key date.toString()) { {formatWithDay(date)} } } {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Max Selected Dates Use the `maxSelectedDates` prop with `selectionMode="multiple"` to limit the number of dates that can be selected. In this example, users can select up to 3 dates. **Example: max-selected-dates** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { ChevronLeft, ChevronRight } from 'lucide-ripple'; import styles from 'styles/date-picker.module.css'; export component MaxSelectedDates() { {'Label'}
component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } }
} ``` ### Multiple Months To create a date picker that displays multiple months side by side: - Set the `numOfMonths` prop to the number of months you want to display. - Use the `datePicker.getOffset({ months: 1 })` to get data for the next month. **Example: multiple-months** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component MultipleMonths() { {'Label'} {'Clear'}
component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { const offset = @context.getOffset({ months: 1 }); for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of offset.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } }
} ``` ### Presets Use the `DatePicker.PresetTrigger` component to add quick-select preset options like "Last 7 days" or "This month". **Example: presets** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component Presets() { {'Label'} {'Clear'}
{'Last 7 days'} {'Last 14 days'} {'Last 30 days'} {'Last 90 days'}
component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } }
} ``` ### Min and Max Use the `min` and `max` props with `parseDate` to restrict the selectable date range. Dates outside this range will be disabled. **Example: min-max** ```ripple import { DatePicker, parseDate } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component MinMax() { {'Label'} {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Unavailable Use the `isDateUnavailable` prop to mark specific dates as unavailable. This example disables weekends. **Example: unavailable** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { isWeekend } from '@internationalized/date'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component Unavailable() { isWeekend(date, locale)} > {'Label'} {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Locale Use the `locale` prop to set the language and formatting, and `startOfWeek` to set the first day of the week (0 = Sunday, 1 = Monday, etc.). **Example: locale** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component Locale() { {'Beschriftung'} {'Löschen'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Month Picker Create a month-only picker by setting `defaultView="month"` and `minView="month"`. Use custom `format` and `parse` functions to handle month/year input format. **Example: month-picker** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { CalendarDate, type DateValue } from '@internationalized/date'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; const format = (date: DateValue) => { const month = String(date.month).padStart(2, '0'); const year = String(date.year); return `${month}/${year}`; }; const parse = (value: string) => { const fullRegex = /^(\d{1,2})\/(\d{4})$/; const fullMatch = value.match(fullRegex); if (fullMatch) { const [, month, year] = fullMatch.map(Number); return new CalendarDate(year, month, 1); } return undefined; }; export component MonthPicker() { {'Label'} {'Clear'} component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Year Picker Create a year-only picker by setting `defaultView="year"` and `minView="year"`. Use custom `format` and `parse` functions to handle year-only input format. **Example: year-picker** ```ripple import { DatePicker, parseDate } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { CalendarDate, type DateValue } from '@internationalized/date'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; const format = (date: DateValue) => String(date.year); const parse = (value: string) => { const fullRegex = /^(\d{4})$/; const fullMatch = value.match(fullRegex); if (fullMatch) { const [, year] = fullMatch.map(Number); return new CalendarDate(year, 1, 1); } return undefined; }; export component YearPicker() { {'Label'} {'Clear'} component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Inline Use the `inline` prop to display the date picker directly on the page, without a popup. > When using the `inline` prop, omit the `Portal`, `Positioner`, and `Content` components to render the calendar inline > within your layout. **Example: inline** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { ChevronLeft, ChevronRight } from 'lucide-ripple'; import styles from 'styles/date-picker.module.css'; export component Inline() { {'Label'}
component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } }
} ``` ### Custom Parsing Use the `parse` prop to implement custom date parsing logic. This allows users to enter dates in flexible formats like "25/12" or "25/12/24" which are automatically converted to valid dates. **Example: format-parse** ```ripple import { DatePicker, parseDate } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { type DateValue } from '@internationalized/date'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; const format = (date: DateValue) => { const day = String(date.day).padStart(2, '0'); const month = String(date.month).padStart(2, '0'); const year = String(date.year); return `${day}/${month}/${year}`; }; const parse = (value: string) => { const fullRegex = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/; const fullMatch = value.match(fullRegex); if (fullMatch) { const [, day, month, year] = fullMatch.map(Number); return parseDate(`${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`); } return undefined; }; export component FormatParse() { {'Label'} {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Month Picker Range Create a month range picker by combining `selectionMode="range"` with `defaultView="month"` and `minView="month"`. This is useful for selecting billing periods or date ranges by month. **Example: month-picker-range** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { CalendarDate, type DateValue } from '@internationalized/date'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; const format = (date: DateValue) => { const month = String(date.month).padStart(2, '0'); const year = String(date.year); return `${month}/${year}`; }; const parse = (value: string) => { const fullRegex = /^(\d{1,2})\/(\d{4})$/; const fullMatch = value.match(fullRegex); if (fullMatch) { const [, month, year] = fullMatch.map(Number); return new CalendarDate(year, month, 1); } return undefined; }; export component MonthPickerRange() { {'Label'} {'Clear'} component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Year Range Create a year range picker by combining `selectionMode="range"` with `defaultView="year"` and `minView="year"`. This is useful for selecting multi-year periods. **Example: year-picker-range** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { CalendarDate, type DateValue } from '@internationalized/date'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; const format = (date: DateValue) => String(date.year); const parse = (value: string) => { const fullRegex = /^(\d{4})$/; const fullMatch = value.match(fullRegex); if (fullMatch) { const [, year] = fullMatch.map(Number); return new CalendarDate(year, 1, 1); } return undefined; }; export component YearPickerRange() { {'Label'} {'Clear'} component children({ context }) { {@context.getDecade().start} {' - '} {@context.getDecade().end} for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Select Today Use the `selectToday` method from the date picker context to add a "Today" button that quickly selects the current date. **Example: select-today** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component SelectToday() { {'Label'} {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Fixed Weeks Use the `fixedWeeks` prop to always display 6 weeks in the calendar, preventing layout shifts when navigating between months. **Example: fixed-weeks** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component FixedWeeks() { {'Label'} {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid({ columns: 4 }); key years[0].value) { for (const year of years; key year.value) { {year.label} } } } } ``` ### Form Use the `name` prop to integrate the date picker with native HTML forms. The selected date value will be submitted as form data. This example also uses `isDateUnavailable` to disable weekends. **Example: form** ```ripple import { DatePicker } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { isWeekend } from '@internationalized/date'; import { Calendar, ChevronLeft, ChevronRight } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component Form() {
{ e.preventDefault(); }} > isWeekend(date, locale)} > {'Label'} {'Clear'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } } component children({ context }) { for (const months of @context.getMonthsGrid( { columns: 4, format: 'short' }, ); key months[0].value) { for (const month of months; key month.value) { {month.label} } } } component children({ context }) { for (const years of @context.getYearsGrid( { columns: 4 }, ); key years[0].value) { for (const year of years; key year.value) { {year.label} } } }
} ``` ### With Time Integrate a time input with the date picker using `CalendarDateTime` from `@internationalized/date`. The time input updates the hour and minute of the selected date value. **Example: with-time** ```ripple import { DatePicker, type CalendarDateTime } from 'ark-ripple/date-picker'; import { Portal } from 'ark-ripple/portal'; import { track } from 'ripple'; import { ChevronLeft, ChevronRight, Calendar } from 'lucide-ripple'; import button from 'styles/button.module.css'; import styles from 'styles/date-picker.module.css'; export component WithTime() { let value = track([]); { @value = e.value as CalendarDateTime[]; }} > {'Label'} component children({ context }) { for (const weekDay of @context.weekDays; key weekDay.short) { {weekDay.short} } for (const week of @context.weeks; key week[0].toString()) { for (const day of week; key day.toString()) { {day.day} } } { @value = [e.value as CalendarDateTime]; }} /> } } ``` ## API Reference ### Props **Component API Reference** **Root Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `closeOnSelect` | `boolean` | No | Whether the calendar should close after the date selection is complete. This is ignored when the selection mode is `multiple`. | | `createCalendar` | `(identifier: CalendarIdentifier) => Calendar` | No | A function that creates a Calendar object for a given calendar identifier. Enables non-Gregorian calendar support (Persian, Buddhist, Islamic, etc.) without bundling all calendars by default. | | `defaultFocusedValue` | `DateValue` | No | The initial focused date when rendered. Use when you don't need to control the focused date of the date picker. | | `defaultOpen` | `boolean` | No | The initial open state of the date picker when rendered. Use when you don't need to control the open state of the date picker. | | `defaultValue` | `DateValue[]` | No | The initial selected date(s) when rendered. Use when you don't need to control the selected date(s) of the date picker. | | `defaultView` | `DateView` | No | The default view of the calendar | | `disabled` | `boolean` | No | Whether the calendar is disabled. | | `fixedWeeks` | `boolean` | No | Whether the calendar should have a fixed number of weeks. This renders the calendar with 6 weeks instead of 5 or 6. | | `focusedValue` | `DateValue` | No | The controlled focused date. | | `format` | `(date: DateValue, details: LocaleDetails) => string` | No | The format of the date to display in the input. | | `id` | `string` | No | The unique identifier of the machine. | | `ids` | `Partial<{ root: string; label: (index: number) => string; table: (id: string) => string; tableHeader: (id: string) => string; tableBody: (id: string) => string; tableRow: (id: string) => string; content: string; ... 10 more ...; positioner: string; }>` | No | The ids of the elements in the date picker. Useful for composition. | | `immediate` | `boolean` | No | Whether to synchronize the present change immediately or defer it to the next frame | | `inline` | `boolean` | No | Whether to render the date picker inline | | `invalid` | `boolean` | No | Whether the date picker is invalid | | `isDateUnavailable` | `(date: DateValue, locale: string) => boolean` | No | Returns whether a date of the calendar is available. | | `lazyMount` | `boolean` | No | Whether to enable lazy mounting | | `locale` | `string` | No | The locale (BCP 47 language tag) to use when formatting the date. | | `max` | `DateValue` | No | The maximum date that can be selected. | | `maxSelectedDates` | `number` | No | The maximum number of dates that can be selected. This is only applicable when `selectionMode` is `multiple`. | | `maxView` | `DateView` | No | The maximum view of the calendar | | `min` | `DateValue` | No | The minimum date that can be selected. | | `minView` | `DateView` | No | The minimum view of the calendar | | `name` | `string` | No | The `name` attribute of the input element. | | `numOfMonths` | `number` | No | The number of months to display. | | `onExitComplete` | `VoidFunction` | No | Function called when the animation ends in the closed state | | `onFocusChange` | `(details: FocusChangeDetails) => void` | No | Function called when the focused date changes. | | `onOpenChange` | `(details: OpenChangeDetails) => void` | No | Function called when the calendar opens or closes. | | `onValueChange` | `(details: ValueChangeDetails) => void` | No | Function called when the value changes. | | `onViewChange` | `(details: ViewChangeDetails) => void` | No | Function called when the view changes. | | `onVisibleRangeChange` | `(details: VisibleRangeChangeDetails) => void` | No | Function called when the visible range changes. | | `open` | `boolean` | No | The controlled open state of the date picker | | `openOnClick` | `boolean` | No | Whether to open the calendar when the input is clicked. | | `outsideDaySelectable` | `boolean` | No | Whether day outside the visible range can be selected. | | `parse` | `(value: string, details: LocaleDetails) => DateValue | undefined` | No | Function to parse the date from the input back to a DateValue. | | `placeholder` | `string` | No | The placeholder text to display in the input. | | `positioning` | `PositioningOptions` | No | The user provided options used to position the date picker content | | `present` | `boolean` | No | Whether the node is present (controlled by the user) | | `readOnly` | `boolean` | No | Whether the calendar is read-only. | | `required` | `boolean` | No | Whether the date picker is required | | `selectionMode` | `SelectionMode` | No | The selection mode of the calendar. - `single` - only one date can be selected - `multiple` - multiple dates can be selected - `range` - a range of dates can be selected | | `showWeekNumbers` | `boolean` | No | Whether to show the week number column in the day view. | | `skipAnimationOnMount` | `boolean` | No | Whether to allow the initial presence animation. | | `startOfWeek` | `number` | No | The first day of the week. `0` - Sunday `1` - Monday `2` - Tuesday `3` - Wednesday `4` - Thursday `5` - Friday `6` - Saturday | | `timeZone` | `string` | No | The time zone to use | | `translations` | `IntlTranslations` | No | The localized messages to use. | | `unmountOnExit` | `boolean` | No | Whether to unmount on exit. | | `value` | `DateValue[]` | No | The controlled selected date(s). | | `view` | `DateView` | No | The view of the calendar | **Root Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | root | | `[data-state]` | "open" | "closed" | | `[data-disabled]` | Present when disabled | | `[data-readonly]` | Present when read-only | | `[data-empty]` | Present when the content is empty | **ClearTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Content Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Content Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | content | | `[data-state]` | "open" | "closed" | | `[data-nested]` | popover | | `[data-has-nested]` | popover | | `[data-placement]` | The placement of the content | | `[data-inline]` | Present when the content is inline | **Content CSS Variables:** | Variable | Description | |----------|-------------| | `--layer-index` | The index of the dismissable in the layer stack | | `--nested-layer-count` | The number of nested date-pickers | **Control Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Control Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | control | | `[data-disabled]` | Present when disabled | | `[data-placeholder-shown]` | Present when placeholder is shown | **Input Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `fixOnBlur` | `boolean` | No | Whether to fix the input value on blur. | | `index` | `number` | No | The index of the input to focus. | **Input Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | input | | `[data-index]` | The index of the item | | `[data-state]` | "open" | "closed" | | `[data-placeholder-shown]` | Present when placeholder is shown | | `[data-invalid]` | Present when invalid | **Label Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Label Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | label | | `[data-state]` | "open" | "closed" | | `[data-index]` | The index of the item | | `[data-disabled]` | Present when disabled | | `[data-readonly]` | Present when read-only | **MonthSelect Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **NextTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **NextTrigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | next-trigger | | `[data-disabled]` | Present when disabled | **Positioner Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Positioner CSS Variables:** | Variable | Description | |----------|-------------| | `--reference-width` | The width of the reference element | | `--reference-height` | The height of the root | | `--available-width` | The available width in viewport | | `--available-height` | The available height in viewport | | `--x` | The x position for transform | | `--y` | The y position for transform | | `--z-index` | The z-index value | | `--transform-origin` | The transform origin for animations | **PresetTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `PresetTriggerValue` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **PrevTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **PrevTrigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | prev-trigger | | `[data-disabled]` | Present when disabled | **RangeText Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **RootProvider Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `UseDatePickerReturn` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `immediate` | `boolean` | No | Whether to synchronize the present change immediately or defer it to the next frame | | `lazyMount` | `boolean` | No | Whether to enable lazy mounting | | `onExitComplete` | `VoidFunction` | No | Function called when the animation ends in the closed state | | `present` | `boolean` | No | Whether the node is present (controlled by the user) | | `skipAnimationOnMount` | `boolean` | No | Whether to allow the initial presence animation. | | `unmountOnExit` | `boolean` | No | Whether to unmount on exit. | **TableBody Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **TableBody Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | table-body | | `[data-view]` | The view of the tablebody | | `[data-disabled]` | Present when disabled | **TableCell Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `value` | `number | DateValue` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `columns` | `number` | No | | | `disabled` | `boolean` | No | | | `visibleRange` | `VisibleRange` | No | | **TableCellTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **TableHead Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **TableHead Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | table-head | | `[data-view]` | The view of the tablehead | | `[data-disabled]` | Present when disabled | **TableHeader Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **TableHeader Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | table-header | | `[data-view]` | The view of the tableheader | | `[data-disabled]` | Present when disabled | **Table Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `columns` | `number` | No | | **Table Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | table | | `[data-columns]` | | | `[data-view]` | The view of the table | **TableRow Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **TableRow Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | table-row | | `[data-disabled]` | Present when disabled | | `[data-view]` | The view of the tablerow | **Trigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **Trigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | trigger | | `[data-placement]` | The placement of the trigger | | `[data-state]` | "open" | "closed" | | `[data-placeholder-shown]` | Present when placeholder is shown | **ValueText Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | | `placeholder` | `string` | No | Text to display when no date is selected. | | `separator` | `string` | No | The separator to use between multiple date values when using default rendering. | **ValueTextRender Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `index` | `number` | Yes | | | `remove` | `() => void` | Yes | | | `value` | `DateValue` | Yes | | | `valueAsString` | `string` | Yes | | **ViewControl Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ViewControl Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | view-control | | `[data-view]` | The view of the viewcontrol | **View Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `view` | `DateView` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **View Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | view | | `[data-view]` | The view of the view | **ViewTrigger Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **ViewTrigger Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | view-trigger | | `[data-view]` | The view of the viewtrigger | **WeekNumberCell Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `week` | `DateValue[]` | Yes | | | `weekIndex` | `number` | Yes | | | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **WeekNumberCell Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | week-number-cell | | `[data-view]` | The view of the weeknumbercell | | `[data-week-index]` | | | `[data-type]` | The type of the item | | `[data-disabled]` | Present when disabled | **WeekNumberHeaderCell Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | **WeekNumberHeaderCell Data Attributes:** | Attribute | Value | |-----------|-------| | `[data-scope]` | date-picker | | `[data-part]` | week-number-header-cell | | `[data-view]` | The view of the weeknumberheadercell | | `[data-type]` | The type of the item | | `[data-disabled]` | Present when disabled | **YearSelect Props:** | Prop | Type | Required | Description | |------|------|----------|-------------| | `asChild` | `boolean` | No | Use the provided child element as the default rendered element, combining their props and behavior. | ### Context **API:** | Property | Type | Description | |----------|------|-------------| | `focused` | `boolean` | Whether the input is focused | | `open` | `boolean` | Whether the date picker is open | | `disabled` | `boolean` | Whether the date picker is disabled | | `invalid` | `boolean` | Whether the date picker is invalid | | `readOnly` | `boolean` | Whether the date picker is read-only | | `inline` | `boolean` | Whether the date picker is rendered inline | | `numOfMonths` | `number` | The number of months to display | | `showWeekNumbers` | `boolean` | Whether the week number column is shown in the day view | | `selectionMode` | `SelectionMode` | The selection mode (single, multiple, or range) | | `maxSelectedDates` | `number` | The maximum number of dates that can be selected (only for multiple selection mode). | | `isMaxSelected` | `boolean` | Whether the maximum number of selected dates has been reached. | | `view` | `DateView` | The current view of the date picker | | `getWeekNumber` | `(week: DateValue[]) => number` | Returns the ISO 8601 week number (1-53) for the given week (array of dates). | | `getDaysInWeek` | `(week: number, from?: DateValue) => DateValue[]` | Returns an array of days in the week index counted from the provided start date, or the first visible date if not given. | | `getOffset` | `(duration: DateDuration) => DateValueOffset` | Returns the offset of the month based on the provided number of months. | | `getRangePresetValue` | `(value: DateRangePreset) => DateValue[]` | Returns the range of dates based on the provided date range preset. | | `getMonthWeeks` | `(from?: DateValue) => DateValue[][]` | Returns the weeks of the month from the provided date. Represented as an array of arrays of dates. | | `isUnavailable` | `(date: DateValue) => boolean` | Returns whether the provided date is available (or can be selected) | | `weeks` | `DateValue[][]` | The weeks of the month. Represented as an array of arrays of dates. | | `weekDays` | `WeekDay[]` | The days of the week. Represented as an array of strings. | | `visibleRange` | `VisibleRange` | The visible range of dates. | | `visibleRangeText` | `VisibleRangeText` | The human readable text for the visible range of dates. | | `value` | `DateValue[]` | The selected date. | | `valueAsDate` | `Date[]` | The selected date as a Date object. | | `valueAsString` | `string[]` | The selected date as a string. | | `focusedValue` | `DateValue` | The focused date. | | `focusedValueAsDate` | `Date` | The focused date as a Date object. | | `focusedValueAsString` | `string` | The focused date as a string. | | `selectToday` | `VoidFunction` | Sets the selected date to today. | | `setValue` | `(values: DateValue[]) => void` | Sets the selected date to the given date. | | `setTime` | `(time: Time, index?: number) => void` | Sets the time for a specific date value. Converts CalendarDate to CalendarDateTime if needed. | | `setFocusedValue` | `(value: DateValue) => void` | Sets the focused date to the given date. | | `clearValue` | `(options?: { focus?: boolean; }) => void` | Clears the selected date(s). | | `setOpen` | `(open: boolean) => void` | Function to open or close the calendar. | | `focusMonth` | `(month: number) => void` | Function to set the selected month. | | `focusYear` | `(year: number) => void` | Function to set the selected year. | | `getYears` | `() => Cell[]` | Returns the months of the year | | `getYearsGrid` | `(props?: YearGridProps) => YearGridValue` | Returns the years of the decade based on the columns. Represented as an array of arrays of years. | | `getDecade` | `() => Range` | Returns the start and end years of the decade. | | `getMonths` | `(props?: MonthFormatOptions) => Cell[]` | Returns the months of the year | | `getMonthsGrid` | `(props?: MonthGridProps) => MonthGridValue` | Returns the months of the year based on the columns. Represented as an array of arrays of months. | | `format` | `(value: DateValue, opts?: Intl.DateTimeFormatOptions) => string` | Formats the given date value based on the provided options. | | `setView` | `(view: DateView) => void` | Sets the view of the date picker. | | `goToNext` | `VoidFunction` | Goes to the next month/year/decade. | | `goToPrev` | `VoidFunction` | Goes to the previous month/year/decade. | | `getDayTableCellState` | `(props: DayTableCellProps) => DayTableCellState` | Returns the state details for a given cell. | | `getMonthTableCellState` | `(props: TableCellProps) => TableCellState` | Returns the state details for a given month cell. | | `getYearTableCellState` | `(props: TableCellProps) => TableCellState` | Returns the state details for a given year cell. | ## Accessibility ### Keyboard Support **`ArrowLeft`** Description: Moves focus to the previous day within the current week. **`ArrowRight`** Description: Moves focus to the next day within the current week. **`ArrowUp`** Description: Moves focus to the same day of the week in the previous week. **`ArrowDown`** Description: Moves focus to the same day of the week in the next week. **`Home`** Description: Moves focus to the first day of the current month. **`End`** Description: Moves focus to the last day of the current month. **`PageUp`** Description: Moves focus to the same day of the month in the previous month. **`PageDown`** Description: Moves focus to the same day of the month in the next month. **`Enter`** Description: Selects the focused date and closes the date picker. **`Esc`** Description: Closes the date picker without selecting any date. # Dialog ## Anatomy ```tsx ``` ## Examples **Example: basic** ```ripple import { Dialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import button from 'styles/button.module.css'; import styles from 'styles/dialog.module.css'; export component Basic() { {'Open Dialog'} {'✕'} {'Welcome Back'} {'Sign in to your account to continue.'} } ``` ### Controlled Manage the dialog state using the `open` and `onOpenChange` props. **Example: controlled** ```ripple import { Dialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import { track } from 'ripple'; import button from 'styles/button.module.css'; import styles from 'styles/dialog.module.css'; export component Controlled() { let open = track(false); { @open = e.open; }} > {'Open Dialog'} {'✕'} {'Session Settings'} {'Manage your session preferences and security options.'} } ``` ### Root Provider An alternative way to control the dialog is to use the `RootProvider` component and the `useDialog` hook. This way you can access the state and methods from outside the component. **Example: root-provider** ```ripple import { Dialog, useDialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import button from 'styles/button.module.css'; import styles from 'styles/dialog.module.css'; export component RootProvider() { const dialog = useDialog();
{'✕'} {'Controlled Externally'} {'This dialog is controlled via the useDialog hook.'}
} ``` ### Alert Dialog For critical confirmations or destructive actions, use `role="alertdialog"`. Alert dialogs differ from regular dialogs in important ways: - **Automatic focus**: The close/cancel button receives focus when opened, prioritizing the safest action - **Requires explicit dismissal**: Cannot be closed by clicking outside, only via button clicks or Escape key **Example: alert-dialog** ```ripple import { Dialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import button from 'styles/button.module.css'; import styles from 'styles/dialog.module.css'; export component AlertDialog() { {'Delete Account'} {'Are you absolutely sure?'} {'This action cannot be undone. This will permanently delete your account and remove your data from our servers.'}
{'Cancel'}
} ``` ### Lazy Mount Use `lazyMount` to render dialog content only when first opened. Combine with `unmountOnExit` to unmount when closed, freeing up resources. **Example: lazy-mount** ```ripple import { Dialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import button from 'styles/button.module.css'; import styles from 'styles/dialog.module.css'; export component LazyMount() { {'Open Dialog'} {'✕'} {'Lazy Loaded'} {'This dialog content is only mounted when opened and unmounts on close.'} } ``` ### Initial Focus Use `initialFocusEl` to control which element receives focus when the dialog opens. **Example: initial-focus** ```ripple import { Dialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import button from 'styles/button.module.css'; import field from 'styles/field.module.css'; import styles from 'styles/dialog.module.css'; export component InitialFocus() { let inputEl: HTMLInputElement; inputEl}> {'Open Dialog'} {'✕'} {'Edit Profile'} {'The first input will be focused when the dialog opens.'}
{ inputEl = el; }} class={field.Input} placeholder="Enter your name..." />
} ``` ### Final Focus Use `finalFocusEl` to control which element receives focus when the dialog closes. Defaults to the trigger element. **Example: final-focus** ```ripple import { Dialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import button from 'styles/button.module.css'; import styles from 'styles/dialog.module.css'; export component FinalFocus() { let finalRef: HTMLButtonElement;
finalRef}> {'Open Dialog'} {'✕'} {'Focus Redirect'} {'When this dialog closes, focus will return to the button above instead of the trigger.'}
} ``` ### Non-Modal Use `modal={false}` to allow interaction with elements outside the dialog. Disables focus trapping and scroll prevention. **Example: non-modal** ```ripple import { Dialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import button from 'styles/button.module.css'; import styles from 'styles/dialog.module.css'; export component NonModal() { {'Open Non-Modal Dialog'} {'✕'} {'Non-Modal Dialog'} {'This dialog allows interaction with elements outside. You can click buttons, select text, and interact with the page behind it.'} } ``` ### Inside Scroll Make the content area scrollable while keeping header and footer fixed using `maxHeight` and `overflow: auto`. **Example: inside-scroll** ```ripple import { Dialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import button from 'styles/button.module.css'; import styles from 'styles/dialog.module.css'; const CONTENT_SECTIONS = [ { title: '1. Acceptance of Terms', body: 'By accessing and using this service, you accept and agree to be bound by the terms and provisions of this agreement.', }, { title: '2. Use License', body: 'Permission is granted to temporarily use this service for personal, non-commercial purposes only. This is the grant of a license, not a transfer of title.', }, { title: '3. User Responsibilities', body: 'You are responsible for maintaining the confidentiality of your account and password. You agree to accept responsibility for all activities that occur under your account.', }, { title: '4. Privacy Policy', body: 'Your use of this service is also governed by our Privacy Policy. Please review our Privacy Policy, which also governs the site and informs users of our data collection practices.', }, { title: '5. Limitations', body: 'In no event shall we be liable for any damages arising out of the use or inability to use the materials on this service.', }, { title: '6. Revisions', body: 'We may revise these terms of service at any time without notice. By using this service you are agreeing to be bound by the then current version of these terms.', }, { title: '7. Governing Law', body: 'These terms and conditions are governed by and construed in accordance with applicable laws and you irrevocably submit to the exclusive jurisdiction of the courts.', }, ]; export component InsideScroll() { {'Open Dialog'} {'✕'} {'Terms of Service'} {'Please review our terms before continuing.'}
for (const item of CONTENT_SECTIONS; key item.title) {

{item.title}

{item.body}

}
{'Decline'} {'Accept'}
} ``` ### Outside Scroll Make the positioner scrollable so the dialog can extend beyond the viewport. **Example: outside-scroll** ```ripple import { Dialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import button from 'styles/button.module.css'; import styles from 'styles/dialog.module.css'; const CONTENT_SECTIONS = [ { title: '1. Information We Collect', body: 'We collect information you provide directly, such as when you create an account, make a purchase, or contact us for support. This may include your name, email address, and payment information.', }, { title: '2. How We Use Your Information', body: 'We use the information we collect to provide and improve our services, process transactions, send communications, and personalize your experience.', }, { title: '3. Information Sharing', body: 'We do not sell your personal information. We may share information with service providers who assist in our operations, or when required by law.', }, { title: '4. Data Security', body: 'We implement appropriate technical and organizational measures to protect your personal information against unauthorized access, alteration, or destruction.', }, { title: '5. Your Rights', body: 'You have the right to access, correct, or delete your personal information. You may also opt out of marketing communications at any time.', }, { title: '6. Cookies and Tracking', body: 'We use cookies and similar technologies to enhance your experience, analyze usage patterns, and deliver targeted content. You can manage cookie preferences in your browser settings.', }, { title: '7. Third-Party Services', body: 'Our service may contain links to third-party websites. We are not responsible for the privacy practices of these external sites.', }, { title: '8. Children Privacy', body: 'Our services are not directed to children under 13. We do not knowingly collect personal information from children without parental consent.', }, { title: '9. International Transfers', body: 'Your information may be transferred to and processed in countries other than your own. We ensure appropriate safeguards are in place for such transfers.', }, { title: '10. Changes to This Policy', body: 'We may update this privacy policy from time to time. We will notify you of significant changes by posting a notice on our website or sending you an email.', }, { title: '11. Data Retention', body: 'We retain your personal information for as long as necessary to fulfill the purposes outlined in this policy, unless a longer retention period is required by law.', }, { title: '12. Contact Us', body: 'If you have questions about this privacy policy or our data practices, please contact our privacy team through the support channels provided on our website.', }, ]; export component OutsideScroll() { let contentRef: HTMLDivElement | null = null; contentRef}> {'Open Dialog'} { contentRef = el; }} class={styles.Content} style={{ margin: '4rem auto', maxHeight: 'none' }} > {'✕'} {'Privacy Policy'} {'This layout allows the dialog to extend beyond the viewport while keeping the outer container scrollable.'}
for (const item of CONTENT_SECTIONS; key item.title) {

{item.title}

{item.body}

}
} ``` ### Context Access the dialog's state and methods with `Dialog.Context` or the `useDialogContext` hook. **Example: context** ```ripple import { Dialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import button from 'styles/button.module.css'; import styles from 'styles/dialog.module.css'; export component Context() { {'Open Dialog'} {'✕'} {'Status'} component children({ context }) { {'Dialog is '} {@context.open ? 'open' : 'closed'} } } ``` ### Open from Menu Open a dialog imperatively from a menu item using the `onClick` handler. **Example: open-from-menu** ```ripple import { Dialog } from 'ark-ripple/dialog'; import { Menu } from 'ark-ripple/menu'; import { Portal } from 'ark-ripple/portal'; import { ChevronDown, X } from 'lucide-ripple'; import { track } from 'ripple'; import dialog from 'styles/dialog.module.css'; import menu from 'styles/menu.module.css'; export component OpenFromMenu() { let open = track(false); {'Actions'} {'Edit'} {'Duplicate'} { @open = true; }} > {'Delete...'} { @open = e.open; }} role="alertdialog" > {'Confirm Delete'} {'Are you sure you want to delete this item? This action cannot be undone.'} } ``` ### Nested Nest dialogs within one another. The parent receives `data-has-nested` and `--nested-layer-count` CSS variable for styling effects like zoom-out: ```css [data-part='content'][data-has-nested] { transform: scale(calc(1 - var(--nested-layer-count) * 0.05)); } ``` **Example: nested** ```ripple import { Dialog, useDialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import button from 'styles/button.module.css'; import styles from 'styles/dialog.module.css'; export component Nested() { const parentDialog = useDialog(); const childDialog = useDialog();
{'✕'} {'Parent Dialog'} {'This is the parent dialog.'}
{'✕'} {'Nested Dialog'} {'This dialog is nested within the parent.'}
} ``` ### Confirmation Intercept close attempts to show confirmation prompts, preventing data loss from unsaved changes. **Example: confirmation** ```ripple import { Dialog, useDialog } from 'ark-ripple/dialog'; import { Portal } from 'ark-ripple/portal'; import { track } from 'ripple'; import button from 'styles/button.module.css'; import field from 'styles/field.module.css'; import styles from 'styles/dialog.module.css'; export component Confirmation() { let formContent = track(''); let isParentDialogOpen = track(false); const confirmDialog = useDialog(); let parentDialogProps = track( () => ({ open: isParentDialogOpen, onOpenChange: (details) => { if (!details.open && @formContent.trim()) { @confirmDialog.setOpen(true); } else { @isParentDialogOpen = details.open; } }, }), ); const parentDialog = useDialog(parentDialogProps); const handleConfirmClose = () => { @formContent = ''; const childSetter = @confirmDialog.setOpen; const parentSetter = @parentDialog.setOpen; childSetter(false); parentSetter(false); };
{'✕'} {'Edit Content'} {'Make changes to your content. You\'ll be asked to confirm before closing if there are unsaved changes.'}