# Introduction Documentation The headless components for Svelte. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page Bits UI is a headless component library for Svelte focused on developer experience, accessibility, and full creative control. Use it to build high-quality, accessible UIs without giving up styling freedom or performance. [![A webpage promoting learning to build custom components. The left side has a dark background with the text "Documentation" at the top, and a large heading "Learn how to build own components" with a "Get started" button below. The right side shows a stylized mobile app interface with a dark gray background. Inside the app is a light pink card displaying "Total distance" and "312 km". Below this are bar graphs for "Mon" to "Sun", with activity shown for Monday through Thursday and dotted outlines for Friday through Sunday. At the bottom of the card is a horizontal slider with a circle indicating a selection. A small, dark purple label with "Dev" written on it points to this slider.](/img/learn.png)](/docs/getting-started) ## Why Bits UI? ![Switch customization UI: Edit toggle style, color, and theme using Tailwind or CSS tools.](/img/bring-own-style.png) ### Bring Your Own Styles Most components ship completely unstyled, with the exception of those required for core functionality. No CSS resets, no design system assumptions. You bring the styles using standard `class` props or `data-*` attributes. [See the styling guide](/docs/styling). ![Accordion builder UI: Easily compose accessible accordion components with Bits UI.](/img/developer-exp.png) ### Building for Developer Experience Everything is designed to stay out of your way: - Full TypeScript coverage - Stable, predictable APIs - Flexible event override system - Great defaults, easily overridden - Comprehensive documentation and examples ![Production-Ready Accessibility](/img/accessibility.png) ### Production-Ready Accessibility Accessibility isn't just an afterthought - it's baked in: - WAI-ARIA compliance - Keyboard navigation by default - Focus management handled for you - Screen reader support built-in ![Composable by Design](/img/composable2.png) ### Composable by Design Components are primitives, not black boxes. They compose cleanly and play well together: - [Render Delegation](/docs/child-snippet) for total flexibility - Chainable events and callbacks - Override-friendly defaults - Minimal dependencies ## Community Bits UI was built and is maintained by [Hunter Johnston](https://x.com/huntabyte) with design support from [Pavel Stianko](https://x.com/pavel_stianko) and his team at [Bitworks Studio](https://bitworks.cz) and tooling support from [Adrian Gonz](https://github.com/AdrianGonz97). Contributions, issues, and feedback are always welcome. Found an issue? [Open one](https://github.com/huntabyte/bits-ui/issues/new). Have a feature request? [Let's discuss](https://github.com/huntabyte/bits-ui/discussions/new?category=feature-requests-ideas) ## Acknowledgments Built on the shoulders of giants: - [Melt UI](https://melt-ui.com) - inspired the internal architecture - [Radix UI](https://radix-ui.com) - API design inspiration - [React Spectrum](https://react-spectrum.adobe.com) - inspiration for the date/time components and excellence in accessibility [Next Getting Started](/docs/getting-started) ---------------------------------------------------- # Child Snippet Documentation Learn how to use the \`child\` snippet to render your own elements. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page The `child` snippet is a powerful feature that gives you complete control over the rendered elements in Bits UI components, allowing for customization while maintaining accessibility and functionality. ## When to Use It You should use the `child` snippet when you need: - Svelte-specific features like transitions, animations, actions, or scoped styles - Integration with custom components in your application - Precise control over the DOM structure - Advanced composition of components ## Basic Usage Many Bits UI components have default HTML elements that wrap their content. For example, `Accordion.Trigger` renders a ` ``` When you need to customize this element, the `child` snippet lets you take control: ```svelte {#snippet child({ props })} Toggle Item {/snippet} {#snippet child({ props })} {/snippet} ``` In this example: - The `props` parameter contains all necessary attributes and event handlers - The `{...props}` spread applies these to your custom element/component - You can add scoped styles, transitions, actions, etc. directly to the element ## How It Works When you use the `child` snippet: 1. The component passes all internal props and your custom props passed to the component via the `props` snippet parameter 2. You decide which element receives these props 3. The component's internal logic continues to work correctly ### Behind the Scenes Components that support the `child` snippet typically implement logic similar to: ```svelte {#if child} {@render child({ props: mergedProps })} {:else} {/if} ``` ## Working with Props ### Custom IDs & Attributes To use custom IDs, event handlers, or other attributes, pass them to the component first: ```svelte console.log("clicked")} > {#snippet child({ props })} {/snippet} ``` The `props` object will now include: - Your custom ID (`id="my-custom-id"`) - Your data attribute (`data-testid="accordion-trigger"`) - Your click event handler, properly merged with internal handlers - All required ARIA attributes and internal event handlers ## Combining with Svelte Features You can apply Svelte-specific features to your custom elements, such as transitions, actions, and scoped styles: ```svelte {#snippet child({ props })}
{/snippet}
``` ## Floating Components Floating content components (tooltips, popovers, dropdowns, etc.) require special handling due to their positioning requirements. ### Required Structure For floating components, you must use a two-level structure: 1. An **outer wrapper element** with `{...wrapperProps}` 2. An **inner content element** with `{...props}` ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
{/if} {/snippet}
``` ### Important Rules for Floating Content - The wrapper element with `{...wrapperProps}` must remain **unstyled** - Positioning is handled by the wrapper element; styling goes on the inner content element - The `open` parameter lets you conditionally render the content, triggering Svelte transitions - Always maintain this two-level structure to ensure proper positioning and behavior ### Components Requiring Wrapper Elements The following components require a wrapper element: - `Combobox.Content` - `DatePicker.Content` - `DateRangePicker.Content` - `DropdownMenu.Content` - `LinkPreview.Content` - `Menubar.Content` - `Popover.Content` - `Select.Content` - `Tooltip.Content` ## Examples ### Basic Custom Element ```svelte {#snippet child({ props })} {/snippet} ``` ### With Svelte Transitions ```svelte {#snippet child({ props, open })} {#if open}
Dialog content with a scale transition
{/if} {/snippet}
``` ### Floating Element Example ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
Custom tooltip content
{/if} {/snippet}
``` ## Common Pitfalls - **Missing props spread**: Always include `{...props}` on your custom element - **Styling the wrapper**: Never style the wrapper element in floating components - **Direct children**: When using child, other children outside the snippet are ignored - **Missing structure**: For floating elements, forgetting the two-level structure will break positioning ## Related Resources - [mergeProps](/docs/utilities/merge-props) Utility - [Styling Guide](/docs/styling) - [Transitions Guide](/docs/transitions) [Previous Getting Started](/docs/getting-started) [Next Ref](/docs/ref) ---------------------------------------------------- ---------------------------------------------------- # Dates and Times Documentation How to work with the various date and time components in Bits UI. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page The date and time components in Bits UI leverage the [@internationalized/date](https://react-spectrum.adobe.com/internationalized/date/index.html) package, providing a unified API for working with dates and times across different locales and time zones. This package is inspired by the [Temporal](https://tc39.es/proposal-temporal/) proposal and is designed to seamlessly integrate with the Temporal API once it becomes available. ## Installation You can install the package using your favorite package manager: ```bash npm install @internationalized/date ``` It's highly recommended to familiarize yourself with the package's documentation before diving into the components. We'll cover the basics of how we use the package in Bits UI in the sections below, but their documentation provides much more detail on the various formats and how to work with them. ## DateValue Types Bits UI uses `DateValue` objects from `@internationalized/date` to represent dates and times consistently. These immutable objects provide specific information about the type of date they represent: We use the `DateValue` objects provided by `@internationalized/date` to represent dates and times in a consistent way. These objects are immutable and provide information about the type of date they represent. The `DateValue` is a union of the following three types: | Type | Description | Example | | ------------------ | --------------------------- | ------------------------------------------------ | | `CalendarDate` | Date without time component | `2024-07-10` | | `CalendarDateTime` | Date with time | `2024-07-10T12:30:00` | | `ZonedDateTime` | Date with time and timezone | `2024-07-10T21:00:00:00-04:00[America/New_York]` | Using these strongly-typed objects allows components to adapt appropriately to the date type you provide. ### CalendarDate Represents a date without a time component. ```ts // Creating a CalendarDate import { CalendarDate, parseDate, today, getLocalTimeZone, } from "@internationalized/date"; // From year, month, day parameters const date = new CalendarDate(2024, 7, 10); // From ISO 8601 string const parsedDate = parseDate("2024-07-10"); // Current date in specific timezone const losAngelesToday = today("America/Los_Angeles"); // Current date in user's timezone const localToday = today(getLocalTimeZone()); ``` See the [CalendarDate API Documentation](https://react-spectrum.adobe.com/internationalized/date/CalendarDate.html) for additional methods. ### CalendarDateTime Represents a date with a time component, but without timezone information. ```ts // Creating a CalendarDateTime import { CalendarDateTime, parseDateTime } from "@internationalized/date"; // From date and time components const dateTime = new CalendarDateTime(2024, 7, 10, 12, 30, 0); // From ISO 8601 string const parsedDateTime = parseDateTime("2024-07-10T12:30:00"); ``` See the [CalendarDateTime API documentation](https://react-spectrum.adobe.com/internationalized/date/CalendarDateTime.html) for additional methods. ### ZonedDateTime Represents a specific date and time in a specific timezone - crucial for events that occur at an exact moment regardless of the user's location (like conferences or live broadcasts). ```ts // Creating a ZonedDateTime import { ZonedDateTime, parseZonedDateTime, parseAbsolute, parseAbsoluteToLocal, } from "@internationalized/date"; const date = new ZonedDateTime( 2022, 2, 3, // Date (year, month, day) "America/Los_Angeles", // Timezone -28800000, // UTC offset in milliseconds 9, 15, 0 // Time (hour, minute, second) ); // From ISO 8601 strings using different parsing functions const date1 = parseZonedDateTime("2024-07-12T00:45[America/New_York]"); const date2 = parseAbsolute("2024-07-12T07:45:00Z", "America/New_York"); const date3 = parseAbsoluteToLocal("2024-07-12T07:45:00Z"); ``` See the [ZonedDateTime API documentation](https://react-spectrum.adobe.com/internationalized/date/ZonedDateTime.html) for more information. ## Working with Date Ranges For components that require date ranges, Bits UI provides a `DateRange` type: ```ts type DateRange = { start: DateValue; end: DateValue; }; ``` This type is used in components such as: - [Date Range Field](/docs/components/date-range-field) - [Date Range Picker](/docs/components/date-range-picker) - [Range Calendar](/docs/components/range-calendar) ## Using the Placeholder Each date/time component in Bits UI has a *bindable* `placeholder` prop that serves multiple important functions: 1. **Starting Point**: Acts as the initial date when no value is selected 2. **Type Definition**: Determines what type of date/time to display if value is absent 3. **Calendar Navigation**: Controls the visible date range in calendar views ### Example: Using Placeholder with Calendar ```svelte ``` ## Updating DateValue Objects Since `DateValue` objects are immutable, you must create new instances when updating them: ```ts // INCORRECT - will not work let placeholder = new CalendarDate(2024, 7, 10); placeholder.month = 8; // Error! DateValue objects are immutable // CORRECT - using methods that return new instances let placeholder = new CalendarDate(2024, 7, 10); // Method 1: Using set() placeholder = placeholder.set({ month: 8 }); // Method 2: Using add() placeholder = placeholder.add({ months: 1 }); // Method 3: Using subtract() placeholder = placeholder.subtract({ days: 5 }); // Method 4: Using cycle() - cycles through valid values placeholder = placeholder.cycle("month", "forward", [1, 3, 5, 7, 9, 11]); ``` ## Formatting and Parsing ### Formatting Dates for Display For consistent, locale-aware date formatting, use the `DateFormatter` class: ```ts import { DateFormatter } from "@internationalized/date"; // Create a formatter for the current locale const formatter = new DateFormatter("en-US", { dateStyle: "full", timeStyle: "short", }); // Format a DateValue const formattedDate = formatter.format(myDateValue.toDate("America/New_York")); // Example output: "Wednesday, July 10, 2024 at 12:30 PM" ``` The `DateFormatter` wraps the native [Intl.DateTimeFormat API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) while fixing browser inconsistencies and polyfilling newer features. ### Parsing Date Strings When working with date strings from APIs or databases, use the appropriate parsing function for your needs: ```ts import { parseDate, // For CalendarDate parseDateTime, // For CalendarDateTime parseZonedDateTime, // For ZonedDateTime with timezone name parseAbsolute, // For ZonedDateTime from UTC string + timezone parseAbsoluteToLocal, // For ZonedDateTime in local timezone } from "@internationalized/date"; // Examples const date = parseDate("2024-07-10"); // CalendarDate const dateTime = parseDateTime("2024-07-10T12:30:00"); // CalendarDateTime const zonedDate = parseZonedDateTime("2024-07-12T00:45[America/New_York]"); // ZonedDateTime const absoluteDate = parseAbsolute("2024-07-12T07:45:00Z", "America/New_York"); // ZonedDateTime const localDate = parseAbsoluteToLocal("2024-07-12T07:45:00Z"); // ZonedDateTime in user's timezone ``` ## Common Gotchas and Tips - **Month Indexing**: Unlike JavaScript's Date object (which is 0-indexed), `@internationalized/date` uses 1-indexed months (January = 1). - **Immutability**: Always reassign when modifying date objects: `date = date.add({ days: 1 })`. - **Timezone Handling**: Use `ZonedDateTime` for schedule-critical events like meetings or appointments. - **Type Consistency**: Match `placeholder` types to your needs - if you need time selection, use `CalendarDateTime` not `CalendarDate`. - **Performance**: Create `DateFormatter` instances once and reuse them rather than creating new instances on each render. ## Related Resources - [Date Field](/docs/components/date-field) - [Date Range Field](/docs/components/date-range-field) - [Date Picker](/docs/components/date-picker) - [Date Range Picker](/docs/components/date-range-picker) - [Calendar](/docs/components/calendar) - [Range Calendar](/docs/components/range-calendar) - [@internationalized/date documentation](https://react-spectrum.adobe.com/internationalized/date/index.html) [Previous Styling](/docs/styling) [Next State Management](/docs/state-management) ---------------------------------------------------- # Getting Started Documentation Learn how to get started using Bits in your app. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page Welcome to Bits UI, a collection of headless component primitives for Svelte 5 that prioritizes developer experience, accessibility, and flexibility. This guide will help you quickly integrate Bits UI into your Svelte application. ## Installation Install bits using your preferred package manager. ```bash npm install bits-ui ``` ## Basic Usage After installation, you can import and use Bits UI components in your Svelte files. Here's a simple example using the [Accordion](/docs/components/accordion) component. ```svelte Item 1 Title This is the collapsible content for this section. Item 2 Title This is the collapsible content for this section. ``` ## Adding Styles Bits UI components are headless by design, meaning they ship with minimal styling. This gives you complete control over the appearance of your components. Each component that renders an HTML element exposes a `class` prop and `style` prop that you can use to apply styles to the element. ### Styling with TailwindCSS or UnoCSS If you're using a CSS framework like TailwindCSS or UnoCSS, you can pass the classes directly to the components: ```svelte Tailwind-styled Accordion This accordion is styled using Tailwind CSS classes. ``` ### Styling with Data Attributes Each Bits UI component applies specific data attributes to the underlying HTML elements. You can use these attributes to target components in your global styles: 1. Check the API Reference for each component to determine its data attributes 2. Use those attributes in your CSS selectors +layout.svelte ```svelte Click me ``` app.css ```css [data-button-root] { height: 3rem; width: 100%; background-color: #3182ce; color: white; border-radius: 0.375rem; padding: 0.5rem 1rem; font-weight: 500; } [data-button-root]:hover { background-color: #2c5282; } ``` With this approach, every `Button.Root` component will have these styles applied to it automatically. ## TypeScript Support Bits UI is built with TypeScript and provides comprehensive type definitions. When using TypeScript, you'll get full type checking and autocompletion: ```svelte ``` ## Next Steps Now that you have Bits UI installed and working, you can: - Explore the [Component Documentation](/docs/components) to learn about all available components - Learn about render delegation using the [Child Snippet](/docs/child-snippet) for maximum flexibility and customization - Learn how Bits UI handles [State Management](/docs/state-management) and how you can take more control over your components ## Resources If you have questions or need help, there are several ways to get support from the Bits UI community: - For confirmed bugs, please [open an issue](https://github.com/huntabyte/bits-ui/issues) on GitHub. - Have a question or need help? Join our [Discord community](https://discord.gg/fdXy3Sk8Gq) or [open a discussion](https://github.com/huntabyte/bits-ui/discussions/new) on GitHub to chat with other developers and the Bits UI team. - Have a feature request or idea? [Open a discussion](https://github.com/huntabyte/bits-ui/discussions/new?category=feature-requests-ideas) on GitHub to share your thoughts. All feature requests start as discussions before formally being moved to issues. [Previous Introduction](/docs/introduction) [Next Child Snippet](/docs/child-snippet) ---------------------------------------------------- # LLMs Documentation How to access LLM-friendly versions of Bits UI documentation. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page At the top of each documentation page, you'll find a convenient "Copy Markdown" button alongside a direct link to the LLM-friendly version of that page (e.g., `/llms.txt`). These tools make it easy to copy the content in Markdown format or access the machine-readable `llms.txt` file tailored for that specific page. Bits UI documentation is designed to be accessible not only to humans but also to large language models (LLMs). We've adopted the [llms.txt](https://llmstxt.org/) proposal standard, which provides a structured, machine-readable format optimized for LLMs. This enables developers, researchers, and AI systems to efficiently parse and utilize our documentation. ## What is llms.txt? The `llms.txt` standard is an emerging convention for presenting documentation in a simplified, text-based format that's easy for LLMs to process. By following this standard, Bits UI ensures compatibility with AI tools and workflows, allowing seamless integration into LLM-powered applications, research, or automation systems. ## Accessing LLM-friendly Documentation To access the LLM-friendly version of any supported Bits UI documentation page, simply append `/llms.txt` to the end of the page's URL. This will return the content in a plain-text, LLM-optimized format. ### Example - **Standard Page**: The Accordion component documentation is available at [bits-ui.com/docs/components/accordion](https://bits-ui.com/docs/components/accordion). - **LLM-friendly Version**: Append `/llms.txt` to access it at [bits-ui.com/docs/components/accordion/llms.txt](https://bits-ui.com/docs/components/accordion/llms.txt). ### Root Index To explore all supported pages in LLM-friendly format, visit the root index at [bits-ui.com/llms.txt](https://bits-ui.com/llms.txt). This page provides a comprehensive list of available documentation endpoints compatible with the `llms.txt` standard. ## Full LLM-friendly Documentation For a complete, consolidated view of the Bits UI documentation in an LLM-friendly format, navigate to [bits-ui.com/docs/llms.txt](https://bits-ui.com/docs/llms.txt). This single endpoint aggregates all documentation content into a machine-readable structure, ideal for bulk processing or ingestion into AI systems. ## Notes - Not all pages may support the `/llms.txt` suffix (those deemed irrelevant to LLMs, such as the Figma page). Check the root [bits-ui.com/llms.txt](https://bits-ui.com/llms.txt) page for an up-to-date list of compatible URLs. - The "Copy Markdown" button at the top of each page provides the same content you'd find in the `/llms.txt` of that page. By embracing the `llms.txt` standard, Bits UI empowers both human developers and AI systems to make the most of our documentation. Whether you're building with Bits UI or training an LLM, these tools are designed to enhance your experience. [Previous Migration Guide](/docs/migration-guide) [Next Accordion](/docs/components/accordion) ---------------------------------------------------- # Ref Documentation Learn about the $bindable ref prop. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page The `ref` prop provides direct access to the underlying HTML elements in Bits UI components, enabling you to manipulate the DOM when necessary. ## Basic Usage Every Bits UI component that renders an HTML element exposes a `ref` prop that you can bind to access the rendered element. This is particularly useful for programmatically manipulating the element, such as focusing inputs or measuring dimensions. ```svelte Trigger content ``` ## With Child Snippet Bits UI uses element IDs to track references to underlying elements. This approach ensures that the `ref` prop works correctly even when using the [child snippet](/docs/child-snippet). ### Simple Delegation Example The `ref` binding will automatically work with delegated child elements/components. ```svelte {#snippet child({ props })} {/snippet} ``` ### Using Custom IDs When you need to use a custom `id` on the element, pass it to the parent component first so it can be correctly registered with the `ref` binding: ```svelte {#snippet child({ props })} {/snippet} ``` ### Common Pitfalls Avoid setting the `id` directly on the child component/element, as this breaks the connection between the `ref` binding and the element: ```svelte {#snippet child({ props })} {/snippet} ``` In this example, the `Accordion.Trigger` component can't track the element because it doesn't know the custom ID. ## Why Possibly `null`? The `ref` value may be `null` until the component mounts in the DOM. This behavior is consistent with native DOM methods like `getElementById` which can return `null`. ## Creating Your Own `ref` Props To implement the same ref pattern in your custom components, Bits UI provides a [WithElementRef](/docs/type-helpers/with-element-ref) type helper. This enables you to create type-safe components that follow the same pattern. ```svelte ``` [Previous Child Snippet](/docs/child-snippet) [Next Transitions](/docs/transitions) ---------------------------------------------------- # State Management Documentation How to manage the state of Bits UI components This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page State management is a critical aspect of modern UI development. Bits UI components support multiple approaches to manage component state, giving you flexibility based on your specific needs. Each component's API reference will highlight what props are `bindable`. You can replace the `value` prop used in the examples on this page with any `bindable` prop. ## Two-Way Binding The simplest approach is using Svelte's built-in two-way binding with `bind:`: ```svelte ``` ### Why Use It? - Zero-boilerplate state updates - External controls work automatically - Great for simple use cases ## Function Binding For complete control, use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) that handles both getting and setting values: ```svelte ``` When the component wants to set the value from an internal action, it will invoke the setter, where you can determine if the setter actually updates the state or not. ### When to Use - Complex state transformation logic - Conditional updates - Debouncing or throttling state changes - Maintaining additional state alongside the primary value - Integrating with external state systems [Previous Dates](/docs/dates) [Next Figma](/docs/figma-file) ---------------------------------------------------- # Styling Documentation Learn how to style Bits UI components. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page We ship almost zero styles with Bits UI by design, giving you complete flexibility when styling your components. For each component that renders an HTML element, we expose the `class` and `style` props to apply styles directly to the component. ## Styling Approaches ### CSS Frameworks If you're using a CSS framework like [TailwindCSS](https://tailwindcss.com/) or [UnoCSS](https://unocss.dev), simply pass the classes to the component: ```svelte Click me ``` ### Data Attributes Each Bits UI component applies specific data attributes to its rendered elements. These attributes provide reliable selectors for styling across your application. app.css ```css /* Target all Accordion.Trigger components */ [data-accordion-trigger] { height: 3rem; width: 100%; background-color: #3182ce; color: #fff; } ``` Import your stylesheet in your layout component: +layout.svelte ```svelte {@render children()} ``` Now every `Accordion.Trigger` component will have the styles applied to it. ### Global Classes Alternatively, you can use global class names: app.css ```css .accordion-trigger { height: 3rem; width: 100%; background-color: #3182ce; color: #fff; } ``` Import your stylesheet in your layout component: +layout.svelte ```svelte {@render children()} ``` Use the global class with the component: ```svelte Click me ``` ### Scoped Styles To use Svelte's scoped styles, use the `child` snippet to bring the element into your component's scope. See the [Child Snippet](/docs/child-snippet) documentation for more information. MyAccordionTrigger.svelte ```svelte {#snippet child({ props })} {/snippet} ``` ### Style Prop All Bits UI components that render an element accept a style prop as either a string or an object of CSS properties. These are merged with internal styles using the [`mergeProps`](/docs/utilities/merge-props) function. ```svelte Click me Click me ``` ## Styling Component States Bits UI components may expose state information through data attributes and CSS variables, allowing you to create dynamic styles based on component state. ### State Data Attributes Components apply state-specific data attributes that you can target in your CSS: ```css /* Style the Accordion.Trigger when open */ [data-accordion-trigger][data-state="open"] { background-color: #f0f0f0; font-weight: bold; } /* Style the Accordion.Trigger when closed */ [data-accordion-trigger][data-state="closed"] { background-color: #ffffff; } /* Style disabled components */ [data-accordion-trigger][data-disabled] { opacity: 0.5; cursor: not-allowed; } ``` See each component's API reference for its specific data attributes. ### CSS Variables Bits UI components may expose CSS variables that allow you to access internal component values. For example, to ensure the `Select.Content` is the same width as the anchor (by default is the `Select.Trigger` unless using a `customAnchor`), you can use the `--bits-select-anchor-width` CSS variable: ```css [data-select-content] { width: var(--bits-select-anchor-width); min-width: var(--bits-select-anchor-width); max-width: var(--bits-select-anchor-width); } ``` See each component's API reference for specific CSS variables it provides. ### Example: Styling an Accordion Here's an example styling an accordion with different states: ```svelte Section 1 Content for section 1 Section 2 (Disabled) Content for section 2 ``` ## Advanced Styling Techniques ### Combining Data Attributes with CSS Variables You can combine data attributes with CSS variables to create dynamic styles based on component state. Here's how to animate the accordion content using the `--bits-accordion-content-height` variable and the `data-state` attribute: ```css /* Basic transition animation */ [data-accordion-content] { overflow: hidden; transition: height 300ms ease-out; height: 0; } [data-accordion-content][data-state="open"] { height: var(--bits-accordion-content-height); } [data-accordion-content][data-state="closed"] { height: 0; } ``` ### Custom Keyframe Animations For more control, use keyframe animations with the CSS variables: ```css /* Define keyframes for opening animation */ @keyframes accordionOpen { 0% { height: 0; opacity: 0; } 80% { height: var(--bits-accordion-content-height); opacity: 0.8; } 100% { height: var(--bits-accordion-content-height); opacity: 1; } } /* Define keyframes for closing animation */ @keyframes accordionClose { 0% { height: var(--bits-accordion-content-height); opacity: 1; } 20% { height: var(--bits-accordion-content-height); opacity: 0.8; } 100% { height: 0; opacity: 0; } } /* Apply animations based on state */ [data-accordion-content][data-state="open"] { animation: accordionOpen 400ms cubic-bezier(0.16, 1, 0.3, 1) forwards; } [data-accordion-content][data-state="closed"] { animation: accordionClose 300ms cubic-bezier(0.7, 0, 0.84, 0) forwards; } ``` ### Example: Animated Accordion Here's an example of an accordion with a custom transition: ```svelte Section 1 Content for section 1 Section 2 Content for section 2 ``` [Previous Transitions](/docs/transitions) [Next Dates](/docs/dates) ---------------------------------------------------- # Transitions Documentation Learn how to use transitions with Bits UI components. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page Svelte Transitions are one of the awesome features of Svelte. Unfortunately, they don't play very nicely with components, due to the fact that they rely on various directives like `in:`, `out:`, and `transition:`, which aren't supported by components. In previous version of Bits UI, we had a workaround for this by exposing a ton of `transition*` props on the components that we felt were most likely to be used with transitions. However, this was a bit of a hack and limited us to *only* Svelte Transitions, and users who wanted to use other libraries or just CSS were left out. With Bits UI for Svelte 5, we've completely removed this workaround and instead exposed props and snippets that allow you to use any animation or transitions library you want. ## The Defaults By default, Bits UI components handle the mounting and unmounting of specific components for you. They are wrapped in a component that ensures the component waits for transitions to finish before unmounting. You can use any CSS transitions or animations you want with this approach, which is what we're doing in the various example components in this documentation, using [tailwindcss-animate](https://github.com/jamiebuilds/tailwindcss-animate). ## Force Mounting On each component that we conditionally render, a `forceMount` prop is exposed. If set to `true`, the component will be forced to mount in the DOM and become visible to the user. You can use this prop in conjunction with the [delegated](/docs/child-snippet) `child` snippet to conditionally render the component and apply Svelte Transitions or another animation library. The `child` snippet exposes a prop that you can use to conditionally render the element and apply your transitions. ```svelte {#snippet child({ props, open })} {#if open}
{/if} {/snippet}
``` In the example above, we're using the `forceMount` prop to tell the component to forcefully mount the `Dialog.Content` component. We're then using the `child` snippet to delegate the rendering of the `Dialog.Content` to a `div` element which we can apply our props and transitions to. We understand this isn't the prettiest syntax, but it enables us to cover every use case. If you intend to use this approach across your application, it's recommended to create a reusable component that handles this logic, like so: MyDialogContent.svelte ```svelte {#snippet child({ props, open })} {#if open}
{@render children?.()}
{/if} {/snippet}
``` Which can then be used alongside the other `Dialog.*` components: ```svelte Open Dialog Dialog Title Dialog Description Close
Other dialog content
``` ### Floating Content Components `Content` components that rely on Floating UI require a slight modification to how the `child` snippet is used. For example, if we were to use the `Popover.Content` component, we need to add a wrapper element within the `child` snippet, and spread the `wrapperProps` snippet prop to it. ```svelte Open Popover {#snippet child({ wrapperProps, props, open })} {#if open}
{/if} {/snippet}
``` [Previous Ref](/docs/ref) [Next Styling](/docs/styling) ---------------------------------------------------- # Accordion Documentation Organizes content into collapsible sections. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte {#each items as item (item.value)} {item.title}
{item.content}
{/each}
``` ## Overview The Accordion component is a versatile UI element designed to organize content into collapsible sections, helping users focus on specific information without being overwhelmed by visual clutter. ## Quick Start ```svelte Item 1 Title This is the collapsible content for this section. Item 2 Title This is the collapsible content for this section. ``` ## Key Features - **Single or Multiple Mode**: Toggle between allowing one open section or multiple sections at once. - **Accessible by Default**: Built-in ARIA attributes and keyboard navigation support. - **Smooth Transitions**: Leverage CSS variables or Svelte transitions for animated open/close effects. - **Flexible State**: Use uncontrolled defaults or take full control with bound values. ## Structure The Accordion is a compound component made up of several parts: - `Accordion.Root`: Container that manages overall state - `Accordion.Item`: Individual collapsible section - `Accordion.Header`: Contains the visible heading - `Accordion.Trigger`: The clickable element that toggles content visibility - `Accordion.Content`: The collapsible body content ## Reusable Components To streamline usage in larger applications, create custom wrapper components for repeated patterns. Below is an example of a reusable `MyAccordionItem` and `MyAccordion`. ### Item Wrapper Combines `Item`, `Header`, `Trigger`, and `Content` into a single component: MyAccordionItem.svelte ```svelte {title} {content} ``` ### Accordion Wrapper Wraps `Root` and renders multiple `MyAccordionItem` components: MyAccordion.svelte ```svelte {#each items as item, i (item.title + i)} {/each} ``` ### Usage Example +page.svelte ```svelte ``` ##### Tip Use unique `value` props for each `Item` if you plan to control the state programatically. ## Managing Value State This section covers how to manage the `value` state of the Accordion. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` See the [State Management](/docs/state-management) documentation for more information. ## Customization ### Single vs. Multiple Set the `type` prop to `"single"` to allow only one accordion item to be open at a time. ```svelte ``` Set the `type` prop to `"multiple"` to allow multiple accordion items to be open at the same time. ```svelte ``` ### Default Open Items Set the `value` prop to pre-open items: ```svelte ``` ### Disable Items Disable specific items with the `disabled` prop: ```svelte ``` ### Hidden Until Found The `hiddenUntilFound` prop enables browser search functionality within collapsed accordion content. When enabled, collapsed content is marked with `hidden="until-found"`, allowing browsers to automatically expand accordion items when users search for text within them. ```svelte Search Demo This content can be found by browser search (Ctrl+F/CMD+F) even when the accordion is closed. The accordion will automatically open when the browser finds matching text. ``` ### Svelte Transitions The Accordion component can be enhanced with Svelte's built-in transition effects or other animation libraries. #### Using `forceMount` and `child` Snippets To apply Svelte transitions to Accordion components, use the `forceMount` prop in combination with the `child` snippet. This approach gives you full control over the mounting behavior and animation of the `Accordion.Content`. ```svelte {#snippet child({ props, open })} {#if open}
This is the accordion content that will transition in and out.
{/if} {/snippet}
``` In this example: - The `forceMount` prop ensures the components are always in the DOM. - The `child` snippet provides access to the open state and component props. - Svelte's `#if` block controls when the content is visible. - Transition directives (`transition:fade` and `transition:fly`) apply the animations. Expand Code ```svelte {#each items as item, i (item.title)} {item.title} {#snippet child({ props, open })} {#if open}
{item.content}
{/if} {/snippet}
{/each}
``` #### Best Practices For cleaner code and better maintainability, consider creating custom reusable components that encapsulate this transition logic. MyAccordionContent.svelte ```svelte {#snippet child({ props, open })} {#if open}
{@render children?.()}
{/if} {/snippet}
``` You can then use the `MyAccordionContent` component alongside the other `Accordion` primitives throughout your application: ```svelte A ``` ## Examples The following examples demonstrate different ways to use the Accordion component. ### Horizontal Cards Use the Accordion component to create a horizontal card layout with collapsible sections. Expand Code ```svelte {#each items as item (item.id)} (value = item.id)} > {item.title}
{item.title} {item.description}
{/each}
``` ### Checkout Steps Use the Accordion component to create a multi-step checkout process. Expand Code ```svelte {#snippet MyAccordionHeader({ value, title }: { value: string; title: string })} {@const isCompleted = completedSteps.has(value)}
{isCompleted ? "✓" : value}
{title}
{/snippet} {#snippet InputField({ label, placeholder, type = "text" }: { label: string; placeholder: string; type?: string; })} {@const id = useId()}
{/snippet} {@render MyAccordionHeader({ title: "Shipping Information", value: "1" })}
{@render InputField({ label: "First Name", placeholder: "John" })} {@render InputField({ label: "Last Name", placeholder: "Doe" })}
{@render InputField({ label: "Address", placeholder: "1234 Elm Street" })}
{@render InputField({ label: "City", placeholder: "Tampa" })} {@render InputField({ label: "ZIP", placeholder: "123456" })}
{ completedSteps.add("1"); activeStep = "2"; }} > Continue to Payment
{@render MyAccordionHeader({ title: "Payment Method", value: "2" })}
{@render InputField({ label: "Card Number", placeholder: "4242 4242 4242 4242" })}
{@render InputField({ label: "Exp. Month", placeholder: "MM" })} {@render InputField({ label: "Exp. Year", placeholder: "YY" })} {@render InputField({ label: "CVC", placeholder: "123" })}
{ completedSteps.add("2"); activeStep = "3"; }} > Continue to Review
{@render MyAccordionHeader({ title: "Payment Method", value: "3" })}

Order Summary

Product 1 $29.99
Product 2 $49.99
Shipping $4.99
Total $84.97
{ completedSteps.add("3"); activeStep = ""; }} > Place Order
``` ## API Reference ### Accordion.Root The root accordion component used to set and manage the state of the accordion. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `type` required | `enum` - 'single' \| 'multiple' | The type of accordion. If set to `'multiple'`, the accordion will allow multiple items to be open at the same time. If set to `single`, the accordion will only allow a single item to be open.`Default:  —— undefined` | | | `value` $bindable | `union` - string\[] \| string | The value of the currently active accordion item. If `type` is `'single'`, this should be a string. If `type` is `'multiple'`, this should be an array of strings.`Default:  —— undefined` | | | `onValueChange` | `function` - string \| string\[] | A callback function called when the active accordion item value changes. If the `type` is `'single'`, the argument will be a string. If `type` is `'multiple'`, the argument will be an array of strings.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the accordion is disabled. When disabled, the accordion cannot be interacted with.`Default: false` | | | `loop` | `boolean` | Whether or not the accordion should loop through items when reaching the end.`Default: false` | | | `orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the accordion.`Default: 'vertical'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | ----------------------------------- | --------------------------------------- | ------- | | `data-orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the component. | | | `data-disabled` | `''` | Present when the component is disabled. | | | `data-accordion-root` | `''` | Present on the root element. | | ### Accordion.Item An accordion item. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the accordion item is disabled.`Default: false` | | | `value` | `string` | The value of the accordion item. This is used to identify when the item is open or closed. If not provided, a unique ID will be generated for this value.`Default: A random unique ID` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | ----------------------------------- | --------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | Whether the accordion item is open or closed. | | | `data-disabled` | `''` | Present when the component is disabled. | | | `data-orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the component. | | | `data-accordion-item` | `''` | Present on the item element. | | ### Accordion.Header The header of the accordion item. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `level` | `union` - 1 \| 2 \| 3 \| 4 \| 5 \| 6 | The heading level of the header. This will be set as the `aria-level` attribute.`Default: 3` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----------------------------------------------- | --------------------------------------- | ------- | | `data-orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the component. | | | `data-disabled` | `''` | Present when the component is disabled. | | | `data-heading-level` | `enum` - '1' \| '2' \| '3' \| '4' \| '5' \| '6' | The heading level of the element. | | | `data-accordion-header` | `''` | Present on the header element. | | ### Accordion.Trigger The button responsible for toggling the accordion item. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----------------------------------- | --------------------------------------- | ------- | | `data-orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the component. | | | `data-disabled` | `''` | Present when the component is disabled. | | | `data-accordion-trigger` | `''` | Present on the trigger element. | | ### Accordion.Content The accordion item content, which is displayed when the item is open. | Property | Type | Description | Details | | ------------------ | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `hiddenUntilFound` | `boolean` | Whether the content should use `hidden='until-found'` when closed. This allows browsers to search within collapsed content and automatically expand the accordion item when matches are found.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { open: boolean; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----------------------------------- | --------------------------------------- | ------- | | `data-orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the component. | | | `data-disabled` | `''` | Present when the component is disabled. | | | `data-accordion-content` | `''` | Present on the content element. | | | CSS Variable | Description | Details | | --------------------------------- | -------------------------------------------- | ------- | | `--bits-accordion-content-height` | The height of the accordion content element. | | | `--bits-accordion-content-width` | The width of the accordion content element. | | [Previous LLMs](/docs/llms) [Next Alert Dialog](/docs/components/alert-dialog) ---------------------------------------------------- # Alert Dialog Documentation A modal window presenting content or seeking user input without navigating away from the current context. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte Subscribe
Confirm your transaction This action cannot be undone. This will initiate a monthly wire in the amount of $10,000 to Huntabyte. Do you wish to continue?
Cancel Continue
``` ## Key Features - **Compound Component Structure**: Build flexible, customizable alert dialogs using sub-components. - **Accessibility**: ARIA-compliant with full keyboard navigation support. - **Portal Support**: Render content outside the normal DOM hierarchy for proper stacking. - **Managed Focus**: Automatically traps focus with customization options. - **Flexible State**: Supports both controlled and uncontrolled open states. ## Structure The Alert Dialog is built from sub-components, each with a specific purpose: - **Root**: Manages state and provides context to child components. - **Trigger**: Toggles the dialog's open/closed state. - **Portal**: Renders its children in a portal, outside the normal DOM hierarchy. - **Overlay**: Displays a backdrop behind the dialog. - **Content**: Holds the dialog's main content. - **Title**: Displays the dialog's title. - **Description**: Displays a description or additional context for the dialog. - **Cancel**: Closes the dialog without action. - **Action**: Confirms the dialog's action. Here's a simple example of an Alert Dialog: ```svelte Open Dialog Confirm Action Are you sure? Cancel Confirm ``` ## Reusable Components For consistency across your app, create a reusable Alert Dialog component. Here's an example: MyAlertDialog.svelte ```svelte {buttonText} {@render title()} {@render description()} {@render children?.()} Cancel Confirm ``` You can then use the `MyAlertDialog` component in your application like so: +page.svelte ```svelte {#snippet title()} Delete your account {/snippet} {#snippet description()} This action cannot be undone. {/snippet} ``` Alternatively, you can define the snippets separately and pass them as props to the component: +page.svelte ```svelte {#snippet title()} Delete your account {/snippet} {#snippet description()} This action cannot be undone. {/snippet} ``` ##### Tip Use string props for simplicity or snippets for dynamic content. ## Managing Open State This section covers how to manage the `open` state of the Alert Dialog. ### Two-Way Binding Use `bind:open` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for total control: ```svelte ``` See the [State Management](/docs/state-management) documentation for more information. ## Focus Management ### Focus Trap Focus is trapped within the dialog by default. To disable: ```svelte ``` ##### Warning Disabling focus trap may reduce accessibility. Use with caution. ### Open Focus By default, when a dialog is opened, focus will be set to the `AlertDialog.Content`. This is needed to allow screen readers to properly read the content. Focusing the `AlertDialog.Content` also ensures that people navigating with their keyboard end up somewhere within the Dialog that they can interact with. You can override this behavior using the `onOpenAutoFocus` prop on the `AlertDialog.Content` component. It's *highly* recommended that you use this prop to focus *something* within the Dialog. You'll first need to cancel the default behavior of focusing the first focusable element by cancelling the event passed to the `onOpenAutoFocus` callback. You can then focus whatever you wish. ```svelte Open AlertDialog { e.preventDefault(); nameInput?.focus(); }} > ``` ### Close Focus By default, when a dialog is closed, focus will be set to the trigger element of the dialog. You can override this behavior using the `onCloseAutoFocus` prop on the `AlertDialog.Content` component. You'll need to cancel the default behavior of focusing the trigger element by cancelling the event passed to the `onCloseAutoFocus` callback, and then focus whatever you wish. ```svelte Open AlertDialog { e.preventDefault(); nameInput?.focus(); }} > ``` ## Advanced Behaviors The Alert Dialog component offers several advanced features to customize its behavior and enhance user experience. This section covers scroll locking, escape key handling, and interaction outside the dialog. ### Scroll Lock By default, when an Alert Dialog opens, scrolling the body is disabled. This provides a more native-like experience, focusing user attention on the dialog content. #### Customizing Scroll Behavior To allow body scrolling while the dialog is open, use the `preventScroll` prop on `AlertDialog.Content`: ```svelte ``` ##### Note Enabling body scroll may affect user focus and accessibility. Use this option judiciously. ### Escape Key Handling By default, pressing the `Escape` key closes an open Alert Dialog. Bits UI provides two methods to customize this behavior. #### Method 1: `escapeKeydownBehavior` The `escapeKeydownBehavior` prop allows you to customize the behavior taken by the component when the `Escape` key is pressed. It accepts one of the following values: - `'close'` (default): Closes the Alert Dialog immediately. - `'ignore'`: Prevents the Alert Dialog from closing. - `'defer-otherwise-close'`: If an ancestor Bits UI component also implements this prop, it will defer the closing decision to that component. Otherwise, the Alert Dialog will close immediately. - `'defer-otherwise-ignore'`: If an ancestor Bits UI component also implements this prop, it will defer the closing decision to that component. Otherwise, the Alert Dialog will ignore the key press and not close. To always prevent the Alert Dialog from closing on Escape key press, set the `escapeKeydownBehavior` prop to `'ignore'` on `Dialog.Content`: ```svelte ``` #### Method 2: `onEscapeKeydown` For more granular control, override the default behavior using the `onEscapeKeydown` prop: ```svelte { e.preventDefault(); // do something else instead }} > ``` This method allows you to implement custom logic when the `Escape` key is pressed. ### Interaction Outside By default, interacting outside the Alert Dialog content area does not close the dialog. Bits UI offers two ways to modify this behavior. #### Method 1: `interactOutsideBehavior` The `interactOutsideBehavior` prop allows you to customize the behavior taken by the component when an interaction (touch, mouse, or pointer event) occurs outside the content. It accepts one of the following values: - `'ignore'` (default): Prevents the Alert Dialog from closing. - `'close'`: Closes the Alert Dialog immediately. - `'defer-otherwise-close'`: If an ancestor Bits UI component also implements this prop, it will defer the closing decision to that component. Otherwise, the Alert Dialog will close immediately. - `'defer-otherwise-ignore'`: If an ancestor Bits UI component also implements this prop, it will defer the closing decision to that component. Otherwise, the Alert Dialog will ignore the event and not close. To make the Alert Dialog close when an interaction occurs outside the content, set the `interactOutsideBehavior` prop to `'close'` on `AlertDialog.Content`: ```svelte ``` #### Method 2: `onInteractOutside` For custom handling of outside interactions, you can override the default behavior using the `onInteractOutside` prop: ```svelte { e.preventDefault(); // do something else instead }} > ``` This approach allows you to implement specific behaviors when users interact outside the Alert Dialog content. ### Best Practices - **Scroll Lock**: Consider your use case carefully before disabling scroll lock. It may be necessary for dialogs with scrollable content or for specific UX requirements. - **Escape Keydown**: Overriding the default escape key behavior should be done thoughtfully. Users often expect the escape key to close modals. - **Outside Interactions**: Ignoring outside interactions can be useful for important dialogs or multi-step processes, but be cautious not to trap users unintentionally. - **Accessibility**: Always ensure that any customizations maintain or enhance the dialog's accessibility. - **User Expectations**: Try to balance custom behaviors with common UX patterns to avoid confusing users. By leveraging these advanced features, you can create highly customized dialog experiences while maintaining usability and accessibility standards. ## Nested Dialogs Alert Dialogs can be nested within each other (or with regular Dialogs) to create more complex layouts. The same nested dialog tracking and styling capabilities are available for Alert Dialogs. ### Styling Nested Alert Dialogs Alert Dialogs provide the same data attributes and CSS variables as regular Dialogs for tracking nesting: **Data Attributes:** - `data-nested-open`: Present on `AlertDialog.Content` and `AlertDialog.Overlay` when nested dialogs are open. - `data-nested`: Present on `AlertDialog.Content` and `AlertDialog.Overlay` when the dialog is a nested dialog, useful for hiding the overlay of nested dialogs to avoid overlapping with parent dialogs. **CSS Variables:** - `--bits-dialog-depth`: The nesting depth (0 for root, 1 for first nested, etc.). - `--bits-dialog-nested-count`: The number of currently open nested dialogs (updates reactively). ```svelte ``` ## Svelte Transitions See the [Dialog](/docs/components/dialog) component for more information on Svelte Transitions with dialog components. ## Working with Forms ### Form Submission When using the `AlertDialog` component, often you'll want to submit a form or perform an asynchronous action when the user clicks the `Action` button. This can be done by waiting for the asynchronous action to complete, then programmatically closing the dialog. ```svelte Confirm your action Are you sure you want to do this?
{ wait(1000).then(() => (open = false)); }} > No, cancel (close dialog) Yes (submit form)
``` ### Inside a Form If you're using an `AlertDialog` *within* a form, you'll need to ensure that the `Portal` is disabled or not included in the `AlertDialog` structure. This is because the `Portal` will render the dialog content *outside* of the form, which will prevent the form from being submitted correctly. ## API Reference ### AlertDialog.Root The root component used to set and manage the state of the alert dialog. | Property | Type | Description | Details | | ---------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------- | | `open` $bindable | `boolean` | The open state of the component.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### AlertDialog.Trigger The element which opens the alert dialog on press. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | --------------------------- | ------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The state of the alert dialog. | | | `data-alert-dialog-trigger` | `''` | Present on the trigger element. | | ### AlertDialog.Content The content displayed within the alert dialog modal. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `restoreScrollDelay` | `number` | The delay in milliseconds before the scrollbar is restored after closing the dialog. This is only applicable when using the `child` snippet for custom transitions and `preventScroll` and `forceMount` are `true`. You should set this to a value greater than the transition duration to prevent content from shifting during the transition.`Default: 0` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The state of the alert dialog. | | | `data-alert-dialog-content` | `''` | Present on the content element. | | | `data-nested-open` | `''` | Present when one or more nested dialogs are open within this dialog. Can be used to style parent dialogs differently when children are open. | | | `data-nested` | `''` | Present when the dialog is a nested dialog, useful for hiding the overlay of nested dialogs to avoid overlapping with the root dialog's overlay. | | | CSS Variable | Description | Details | | ---------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------- | | `--bits-dialog-depth` | The nesting depth of the dialog (0 for root dialogs, 1 for first nested, etc.). | | | `--bits-dialog-nested-count` | The number of currently open nested dialogs within this dialog. Updates reactively as nested dialogs open and close. | | ### AlertDialog.Overlay An overlay which covers the body when the alert dialog is open. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The state of the alert dialog. | | | `data-alert-dialog-overlay` | `''` | Present on the overlay element. | | | `data-nested-open` | `''` | Present when one or more nested dialogs are open within this dialog. Can be used to style parent dialogs differently when children are open. | | | `data-nested` | `''` | Present when the dialog is a nested dialog, useful for hiding the overlay of nested dialogs to avoid overlapping with the root dialog's overlay. | | | CSS Variable | Description | Details | | ---------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------- | | `--bits-dialog-depth` | The nesting depth of the dialog (0 for root dialogs, 1 for first nested, etc.). | | | `--bits-dialog-nested-count` | The number of currently open nested dialogs within this dialog. Updates reactively as nested dialogs open and close. | | ### AlertDialog.Portal A portal which renders the alert dialog into the body when it is open. | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### AlertDialog.Action The button responsible for taking an action within the alert dialog. This button does not close the dialog out of the box. See the [Form Submission](#form-submission) documentation for more information. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | ----- | ------------------------------ | ------- | | `data-alert-dialog-action` | `''` | Present on the action element. | | ### AlertDialog.Cancel A button used to close the alert dialog without taking an action. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | ----- | ------------------------------ | ------- | | `data-alert-dialog-cancel` | `''` | Present on the cancel element. | | ### AlertDialog.Title An accessible title for the alert dialog. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `level` | `union` - 1 \| 2 \| 3 \| 4 \| 5 \| 6 | The heading level of the title. This will be set as the `aria-level` attribute.`Default: 3` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----- | ----------------------------- | ------- | | `data-alert-dialog-title` | `''` | Present on the title element. | | ### AlertDialog.Description An accessible description for the alert dialog. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | ----- | ----------------------------------- | ------- | | `data-alert-dialog-description` | `''` | Present on the description element. | | [Previous Accordion](/docs/components/accordion) [Next Aspect Ratio](/docs/components/aspect-ratio) ---------------------------------------------------- # Aspect Ratio Documentation Displays content while maintaining a specified aspect ratio. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte an abstract painting ``` ## Architecture - **Root**: The root component which contains the aspect ratio logic ## Structure Here's an overview of how the Aspect Ratio component is structured in code: ```svelte ``` ## Reusable Component If you plan on using a lot of `AspectRatio` components throughout your application, you can create a reusable component that combines the `AspectRatio.Root` and whatever other elements you'd like to render within it. In the following example, we're creating a reusable `MyAspectRatio` component that takes in a `src` prop and renders an `img` element with the `src` prop. MyAspectRatio.svelte ```svelte ``` You can then use the `MyAspectRatio` component in your application like so: +page.svelte ```svelte ``` ## Custom Ratio Use the `ratio` prop to set a custom aspect ratio for the image. ```svelte ``` ## API Reference ### AspectRatio.Root The aspect ratio component. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ratio` | `number` | The desired aspect ratio.`Default: 1` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----- | ---------------------------- | ------- | | `data-aspect-ratio-root` | `''` | Present on the root element. | | [Previous Alert Dialog](/docs/components/alert-dialog) [Next Avatar](/docs/components/avatar) ---------------------------------------------------- # Avatar Documentation Represents an entity with an image and fallback placeholder. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
HB
``` ## Overview The Avatar component provides a consistent way to display user or entity images throughout your application. It handles image loading states gracefully and offers fallback options when images fail to load, ensuring your UI remains resilient. ## Features - **Smart Image Loading**: Automatically detects and handles image loading states - **Fallback System**: Displays alternatives when images are unavailable or slow to load - **Compound Structure**: Flexible primitives that can be composed and customized - **Customizable**: Choose to show the image immediately without a load check when you're certain the image will load. ## Architecture The Avatar component follows a compound component pattern with three key parts: - **Avatar.Root**: Container that manages the state of the image and its fallback - **Avatar.Image**: Displays user or entity image - **Avatar.Fallback**: Shows when the image is loading or fails to load ## Quick Start To get started with the Avatar component, you can use the `Avatar.Root`, `Avatar.Image`, and `Avatar.Fallback` primitives to create a basic avatar component: ```svelte HB ``` ## Reusable Components You can create your own reusable Avatar component to maintain consistent styling and behavior throughout your application: UserAvatar.svelte ```svelte {fallback} ``` Then use it throughout your application: +page.svelte ```svelte {#each users as user} {/each} ``` ## Customization ### Skip Loading Check When you're confident that an image will load (such as local assets), you can bypass the loading check: ```svelte HB ``` ## Examples ### Clickable with Link Preview This example demonstrates how to create a clickable avatar composed with a [Link Preview](/docs/components/link-preview): Expand Code ```svelte
HB
HB

@huntabyte

I do things on the internet.

FL, USA
Joined May 2020
``` ## API Reference ### Avatar.Root The root component used to set and manage the state of the avatar. | Property | Type | Description | Details | | ------------------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `loadingStatus` $bindable | `enum` - 'loading' \| 'loaded' \| 'error' | The loading status of the avatars source image. You can bind a variable to track the status outside of the component and use it to show a loading indicator or error message.`Default:  —— undefined` | | | `onLoadingStatusChange` | `function` - (status: LoadingStatus) => void | A callback function called when the loading status of the image changes.`Default:  —— undefined` | | | `delayMs` | `number` | How long to wait before showing the image after it has loaded. This can be useful to prevent a harsh flickering effect when the image loads quickly.`Default: 0` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------ | ----------------------------------------- | -------------------------------- | ------- | | `data-status` | `enum` - 'loading' \| 'loaded' \| 'error' | The loading status of the image. | | | `data-avatar-root` | `''` | Present on the root element. | | ### Avatar.Image The avatar image displayed once it has loaded. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLImageElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----------------------------------------- | -------------------------------- | ------- | | `data-status` | `enum` - 'loading' \| 'loaded' \| 'error' | The loading status of the image. | | | `data-avatar-image` | `''` | Present on the root element. | | ### Avatar.Fallback The fallback displayed while the avatar image is loading or if it fails to load | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | ----------------------------------------- | -------------------------------- | ------- | | `data-status` | `enum` - 'loading' \| 'loaded' \| 'error' | The loading status of the image. | | | `data-avatar-fallback` | `''` | Present on the fallback element. | | [Previous Aspect Ratio](/docs/components/aspect-ratio) [Next Button](/docs/components/button) ---------------------------------------------------- # Button Documentation A component that can switch between a button and an anchor tag based on the \`href\` prop. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte Unlimited ``` ## Structure ```svelte ``` ## API Reference ### Button.Root A component that can switch between a button and an anchor tag based on the `href`/`type` props. | Property | Type | Description | Details | | --------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------- | ------- | | `href` | `string` | An optional prop that when passed converts the button into an anchor tag.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the button is disabled. When disabled, the button cannot be interacted with.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------ | ----- | ------------------------------ | ------- | | `data-button-root` | `''` | Present on the button element. | | [Previous Avatar](/docs/components/avatar) [Next Calendar](/docs/components/calendar) ---------------------------------------------------- # Calendar Documentation Displays dates and days of the week, facilitating date-related interactions. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte {#snippet children({ months, weekdays })}
{#each months as month, i (i)} {#each weekdays as day, i (i)}
{day.slice(0, 2)}
{/each}
{#each month.weeks as weekDates, i (i)} {#each weekDates as date, i (i)} {date.day} {/each} {/each}
{/each}
{/snippet}
``` ##### Heads up! Before diving into this component, it's important to understand how dates/times work in Bits UI. Please read the [Dates](/docs/dates) documentation to learn more! ## Structure ```svelte {#snippet children({ months, weekdays })} {#each months as month} {#each weekdays as day} {day} {/each} {#each month.weeks as weekDates} {#each weekDates as date} {/each} {/each} {/each} {/snippet} ``` ## Placeholder The `placeholder` prop for the `Calendar.Root` component determines what date our calendar should start with when the user hasn't selected a date yet. It also determines the current "view" of the calendar. As the user navigates through the calendar, the `placeholder` will be updated to reflect the currently focused date in that view. By default, the `placeholder` will be set to the closed alowed (by `maxValue`, `minValue`) value to current date, and be of type `CalendarDate`. ## Managing Placeholder State This section covers how to manage the `placeholder` state of the Calendar. ### Two-Way Binding Use `bind:placeholder` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` See the [State Management](/docs/state-management) documentation for more information. ## Managing Value State This section covers how to manage the `value` state of the Calendar. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` See the [State Management](/docs/state-management) documentation for more information. ## Default Value Often, you'll want to start the `Calendar.Root` component with a default value. Likely this value will come from a database in the format of an ISO 8601 string. You can use the `parseDate` function from the `@internationalized/date` package to parse the string into a `CalendarDate` object. ```svelte ``` ## Validation ### Minimum Value You can set a minimum value for the calendar by using the `minValue` prop on `Calendar.Root`. If a user selects a date that is less than the minimum value, the calendar will be marked as invalid. ```svelte ``` ### Maximum Value You can set a maximum value for the calendar by using the `maxValue` prop on `Calendar.Root`. If a user selects a date that is greater than the maximum value, the calendar will be marked as invalid. ```svelte ``` ### Unavailable Dates You can specify specific dates that are unavailable for selection by using the `isDateUnavailable` prop. This prop accepts a function that returns a boolean value indicating whether a date is unavailable or not. ```svelte ``` ### Disabled Dates You can specify specific dates that are disabled for selection by using the `isDateDisabled` prop. ```svelte ``` ### Max Days You can set the `maxDays` prop to limit the maximum number of days that can be selected when the calendar is `'multiple'` type. ```svelte ``` Expand Code ```svelte {#snippet children({ months, weekdays })}
{#each months as month, i (i)} {#each weekdays as day, i (i)}
{day.slice(0, 2)}
{/each}
{#each month.weeks as weekDates, i (i)} {#each weekDates as date, i (i)} {date.day} {/each} {/each}
{/each}
{/snippet}
``` ## Appearance & Behavior ### Fixed Weeks You can use the `fixedWeeks` prop to ensure that the calendar renders a fixed number of weeks, regardless of the number of days in the month. This is useful to keep the calendar visually consistent when the number of days in the month changes. ```svelte ``` ### Multiple Months You can use the `numberOfMonths` prop to render multiple months at once. ```svelte ``` ### Paged Navigation By default, when the calendar has more than one month, the previous and next buttons will shift the calendar forward or backward by one month. However, you can change this behavior by setting the `pagedNavigation` prop to `true`, which will shift the calendar forward or backward by the number of months being displayed. ```svelte ``` ### Localization The calendar will automatically format the content of the calendar according to the `locale` prop, which defaults to `'en-US'`, but can be changed to any locale supported by the [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) API. ```svelte ``` ### Week Starts On The calendar will automatically format the content of the calendar according to the `locale`, which will determine what day of the week is the first day of the week. You can also override this by setting the `weekStartsOn` prop, where `0` is Sunday and `6` is Saturday to force a consistent first day of the week across all locales. ```svelte ``` ### Multiple Selection You can set the `type` prop to `'multiple'` to allow users to select multiple dates at once. ```svelte ``` ## Custom Composition ### Month Selector The `Calendar` component includes a `PrevButton` and `NextButton` component to allow users to navigate between months. This is useful, but sometimes you may want to allow the user to select a specific month from a list of months, rather than having to navigate one at a time. To achieve this, you can use the `placeholder` prop to set the month of the the calendar view programmatically. ```svelte ``` Updating the `placeholder` will update the calendar view to reflect the new month. ## Examples ### Month and Year Selects This example demonstrates how to use the `placeholder` prop to set the month and year of the calendar view programmatically. Expand Code ```svelte {#snippet children({ months, weekdays })}
{#each months as month, i (i)} {#each weekdays as day, i (i)}
{day.slice(0, 2)}
{/each}
{#each month.weeks as weekDates, i (i)} {#each weekDates as date, i (i)} {date.day} {/each} {/each}
{/each}
{/snippet}
``` ### Preset Dates This example demonstrates how to programatically set the `value` of the calendar to a specific date when a user presses a button. Expand Code ```svelte
{#snippet children({ months, weekdays })}
{#each months as month, i (i)} {#each weekdays as day, i (i)}
{day.slice(0, 2)}
{/each}
{#each month.weeks as weekDates, i (i)} {#each weekDates as date, i (i)} {date.day} {/each} {/each}
{/each}
{/snippet}
{#each presets as preset (preset.label)} Set date to {preset.label} {/each}
``` ## API Reference ### Calendar.Root The root calendar component which contains all other calendar components. | Property | Type | Description | Details | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `type` required | `enum` - 'single' \| 'multiple' | The type of the component, used to determine the type of the value, when `'multiple'` the value will be an array.`Default:  —— undefined` | | | `value` $bindable | `union` - DateValue \| DateValue\[] | The selected date(s). If `type` is `'single'`, this will be a `DateValue`. If `type` is `'multiple'`, this will be an array of `DateValue`s.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: DateValue) => void \| (value: DateValue\[]) => void | A function that is called when the selected date changes.`Default:  —— undefined` | | | `placeholder` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The placeholder date, which is used to determine what month to display when no date is selected. This updates as the user navigates the calendar, and can be used to programmatically control the calendar's view.`Default:  —— undefined` | | | `onPlaceholderChange` | `function` - (date: DateValue) => void | A function that is called when the placeholder date changes.`Default:  —— undefined` | | | `pagedNavigation` | `boolean` | Whether or not to use paged navigation for the calendar. Paged navigation causes the previous and next buttons to navigate by the number of months displayed at once, rather than by one month.`Default: false` | | | `preventDeselect` | `boolean` | Whether or not to prevent the user from deselecting a date without selecting another date first.`Default: false` | | | `weekStartsOn` | `number` | An absolute day of the week to start the calendar on, regardless of locale. `0` is Sunday, `1` is Monday, etc. If not provided, the calendar will default to the locale's first day of the week.`Default:  —— undefined` | | | `weekdayFormat` | `enum` - 'narrow' \| 'short' \| 'long' | The format to use for the weekday strings provided via the `weekdays` slot prop.`Default: ''narrow''` | | | `calendarLabel` | `string` | The accessible label for the calendar.`Default:  —— undefined` | | | `fixedWeeks` | `boolean` | Whether or not to always display 6 weeks in the calendar.`Default: false` | | | `isDateDisabled` | `function` - (date: DateValue) => boolean | A function that returns whether or not a date is disabled.`Default:  —— undefined` | | | `isDateUnavailable` | `function` - (date: DateValue) => boolean | A function that returns whether or not a date is unavailable.`Default:  —— undefined` | | | `maxValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The maximum date that can be selected.`Default:  —— undefined` | | | `minValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The minimum date that can be selected.`Default:  —— undefined` | | | `locale` | `string` | The locale to use for formatting dates.`Default: 'en'` | | | `numberOfMonths` | `number` | The number of months to display at once.`Default: 1` | | | `disabled` | `boolean` | Whether or not the calendar is disabled.`Default: false` | | | `readonly` | `boolean` | Whether or not the calendar is readonly.`Default: false` | | | `initialFocus` | `boolean` | If `true`, the calendar will focus the selected day, today, or the first day of the month in that order depending on what is visible when the calendar is mounted.`Default: false` | | | `disableDaysOutsideMonth` | `boolean` | Whether or not to disable days outside the current month.`Default: false` | | | `maxDays` | `number` | The maximum number of days that can be selected when the calendar is `'multiple'` type.`Default:  —— undefined` | | | `monthFormat` | `union` - short \| long \| narrow \| numeric \| 2-digit \| (month: number) => string | The format to use for the month strings provided via the `months` slot prop.`Default: 'long'` | | | `yearFormat` | `union` - numeric \| 2-digit \| (year: number) => string | The format to use for the year strings provided via the `years` slot prop.`Default: 'numeric'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type Month\ = { /\*\* \* A DateValue used to represent the month. Since days \* from the previous and next months may be included in the \* calendar grid, we need a source of truth for the value \* the grid is representing. \*/ value: DateValue; /\*\* \* An array of arrays representing the weeks in the calendar. \* Each sub-array represents a week, and contains the dates for each \* day in that week. This structure is useful for rendering the calendar \* grid using a table, where each row represents a week and each cell \* represents a day. \*/ weeks: T\[]\[]; /\*\* \* An array of all the dates in the current month, including dates from \* the previous and next months that are used to fill out the calendar grid. \* This array is useful for rendering the calendar grid in a customizable way, \* as it provides all the dates that should be displayed in the grid in a flat \* array. \*/ dates: T\[]; }; type ChildrenSnippetProps = { months: Month\\[]; weekdays: string\[]; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type Month\ = { /\*\* \* A DateValue used to represent the month. Since days \* from the previous and next months may be included in the \* calendar grid, we need a source of truth for the value \* the grid is representing. \*/ value: DateValue; /\*\* \* An array of arrays representing the weeks in the calendar. \* Each sub-array represents a week, and contains the dates for each \* day in that week. This structure is useful for rendering the calendar \* grid using a table, where each row represents a week and each cell \* represents a day. \*/ weeks: T\[]\[]; /\*\* \* An array of all the dates in the current month, including dates from \* the previous and next months that are used to fill out the calendar grid. \* This array is useful for rendering the calendar grid in a customizable way, \* as it provides all the dates that should be displayed in the grid in a flat \* array. \*/ dates: T\[]; }; type ChildSnippetProps = { props: Record\; months: Month\\[]; weekdays: string\[]; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the root element when the calendar is invalid. | | | `data-disabled` | `''` | Present on the root element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the root element when the calendar is readonly. | | | `data-calendar-root` | `''` | Present on the root element. | | ### Calendar.Header The header of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | ----- | ------------------------------------------------------------ | ------- | | `data-disabled` | `''` | Present on the header element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the header element when the calendar is readonly. | | | `data-calendar-header` | `''` | Present on the header element. | | ### Calendar.Heading The heading of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | ------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the heading element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the heading element when the calendar is readonly. | | | `data-calendar-heading` | `''` | Present on the heading element. | | ### Calendar.NextButton The next button of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | ----- | -------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the next button element when the calendar or this button is disabled. | | | `data-calendar-next-button` | `''` | Present on the next button element. | | ### Calendar.PrevButton The previous button of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | ----- | -------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the prev button element when the calendar or this button is disabled. | | | `data-calendar-prev-button` | `''` | Present on the prev button element. | | ### Calendar.Cell A cell in the calendar grid. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `date` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The date for the cell.`Default:  —— undefined` | | | `month` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The current month the date is being displayed in.`Default:  —— undefined` | | | `ref` $bindable | `HTMLTableCellElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | --------------------------------------------------- | ------- | | `data-disabled` | `''` | Present when the day is disabled. | | | `data-unavailable` | `''` | Present when the day is unavailable. | | | `data-today` | `''` | Present when the day is today. | | | `data-outside-month` | `''` | Present when the day is outside the current month. | | | `data-outside-visible-months` | `''` | Present when the day is outside the visible months. | | | `data-focused` | `''` | Present when the day is focused. | | | `data-selected` | `''` | Present when the day is selected. | | | `data-value` | `''` | The date in the format "YYYY-MM-DD". | | | `data-calendar-cell` | `''` | Present on the cell element. | | ### Calendar.Day A day in the calendar grid. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | --------------------------------------------------- | ------- | | `data-disabled` | `''` | Present when the day is disabled. | | | `data-unavailable` | `''` | Present when the day is unavailable. | | | `data-today` | `''` | Present when the day is today. | | | `data-outside-month` | `''` | Present when the day is outside the current month. | | | `data-outside-visible-months` | `''` | Present when the day is outside the visible months. | | | `data-focused` | `''` | Present when the day is focused. | | | `data-selected` | `''` | Present when the day is selected. | | | `data-value` | `''` | The date in the format "YYYY-MM-DD". | | | `data-calendar-day` | `''` | Present on the day element. | | ### Calendar.Grid The grid of dates in the calendar, typically representing a month. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid element when the calendar is readonly. | | | `data-calendar-grid` | `''` | Present on the grid element. | | ### Calendar.GridBody The body of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableSectionElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid element when the calendar is readonly. | | | `data-calendar-grid-body` | `''` | Present on the grid body element. | | ### Calendar.GridHead The head of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableSectionElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----- | --------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid head element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid head element when the calendar is readonly. | | | `data-calendar-grid-head` | `''` | Present on the grid head element. | | ### Calendar.GridRow A row in the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableRowElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----- | -------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid row element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid row element when the calendar is readonly. | | | `data-calendar-grid-row` | `''` | Present on the grid row element. | | ### Calendar.HeadCell A cell in the head of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableCellElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----- | --------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the head cell element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the head cell element when the calendar is readonly. | | | `data-calendar-head-cell` | `''` | Present on the head cell element. | | ### Calendar.MonthSelect A select you can use to navigate to a specific month in the calendar view. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `months` | `number[]` | The month values to render in the select.`Default: [1-12]` | | | `monthFormat` | `enum` - 'narrow' \| 'short' \| 'long' \| 'numeric' \| '2-digit' \| '(month: number) => string' | The format to use for the month strings provided via the `months` slot prop. If a function is provided, it will be called with the month number as an argument and should return a string.`Default: ''narrow''` | | | `ref` $bindable | `HTMLSelectElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { monthItems: Array<{ value: number; label: string }>; selectedMonthItem: { value: number; label: string }; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; monthItems: Array<{ value: number; label: string }>; selectedMonthItem: { value: number; label: string }; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | ----- | ------------------------------------------------------------------ | ------- | | `data-disabled` | `''` | Present on the month select element when the calendar is disabled. | | | `data-calendar-month-select` | `''` | Present on the month select element. | | ### Calendar.YearSelect A select you can use to navigate to a specific year in the calendar view. | Property | Type | Description | Details | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `years` | `number[]` | The year values to render in the select.``Default: The current year or placeholder year (whichever is higher) + 10 and minus 100 years. When a `minValue`/`maxValue` is provided to `Calendar.Root`, those will be used to constrain the range.`` | | | `yearFormat` | `enum` - 'numeric' \| '2-digit' \| '(year: number) => string' | The format to use for the year strings provided via the `years` slot prop. If a function is provided, it will be called with the year as an argument and should return a string.`Default: ''numeric''` | | | `ref` $bindable | `HTMLSelectElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { yearItems: Array<{ value: number; label: string }>; selectedYearItem: { value: number; label: string }; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; yearItems: Array<{ value: number; label: string }>; selectedYearItem: { value: number; label: string }; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | ----- | ----------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the year select element when the calendar is disabled. | | | `data-calendar-year-select` | `''` | Present on the year select element. | | [Previous Button](/docs/components/button) [Next Checkbox](/docs/components/checkbox) ---------------------------------------------------- # Checkbox Documentation Enables users to select or deselect options with support for indeterminate states. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
{#snippet children({ checked, indeterminate })}
{#if indeterminate} {:else if checked} {/if}
{/snippet}
Accept terms and conditions
``` ## Overview The Checkbox component provides a flexible and accessible way to create checkbox inputs in your Svelte applications. It supports three states: checked, unchecked, and indeterminate, allowing for complex form interactions and data representations. ## Key Features - **Tri-State Support**: Handles checked, unchecked, and indeterminate states, providing versatility in form design. - **Accessibility**: Built with WAI-ARIA guidelines in mind, ensuring keyboard navigation and screen reader support. - **Flexible State Management**: Supports both controlled and uncontrolled state, allowing for full control over the checkbox's checked state. ## Architecture The Checkbox component is composed of the following parts: - **Root**: The main component that manages the state and behavior of the checkbox. ## Structure Here's an overview of how the Checkbox component is structured in code: ```svelte {#snippet children({ checked, indeterminate })} {#if indeterminate} - {:else if checked} ✅ {:else} ❌ {/if} {/snippet} ``` ## Reusable Components It's recommended to use the `Checkbox` primitive to create your own custom checkbox component that can be used throughout your application. In the example below, we're using the `Checkbox` and [`Label`](/docs/components/label) components to create a custom checkbox component. MyCheckbox.svelte ```svelte {#snippet children({ checked, indeterminate })} {#if indeterminate} - {:else if checked} ✅ {:else} ❌ {/if} {/snippet} {labelText} ``` You can then use the `MyCheckbox` component in your application like so: +page.svelte ```svelte ``` ## Managing Checked State This section covers how to manage the `checked` state of the Checkbox. ### Two-Way Binding Use `bind:checked` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Indeterminate State This section covers how to manage the `indeterminate` state of the Checkbox. ### Two-Way Binding Use `bind:indeterminate` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Disabled State You can disable the checkbox by setting the `disabled` prop to `true`. ```svelte ``` ## HTML Forms If you set the `name` prop, a hidden checkbox input will be rendered to submit the value of the checkbox with a form. By default, the checkbox will be submitted with default checkbox value of `'on'` if the `checked` prop is `true`. ```svelte ``` ### Custom Input Value If you'd prefer to submit a different value, you can use the `value` prop to set the value of the hidden input. For example, if you wanted to submit a string value, you could do the following: ```svelte ``` ### Required If you want to make the checkbox required, you can use the `required` prop. ```svelte ``` This will apply the `required` attribute to the hidden input element, ensuring that proper form submission is enforced. ## Checkbox Groups You can use the `Checkbox.Group` component to create a checkbox group. ```svelte Notifications ``` Expand Code ```svelte Notifications
{@render MyCheckbox({ label: "Marketing", value: "marketing" })} {@render MyCheckbox({ label: "Promotions", value: "promotions" })} {@render MyCheckbox({ label: "News", value: "news" })} {@render MyCheckbox({ label: "Updates", value: "updates" })}
{#snippet MyCheckbox({ value, label }: { value: string; label: string })} {@const id = useId()}
{#snippet children({ checked, indeterminate })}
{#if indeterminate} {:else if checked} {/if}
{/snippet}
{label}
{/snippet} ``` ### Managing Value State This section covers how to manage the `value` state of a Checkbox Group. #### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte Items ``` #### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ### HTML Forms To render hidden `` elements for the various checkboxes within a group, pass a `name` to `Checkbox.Group`. All descendent checkboxes will then render hidden inputs with the same name. ```svelte ``` When a `Checkbox.Group` component is used, its descendent `Checkbox.Root` components will use certain properties from the group, such as the `name`, `required`, and `disabled`. ## API Reference ### Checkbox.Root The button component used to toggle the state of the checkbox. | Property | Type | Description | Details | | ------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `checked` $bindable | `boolean` | The checkbox button's checked state.`Default: false` | | | `onCheckedChange` | `function` - (checked: boolean) => void | A callback that is fired when the checkbox button's checked state changes.`Default:  —— undefined` | | | `indeterminate` $bindable | `boolean` | Whether the checkbox is an indeterminate state or not.`Default: false` | | | `onIndeterminateChange` | `function` - (indeterminate: boolean) => void | A callback that is fired when the indeterminate state changes.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the checkbox button is disabled. This prevents the user from interacting with it.`Default: false` | | | `required` | `boolean` | Whether or not the checkbox is required.`Default: false` | | | `name` | `string` | The name of the checkbox. If provided a hidden input will be render to use for form submission. If not provided, the hidden input will not be rendered.`Default:  —— undefined` | | | `value` | `string` | The value of the checkbox. This is what is submitted with the form when the checkbox is checked.`Default:  —— undefined` | | | `readonly` | `boolean` | Whether or not the checkbox is read only. If `true`, the checkbox will be focusable by the user, but will not be able to be checked/unchecked.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { checked: boolean; indeterminate: boolean; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; checked: boolean; indeterminate: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ---------------------------------------------------- | ------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'checked' \| 'unchecked' \| 'indeterminate' | The checkbox's state of checked, unchecked, or indeterminate. | | | `data-disabled` | `''` | Present when the checkbox is disabled. | | | `data-readonly` | `''` | Present when the checkbox is read only. | | | `data-checkbox-root` | `''` | Present on the root element. | | ### Checkbox.Group A group that synchronizes its value state with its descendant checkboxes. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `value` $bindable | `string[]` | The value of the group. This is an array of the values of the checked checkboxes within the group.`Default: []` | | | `onValueChange` | `function` - (value: string\[]) => void | A callback that is fired when the checkbox group's value state changes.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the checkbox group is disabled. If `true`, all checkboxes within the group will be disabled. To disable a specific checkbox in the group, pass the `disabled` prop to the checkbox.`Default: false` | | | `required` | `boolean` | Whether or not the checkbox group is required for form submission.`Default: false` | | | `name` | `string` | The name of the checkbox group. If provided a hidden input will be rendered to use for form submission.`Default:  —— undefined` | | | `readonly` | `boolean` | Whether or not the checkbox group is read only. If `true`, the group will be focusable by the user, but the checkboxes will not be able to be checked/unchecked.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | ----- | --------------------------------------------- | ------- | | `data-disabled` | `''` | Present when the checkbox group is disabled. | | | `data-checkbox-group` | `''` | Present on the group element. | | | `data-readonly` | `''` | Present when the checkbox group is read only. | | ### Checkbox.GroupLabel An accessible label for the checkbox group. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLLabelElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | ----- | -------------------------------------------- | ------- | | `data-disabled` | `''` | Present when the checkbox group is disabled. | | | `data-checkbox-group-label` | `''` | Present on the label element. | | [Previous Calendar](/docs/components/calendar) [Next Collapsible](/docs/components/collapsible) ---------------------------------------------------- # Collapsible Documentation Conceals or reveals content sections. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte

@huntabyte starred 3 repositories

@huntabyte/bits-ui
@huntabyte/shadcn-svelte
@svecosystem/runed
``` ## Overview The Collapsible component enables you to create expandable and collapsible content sections. It provides an efficient way to manage space and organize information in user interfaces, enabling users to show or hide content as needed. ## Key Features - **Accessibility**: ARIA attributes for screen reader compatibility and keyboard navigation. - **Transition Support**: CSS variables and data attributes for smooth transitions between states. - **Flexible State Management**: Supports controlled and uncontrolled state, take control if needed. - **Compound Component Structure**: Provides a set of sub-components that work together to create a fully-featured collapsible. - **Hidden Until Found**: Support for the `hidden="until-found"` attribute for browser search integration. ## Architecture The Collapsible component is composed of a few sub-components, each with a specific role: - **Root**: The parent container that manages the state and context for the collapsible functionality. - **Trigger**: The interactive element (e.g., button) that toggles the expanded/collapsed state of the content. - **Content**: The container for the content that will be shown or hidden based on the collapsible state. ## Structure Here's an overview of how the Collapsible component is structured in code: ```svelte ``` ## Reusable Components It's recommended to use the `Collapsible` primitives to create your own custom collapsible component that can be used throughout your application. MyCollapsible.svelte ```svelte {buttonText} {@render children?.()} ``` You can then use the `MyCollapsible` component in your application like so: +page.svelte ```svelte Here is my collapsible content. ``` ## Managing Open State This section covers how to manage the `open` state of the Collapsible. ### Two-Way Binding Use `bind:open` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Svelte Transitions The Collapsible component can be enhanced with Svelte's built-in transition effects or other animation libraries. ### Using `forceMount` and `child` Snippets To apply Svelte transitions to Collapsible components, use the `forceMount` prop in combination with the `child` snippet. This approach gives you full control over the mounting behavior and animation of the `Collapsible.Content`. ```svelte Open {#snippet child({ props, open })} {#if open}
{/if} {/snippet}
``` In this example: - The `forceMount` prop ensures the content is always in the DOM. - The `child` snippet provides access to the open state and component props. - Svelte's `#if` block controls when the content is visible. - Transition directive (`transition:fade`) apply the animations. ### Best Practices For cleaner code and better maintainability, consider creating custom reusable components that encapsulate this transition logic. MyCollapsibleContent.svelte ```svelte {#snippet child({ props, open })} {#if open}
{@render children?.()}
{/if} {/snippet}
``` You can then use the `MyCollapsibleContent` component alongside the other `Collapsible` primitives throughout your application: ```svelte Open ``` ## Hidden Until Found The `hiddenUntilFound` prop enables integration with the browser's find-in-page functionality. When enabled, the collapsible content is marked with `hidden="until-found"`, which allows browsers to automatically expand collapsed content when users search for text within it. Expand Code ```svelte
Try searching for "searchable content" on this page (Ctrl+F / Cmd+F)

FAQ: How does search work?

This collapsible contains searchable content that demonstrates the hiddenUntilFound feature. When you search for text within this collapsed section, the browser will automatically expand it to show the matching results.

``` ### Basic Usage ```svelte Show More Details

This content will be automatically revealed when users search for text within it using Ctrl+F (Cmd+F on Mac).

For example, try searching for "automatically revealed" on this page.

``` ## API Reference ### Collapsible.Root The root collapsible container which manages the state of the collapsible. | Property | Type | Description | Details | | ---------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `open` $bindable | `boolean` | The open state of the collapsible. The content will be visible when this is true, and hidden when it's false.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the collapsible is disabled. This prevents the user from interacting with it.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | --------------------------- | ----------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The collapsible's open state. | | | `data-disabled` | `''` | Present when the collapsible is disabled. | | | `data-collapsible-root` | `''` | Present on the root element. | | ### Collapsible.Trigger The button responsible for toggling the collapsible's open state. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | --------------------------- | --------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The collapsible's open state. | | | `data-disabled` | `''` | Present when the collapsible or this trigger is disabled. | | | `data-collapsible-trigger` | `''` | Present on the trigger element. | | ### Collapsible.Content The content displayed when the collapsible is open. | Property | Type | Description | Details | | ------------------ | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `hiddenUntilFound` | `boolean` | When true, the content will be marked with `hidden="until-found"` when collapsed, allowing browsers to find and automatically expand the content during page searches.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { open: boolean; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | --------------------------- | ----------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The collapsible's open state. | | | `data-disabled` | `''` | Present when the collapsible is disabled. | | | `data-collapsible-content` | `''` | Present on the content element. | | | CSS Variable | Description | Details | | ----------------------------------- | ---------------------------------------------- | ------- | | `--bits-collapsible-content-height` | The height of the collapsible content element. | | | `--bits-collapsible-content-width` | The width of the collapsible content element. | | [Previous Checkbox](/docs/components/checkbox) [Next Combobox](/docs/components/combobox) ---------------------------------------------------- # Combobox Documentation Enables users to pick from a list of options displayed in a dropdown. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte { if (!o) searchValue = ""; }} >
(searchValue = e.currentTarget.value)} class="h-input rounded-9px border-border-input bg-background placeholder:text-foreground-alt/50 focus:ring-foreground focus:ring-offset-background focus:outline-hidden inline-flex w-[296px] touch-none truncate border px-11 text-base transition-colors focus:ring-2 focus:ring-offset-2 sm:text-sm" placeholder="Search a fruit" aria-label="Search a fruit" />
{#each filteredFruits as fruit, i (i + fruit.value)} {#snippet children({ selected })} {fruit.label} {#if selected}
{/if} {/snippet}
{:else} No results found, try again. {/each}
``` ## Overview The Combobox component combines the functionality of an input field with a dropdown list of selectable options. It provides users with the ability to search, filter, and select from a predefined set of choices. ## Key Features - **Keyboard Navigation**: Full support for keyboard interactions, allowing users to navigate and select options without using a mouse. - **Customizable Rendering**: Flexible architecture for rendering options, including support for grouped items. - **Accessibility**: Built with ARIA attributes and keyboard interactions to ensure screen reader compatibility and accessibility standards. - **Portal Support**: Ability to render the dropdown content in a portal, preventing layout issues in complex UI structures. ## Architecture The Combobox component is composed of several sub-components, each with a specific role: - **Root**: The main container component that manages the state and context for the combobox. - **Input**: The input field that allows users to enter search queries. - **Trigger**: The button or element that opens the dropdown list. - **Portal**: Responsible for portalling the dropdown content to the body or a custom target. - **Group**: A container for grouped items, used to group related items. - **GroupHeading**: A heading for a group of items, providing a descriptive label for the group. - **Item**: An individual item within the list. - **Content**: The dropdown container that displays the items. It uses [Floating UI](https://floating-ui.com/) to position the content relative to the trigger. - **ContentStatic**: An alternative to the Content component, that enables you to opt-out of Floating UI and position the content yourself. - **Viewport**: The visible area of the dropdown content, used to determine the size and scroll behavior. - **ScrollUpButton**: A button that scrolls the content up when the content is larger than the viewport. - **ScrollDownButton**: A button that scrolls the content down when the content is larger than the viewport. - **Arrow**: An arrow element that points to the trigger when using the `Combobox.Content` component. ## Structure Here's an overview of how the Combobox component is structured in code: ```svelte ``` ## Reusable Components It's recommended to use the `Combobox` primitives to build your own custom combobox component that can be reused throughout your application. CustomCombobox.svelte ```svelte Open {#each filteredItems as item, i (i + item.value)} {#snippet children({ selected })} {item.label} {selected ? "✅" : ""} {/snippet} {:else} No results found {/each} ``` +page.svelte ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the Combobox. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Open State This section covers how to manage the `open` state of the Combobox. ### Two-Way Binding Use `bind:open` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Opt-out of Floating UI When you use the `Combobox.Content` component, Bits UI uses [Floating UI](https://floating-ui.com/) to position the content relative to the trigger, similar to other popover-like components. You can opt-out of this behavior by instead using the `Combobox.ContentStatic` component. ```svelte ``` When using this component, you'll need to handle the positioning of the content yourself. Keep in mind that using `Combobox.Portal` alongside `Combobox.ContentStatic` may result in some unexpected positioning behavior, feel free to not use the portal or work around it. ## Custom Anchor By default, the `Combobox.Content` is anchored to the `Combobox.Input` component, which determines where the content is positioned. If you wish to instead anchor the content to a different element, you can pass either a selector string or an `HTMLElement` to the `customAnchor` prop of the `Combobox.Content` component. ```svelte
``` ## What is the Viewport? The `Combobox.Viewport` component is used to determine the size of the content in order to determine whether or not the scroll up and down buttons should be rendered. If you wish to set a minimum/maximum height for the select content, you should apply it to the `Combobox.Viewport` component. ## Scroll Up/Down Buttons The `Combobox.ScrollUpButton` and `Combobox.ScrollDownButton` components are used to render the scroll up and down buttons when the select content is larger than the viewport. You must use the `Combobox.Viewport` component when using the scroll buttons. ### Custom Scroll Delay The initial and subsequent scroll delays can be controlled using the `delay` prop on the buttons. For example, we can use the [`cubicOut`](https://svelte.dev/docs/svelte/svelte-easing#cubicOut) easing function from Svelte to create a smooth scrolling effect that speeds up over time. Expand Code ```svelte { if (!o) searchValue = ""; }} >
(searchValue = e.currentTarget.value)} class="h-input rounded-9px border-border-input bg-background placeholder:text-foreground-alt/50 focus:ring-foreground focus:ring-offset-background focus:outline-hidden inline-flex w-[296px] truncate border px-11 text-base transition-colors focus:ring-2 focus:ring-offset-2 sm:text-sm" placeholder="Search a fruit" aria-label="Search a fruit" />
{#each filteredFruits as fruit, i (i + fruit.value)} {#snippet children({ selected })} {fruit.label} {#if selected}
{/if} {/snippet}
{:else} No results found, try again. {/each}
``` ## Native Scrolling/Overflow If you don't want to use the [scroll buttons](#scroll-updown-buttons) and prefer to use the standard scrollbar/overflow behavior, you can omit the `Combobox.Scroll[Up|Down]Button` components and the `Combobox.Viewport` component. You'll need to set a height on the `Combobox.Content` component and appropriate `overflow` styles to enable scrolling. ## Scroll Lock To prevent the user from scrolling outside of the `Combobox.Content` component when open, you can set the `preventScroll` prop to `true`. ```svelte ``` ## Highlighted Items The Combobox component follows the [WAI-ARIA descendant pattern](https://www.w3.org/TR/wai-aria-practices-1.2/#combobox) for highlighting items. This means that the `Combobox.Input` retains focus the entire time, even when navigating with the keyboard, and items are highlighted as the user navigates them. ### Styling Highlighted Items You can use the `data-highlighted` attribute on the `Combobox.Item` component to style the item differently when it is highlighted. ### onHighlight / onUnhighlight To trigger side effects when an item is highlighted or unhighlighted, you can use the `onHighlight` and `onUnhighlight` props. ```svelte console.log('I am highlighted!')} onUnhighlight={() => console.log('I am unhighlighted!')} /> ``` ## Svelte Transitions You can use the `forceMount` prop along with the `child` snippet to forcefully mount the `Combobox.Content` component to use Svelte Transitions or another animation library that requires more control. ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
{/if} {/snippet}
``` Of course, this isn't the prettiest syntax, so it's recommended to create your own reusable content component that handles this logic if you intend to use this approach. For more information on using transitions with Bits UI components, see the [Transitions](/docs/transitions) documentation. Expand Code ```svelte { if (!o) searchValue = ""; }} >
(searchValue = e.currentTarget.value)} class="h-input rounded-9px border-border-input bg-background placeholder:text-foreground-alt/50 focus:ring-foreground focus:ring-offset-background focus:outline-hidden inline-flex w-[296px] truncate border px-11 text-base transition-colors focus:ring-2 focus:ring-offset-2 sm:text-sm" placeholder="Search a fruit" aria-label="Search a fruit" />
{#snippet child({ wrapperProps, props, open })} {#if open}
{#each filteredFruits as fruit, i (i + fruit.value)} {#snippet children({ selected })} {fruit.label} {#if selected}
{/if} {/snippet}
{:else} No results found, try again. {/each}
{/if} {/snippet}
``` ## API Reference ### Combobox.Root The root combobox component which manages & scopes the state of the combobox. | Property | Type | Description | Details | | ---------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `type` required | `enum` - 'single' \| 'multiple' | The type of combobox.`Default:  —— undefined` | | | `value` $bindable | `union` - string \| string\[] | The value of the combobox. When the type is `'single'`, this should be a string. When the type is `'multiple'`, this should be an array of strings.`Default:  —— undefined` | | | `onValueChange` | `function` - (string) => void \| (string\[]) => void | A callback that is fired when the combobox value changes. When the type is `'single'`, the argument will be a string. When the type is `'multiple'`, the argument will be an array of strings.`Default:  —— undefined` | | | `open` $bindable | `boolean` | The open state of the combobox menu.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the combobox component is disabled.`Default: false` | | | `name` | `string` | The name to apply to the hidden input element for form submission. If provided, a hidden input element will be rendered to submit the value of the combobox.`Default:  —— undefined` | | | `required` | `boolean` | Whether or not the combobox menu is required.`Default: false` | | | `scrollAlignment` | `enum` - 'nearest' \| 'center' | The alignment of the highlighted item when scrolling.`Default: ''nearest''` | | | `loop` | `boolean` | Whether or not the combobox menu should loop through items.`Default: false` | | | `allowDeselect` | `boolean` | Whether or not the user can deselect the selected item by pressing it in a single select.`Default: true` | | | `items` | `Item[]` - { value: string; label: string; disabled?: boolean}\[] | Optionally provide an array of objects representing the items in the select for autofill capabilities. Only applicable to combobox's with type `single``Default:  —— undefined` | | | `inputValue` | `string` | A read-only value that controls the text displayed in the combobox input. Use this to programmatically update the input value when the selection changes outside the component, ensuring the displayed text stays in sync with the actual value.`Default:  —— undefined` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### Combobox.Trigger A button which toggles the combobox's open state. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | --------------------------- | -------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The combobox's open state. | | | `data-disabled` | `''` | Present when the combobox is disabled. | | | `data-combobox-trigger` | `''` | Present on the trigger element. | | ### Combobox.Viewport An optional element to track the scroll position of the combobox for rendering the scroll up/down buttons. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----- | -------------------------------- | ------- | | `data-combobox-viewport` | `''` | Present on the viewport element. | | ### Combobox.Content The element which contains the combobox's items. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: false` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not the combobox should loop through items when reaching the end.`Default: false` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | --------------------------- | ------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The combobox's open state. | | | `data-combobox-content` | `''` | Present on the content element. | | | CSS Variable | Description | Details | | ------------------------------------------ | -------------------------------------------- | ------- | | `--bits-combobox-content-transform-origin` | The transform origin of the content element. | | | `--bits-combobox-content-available-width` | The available width of the content element. | | | `--bits-combobox-content-available-height` | The available height of the content element. | | | `--bits-combobox-anchor-width` | The width of the anchor element. | | | `--bits-combobox-anchor-height` | The height of the anchor element. | | ### Combobox.ContentStatic The element which contains the combobox's items. (Static/No Floating UI) | Property | Type | Description | Details | | ------------------------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not the combobox should loop through items when reaching the end.`Default: false` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { open: boolean; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | --------------------------- | ------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The combobox's open state. | | | `data-combobox-content` | `''` | Present on the content element. | | ### Combobox.Portal When used, will render the combobox content into the body or custom `to` element when open | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### Combobox.Item A combobox item, which must be a child of the `Combobox.Content` component. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` required | `string` | The value of the item.`Default:  —— undefined` | | | `label` | `string` | The label of the item, which is what the list will be filtered by.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the combobox item is disabled. This will prevent interaction/selection.`Default: false` | | | `onHighlight` | `function` - () => void | A callback that is fired when the item is highlighted.`Default:  —— undefined` | | | `onUnhighlight` | `function` - () => void | A callback that is fired when the item is unhighlighted.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | -------- | --------------------------------------------------------------------------------------------------- | ------- | | `data-value` | `string` | The value of the combobox item. | | | `data-label` | `string` | The label of the combobox item. | | | `data-disabled` | `''` | Present when the item is disabled. | | | `data-highlighted` | `''` | Present when the item is highlighted, which is either via keyboard navigation of the menu or hover. | | | `data-selected` | `''` | Present when the item is selected. | | | `data-combobox-item` | `''` | Present on the item element. | | ### Combobox.Input A representation of the combobox input element, which is typically displayed in the content. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `defaultValue` | `string` | The default value of the input. This is not a reactive prop and is only used to populate the input when the combobox is first mounted if there is already a value set.`Default:  —— undefined` | | | `clearOnDeselect` | `boolean` | Whether to clear the input when the last item is deselected.`Default: false` | | | `ref` $bindable | `HTMLInputElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | --------------------------- | -------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The combobox's open state. | | | `data-disabled` | `''` | Present when the combobox is disabled. | | | `data-combobox-input` | `''` | Present on the input element. | | ### Combobox.Group A group of related combobox items. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | ----- | ----------------------------- | ------- | | `data-combobox-group` | `''` | Present on the group element. | | ### Combobox.GroupHeading A heading for the parent combobox group. This is used to describe a group of related combobox items. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | ------------------------------------- | ------- | | `data-combobox-group-heading` | `''` | Present on the group heading element. | | ### Combobox.ScrollUpButton An optional scroll up button element to improve the scroll experience within the combobox. Should be used in conjunction with the `Combobox.Viewport` component. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `delay` | `function` - (tick: number) => number | Controls the initial delay (tick 0) and delay between auto-scrolls in milliseconds.`Default: () => 50` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------------- | ----- | ---------------------------------------- | ------- | | `data-combobox-scroll-up-button` | `''` | Present on the scroll up button element. | | ### Combobox.ScrollDownButton An optional scroll down button element to improve the scroll experience within the combobox. Should be used in conjunction with the `Combobox.Viewport` component. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `delay` | `function` - (tick: number) => number | Controls the initial delay (tick 0) and delay between auto-scrolls in milliseconds.`Default: () => 50` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------------- | ----- | ------------------------------------------ | ------- | | `data-combobox-scroll-down-button` | `''` | Present on the scroll down button element. | | ### Combobox.Arrow An optional arrow element which points to the content when open. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `width` | `number` | The width of the arrow in pixels.`Default: 8` | | | `height` | `number` | The height of the arrow in pixels.`Default: 8` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------- | ----- | ----------------------------- | ------- | | `data-arrow` | `''` | Present on the arrow element. | | [Previous Collapsible](/docs/components/collapsible) [Next Command](/docs/components/command) ---------------------------------------------------- # Command Documentation A command menu component that enables users to search, filter, and select items. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte No results found. Suggestions Introduction Delegation Styling Components Calendar Radio Group Combobox ``` ## Overview The Command component, also known as a command menu, is designed to provide users with a quick and efficient way to search, filter, and select items within an application. It combines the functionality of a search input with a dynamic, filterable list of commands or options, making it ideal for applications that require fast navigation or action execution. ## Key Features - **Dynamic Filtering**: As users type in the input field, the list of commands or items is instantly filtered and sorted based on an (overridable) scoring algorithm. - **Keyboard Navigation**: Full support for keyboard interactions, allowing users to quickly navigate and select items without using a mouse. - **Grouped Commands**: Ability to organize commands into logical groups, enhancing readability and organization. - **Empty and Loading States**: Built-in components to handle scenarios where no results are found or when results are being loaded. - **Accessibility**: Designed with ARIA attributes and keyboard interactions to ensure screen reader compatibility and accessibility standards. ## Architecture The Command component is composed of several sub-components, each with a specific role: - **Root**: The main container that manages the overall state and context of the command menu. - **Input**: The text input field where users can type to search or filter commands. - **List**: The container for the list of commands or items. - **Viewport**: The visible area of the command list, which applies CSS variables to handle dynamic resizing/animations based on the height of the list. - **Empty**: A component to display when no results are found. - **Loading**: A component to display while results are being fetched or processed. - **Group**: A container for a group of items within the command menu. - **GroupHeading**: A header element to provide an accessible label for a group of items. - **GroupItems**: A container for the items within a group. - **Item**: Individual selectable command or item. - **LinkItem**: A variant of `Command.Item` specifically for link-based actions. - **Separator**: A visual separator to divide different sections of the command list. ## Structure Here's an overview of how the Command component is structured in code: ```svelte ``` ## Managing Value State Bits UI offers several approaches to manage and synchronize the Command's value state, catering to different levels of control and integration needs. ### 1. Two-Way Binding For seamless state synchronization, use Svelte's `bind:value` directive. This method automatically keeps your local state in sync with the component's internal state. ```svelte ``` #### Key Benefits - Simplifies state management - Automatically updates `myValue` when the internal state changes (e.g., via clicking on an item) - Allows external control (e.g., selecting an item via a separate button) ### 2. Change Handler To perform additional logic on state changes, use the `onValueChange` prop. This approach is useful when you need to execute side effects when the value changes. ```svelte { // do something with the new value console.log(value); }} > ``` #### Use Cases - Implementing custom behaviors on value change - Integrating with external state management solutions - Triggering side effects (e.g., logging, data fetching) ### 3. Fully Controlled For complete control over the component's state, use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) to manage the value state externally. You pass a getter function and a setter function to the `bind:value` directive, giving you full control over how the value is updated/retrieved. ```svelte myValue, (newValue) => (myValue = newValue)}> ``` #### When to Use - Implementing complex value change logic - Coordinating multiple UI elements - Debugging state-related issues ##### Note While powerful, fully controlled state should be used judiciously as it increases complexity and can cause unexpected behaviors if not handled carefully. For more in-depth information on controlled components and advanced state management techniques, refer to our [State Management](/docs/state-management) documentation. ## In a Modal You can combine the `Command` component with the `Dialog` component to display the command menu within a modal. Expand Code ```svelte Open Command Menu ⌘J Command Menu This is the command menu. Use the arrow keys to navigate and press ⌘K to open the search bar. No results found. Suggestions Introduction Delegation Styling Components Calendar Radio Group Combobox ``` ## Grid You can add the `columns` prop to use the command as a grid. Expand Code ```svelte
{#if views.length > 1} {/if} { if (e.key === "Backspace" && search.length === 0) { e.preventDefault(); popView(); } }} placeholder={currentView.placeholder} />
{#if currentView.columns !== undefined} {currentView.empty} {#each currentView.groups as group (group)} {group.name} {#each group.items as groupItem (groupItem)} {#if groupItem.icon} {:else} {groupItem.content} {/if} {/each} {/each} {:else} {currentView.empty} {#each currentView.groups as group (group)} {group.name} {#each group.items as groupItem (groupItem)} {#if groupItem.icon} {/if} {groupItem.content} {/each} {/each} {/if}
``` ## Filtering ### Custom Filter By default, the `Command` component uses a scoring algorithm to determine how the items should be sorted/filtered. You can provide a custom filter function to override this behavior. The function should return a number between `0` and `1`, with `1` being a perfect match, and `0` being no match, resulting in the item being hidden entirely. The following example shows how you might implement a strict substring match filter: ```svelte ``` ### Extend Default Filter By default, the `Command` component uses the `computeCommandScore` function to determine the score of each item and filters/sorts them accordingly. This function is exported for you to use and extend as needed. ```svelte ``` ### Disable Filtering You can disable filtering by setting the `shouldFilter` prop to `false`. ```svelte ``` This is useful when you have a lot of custom logic, need to fetch items asynchronously, or just want to handle filtering yourself. You'll be responsible for iterating over the items and determining which ones should be shown. ## Item Selection You can use the `onSelect` prop to handle the selection of items. ```svelte console.log("selected something!")} /> ``` ## Links If you want one of the items to get all the benefits of a link (prefetching, etc.), you should use the `Command.LinkItem` component instead of the `Command.Item` component. The only difference is that the `Command.LinkItem` component will render an `a` element instead of a `div` element. ```svelte ``` ## Imperative API For more advanced use cases, such as custom keybindings, the `Command.Root` component exposes several methods for programmatic control. Access these by binding to the component: ```svelte ``` ### Methods #### `getValidItems()` Returns an array of valid (non-disabled, visible) command items. Useful for checking bounds before operations. ```ts const items = command.getValidItems(); console.log(items.length); // number of selectable items ``` #### `updateSelectedToIndex(index: number)` Sets selection to item at specified index. No-op if index is invalid. ```ts // select third item (if it exists) command.updateSelectedToIndex(2); // with bounds check const items = command.getValidItems(); if (index < items.length) { command.updateSelectedToIndex(index); } ``` #### `updateSelectedByGroup(change: 1 | -1)` Moves selection to first item in next/previous group. Falls back to next/previous item if no group found. ```ts command.updateSelectedByGroup(1); // move to next group command.updateSelectedByGroup(-1); // move to previous group ``` #### `updateSelectedByItem(change: 1 | -1)` Moves selection up/down relative to current item. Wraps around if `loop` option enabled. ```ts command.updateSelectedByItem(1); // next item command.updateSelectedByItem(-1); // previous item ``` ### Usage Example ```svelte { if (e.key === "o") { jumpToLastItem(); } }} /> ``` ## Common Mistakes ### Duplicate `value`s The value of each `Command.Item` ***must*** be unique. If you have two items with the same value, the component will not be able to determine which one to select, causing unexpected behavior when navigating with the keyboard or hovering with the mouse. If the text content of two items are the same for one reason or another, you should use the `value` prop to set a unique value for each item. When a `value` is set, the text content is used for display purposes only. The `value` prop is used for filtering and selection. A common pattern is to postfix the `value` with something unique, like an ID or a number so that filtering will still match the value. ```svelte My Item My Item ``` ## API Reference ### Command.Root The main container that manages the overall state and context of the component. | Property | Type | Description | Details | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string` | The value of the command.`Default:` | | | `onValueChange` | `function` - (value: string) => void | A callback that is fired when the command value changes.`Default:  —— undefined` | | | `label` | `string` | An accessible label for the command menu. This is not visible and is only used for screen readers.`Default:  —— undefined` | | | `filter` | `function` - (value: string, search: string, keywords?: string\[]) => number; | A custom filter function used to filter items. This function should return a number between `0` and `1`, with `1` being a perfect match, and `0` being no match, resulting in the item being hidden entirely. The items are sorted/filtered based on this score.`Default:  —— undefined` | | | `shouldFilter` | `boolean` | Whether or not the command menu should filter items. This is useful when you want to apply custom filtering logic outside of the Command component.`Default: true` | | | `columns` | `number` | The number of columns in the grid layout if`Default:  —— undefined` | | | `onStateChange` | `function` - type CommandState = { /\*\* The value of the search query \*/ search: string; /\*\* The value of the selected command menu item \*/ value: string; /\*\* The filtered items \*/ filtered: { /\*\* The count of all visible items. \*/ count: number; /\*\* Map from visible item id to its search store. \*/ items: Map\; /\*\* Set of groups with at least one visible item. \*/ groups: Set\; }; }; type onStateChange = (state: Readonly\) => void; | A callback that fires when the command's internal state changes. This callback receives a readonly snapshot of the current state. The callback is debounced and only fires once per batch of related updates (e.g., when typing triggers filtering and selection changes).`Default:  —— undefined` | | | `loop` | `boolean` | Whether or not the command menu should loop through items when navigating with the keyboard.`Default: false` | | | `disablePointerSelection` | `boolean` | Set this to true to prevent items from being selected when the users pointer moves over them.`Default: false` | | | `vimBindings` | `boolean` | Whether VIM bindings should be enabled or not, which allow the user to navigate using ctrl+n/j/p/k`Default: true` | | | `disableInitialScroll` | `boolean` | Whether to disable scrolling the selected item into view on initial mount. When `true`, prevents automatic scrolling when the command menu first renders and selects its first item, but still allows scrolling on subsequent selections.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----- | ---------------------------- | ------- | | `data-command-root` | `''` | Present on the root element. | | ### Command.Input The text input field where users can type to search or filter commands. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string` | The value of the search query. This is used to filter items and to search for items.`Default:  —— undefined` | | | `ref` $bindable | `HTMLInputElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----- | ----------------------------- | ------- | | `data-command-input` | `''` | Present on the input element. | | ### Command.List The container for the viewport, items, and other elements of the command menu. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----- | ---------------------------- | ------- | | `data-command-list` | `''` | Present on the list element. | | | CSS Variable | Description | Details | | ---------------------------- | ---------------------------------------------------------------------------------------------- | ------- | | `--bits-command-list-height` | The height of the command list element, which is computed by the `Command.Viewport` component. | | ### Command.Viewport The visible area of the command list, which applies CSS variables to handle dynamic resizing/animations based on the height of the list. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | -------------------------------- | ------- | | `data-command-viewport` | `''` | Present on the viewport element. | | ### Command.Group A container for a group of items within the command menu. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` | `string` | If a `Command.GroupHeading` is used within this group, the contents of the heading will be used as the value. If the content is dynamic or you wish to have a more specific value, you can provide a unique value for the group here.`Default:  —— undefined` | | | `forceMount` | `boolean` | Whether or not the group should always be mounted to the DOM, regardless of the internal filtering logic`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----- | ----------------------------- | ------- | | `data-command-group` | `''` | Present on the group element. | | ### Command.GroupHeading A heading element to provide an accessible label for a group of items. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | ----- | ------------------------------------- | ------- | | `data-command-group-heading` | `''` | Present on the group heading element. | | ### Command.GroupItems The container for the items within a group. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | ----- | ----------------------------------- | ------- | | `data-command-group-items` | `''` | Present on the group items element. | | ### Command.Item Represents a single item within the command menu. If you wish to render an anchor element to link to a page, use the `Command.LinkItem` component. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` required | `string` | The value of the item.`Default:  —— undefined` | | | `keywords` | `string[]` | An array of additional keywords or aliases that will be used to filter the item.`Default:  —— undefined` | | | `forceMount` | `boolean` | Whether or not the item should always be mounted to the DOM, regardless of the internal filtering logic`Default: false` | | | `onSelect` | `function` - () => void | A callback that is fired when the item is selected.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the combobox item is disabled. This will prevent interaction/selection.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----- | ---------------------------------- | ------- | | `data-disabled` | `''` | Present when the item is disabled. | | | `data-selected` | `''` | Present when the item is selected. | | | `data-command-item` | `''` | Present on the item element. | | ### Command.LinkItem Similar to the `Command.Item` component, but renders an anchor element to take advantage of preloading before navigation. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` required | `string` | The value of the item.`Default:  —— undefined` | | | `keywords` | `string[]` | An array of additional keywords or aliases that will be used to filter the item.`Default:  —— undefined` | | | `forceMount` | `boolean` | Whether or not the item should always be mounted to the DOM, regardless of the internal filtering logic`Default: false` | | | `onSelect` | `function` - () => void | A callback that is fired when the item is selected.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the combobox item is disabled. This will prevent interaction/selection.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----- | ---------------------------------- | ------- | | `data-disabled` | `''` | Present when the item is disabled. | | | `data-selected` | `''` | Present when the item is selected. | | | `data-command-item` | `''` | Present on the item element. | | ### Command.Empty A component to display when no results are found. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `forceMount` | `boolean` | Whether or not to forcefully mount the empty state, regardless of the internal filtering logic. Useful when you want to handle filtering yourself.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----- | ----------------------------- | ------- | | `data-command-empty` | `''` | Present on the empty element. | | ### Command.Loading A component to display while results are being fetched or processed. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `progress` | `number` | The progress of the loading state.`Default: 0` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | ----- | ------------------------------- | ------- | | `data-command-loading` | `''` | Present on the loading element. | | ### Command.Separator A visual separator to divide different sections of the command list. Visible when the search query is empty or the `forceMount` prop is `true`. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `forceMount` | `boolean` | Whether or not the separator should always be mounted to the DOM, regardless of the internal filtering logic`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----- | --------------------------------- | ------- | | `data-command-separator` | `''` | Present on the separator element. | | [Previous Combobox](/docs/components/combobox) [Next Context Menu](/docs/components/context-menu) ---------------------------------------------------- # Context Menu Documentation Displays contextual options and actions triggered by right-click. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
Right click me
Edit
E
Add
N
Header Paragraph Codeblock List Task
Duplicate
D
Delete
``` ## Structure ```svelte {#snippet children({ checked })} {checked ? "✅" : ""} {/snippet} {#snippet children({ checked })} {checked ? "✅" : ""} {/snippet} ``` ## Reusable Components If you're planning to use Context Menu in multiple places, you can create a reusable component that wraps the Context Menu component. This example shows you how to create a Context Menu component that accepts a few custom props that make it more capable. CustomContextMenu.svelte ```svelte {@render trigger()} Select an Office {#each items as item} {item} {/each} ``` You can then use the `CustomContextMenu` component like this: ```svelte {#snippet triggerArea()}
Right-click me
{/snippet}
``` Alternatively, you can define the snippet(s) separately and pass them as props to the component: ```svelte {#snippet triggerArea()}
Right-click me
{/snippet} ``` ## Managing Open State This section covers how to manage the `open` state of the menu. ### Two-Way Binding Use `bind:open` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Radio Groups You can combine the `ContextMenu.RadioGroup` and `ContextMenu.RadioItem` components to create a radio group within a menu. ```svelte {#each values as value} {#snippet children({ checked })} {#if checked} ✅ {/if} {value} {/snippet} {/each} ``` See the [RadioGroup](#radiogroup) and [RadioItem](#radioitem) APIs for more information. ## Checkbox Items You can use the `ContextMenu.CheckboxItem` component to create a `menuitemcheckbox` element to add checkbox functionality to menu items. ```svelte {#snippet children({ checked, indeterminate })} {#if indeterminate} - {:else if checked} ✅ {/if} Notifications {/snippet} ``` See the [CheckboxItem API](#checkboxitem) for more information. ## Checkbox Groups You can use the `ContextMenu.CheckboxGroup` component around a set of `ContextMenu.CheckboxItem` components to create a checkbox group within a menu, where the `value` prop is an array of the selected values. ```svelte Favorite color {#snippet children({ checked })} {#if checked} ✅ {/if} Red {/snippet} {#snippet children({ checked })} {#if checked} ✅ {/if} Blue {/snippet} {#snippet children({ checked })} {#if checked} ✅ {/if} Green {/snippet} ``` The `value` state does not persist between menu open/close cycles. To persist the state, you must store it in a `$state` variable and pass it to the `value` prop. ## Nested Menus You can create nested menus using the `ContextMenu.Sub` component to create complex menu structures. ```svelte Item 1 Item 2 Open Sub Menu Sub Item 1 Sub Item 2 ``` ## Svelte Transitions You can use the `forceMount` prop along with the `child` snippet to forcefully mount the `ContextMenu.Content` component to use Svelte Transitions or another animation library that requires more control. ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
Item 1 Item 2
{/if} {/snippet}
``` Of course, this isn't the prettiest syntax, so it's recommended to create your own reusable content component that handles this logic if you intend to use this approach. For more information on using transitions with Bits UI components, see the [Transitions](/docs/transitions) documentation. Expand Code ```svelte
Right click me
{#snippet child({ wrapperProps, props, open })} {#if open}
Edit
E
Add
N
Header Paragraph Codeblock List Task
Duplicate
D
Delete
{/if} {/snippet}
``` ## API Reference ### ContextMenu.Root The root component which manages & scopes the state of the context menu. | Property | Type | Description | Details | | ---------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------- | | `open` $bindable | `boolean` | The open state of the menu.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### ContextMenu.Trigger The element which when right-clicked, opens the context menu. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the menu trigger is disabled.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-context-menu-trigger` | `''` | Present on the trigger element. | | ### ContextMenu.Portal A component that portals the content of the dropdown menu to the body or a custom target (if provided). | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### ContextMenu.Content The content displayed when the context menu is open. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `loop` | `boolean` | Whether or not the context menu should loop through items when reaching the end.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-context-menu-content` | `''` | Present on the content element. | | | CSS Variable | Description | Details | | ---------------------------------------------- | -------------------------------------------- | ------- | | `--bits-context-menu-content-transform-origin` | The transform origin of the content element. | | | `--bits-context-menu-content-available-width` | The available width of the content element. | | | `--bits-context-menu-content-available-height` | The available height of the content element. | | | `--bits-context-menu-anchor-width` | The width of the anchor element. | | | `--bits-context-menu-anchor-height` | The height of the anchor element. | | ### ContextMenu.ContentStatic The content displayed when the context menu is open. (Static/No Floating UI) | Property | Type | Description | Details | | ------------------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `loop` | `boolean` | Whether or not the context menu should loop through items when reaching the end.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-context-menu-content` | `''` | Present on the content element. | | ### ContextMenu.Item A menu item within the context menu. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the menu item is disabled.`Default: false` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `closeOnSelect` | `boolean` | Whether or not the menu item should close when selected.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ---------- | ------------------------------------------ | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-context-menu-item` | `''` | Present on the item element. | | ### ContextMenu.CheckboxGroup A group of checkbox menu items, where multiple can be checked at a time. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string[]` | The value of the group. This is an array of the values of the checked checkboxes within the group.`Default: []` | | | `onValueChange` | `function` - (value: string\[]) => void | A callback that is fired when the checkbox group's value state changes.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------------- | ----- | -------------------------------------- | ------- | | `data-context-menu-checkbox-group` | `''` | Present on the checkbox group element. | | ### ContextMenu.CheckboxItem A menu item that can be controlled and toggled like a checkbox. | Property | Type | Description | Details | | ------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the checkbox menu item is disabled. Disabled items cannot be interacted with and are skipped when navigating with the keyboard.`Default: false` | | | `checked` $bindable | `boolean` | The checked state of the checkbox.`Default: false` | | | `onCheckedChange` | `function` - (checked: boolean) => void | A callback that is fired when the checked state changes.`Default:  —— undefined` | | | `indeterminate` $bindable | `boolean` | The indeterminate state of the checkbox.`Default: false` | | | `onIndeterminateChange` | `function` - (indeterminate: boolean) => void | A callback that is fired when the indeterminate state changes.`Default:  —— undefined` | | | `value` | `string` | The value of the checkbox item when used in a `*Menu.CheckboxGroup`.`Default:  —— undefined` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `closeOnSelect` | `boolean` | Whether or not the menu item should close when selected.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { checked: boolean; indeterminate: boolean; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; checked: boolean; indeterminate: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------------- | ---------------------------------------------------- | ------------------------------------------ | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-state` | `enum` - 'checked' \| 'unchecked' \| 'indeterminate' | The checkbox menu item's checked state. | | | `data-context-menu-checkbox-item` | `''` | Present on the checkbox item element. | | ### ContextMenu.RadioGroup A group of radio menu items, where only one can be checked at a time. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string` | The value of the currently checked radio menu item.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: string) => void | A callback that is fired when the radio group's value changes.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | ----- | ----------------------------------- | ------- | | `data-context-menu-radio-group` | `''` | Present on the radio group element. | | ### ContextMenu.RadioItem A menu item that can be controlled and toggled like a radio button. It must be a child of a `RadioGroup`. | Property | Type | Description | Details | | ---------------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` required | `string` | The value of the radio item. When checked, the parent `RadioGroup`'s value will be set to this value.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the radio menu item is disabled. Disabled items cannot be interacted with and are skipped when navigating with the keyboard.`Default: false` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `closeOnSelect` | `boolean` | Whether or not the menu item should close when selected.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { checked: boolean; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; checked: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------ | --------------------------------- | ------------------------------------------ | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-state` | `enum` - 'checked' \| 'unchecked' | The radio menu item's checked state. | | | `data-value` | `''` | The value of the radio item. | | | `data-context-menu-radio-item` | `''` | Present on the radio item element. | | ### ContextMenu.Separator A horizontal line to visually separate menu items. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ---------- | --------------------------------- | ------- | | `data-orientation` | `vertical` | The orientation of the separator. | | | `data-menu-separator` | `''` | Present on the separator element. | | | `data-context-menu-separator` | `''` | Present on the separator element. | | ### ContextMenu.Arrow An optional arrow which points to the context menu's anchor/trigger point. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `width` | `number` | The width of the arrow in pixels.`Default: 8` | | | `height` | `number` | The height of the arrow in pixels.`Default: 8` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-context-menu-arrow` | `''` | Present on the arrow element. | | ### ContextMenu.Group A group of menu items. It should be passed an `aria-label` or have a child `ContextMenu.GroupHeading` component to provide a label for a group of menu items. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----- | ----------------------------- | ------- | | `data-context-menu-group` | `''` | Present on the group element. | | ### ContextMenu.GroupHeading A heading for a group which will be skipped when navigating with the keyboard. It is used to provide a visual label for a group of menu items and must be a child of either a `ContextMenu.Group` or `ContextMenu.RadioGroup` component. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----- | ------------------------------------- | ------- | | `data-menu-group-heading` | `''` | Present on the group heading element. | | ### ContextMenu.Sub A submenu belonging to the parent context menu. Responsible for managing the state of the submenu. | Property | Type | Description | Details | | ---------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------- | | `open` $bindable | `boolean` | The open state of the submenu.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### ContextMenu.SubTrigger A menu item which when pressed or hovered, opens the submenu it is a child of. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the submenu trigger is disabled.`Default: false` | | | `openDelay` | `number` | The amount of time in ms from when the mouse enters the subtrigger until the submenu opens.`Default: 100` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-context-menu-sub-trigger` | `''` | Present on the submenu trigger element. | | ### ContextMenu.SubContent The submenu content displayed when the parent submenu is open. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not to loop through the menu items in when navigating with the keyboard.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-context-menu-sub-content` | `''` | Present on the submenu content element. | | ### ContextMenu.SubContentStatic The submenu content displayed when the parent submenu menu is open. (Static/No Floating UI) | Property | Type | Description | Details | | ------------------------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not to loop through the menu items when reaching the end of the list when using the keyboard.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { open: boolean; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-context-menu-sub-content` | `''` | Present on the submenu content element. | | [Previous Command](/docs/components/command) [Next Date Field](/docs/components/date-field) ---------------------------------------------------- # Date Field Documentation An alternative to the native \`\\` element. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
Birthday {#snippet children({ segments })} {#each segments as { part, value }, i (part + i)}
{#if part === "literal"} {value} {:else} {value} {/if}
{/each} {/snippet}
``` ##### Heads up! Before diving into this component, it's important to understand how dates/times work in Bits UI. Please read the [Dates](/docs/dates) documentation to learn more! ## Overview The `DateField` component is an alternative to the native `` element. It provides a more flexible and customizable way to select dates within a designated field. ## Structure ```svelte Check-in date {#snippet children({ segments })} {#each segments as { part, value }} {value} {/each} {/snippet} ``` ## Reusable Components It's recommended to use the `DateField` primitives to build your own custom date field component that can be used throughout your application. The following example shows how you might create a reusable `MyDateField` component that can be used throughout your application. For style inspiration, reference the featured demo at the top of this page. MyDateField.svelte ```svelte {labelText} {#snippet children({ segments })} {#each segments as { part, value }} {value} {/each} {/snippet} ``` Expand Code ```svelte
{labelText} {#snippet children({ segments })} {#each segments as { part, value }, i (part + i)}
{#if part === "literal"} {value} {:else} {value} {/if}
{/each} {/snippet}
``` We'll be using this newly created `MyDateField` component in the following demos and examples to prevent repeating the same code, so be sure to reference it as you go through the documentation. ## Segments A segment of the `DateField` represents a not only a specific part of the date, such as the day, month, year, hour, but can also reference a `"literal"` which is typically a separator between the different parts of the date, and varies based on the `locale`. Notice that in the `MyDateField` component we created, we're styling the `DateField.Segment` components differently based on whether they are a `"literal"` or not. ## Placeholder The `placeholder` prop for the `DateField.Root` component isn't what is displayed when the field is empty, but rather what date our field should start with when the user attempts to cycle through the segments. The placeholder can also be used to set a granularity for the date field, which will determine which type of `DateValue` object is used for the `value`. By default, the `placeholder` will be set to the closed alowed (by `maxValue`, `minValue`) value to current date, and be of type `CalendarDate`. However, if we wanted this date field to also allow for selecting a time, we could set the placeholder to a `CalendarDateTime` object. ```svelte ``` If we're collecting a date from the user where we want the timezone as well, we can use a `ZonedDateTime` object instead. ```svelte ``` ##### Leap Years! If you're creating a date field for something like a birthday, ensure your placeholder is set in a leap year to ensure users born on a leap year will be able to select the correct date. ## Managing Placeholder State This section covers how to manage the `placeholder` state of the Date Field. ### Two-Way Binding Use `bind:placeholder` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the Date Field. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled For complete control over the component's state, use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) to manage the value state externally. ```svelte ``` ## Default Value Often, you'll want to start the `DateField.Root` component with a default value. Likely this value will come from a database in the format of an ISO 8601 string. You can use the `parseDate` function from the `@internationalized/date` package to parse the string into a `CalendarDate` object. +page.svelte ```svelte ``` Now our input is populated with the default value. In addition to the `parseDate` function, you can also use `parseDateTime` or `parseZonedDateTime` to parse the string into a `CalendarDateTime` or `ZonedDateTime` object respectively. ## Validation ### Minimum Value You can set a minimum value for the `DateField.Root` component by using the `minValue` prop. If a user selects a date that is less than the minimum value, the date field will be marked as invalid. ```svelte ``` In the example above, we're setting the minimum value to today, and the default value to yesterday. This causes the date field to be marked as invalid, and we can style it accordingly. If you adjust the date to be greater than the minimum value, the invalid state will be cleared. ### Maximum Value You can set a maximum value for the `DateField.Root` component by using the `maxValue` prop. If a user selects a date that is greater than the maximum value, the date field will be marked as invalid. ```svelte ``` In the example above, we're setting the maximum value to today, and the default value to tomorrow. This causes the date field to be marked as invalid, and we can style it accordingly. If you adjust the date to be less than the maximum value, the invalid state will be cleared. ### Custom Validation You can use the `validate` prop to provide a custom validation function for the date field. This function should return a string or array of strings as validation errors if the date is invalid, or undefined/nothing if the date is valid. The strings are then passed to the `onInvalid` callback, which you can use to display an error message to the user. ```svelte ``` Try selecting a date that is the first day of the month to see the date field marked as invalid. ## Granularity The `granularity` prop sets the granularity of the date field, which determines which segments are rendered in the date field. The `granularity` can be set to either `'day'`, `'hour'`, `'minute'`, or `'second'`. ```svelte ``` In the example above, we're setting the granularity to `'second'`, which means that the date field will include an additional segment for the seconds. ## Localization You can use the `locale` prop to set the locale of the date field. This will affect the formatting of the date field's segments and placeholders. ```svelte ``` ## API Reference ### DateField.Root The root date field component. | Property | Type | Description | Details | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The selected date.`Default:  —— undefined` | | | `onValueChange` | `function` - (date: DateValue) => void | A function that is called when the date value changes.`Default:  —— undefined` | | | `placeholder` $bindable | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The placeholder date, which is used to determine what date to start the segments from when no value exists.`Default:  —— undefined` | | | `onPlaceholderChange` | `function` - (date: DateValue) => void | A function that is called when the placeholder date changes.`Default:  —— undefined` | | | `required` | `boolean` | Whether or not the date field is required.`Default: false` | | | `validate` | `function` - (date: DateValue) => string\[] \| string \| void | A function that returns whether or not a date is valid.`Default:  —— undefined` | | | `onInvalid` | `function` - (reason: 'min' \| 'max' \| 'custom', msg?: string \| string\[]) => void | A callback fired when the value is invalid.`Default:  —— undefined` | | | `errorMessageId` | `string` | The `id` of the element which contains the error messages for the date field when the date is invalid.`Default:  —— undefined` | | | `hourCycle` | `enum` - '12' \| '24' | The hour cycle to use for formatting times. Defaults to the locale preference`Default:  —— undefined` | | | `granularity` | `enum` - 'day' \| 'hour' \| 'minute' \| 'second' | The granularity to use for formatting the field. Defaults to `'day'` if a `CalendarDate` is provided, otherwise defaults to `'minute'`. The field will render segments for each part of the date up to and including the specified granularity.`Default:  —— undefined` | | | `hideTimeZone` | `boolean` | Whether or not to hide the time zone segment of the field.`Default: false` | | | `maxValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The maximum valid date that can be entered.`Default:  —— undefined` | | | `minValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The minimum valid date that can be entered.`Default:  —— undefined` | | | `locale` | `string` | The locale to use for formatting dates.`Default: en-US` | | | `disabled` | `boolean` | Whether or not the field is disabled.`Default: false` | | | `readonly` | `boolean` | Whether or not the field is readonly.`Default: false` | | | `readonlySegments` | `EditableSegmentPart[]` - "day" \| "month" \| "year" \| "hour" \| "minute" \| "second" \| "dayPeriod" | An array of segments that should be readonly, which prevent user input on them.`Default:  —— undefined` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### DateField.Input The container for the segments of the date field. | Property | Type | Description | Details | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `name` | `string` | The name of the date field used for form submission. If provided, a hidden input element will be rendered alongside the date field.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - import type { SegmentPart } from "bits-ui"; type ChildrenSnippetProps = { segments: Array<{ part: SegmentPart; value: string }>; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - import type { SegmentPart } from "bits-ui"; type ChildSnippetProps = { props: Record\; segments: Array<{ part: SegmentPart; value: string }>; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | -------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid. | | | `data-disabled` | `''` | Present on the element when the field is disabled. | | | `data-date-field-input` | `''` | Present on the element. | | ### DateField.Segment A segment of the date field. | Property | Type | Description | Details | | --------------- | -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `part` required | `SegmentPart` - "day" \|"month" \| "year" \| "hour" \| "minute" \| "second" \| "dayPeriod" \| "timeZoneName" \| "literal"; | The part of the date to render.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-disabled` | `''` | Present on the element when the field is disabled | | | `data-readonly` | `''` | Present on the element when the field or segment is readonly | | | `data-segment` | `enum` - 'day' \| 'month' \| 'year' \| 'hour' \| 'minute' \| 'second' \| 'dayPeriod' \| 'timeZoneName' \| 'literal' | The part of the date being rendered. | | | `data-date-field-segment` | `''` | Present on the element. | | ### DateField.Label The label for the date field. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | ------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-disabled` | `''` | Present on the element when the field is disabled | | | `data-date-field-label` | `''` | Present on the element. | | [Previous Context Menu](/docs/components/context-menu) [Next Date Picker](/docs/components/date-picker) ---------------------------------------------------- # Date Picker Documentation Enables users to select dates using an input field and calendar interface. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
Birthday {#snippet children({ segments })} {#each segments as { part, value }, i (part + i)}
{#if part === "literal"} {value} {:else} {value} {/if}
{/each} {/snippet}
{#snippet children({ months, weekdays })}
{#each months as month (month.value)} {#each weekdays as day (day)}
{day.slice(0, 2)}
{/each}
{#each month.weeks as weekDates (weekDates)} {#each weekDates as date (date)} {date.day} {/each} {/each}
{/each}
{/snippet}
``` ##### Heads up! Before diving into this component, it's important to understand how dates/times work in Bits UI. Please read the [Dates](/docs/dates) documentation to learn more! ## Structure ```svelte {#snippet children({ segments })} {#each segments as { part, value }} {value} {/each} {/snippet} {#snippet children({ months, weekdays })} {#each months as month} {#each weekdays as day} {day} {/each} {#each month.weeks as weekDates} {#each weekDates as date} {/each} {/each} {/each} {/snippet} ``` ## Managing Placeholder State This section covers how to manage the `placeholder` state of the component. ### Two-Way Binding Use `bind:placeholder` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Open State This section covers how to manage the `open` state of the component. ### Two-Way Binding Use `bind:open` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Customization The `DatePicker` component is made up of three other Bits UI components: [Date Field](/docs/components/date-field), [Calendar](/docs/components/calendar), and [Popover](/docs/components/popover). You can check out the documentation for each of these components to learn more about their customization options, each of which can be used to customize the `DatePicker` component. ## API Reference ### DatePicker.Root The root date picker component. | Property | Type | Description | Details | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The selected date.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: DateValue) => void \| (value: DateValue\[]) => void | A function that is called when the selected date changes.`Default:  —— undefined` | | | `open` $bindable | `boolean` | The open state of the popover content.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `placeholder` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The placeholder date, which is used to determine what month to display when no date is selected. This updates as the user navigates the calendar, and can be used to programmatically control the calendar's view.`Default:  —— undefined` | | | `onPlaceholderChange` | `function` - (date: DateValue) => void | A function that is called when the placeholder date changes.`Default:  —— undefined` | | | `isDateUnavailable` | `function` - (date: DateValue) => boolean | A function that returns whether or not a date is unavailable.`Default:  —— undefined` | | | `isDateDisabled` | `function` - (date: DateValue) => boolean | A function that returns whether or not a date is disabled.`Default:  —— undefined` | | | `validate` | `function` - (date: DateValue) => string\[] \| string \| void | A function that returns whether or not a date is valid.`Default:  —— undefined` | | | `onInvalid` | `function` - (reason: 'min' \| 'max' \| 'custom', msg?: string \| string\[]) => void | A callback fired when the value is invalid.`Default:  —— undefined` | | | `required` | `boolean` | Whether or not the date field is required.`Default: false` | | | `errorMessageId` | `string` | The `id` of the element which contains the error messages for the date field when the date is invalid.`Default:  —— undefined` | | | `readonlySegments` | `EditableSegmentPart[]` - "day" \| "month" \| "year" \| "hour" \| "minute" \| "second" \| "dayPeriod" | An array of segments that should be readonly, which prevent user input on them.`Default:  —— undefined` | | | `disableDaysOutsideMonth` | `boolean` | Whether or not to disable days outside the current month.`Default: false` | | | `closeOnDateSelect` | `boolean` | Whether or not to close the popover when a date is selected.`Default: true` | | | `pagedNavigation` | `boolean` | Whether or not to use paged navigation for the calendar. Paged navigation causes the previous and next buttons to navigate by the number of months displayed at once, rather than by one month.`Default: false` | | | `preventDeselect` | `boolean` | Whether or not to prevent the user from deselecting a date without selecting another date first.`Default: false` | | | `weekStartsOn` | `number` | An absolute day of the week to start the calendar on, regardless of locale. `0` is Sunday, `1` is Monday, etc. If not provided, the calendar will default to the locale's first day of the week.`Default:  —— undefined` | | | `weekdayFormat` | `enum` - 'narrow' \| 'short' \| 'long' | The format to use for the weekday strings provided via the `weekdays` slot prop.`Default: ''narrow''` | | | `calendarLabel` | `string` | The accessible label for the calendar.`Default:  —— undefined` | | | `fixedWeeks` | `boolean` | Whether or not to always display 6 weeks in the calendar.`Default: false` | | | `maxValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The maximum date that can be selected.`Default:  —— undefined` | | | `minValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The minimum date that can be selected.`Default:  —— undefined` | | | `locale` | `string` | The locale to use for formatting dates.`Default: 'en'` | | | `numberOfMonths` | `number` | The number of months to display at once.`Default: 1` | | | `disabled` | `boolean` | Whether or not the Date Picker is disabled.`Default: false` | | | `readonly` | `boolean` | Whether or not the Date Picker is readonly.`Default: false` | | | `hourCycle` | `enum` - '12' \| '24' | The hour cycle to use for formatting times. Defaults to the locale preference`Default:  —— undefined` | | | `granularity` | `enum` - 'day' \| 'hour' \| 'minute' \| 'second' | The granularity to use for formatting the field. Defaults to `'day'` if a `CalendarDate` is provided, otherwise defaults to `'minute'`. The field will render segments for each part of the date up to and including the specified granularity.`Default:  —— undefined` | | | `hideTimeZone` | `boolean` | Whether or not to hide the time zone segment of the field.`Default: false` | | | `initialFocus` | `boolean` | If `true`, the calendar will focus the selected day, today, or the first day of the month in that order depending on what is visible when the calendar is mounted.`Default: false` | | | `monthFormat` | `union` - short \| long \| narrow \| numeric \| 2-digit \| (month: number) => string | The format to use for the month strings provided via the `months` slot prop.`Default: 'long'` | | | `yearFormat` | `union` - numeric \| 2-digit \| (year: number) => string | The format to use for the year strings provided via the `years` slot prop.`Default: 'numeric'` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### DatePicker.Label The label for the date field. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | ------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-disabled` | `''` | Present on the element when the field is disabled | | | `data-date-field-label` | `''` | Present on the element. | | ### DatePicker.Input The field input component which contains the segments of the date field. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | `name` | `string` | The name of the date field used for form submission. If provided, a hidden input element will be rendered alongside the date field.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | -------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid. | | | `data-disabled` | `''` | Present on the element when the field is disabled. | | | `data-date-field-input` | `''` | Present on the element. | | ### DatePicker.Segment A segment of the date field. | Property | Type | Description | Details | | --------------- | -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `part` required | `SegmentPart` - "day" \|"month" \| "year" \| "hour" \| "minute" \| "second" \| "dayPeriod" \| "timeZoneName" \| "literal"; | The part of the date to render.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-disabled` | `''` | Present on the element when the field is disabled | | | `data-readonly` | `''` | Present on the element when the field or segment is readonly | | | `data-segment` | `enum` - 'day' \| 'month' \| 'year' \| 'hour' \| 'minute' \| 'second' \| 'dayPeriod' \| 'timeZoneName' \| 'literal' | The part of the date being rendered. | | | `data-date-field-segment` | `''` | Present on the element. | | ### DatePicker.Trigger A component which toggles the opening and closing of the popover on press. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | --------------------------- | -------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | Whether the popover is open or closed. | | | `data-popover-trigger` | `''` | Present on the trigger element. | | ### DatePicker.Content The contents of the popover which are displayed when the popover is open. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: false` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | --------------------------- | -------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | Whether the popover is open or closed. | | | `data-popover-content` | `''` | Present on the content element. | | | CSS Variable | Description | Details | | ----------------------------------------- | -------------------------------------------- | ------- | | `--bits-popover-content-transform-origin` | The transform origin of the content element. | | | `--bits-popover-content-available-width` | The available width of the content element. | | | `--bits-popover-content-available-height` | The available height of the content element. | | | `--bits-popover-anchor-width` | The width of the anchor element. | | | `--bits-popover-anchor-height` | The height of the anchor element. | | ### DatePicker.Portal When used, will render the popover content into the body or custom `to` element when open | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### DatePicker.Calendar The calendar component containing the grids of dates. | Data Attribute | Value | Description | Details | | -------------------- | ----- | -------------------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the calendar element when the calendar is invalid. | | | `data-disabled` | `''` | Present on the calendar element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the calendar element when the calendar is readonly. | | | `data-calendar-root` | `''` | Present on the calendar element. | | ### DatePicker.Header The header of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | ----- | ------------------------------------------------------------ | ------- | | `data-disabled` | `''` | Present on the header element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the header element when the calendar is readonly. | | | `data-calendar-header` | `''` | Present on the header element. | | ### DatePicker.PrevButton The previous button of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | ----- | -------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the prev button element when the calendar or this button is disabled. | | | `data-calendar-prev-button` | `''` | Present on the prev button element. | | ### DatePicker.Heading The heading of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | ------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the heading element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the heading element when the calendar is readonly. | | | `data-calendar-heading` | `''` | Present on the heading element. | | ### DatePicker.NextButton The next button of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | ----- | -------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the next button element when the calendar or this button is disabled. | | | `data-calendar-next-button` | `''` | Present on the next button element. | | ### DatePicker.Grid The grid of dates in the calendar, typically representing a month. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid element when the calendar is readonly. | | | `data-calendar-grid` | `''` | Present on the grid element. | | ### DatePicker.GridRow A row in the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableRowElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----- | -------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid row element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid row element when the calendar is readonly. | | | `data-calendar-grid-row` | `''` | Present on the grid row element. | | ### DatePicker.GridHead The head of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableSectionElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----- | --------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid head element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid head element when the calendar is readonly. | | | `data-calendar-grid-head` | `''` | Present on the grid head element. | | ### DatePicker.HeadCell A cell in the head of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableCellElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----- | --------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the head cell element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the head cell element when the calendar is readonly. | | | `data-calendar-head-cell` | `''` | Present on the head cell element. | | ### DatePicker.GridBody The body of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableSectionElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid element when the calendar is readonly. | | | `data-calendar-grid-body` | `''` | Present on the grid body element. | | ### DatePicker.Cell A cell in the calendar grid. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `date` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The date for the cell.`Default:  —— undefined` | | | `month` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The current month the date is being displayed in.`Default:  —— undefined` | | | `ref` $bindable | `HTMLTableCellElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | --------------------------------------------------- | ------- | | `data-disabled` | `''` | Present when the day is disabled. | | | `data-unavailable` | `''` | Present when the day is unavailable. | | | `data-today` | `''` | Present when the day is today. | | | `data-outside-month` | `''` | Present when the day is outside the current month. | | | `data-outside-visible-months` | `''` | Present when the day is outside the visible months. | | | `data-focused` | `''` | Present when the day is focused. | | | `data-selected` | `''` | Present when the day is selected. | | | `data-value` | `''` | The date in the format "YYYY-MM-DD". | | | `data-calendar-cell` | `''` | Present on the cell element. | | ### DatePicker.Day A day in the calendar grid. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | --------------------------------------------------- | ------- | | `data-disabled` | `''` | Present when the day is disabled. | | | `data-unavailable` | `''` | Present when the day is unavailable. | | | `data-today` | `''` | Present when the day is today. | | | `data-outside-month` | `''` | Present when the day is outside the current month. | | | `data-outside-visible-months` | `''` | Present when the day is outside the visible months. | | | `data-focused` | `''` | Present when the day is focused. | | | `data-selected` | `''` | Present when the day is selected. | | | `data-value` | `''` | The date in the format "YYYY-MM-DD". | | | `data-calendar-day` | `''` | Present on the day element. | | ### DatePicker.MonthSelect A select you can use to navigate to a specific month in the calendar view. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `months` | `number[]` | The month values to render in the select.`Default: [1-12]` | | | `monthFormat` | `enum` - 'narrow' \| 'short' \| 'long' \| 'numeric' \| '2-digit' \| '(month: number) => string' | The format to use for the month strings provided via the `months` slot prop. If a function is provided, it will be called with the month number as an argument and should return a string.`Default: ''narrow''` | | | `ref` $bindable | `HTMLSelectElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { monthItems: Array<{ value: number; label: string }>; selectedMonthItem: { value: number; label: string }; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; monthItems: Array<{ value: number; label: string }>; selectedMonthItem: { value: number; label: string }; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | ----- | ------------------------------------------------------------------ | ------- | | `data-disabled` | `''` | Present on the month select element when the calendar is disabled. | | | `data-calendar-month-select` | `''` | Present on the month select element. | | ### DatePicker.YearSelect A select you can use to navigate to a specific year in the calendar view. | Property | Type | Description | Details | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `years` | `number[]` | The year values to render in the select.``Default: The current year or placeholder year (whichever is higher) + 10 and minus 100 years. When a `minValue`/`maxValue` is provided to `Calendar.Root`, those will be used to constrain the range.`` | | | `yearFormat` | `enum` - 'numeric' \| '2-digit' \| '(year: number) => string' | The format to use for the year strings provided via the `years` slot prop. If a function is provided, it will be called with the year as an argument and should return a string.`Default: ''numeric''` | | | `ref` $bindable | `HTMLSelectElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { yearItems: Array<{ value: number; label: string }>; selectedYearItem: { value: number; label: string }; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; yearItems: Array<{ value: number; label: string }>; selectedYearItem: { value: number; label: string }; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | ----- | ----------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the year select element when the calendar is disabled. | | | `data-calendar-year-select` | `''` | Present on the year select element. | | [Previous Date Field](/docs/components/date-field) [Next Date Range Field](/docs/components/date-range-field) ---------------------------------------------------- # Date Range Field Documentation Enables users to input a range of dates within a designated field. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte Hotel dates
{#each ["start", "end"] as const as type (type)} {#snippet children({ segments })} {#each segments as { part, value }, i (part + i)}
{#if part === "literal"} {value} {:else} {value} {/if}
{/each} {/snippet}
{#if type === "start"} {/if} {/each}
``` ##### Heads up! Before diving into this component, it's important to understand how dates/times work in Bits UI. Please read the [Dates](/docs/dates) documentation to learn more! ## Overview The `DateRangeField` component combines two [Date Field](/docs/components/date-field) components to create a date range field. Check out the [Date Field](/docs/components/date-field) component documentation for information on how to customize this component. ## Structure ```svelte Check-in date {#each ["start", "end"] as const as type} {#snippet children({ segments })} {#each segments as { part, value }} {value} {/each} {/snippet} {/each} ``` ## Managing Placeholder State This section covers how to manage the `placeholder` state of the component. ### Two-Way Binding Use `bind:placeholder` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## API Reference ### DateRangeField.Root The root date field component. | Property | Type | Description | Details | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `DateRange` - { start: DateValue; end: DateValue } | The selected date range.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: DateRange) => void | A function that is called when the selected date changes.`Default:  —— undefined` | | | `placeholder` $bindable | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The placeholder date, which is used to determine what date to start the segments from when no value exists.`Default:  —— undefined` | | | `onPlaceholderChange` | `function` - (date: DateValue) => void | A function that is called when the placeholder date changes.`Default:  —— undefined` | | | `errorMessageId` | `string` | The `id` of the element which contains the error messages for the date field when the date is invalid.`Default:  —— undefined` | | | `validate` | `function` - (date: DateValue) => string\[] \| string \| void | A function that returns whether or not a date is valid.`Default:  —— undefined` | | | `onInvalid` | `function` - (reason: 'min' \| 'max' \| 'custom', msg?: string \| string\[]) => void | A callback fired when the value is invalid.`Default:  —— undefined` | | | `minValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The minimum valid date that can be entered.`Default:  —— undefined` | | | `maxValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The maximum valid date that can be entered.`Default:  —— undefined` | | | `granularity` | `enum` - 'day' \| 'hour' \| 'minute' \| 'second' | The granularity to use for formatting the field. Defaults to `'day'` if a `CalendarDate` is provided, otherwise defaults to `'minute'`. The field will render segments for each part of the date up to and including the specified granularity.`Default:  —— undefined` | | | `hideTimeZone` | `boolean` | Whether or not to hide the time zone segment of the field.`Default: false` | | | `hourCycle` | `enum` - '12' \| '24' | The hour cycle to use for formatting times. Defaults to the locale preference`Default:  —— undefined` | | | `locale` | `string` | The locale to use for formatting dates.`Default: en-US` | | | `disabled` | `boolean` | Whether or not the field is disabled.`Default: false` | | | `readonly` | `boolean` | Whether or not the field is readonly.`Default: false` | | | `readonlySegments` | `EditableSegmentPart[]` - "day" \| "month" \| "year" \| "hour" \| "minute" \| "second" \| "dayPeriod" | An array of segments that should be readonly, which prevent user input on them.`Default:  —— undefined` | | | `required` | `boolean` | Whether or not the date field is required.`Default: false` | | | `onStartValueChange` | `function` - (value: DateValue) => void | A function that is called when the start date changes.`Default:  —— undefined` | | | `onEndValueChange` | `function` - (value: DateValue) => void | A function that is called when the end date changes.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | ----- | ---------------------------- | ------- | | `data-date-range-field-root` | `''` | Present on the root element. | | ### DateRangeField.Input The container for the segments of the date field. | Property | Type | Description | Details | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `type` required | `enum` - 'start' \| 'end' | The type of field to render (start or end).`Default:  —— undefined` | | | `name` | `string` | The name of the date field used for form submission. If provided, a hidden input element will be rendered alongside the date field.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - import type { SegmentPart } from "bits-ui"; type ChildrenSnippetProps = { segments: Array<{ part: SegmentPart; value: string }>; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - import type { SegmentPart } from "bits-ui"; type ChildSnippetProps = { props: Record\; segments: Array<{ part: SegmentPart; value: string }>; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | -------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid. | | | `data-disabled` | `''` | Present on the element when the field is disabled. | | | `data-date-field-input` | `''` | Present on the element. | | ### DateRangeField.Segment A segment of the date field. | Property | Type | Description | Details | | --------------- | -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `part` required | `SegmentPart` - "month" \| "day" \| "year" \| "hour" \| "minute" \| "second" \| "dayPeriod" \| "timeZoneName" \| "literal" | The part of the date to render.`Default:  —— undefined` | | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-disabled` | `''` | Present on the element when the field is disabled | | | `data-segment` | `enum` - 'month' \| 'day' \| 'year' \| 'hour' \| 'minute' \| 'second' \| 'dayPeriod' \| 'timeZoneName' \| 'literal' | The type of segment the element represents. | | | `data-date-field-segment` | `''` | Present on the element. | | ### DateRangeField.Label The label for the date field. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | ------------------------------------------------ | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-date-field-label` | `''` | Present on the element. | | [Previous Date Picker](/docs/components/date-picker) [Next Date Range Picker](/docs/components/date-range-picker) ---------------------------------------------------- # Date Range Picker Documentation Enables users to select a range of dates using an input field and calendar interface. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte Rental Days
{#each ["start", "end"] as const as type (type)} {#snippet children({ segments })} {#each segments as { part, value }, i (part + i)}
{#if part === "literal"} {value} {:else} {value} {/if}
{/each} {/snippet}
{#if type === "start"} {/if} {/each}
{#snippet children({ months, weekdays })}
{#each months as month (month.value)} {#each weekdays as day (day)}
{day.slice(0, 2)}
{/each}
{#each month.weeks as weekDates (weekDates)} {#each weekDates as date (date)} {date.day} {/each} {/each}
{/each}
{/snippet}
``` ##### Heads up! Before diving into this component, it's important to understand how dates/times work in Bits UI. Please read the [Dates](/docs/dates) documentation to learn more! ## Structure ```svelte {#each ["start", "end"] as const as type} {#snippet children({ segments })} {#each segments as { part, value }} {value} {/each} {/snippet} {/each} {#snippet children({ months, weekdays })} {#each months as month} {#each weekdays as day} {day} {/each} {#each month.weeks as weekDates} {#each weekDates as date} {date.day} {/each} {/each} {/each} {/snippet} ``` ## Managing Placeholder State This section covers how to manage the `placeholder` state of the component. ### Two-Way Binding Use `bind:placeholder` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Open State This section covers how to manage the `open` state of the component. ### Two-Way Binding Use `bind:open` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Customization The `DateRangePicker` component is made up of three other Bits UI components: [Date Range Field](/docs/components/date-range-field), [Range Calendar](/docs/components/range-calendar), and [Popover](/docs/components/popover). You can check out the documentation for each of these components to learn more about their customization options, each of which can be used to customize the `DateRangePicker` component. ## API Reference ### DateRangePicker.Root The root date picker component. | Property | Type | Description | Details | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `DateRange` - { start: DateValue; end: DateValue } | The selected date range.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: DateRange) => void | A function that is called when the selected date changes.`Default:  —— undefined` | | | `placeholder` $bindable | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The placeholder date, which is used to determine what date to start the segments from when no value exists.`Default:  —— undefined` | | | `onPlaceholderChange` | `function` - (date: DateValue) => void | A function that is called when the placeholder date changes.`Default:  —— undefined` | | | `readonlySegments` | `EditableSegmentPart[]` - "day" \| "month" \| "year" \| "hour" \| "minute" \| "second" \| "dayPeriod" | An array of segments that should be readonly, which prevent user input on them.`Default:  —— undefined` | | | `isDateUnavailable` | `function` - (date: DateValue) => boolean | A function that returns whether or not a date is unavailable.`Default:  —— undefined` | | | `minValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The minimum valid date that can be entered.`Default:  —— undefined` | | | `maxValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The maximum valid date that can be entered.`Default:  —— undefined` | | | `validate` | `function` - (date: DateValue) => string\[] \| string \| void | A function that returns whether or not a date is valid.`Default:  —— undefined` | | | `onInvalid` | `function` - (reason: 'min' \| 'max' \| 'custom', msg?: string \| string\[]) => void | A callback fired when the value is invalid.`Default:  —— undefined` | | | `granularity` | `enum` - 'day' \| 'hour' \| 'minute' \| 'second' | The granularity to use for formatting the field. Defaults to `'day'` if a `CalendarDate` is provided, otherwise defaults to `'minute'`. The field will render segments for each part of the date up to and including the specified granularity.`Default:  —— undefined` | | | `hideTimeZone` | `boolean` | Whether or not to hide the time zone segment of the field.`Default: false` | | | `errorMessageId` | `string` | The `id` of the element which contains the error messages for the date field when the date is invalid.`Default:  —— undefined` | | | `hourCycle` | `enum` - '12' \| '24' | The hour cycle to use for formatting times. Defaults to the locale preference`Default:  —— undefined` | | | `locale` | `string` | The locale to use for formatting dates.`Default: en-US` | | | `disabled` | `boolean` | Whether or not the field is disabled.`Default: false` | | | `readonly` | `boolean` | Whether or not the field is readonly.`Default: false` | | | `required` | `boolean` | Whether or not the date field is required.`Default: false` | | | `closeOnRangeSelect` | `boolean` | Whether or not to close the popover when a date range is selected.`Default: true` | | | `disableDaysOutsideMonth` | `boolean` | Whether or not to disable days outside the current month.`Default: false` | | | `pagedNavigation` | `boolean` | Whether or not to use paged navigation for the calendar. Paged navigation causes the previous and next buttons to navigate by the number of months displayed at once, rather than by one month.`Default: false` | | | `preventDeselect` | `boolean` | Whether or not to prevent the user from deselecting a date without selecting another date first.`Default: false` | | | `weekdayFormat` | `enum` - 'narrow' \| 'short' \| 'long' | The format to use for the weekday strings provided via the `weekdays` slot prop.`Default: ''narrow''` | | | `weekStartsOn` | `number` | An absolute day of the week to start the calendar on, regardless of locale. `0` is Sunday, `1` is Monday, etc. If not provided, the calendar will default to the locale's first day of the week.`Default:  —— undefined` | | | `calendarLabel` | `string` | The accessible label for the calendar.`Default:  —— undefined` | | | `fixedWeeks` | `boolean` | Whether or not to always display 6 weeks in the calendar.`Default: false` | | | `isDateDisabled` | `function` - (date: DateValue) => boolean | A function that returns whether or not a date is disabled.`Default:  —— undefined` | | | `numberOfMonths` | `number` | The number of months to display at once.`Default: 1` | | | `open` $bindable | `boolean` | The open state of the popover content.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `onEndValueChange` | `function` - (value: DateValue) => void | A function that is called when the end date changes.`Default:  —— undefined` | | | `onStartValueChange` | `function` - (value: DateValue) => void | A function that is called when the start date changes.`Default:  —— undefined` | | | `minDays` | `number` | The minimum number of days that can be selected in a range.`Default:  —— undefined` | | | `maxDays` | `number` | The maximum number of days that can be selected in a range.`Default:  —— undefined` | | | `excludeDisabled` | `boolean` | Whether to automatically reset the range if any date within the selected range becomes disabled.`Default: false` | | | `monthFormat` | `union` - short \| long \| narrow \| numeric \| 2-digit \| (month: number) => string | The format to use for the month strings provided via the `months` slot prop.`Default: 'long'` | | | `yearFormat` | `union` - numeric \| 2-digit \| (year: number) => string | The format to use for the year strings provided via the `years` slot prop.`Default: 'numeric'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the root element when the calendar is invalid. | | | `data-disabled` | `''` | Present on the root element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the root element when the calendar is readonly. | | | `data-calendar-root` | `''` | Present on the root element. | | ### DateRangePicker.Label The label for the date field. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | ------------------------------------------------ | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-date-field-label` | `''` | Present on the element. | | ### DateRangePicker.Input The field input component which contains the segments of the date field. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `name` | `string` | The name of the input field used for form submission. If provided a hidden input will be rendered alongside the field.`Default:  —— undefined` | | | `type` required | `enum` - 'start' \| 'end' | The type of field to render (start or end).`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | -------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid. | | | `data-disabled` | `''` | Present on the element when the field is disabled. | | | `data-date-field-input` | `''` | Present on the element. | | ### DateRangePicker.Segment A segment of the date field. | Property | Type | Description | Details | | --------------- | -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `part` required | `SegmentPart` - "month" \| "day" \| "year" \| "hour" \| "minute" \| "second" \| "dayPeriod" \| "timeZoneName" \| "literal" | The part of the date to render.`Default:  —— undefined` | | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-disabled` | `''` | Present on the element when the field is disabled | | | `data-segment` | `enum` - 'month' \| 'day' \| 'year' \| 'hour' \| 'minute' \| 'second' \| 'dayPeriod' \| 'timeZoneName' \| 'literal' | The type of segment the element represents. | | | `data-date-field-segment` | `''` | Present on the element. | | ### DateRangePicker.Trigger A component which toggles the opening and closing of the popover on press. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | --------------------------- | -------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | Whether the popover is open or closed. | | | `data-popover-trigger` | `''` | Present on the trigger element. | | ### DateRangePicker.Content The contents of the popover which are displayed when the popover is open. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: false` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | --------------------------- | -------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | Whether the popover is open or closed. | | | `data-popover-content` | `''` | Present on the content element. | | | CSS Variable | Description | Details | | ----------------------------------------- | -------------------------------------------- | ------- | | `--bits-popover-content-transform-origin` | The transform origin of the content element. | | | `--bits-popover-content-available-width` | The available width of the content element. | | | `--bits-popover-content-available-height` | The available height of the content element. | | | `--bits-popover-anchor-width` | The width of the anchor element. | | | `--bits-popover-anchor-height` | The height of the anchor element. | | ### DateRangePicker.Portal When used, will render the popover content into the body or custom `to` element when open | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### DateRangePicker.Calendar The calendar component containing the grids of dates. | Data Attribute | Value | Description | Details | | -------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the root element when the calendar is invalid. | | | `data-disabled` | `''` | Present on the root element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the root element when the calendar is readonly. | | | `data-calendar-root` | `''` | Present on the root element. | | ### DateRangePicker.Header The header of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | ----- | ------------------------------------------------------------ | ------- | | `data-disabled` | `''` | Present on the header element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the header element when the calendar is readonly. | | | `data-range-calendar-header` | `''` | Present on the header element. | | ### DateRangePicker.PrevButton The previous button of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------------- | ----- | -------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the prev button element when the calendar or this button is disabled. | | | `data-range-calendar-prev-button` | `''` | Present on the prev button element. | | ### DateRangePicker.Heading The heading of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | ------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the heading element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the heading element when the calendar is readonly. | | | `data-range-calendar-heading` | `''` | Present on the heading element. | | ### DateRangePicker.NextButton The next button of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------------- | ----- | -------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the next button element when the calendar or this button is disabled. | | | `data-range-calendar-next-button` | `''` | Present on the next button element. | | ### DateRangePicker.Grid The grid of dates in the calendar, typically representing a month. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid element when the calendar is readonly. | | | `data-range-calendar-grid` | `''` | Present on the grid element. | | ### DateRangePicker.GridRow A row in the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableRowElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------ | ----- | -------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid row element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid row element when the calendar is readonly. | | | `data-range-calendar-grid-row` | `''` | Present on the grid row element. | | ### DateRangePicker.GridHead The head of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableSectionElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | ----- | --------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid head element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid head element when the calendar is readonly. | | | `data-range-calendar-grid-head` | `''` | Present on the grid head element. | | ### DateRangePicker.HeadCell A cell in the head of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableCellElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | ----- | --------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the head cell element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the head cell element when the calendar is readonly. | | | `data-range-calendar-head-cell` | `''` | Present on the head cell element. | | ### DateRangePicker.GridBody The body of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableSectionElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid element when the calendar is readonly. | | | `data-range-calendar-grid-body` | `''` | Present on the grid body element. | | ### DateRangePicker.Cell A cell in the calendar grid. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `date` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The date for the cell.`Default:  —— undefined` | | | `month` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The current month the date is being displayed in.`Default:  —— undefined` | | | `ref` $bindable | `HTMLTableCellElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | ------------------------------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present when the day is disabled. | | | `data-unavailable` | `''` | Present when the day is unavailable. | | | `data-today` | `''` | Present when the day is today. | | | `data-outside-month` | `''` | Present when the day is outside the current month. | | | `data-outside-visible-months` | `''` | Present when the day is outside the visible months. | | | `data-focused` | `''` | Present when the day is focused. | | | `data-selected` | `''` | Present when the day is selected. | | | `data-value` | `''` | The date in the format "YYYY-MM-DD". | | | `data-range-calendar-cell` | `''` | Present on the cell element. | | | `data-range-start` | `''` | Present when the cell is the start of a selection range. | | | `data-range-end` | `''` | Present when the cell is the end of a selection range. | | | `data-range-middle` | `''` | Present when the cell is in the middle of a selection range, but not the start or end of the selection. | | | `data-highlighted` | `''` | Present when the cell is highlighted within a selection range. | | ### DateRangePicker.Day A day in the calendar grid. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | ------------------------------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present when the day is disabled. | | | `data-unavailable` | `''` | Present when the day is unavailable. | | | `data-today` | `''` | Present when the day is today. | | | `data-outside-month` | `''` | Present when the day is outside the current month. | | | `data-outside-visible-months` | `''` | Present when the day is outside the visible months. | | | `data-focused` | `''` | Present when the day is focused. | | | `data-selected` | `''` | Present when the day is selected. | | | `data-value` | `''` | The date in the format "YYYY-MM-DD". | | | `data-range-calendar-day` | `''` | Present on the day element. | | | `data-range-start` | `''` | Present when the cell is the start of a selection range. | | | `data-range-end` | `''` | Present when the cell is the end of a selection range. | | | `data-range-middle` | `''` | Present when the cell is in the middle of a selection range, but not the start or end of the selection. | | | `data-highlighted` | `''` | Present when the cell is highlighted within a selection range. | | ### DateRangePicker.MonthSelect A select you can use to navigate to a specific month in the calendar view. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `months` | `number[]` | The month values to render in the select.`Default: [1-12]` | | | `monthFormat` | `enum` - 'narrow' \| 'short' \| 'long' \| 'numeric' \| '2-digit' \| '(month: number) => string' | The format to use for the month strings provided via the `months` slot prop. If a function is provided, it will be called with the month number as an argument and should return a string.`Default: ''narrow''` | | | `ref` $bindable | `HTMLSelectElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { monthItems: Array<{ value: number; label: string }>; selectedMonthItem: { value: number; label: string }; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; monthItems: Array<{ value: number; label: string }>; selectedMonthItem: { value: number; label: string }; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------------- | ----- | ------------------------------------------------------------------ | ------- | | `data-disabled` | `''` | Present on the month select element when the calendar is disabled. | | | `data-range-calendar-month-select` | `''` | Present on the month select element. | | ### DateRangePicker.YearSelect A select you can use to navigate to a specific year in the calendar view. | Property | Type | Description | Details | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `years` | `number[]` | The year values to render in the select.``Default: The current year or placeholder year (whichever is higher) + 10 and minus 100 years. When a `minValue`/`maxValue` is provided to `Calendar.Root`, those will be used to constrain the range.`` | | | `yearFormat` | `enum` - 'numeric' \| '2-digit' \| '(year: number) => string' | The format to use for the year strings provided via the `years` slot prop. If a function is provided, it will be called with the year as an argument and should return a string.`Default: ''numeric''` | | | `ref` $bindable | `HTMLSelectElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { yearItems: Array<{ value: number; label: string }>; selectedYearItem: { value: number; label: string }; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; yearItems: Array<{ value: number; label: string }>; selectedYearItem: { value: number; label: string }; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------------- | ----- | ----------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the year select element when the calendar is disabled. | | | `data-range-calendar-year-select` | `''` | Present on the year select element. | | [Previous Date Range Field](/docs/components/date-range-field) [Next Dialog](/docs/components/dialog) ---------------------------------------------------- # Dialog Documentation A modal window for displaying content or requesting user input. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte New API key Create API key Create and manage API keys. You can create multiple keys to organize your applications.
API Key
Save
Close
``` ## Overview The Dialog component in Bits UI provides a flexible and accessible way to create modal dialogs in your Svelte applications. It follows a compound component pattern, allowing for fine-grained control over the dialog's structure and behavior while maintaining accessibility and ease of use. ## Key Features - **Compound Component Structure**: Offers a set of sub-components that work together to create a fully-featured dialog. - **Accessibility**: Built with WAI-ARIA guidelines in mind, ensuring keyboard navigation and screen reader support. - **Customizable**: Each sub-component can be styled and configured independently. - **Portal Support**: Content can be rendered in a portal, ensuring proper stacking context. - **Managed Focus**: Automatically manages focus, with the option to take control if needed. - **Flexible State Management**: Supports both controlled and uncontrolled state, allowing for full control over the dialog's open state. ## Architecture The Dialog component is composed of several sub-components, each with a specific role: - **Root**: The main container component that manages the state of the dialog. Provides context for all child components. - **Trigger**: A button that toggles the dialog's open state. - **Portal**: Renders its children in a portal, outside the normal DOM hierarchy. - **Overlay**: A backdrop that sits behind the dialog content. - **Content**: The main container for the dialog's content. - **Title**: Renders the dialog's title. - **Description**: Renders a description or additional context for the dialog. - **Close**: A button that closes the dialog. ## Structure Here's an overview of how the Dialog component is structured in code: ```svelte ``` ## Reusable Components Bits UI provides a comprehensive set of Dialog components that serve as building blocks for creating customized, reusable Dialog implementations. This approach offers flexibility in design while maintaining consistency and accessibility across your application. ### Building a Reusable Dialog The following example demonstrates how to create a versatile, reusable Dialog component using Bits UI building blocks. This implementation showcases the flexibility of the component API by combining props and snippets. MyDialog.svelte ```svelte {buttonText} {@render title()} {@render description()} {@render children?.()} Close Dialog ``` #### Usage with Inline Snippets ```svelte {#snippet title()} Account settings {/snippet} {#snippet description()} Manage your account settings and preferences. {/snippet} ``` #### Usage with Separate Snippets ```svelte {#snippet title()} Account settings {/snippet} {#snippet description()} Manage your account settings and preferences. {/snippet} ``` ### Best Practices - **Prop Flexibility**: Design your component to accept props for any nested components for maximum flexibility - **Styling Options**: Use tools like `clsx` to merge class overrides - **Binding Props**: Use `bind:` and expose `$bindable` props to provide consumers with full control - **Type Safety**: Use the exported types from Bits UI to type your component props ## Managing Open State This section covers how to manage the `open` state of the component. ### Two-Way Binding Use `bind:open` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Focus Management Proper focus management is crucial for accessibility and user experience in modal dialogs. Bits UI's Dialog component provides several features to help you manage focus effectively. ### Focus Trap By default, the Dialog implements a focus trap, adhering to the WAI-ARIA design pattern for modal dialogs. This ensures that keyboard focus remains within the Dialog while it's open, preventing users from interacting with the rest of the page. #### Disabling the Focus Trap While not recommended, you can disable the focus trap if absolutely necessary: ```svelte ``` ##### Accessibility Warning Disabling the focus trap may compromise accessibility. Only do this if you have a specific reason and implement an alternative focus management strategy. ### Open Focus When a Dialog opens, focus is automatically set to the first focusable element within `Dialog.Content`. This ensures keyboard users can immediately interact with the Dialog contents. #### Customizing Initial Focus To specify which element receives focus when the Dialog opens, use the `onOpenAutoFocus` prop on `Dialog.Content`: ```svelte Open Dialog { e.preventDefault(); nameInput?.focus(); }} > ``` ##### Important Always ensure that *something* within the Dialog receives focus when it opens. This is crucial for maintaining keyboard navigation context and makes your users happy. ### Close Focus When a Dialog closes, focus returns to the element that triggered its opening (typically the `Dialog.Trigger`). #### Customizing Close Focus To change which element receives focus when the Dialog closes, use the `onCloseAutoFocus` prop on `Dialog.Content`: ```svelte Open Dialog { e.preventDefault(); nameInput?.focus(); }} > ``` ### Best Practices - Always maintain a clear focus management strategy for your Dialogs. - Ensure that focus is predictable and logical for keyboard users. - Test your focus management with keyboard navigation to verify its effectiveness. ## Advanced Behaviors Bits UI's Dialog component offers several advanced features to customize its behavior and enhance user experience. This section covers scroll locking, escape key handling, and interaction outside the dialog. ### Scroll Lock By default, when a Dialog opens, scrolling the body is disabled. This provides a more native-like experience, focusing user attention on the dialog content. #### Customizing Scroll Behavior To allow body scrolling while the dialog is open, use the `preventScroll` prop on `Dialog.Content`: ```svelte ``` ##### Note Enabling body scroll may affect user focus and accessibility. Use this option judiciously. ### Escape Key Handling By default, pressing the `Escape` key closes an open Dialog. Bits UI provides two methods to customize this behavior. #### Method 1: `escapeKeydownBehavior` The `escapeKeydownBehavior` prop allows you to customize the behavior taken by the component when the `Escape` key is pressed. It accepts one of the following values: - `'close'` (default): Closes the Dialog immediately. - `'ignore'`: Prevents the Dialog from closing. - `'defer-otherwise-close'`: If an ancestor Bits UI component also implements this prop, it will defer the closing decision to that component. Otherwise, the Dialog will close immediately. - `'defer-otherwise-ignore'`: If an ancestor Bits UI component also implements this prop, it will defer the closing decision to that component. Otherwise, the Dialog will ignore the key press and not close. To always prevent the Dialog from closing on Escape key press, set the `escapeKeydownBehavior` prop to `'ignore'` on `Dialog.Content`: ```svelte ``` #### Method 2: `onEscapeKeydown` For more granular control, override the default behavior using the `onEscapeKeydown` prop: ```svelte { e.preventDefault(); // do something else instead }} > ``` This method allows you to implement custom logic when the `Escape` key is pressed. ### Interaction Outside By default, interacting outside the Dialog content area closes the Dialog. Bits UI offers two ways to modify this behavior. #### Method 1: `interactOutsideBehavior` The `interactOutsideBehavior` prop allows you to customize the behavior taken by the component when an interaction (touch, mouse, or pointer event) occurs outside the content. It accepts one of the following values: - `'close'` (default): Closes the Dialog immediately. - `'ignore'`: Prevents the Dialog from closing. - `'defer-otherwise-close'`: If an ancestor Bits UI component also implements this prop, it will defer the closing decision to that component. Otherwise, the Dialog will close immediately. - `'defer-otherwise-ignore'`: If an ancestor Bits UI component also implements this prop, it will defer the closing decision to that component. Otherwise, the Dialog will ignore the event and not close. To always prevent the Dialog from closing when an interaction occurs outside the content, set the `interactOutsideBehavior` prop to `'ignore'` on `Dialog.Content`: ```svelte ``` #### Method 2: `onInteractOutside` For custom handling of outside interactions, you can override the default behavior using the `onInteractOutside` prop: ```svelte { e.preventDefault(); // do something else instead }} > ``` This approach allows you to implement specific behaviors when users interact outside the Dialog content. ### Best Practices - **Scroll Lock**: Consider your use case carefully before disabling scroll lock. It may be necessary for dialogs with scrollable content or for specific UX requirements. - **Escape Keydown**: Overriding the default escape key behavior should be done thoughtfully. Users often expect the escape key to close modals. - **Outside Interactions**: Ignoring outside interactions can be useful for important dialogs or multi-step processes, but be cautious not to trap users unintentionally. - **Accessibility**: Always ensure that any customizations maintain or enhance the dialog's accessibility. - **User Expectations**: Try to balance custom behaviors with common UX patterns to avoid confusing users. By leveraging these advanced features, you can create highly customized dialog experiences while maintaining usability and accessibility standards. ## Nested Dialogs Dialogs can be nested within each other to create more complex user interfaces: Expand Code ```svelte Open First Dialog First Dialog This is the first dialog in the nested dialog stack. Open Second Dialog Second Dialog This is the second dialog in the nested dialog stack. Close Second Dialog
Close
``` ### Styling Nested Dialogs The Dialog component automatically tracks nesting information that can be used to create visual hierarchy when dialogs are nested. This is particularly useful for creating effects like scaling down or dimming parent dialogs when child dialogs open. #### Available Styling Hooks Each dialog provides the following data attributes and CSS variables: **Data Attributes:** - `data-nested-open`: Present on `Dialog.Content` and `Dialog.Overlay` when one or more nested dialogs are open within this dialog. - `data-nested`: Present on `Dialog.Content` and `Dialog.Overlay` when the dialog is a nested dialog, useful for hiding the overlay of nested dialogs to avoid overlapping with parent dialogs. **CSS Variables:** - `--bits-dialog-depth`: The nesting depth of the dialog (0 for root, 1 for first nested, etc.). - `--bits-dialog-nested-count`: The number of currently open nested dialogs within this dialog (updates reactively). #### Example: Scale Down Parent Dialogs ```svelte Open Dialog ``` These styling hooks allow you to create sophisticated visual feedback that helps users understand the hierarchy of nested dialogs. ## Svelte Transitions The Dialog component can be enhanced with Svelte's built-in transition effects or other animation libraries. ### Using `forceMount` and `child` Snippets To apply Svelte transitions to Dialog components, use the `forceMount` prop in combination with the `child` snippet. This approach gives you full control over the mounting behavior and animation of `Dialog.Content` and `Dialog.Overlay`. ```svelte {#snippet child({ props, open })} {#if open}
{/if} {/snippet}
{#snippet child({ props, open })} {#if open}
{/if} {/snippet}
``` In this example: - The `forceMount` prop ensures the components are always in the DOM. - The `child` snippet provides access to the open state and component props. - Svelte's `#if` block controls when the content is visible. - Transition directives (`transition:fade` and `transition:fly`) apply the animations. ### Best Practices For cleaner code and better maintainability, consider creating custom reusable components that encapsulate this transition logic. MyDialogOverlay.svelte ```svelte {#snippet child({ props, open })} {#if open}
{@render children?.()}
{/if} {/snippet}
``` You can then use the `MyDialogOverlay` component alongside the other `Dialog` primitives throughout your application: ```svelte Open ``` ## Working with Forms ### Form Submission When using the `Dialog` component, often you'll want to submit a form or perform an asynchronous action and then close the dialog. This can be done by waiting for the asynchronous action to complete, then programmatically closing the dialog. ```svelte Confirm your action Are you sure you want to do this?
{ wait(1000).then(() => (open = false)); }} >
``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Groups To group related menu items, you can use the `DropdownMenu.Group` component along with either a `DropdownMenu.GroupHeading` or an `aria-label` attribute on the `DropdownMenu.Group` component. ```svelte File New Open Save Save As New Open Save Save As ``` ### Group Heading The `DropdownMenu.GroupHeading` component must be a child of either a `DropdownMenu.Group` or `DropdownMenu.RadioGroup` component. If used on its own, an error will be thrown during development. ```svelte File Favorite color ``` ## Radio Groups You can combine the `DropdownMenu.RadioGroup` and `DropdownMenu.RadioItem` components to create a radio group within a menu. ```svelte Favorite number {#each values as value} {#snippet children({ checked })} {#if checked} ✅ {/if} {value} {/snippet} {/each} ``` The `value` state does not persist between menu open/close cycles. To persist the state, you must store it in a `$state` variable and pass it to the `value` prop. ## Checkbox Items You can use the `DropdownMenu.CheckboxItem` component to create a `menuitemcheckbox` element to add checkbox functionality to menu items. ```svelte {#snippet children({ checked, indeterminate })} {#if indeterminate} - {:else if checked} ✅ {/if} Notifications {/snippet} ``` The `checked` state does not persist between menu open/close cycles. To persist the state, you must store it in a `$state` variable and pass it to the `checked` prop. ## Checkbox Groups You can use the `DropdownMenu.CheckboxGroup` component around a set of `DropdownMenu.CheckboxItem` components to create a checkbox group within a menu, where the `value` prop is an array of the selected values. ```svelte Favorite color {#snippet children({ checked })} {#if checked} ✅ {/if} Red {/snippet} {#snippet children({ checked })} {#if checked} ✅ {/if} Blue {/snippet} {#snippet children({ checked })} {#if checked} ✅ {/if} Green {/snippet} ``` The `value` state does not persist between menu open/close cycles. To persist the state, you must store it in a `$state` variable and pass it to the `value` prop. ## Nested Menus You can create nested menus using the `DropdownMenu.Sub` component to create complex menu structures. ```svelte Item 1 Item 2 Open Sub Menu Sub Item 1 Sub Item 2 ``` ## Svelte Transitions You can use the `forceMount` prop along with the `child` snippet to forcefully mount the `DropdownMenu.Content` component to use Svelte Transitions or another animation library that requires more control. ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
Item 1 Item 2
{/if} {/snippet}
``` Of course, this isn't the prettiest syntax, so it's recommended to create your own reusable content component that handles this logic if you intend to use this approach. For more information on using transitions with Bits UI components, see the [Transitions](/docs/transitions) documentation. Expand Code ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
Profile
P
Billing
B
Settings
S
{#snippet children({ checked })}
Notifications
{#if checked} {/if}
{/snippet}
Workspace
{#snippet children({ checked })} HJ @huntabyte {#if checked} {/if} {/snippet} {#snippet children({ checked })} PS @pavel_stianko {#if checked} {/if} {/snippet} {#snippet children({ checked })} CK @cokakoala_ {#if checked} {/if} {/snippet} {#snippet children({ checked })} TL @thomasglopes {#if checked} {/if} {/snippet}
{/if} {/snippet}
``` ## Custom Anchor By default, the `DropdownMenu.Content` is anchored to the `DropdownMenu.Trigger` component, which determines where the content is positioned. If you wish to instead anchor the content to a different element, you can pass either a selector `string` or an `HTMLElement` to the `customAnchor` prop of the `DropdownMenu.Content` component. ```svelte
``` ## API Reference ### DropdownMenu.Root The root component which manages & scopes the state of the dropdown menu. | Property | Type | Description | Details | | ---------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------- | | `open` $bindable | `boolean` | The open state of the menu.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### DropdownMenu.Trigger The button element which toggles the dropdown menu. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the menu trigger is disabled.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-dropdown-menu-trigger` | `''` | Present on the trigger element. | | ### DropdownMenu.Portal A component that portals the content of the dropdown menu to the body or a custom target (if provided). | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### DropdownMenu.Content The content displayed when the dropdown menu is open. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not to loop through the menu items in when navigating with the keyboard.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-dropdown-menu-content` | `''` | Present on the content element. | | | CSS Variable | Description | Details | | ----------------------------------------------- | -------------------------------------------- | ------- | | `--bits-dropdown-menu-content-transform-origin` | The transform origin of the content element. | | | `--bits-dropdown-menu-content-available-width` | The available width of the content element. | | | `--bits-dropdown-menu-content-available-height` | The available height of the content element. | | | `--bits-dropdown-menu-anchor-width` | The width of the anchor element. | | | `--bits-dropdown-menu-anchor-height` | The height of the anchor element. | | ### DropdownMenu.ContentStatic The content displayed when the dropdown menu is open. (Static/No Floating UI) | Property | Type | Description | Details | | ------------------------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not to loop through the menu items in when navigating with the keyboard.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { open: boolean; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-dropdown-menu-content` | `''` | Present on the content element. | | ### DropdownMenu.Item A menu item within the dropdown menu. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the menu item is disabled.`Default: false` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `closeOnSelect` | `boolean` | Whether or not the menu item should close when selected.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ---------- | ------------------------------------------ | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-dropdown-menu-item` | `''` | Present on the item element. | | ### DropdownMenu.CheckboxGroup A group of checkbox menu items, where multiple can be checked at a time. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string[]` | The value of the group. This is an array of the values of the checked checkboxes within the group.`Default: []` | | | `onValueChange` | `function` - (value: string\[]) => void | A callback that is fired when the checkbox group's value state changes.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------------- | ----- | -------------------------------------- | ------- | | `data-dropdown-menu-checkbox-group` | `''` | Present on the checkbox group element. | | ### DropdownMenu.CheckboxItem A menu item that can be controlled and toggled like a checkbox. | Property | Type | Description | Details | | ------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the checkbox menu item is disabled. Disabled items cannot be interacted with and are skipped when navigating with the keyboard.`Default: false` | | | `checked` $bindable | `boolean` | The checked state of the checkbox.`Default: false` | | | `onCheckedChange` | `function` - (checked: boolean) => void | A callback that is fired when the checked state changes.`Default:  —— undefined` | | | `indeterminate` $bindable | `boolean` | The indeterminate state of the checkbox.`Default: false` | | | `onIndeterminateChange` | `function` - (indeterminate: boolean) => void | A callback that is fired when the indeterminate state changes.`Default:  —— undefined` | | | `value` | `string` | The value of the checkbox item when used in a `*Menu.CheckboxGroup`.`Default:  —— undefined` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `closeOnSelect` | `boolean` | Whether or not the menu item should close when selected.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { checked: boolean; indeterminate: boolean; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; checked: boolean; indeterminate: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------------- | ---------------------------------------------------- | ------------------------------------------ | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-state` | `enum` - 'checked' \| 'unchecked' \| 'indeterminate' | The checkbox menu item's checked state. | | | `data-dropdown-menu-checkbox-item` | `''` | Present on the checkbox item element. | | ### DropdownMenu.RadioGroup A group of radio menu items, where only one can be checked at a time. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string` | The value of the currently checked radio menu item.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: string) => void | A callback that is fired when the radio group's value changes.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------------- | ----- | ----------------------------------- | ------- | | `data-dropdown-menu-radio-group` | `''` | Present on the radio group element. | | ### DropdownMenu.RadioItem A menu item that can be controlled and toggled like a radio button. It must be a child of a `RadioGroup`. | Property | Type | Description | Details | | ---------------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` required | `string` | The value of the radio item. When checked, the parent `RadioGroup`'s value will be set to this value.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the radio menu item is disabled. Disabled items cannot be interacted with and are skipped when navigating with the keyboard.`Default: false` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `closeOnSelect` | `boolean` | Whether or not the menu item should close when selected.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { checked: boolean; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; checked: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | --------------------------------- | ------------------------------------------ | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-state` | `enum` - 'checked' \| 'unchecked' | The radio menu item's checked state. | | | `data-value` | `''` | The value of the radio item. | | | `data-dropdown-menu-radio-item` | `''` | Present on the radio item element. | | ### DropdownMenu.Separator A horizontal line to visually separate menu items. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------ | ---------- | --------------------------------- | ------- | | `data-orientation` | `vertical` | The orientation of the separator. | | | `data-menu-separator` | `''` | Present on the separator element. | | | `data-dropdown-menu-separator` | `''` | Present on the separator element. | | ### DropdownMenu.Arrow An optional arrow which points to the dropdown menu's anchor/trigger point. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `width` | `number` | The width of the arrow in pixels.`Default: 8` | | | `height` | `number` | The height of the arrow in pixels.`Default: 8` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-dropdown-menu-arrow` | `''` | Present on the arrow element. | | ### DropdownMenu.Group A group of menu items. It should be passed an `aria-label` or have a child `DropdownMenu.GroupHeading` component to provide a label for a group of menu items. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | ----- | ----------------------------- | ------- | | `data-dropdown-menu-group` | `''` | Present on the group element. | | ### DropdownMenu.GroupHeading A heading for a group which will be skipped when navigating with the keyboard. It is used to provide a description for a group of menu items and must be a child of either a `DropdownMenu.Group` or `DropdownMenu.RadioGroup` component. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------------- | ----- | ------------------------------------- | ------- | | `data-dropdown-menu-group-heading` | `''` | Present on the group heading element. | | ### DropdownMenu.Sub A submenu belonging to the parent dropdown menu. Responsible for managing the state of the submenu. | Property | Type | Description | Details | | ---------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------- | | `open` $bindable | `boolean` | The open state of the submenu.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### DropdownMenu.SubTrigger A menu item which when pressed or hovered, opens the submenu it is a child of. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the submenu trigger is disabled.`Default: false` | | | `openDelay` | `number` | The amount of time in ms from when the mouse enters the subtrigger until the submenu opens.`Default: 100` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-dropdown-menu-sub-trigger` | `''` | Present on the submenu trigger element. | | ### DropdownMenu.SubContent The submenu content displayed when the parent submenu is open. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not to loop through the menu items in when navigating with the keyboard.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-dropdown-menu-sub-content` | `''` | Present on the submenu content element. | | ### DropdownMenu.SubContentStatic The submenu content displayed when the parent submenu menu is open. (Static/No Floating UI) | Property | Type | Description | Details | | ------------------------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not to loop through the menu items when reaching the end of the list when using the keyboard.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { open: boolean; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-dropdown-menu-sub-content` | `''` | Present on the submenu content element. | | [Previous Dialog](/docs/components/dialog) [Next Label](/docs/components/label) ---------------------------------------------------- # Label Documentation Identifies or describes associated UI elements. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
{#snippet children({ checked, indeterminate })}
{#if indeterminate} {:else if checked} {/if}
{/snippet}
Accept terms and conditions
``` ## Structure ```svelte ``` ## API Reference ### Label.Root An enhanced label component that can be used with any input. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLLabelElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------- | ----- | ---------------------------- | ------- | | `data-label-root` | `''` | Present on the root element. | | [Previous Dropdown Menu](/docs/components/dropdown-menu) [Next Link Preview](/docs/components/link-preview) ---------------------------------------------------- # Link Preview Documentation Displays a summarized preview of a linked content's details or information. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
HB
HB

@huntabyte

I do things on the internet.

FL, USA
Joined May 2020
``` ## Overview A component that lets users preview a link before they decide to follow it. This is useful for providing non-essential context or additional information about a link without having to navigate away from the current page. ##### A note about mobile devices! This component is only intended to be used with a mouse or other pointing device. It doesn't respond to touch events, and the preview content cannot be accessed via the keyboard. On touch devices, the link will be followed immediately. As it is not accessible to all users, the preview should not contain vital information. ## Structure ```svelte ``` ## Managing Open State This section covers how to manage the `open` state of the component. ### Two-Way Binding Use `bind:open` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Opt-out of Floating UI When you use the `LinkPreview.Content` component, Bits UI uses [Floating UI](https://floating-ui.com/) to position the content relative to the trigger, similar to other popover-like components. You can opt-out of this behavior by instead using the `LinkPreview.ContentStatic` component. This component does not use Floating UI and leaves positioning the content entirely up to you. ```svelte ``` ##### Heads up! The `LinkPreview.Arrow` component is designed to be used with Floating UI and `LinkPreview.Content`, so you may experience unexpected behavior if you attempt to use it with `LinkPreview.ContentStatic`. ## Custom Anchor By default, the `LinkPreview.Content` is anchored to the `LinkPreview.Trigger` component, which determines where the content is positioned. If you wish to instead anchor the content to a different element, you can pass either a selector `string` or an `HTMLElement` to the `customAnchor` prop of the `LinkPreview.Content` component. ```svelte
``` ## Svelte Transitions You can use the `forceMount` prop along with the `child` snippet to forcefully mount the `LinkPreview.Content` component to use Svelte Transitions or another animation library that requires more control. ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
{/if} {/snippet}
``` Of course, this isn't the prettiest syntax, so it's recommended to create your own reusable content component that handles this logic if you intend to use this approach. For more information on using transitions with Bits UI components, see the [Transitions](/docs/transitions) documentation. Expand Code ```svelte
HB
{#snippet child({ open, props, wrapperProps })} {#if open}
HB

@huntabyte

I do things on the internet.

FL, USA
Joined May 2020
{/if} {/snippet}
``` ## API Reference ### LinkPreview\.Root The root component used to manage the state of the state of the link preview. | Property | Type | Description | Details | | ------------------------ | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------- | | `open` $bindable | `boolean` | The open state of the link preview component.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `openDelay` | `number` | The amount of time in milliseconds to delay opening the preview when hovering over the trigger.`Default: 700` | | | `closeDelay` | `number` | The amount of time in milliseconds to delay closing the preview when the mouse leaves the trigger.`Default: 300` | | | `disabled` | `boolean` | Whether or not the link preview is disabled.`Default: false` | | | `ignoreNonKeyboardFocus` | `boolean` | Whether the link preview should ignore non-keyboard focus.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### LinkPreview\.Trigger A component which triggers the opening and closing of the link preview on hover or focus. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLAnchorElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | --------------------------- | --------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | Whether the accordion item is open or closed. | | | `data-link-preview-trigger` | `''` | Present on the trigger element. | | ### LinkPreview\.Content The contents of the link preview which are displayed when the preview is open. | Property | Type | Description | Details | | ------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | --------------------------- | --------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | Whether the accordion item is open or closed. | | | `data-link-preview-content` | `''` | Present on the content element. | | | CSS Variable | Description | Details | | ---------------------------------------------- | -------------------------------------------- | ------- | | `--bits-link-preview-content-transform-origin` | The transform origin of the content element. | | | `--bits-link-preview-content-available-width` | The available width of the content element. | | | `--bits-link-preview-content-available-height` | The available height of the content element. | | | `--bits-link-preview-anchor-width` | The width of the anchor element. | | | `--bits-link-preview-anchor-height` | The height of the anchor element. | | ### LinkPreview\.ContentStatic The contents of the link preview which are displayed when the preview is open. (Static/No Floating UI) | Property | Type | Description | Details | | ------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | --------------------------- | --------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | Whether the accordion item is open or closed. | | | `data-link-preview-content` | `''` | Present on the content element. | | ### LinkPreview\.Arrow An optional arrow element which points to the trigger when the preview is open. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `width` | `number` | The width of the arrow in pixels.`Default: 8` | | | `height` | `number` | The height of the arrow in pixels.`Default: 8` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----- | ----------------------------- | ------- | | `data-link-preview-arrow` | `''` | Present on the arrow element. | | ### LinkPreview\.Portal When used, will render the link preview content into the body or custom `to` element when open | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | [Previous Label](/docs/components/label) [Next Menubar](/docs/components/menubar) ---------------------------------------------------- # Menubar Documentation A horizontal bar containing a collection of menus. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
File {#each grids as grid (grid.label)} {#snippet children({ checked })} {grid.label} grid
{#if checked} {@render SwitchOn()} {:else} {@render SwitchOff()} {/if}
{/snippet}
{/each} {#each views as view, i (view.label + i)} {#snippet children({ checked })} {view.label}
{#if checked} {/if}
{/snippet}
{/each}
Edit Undo Redo Find
Search the web Find... Find Next Find Previous
Cut Copy Paste
View {#each showConfigs as config, i (config.label + i)} {#snippet children({ checked })} {config.label}
{#if checked} {@render SwitchOn()} {:else} {@render SwitchOff()} {/if}
{/snippet}
{/each} Reload Force Reload Toggle Fullscreen Hide Sidebar
Profiles {#each profiles as profile, i (profile.label + i)} {#snippet children({ checked })} {profile.label}
{#if checked} {/if}
{/snippet}
{/each}
Edit... Add Profile...
{#snippet SwitchOn()}
{/snippet} {#snippet SwitchOff()}
{/snippet} ``` ## Structure ```svelte {#snippet children({ checked })} {checked ? "✅" : ""} {/snippet} {#snippet children({ checked })} {checked ? "✅" : ""} {/snippet} ``` ## Reusable Components If you're planning to use Menubar in multiple places, you can create reusable components that wrap the different parts of the Menubar. In the following example, we're creating a reusable `MyMenubarMenu` component that contains the trigger, content, and items of a menu. MyMenubarMenu.svelte ```svelte {triggerText} {#each items as item} {item.label} {/each} ``` Now, we can use the `MyMenubarMenu` component within a `Menubar.Root` component to render out the various menus. ```svelte {#each menubarMenus as { title, items }} {/each} ``` ## Managing Value State This section covers how to manage the `value` state of the menubar. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Radio Groups You can combine the `Menubar.RadioGroup` and `Menubar.RadioItem` components to create a radio group within a menu. ```svelte {#each values as value} {#snippet children({ checked })} {#if checked} ✅ {/if} {value} {/snippet} {/each} ``` ## Checkbox Items You can use the `Menubar.CheckboxItem` component to create a `menuitemcheckbox` element to add checkbox functionality to menu items. ```svelte {#snippet children({ checked, indeterminate })} {#if indeterminate} - {:else if checked} ✅ {/if} Notifications {/snippet} ``` ## Checkbox Groups You can use the `Menubar.CheckboxGroup` component around a set of `Menubar.CheckboxItem` components to create a checkbox group within a menu, where the `value` prop is an array of the selected values. ```svelte Favorite color {#snippet children({ checked })} {#if checked} ✅ {/if} Red {/snippet} {#snippet children({ checked })} {#if checked} ✅ {/if} Blue {/snippet} {#snippet children({ checked })} {#if checked} ✅ {/if} Green {/snippet} ``` The `value` state does not persist between menu open/close cycles. To persist the state, you must store it in a `$state` variable and pass it to the `value` prop. ## Nested Menus You can create nested menus using the `Menubar.Sub` component to create complex menu structures. ```svelte Item 1 Item 2 Open Sub Menu Sub Item 1 Sub Item 2 ``` ## Svelte Transitions You can use the `forceMount` prop along with the `child` snippet to forcefully mount the `Menubar.Content` component to use Svelte Transitions or another animation library that requires more control. ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
Item 1 Item 2
{/if} {/snippet}
``` Of course, this isn't the prettiest syntax, so it's recommended to create your own reusable content component that handles this logic if you intend to use this approach. For more information on using transitions with Bits UI components, see the [Transitions](/docs/transitions) documentation. ## API Reference ### Menubar.Root The root menubar component which manages & scopes the state of the menubar. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string` | The value of the currently active menu.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: string) => void | A callback function called when the active menu value changes.`Default:  —— undefined` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not to loop through the menubar menu triggers when navigating with the keyboard.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | ### Menubar.Menu A menu within the menubar. | Property | Type | Description | Details | | -------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` | `string` | The value of this menu within the menubar, used to identify it when determining which menu is active.`Default:  —— undefined` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### Menubar.Trigger The button element which toggles the dropdown menu. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the menu trigger is disabled.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-menubar-trigger` | `''` | Present on the trigger element. | | ### Menubar.Portal A component that portals the content of the dropdown menu to the body or a custom target (if provided). | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### Menubar.Content The content displayed when the dropdown menu is open. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not to loop through the menu items in when navigating with the keyboard.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-menubar-content` | `''` | Present on the content element. | | | CSS Variable | Description | Details | | ---------------------------------------------- | -------------------------------------------- | ------- | | `--bits-menubar-menu-content-transform-origin` | The transform origin of the content element. | | | `--bits-menubar-menu-content-available-width` | The available width of the content element. | | | `--bits-menubar-menu-content-available-height` | The available height of the content element. | | | `--bits-menubar-menu-anchor-width` | The width of the anchor element. | | | `--bits-menubar-menu-anchor-height` | The height of the anchor element. | | ### Menubar.Item A menu item within the dropdown menu. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the menu item is disabled.`Default: false` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `closeOnSelect` | `boolean` | Whether or not the menu item should close when selected.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ---------- | ------------------------------------------ | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-menubar-item` | `''` | Present on the item element. | | ### Menubar.CheckboxGroup A group of checkbox menu items, where multiple can be checked at a time. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string[]` | The value of the group. This is an array of the values of the checked checkboxes within the group.`Default: []` | | | `onValueChange` | `function` - (value: string\[]) => void | A callback that is fired when the checkbox group's value state changes.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | -------------------------------------- | ------- | | `data-menubar-checkbox-group` | `''` | Present on the checkbox group element. | | ### Menubar.CheckboxItem A menu item that can be controlled and toggled like a checkbox. | Property | Type | Description | Details | | ------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the checkbox menu item is disabled. Disabled items cannot be interacted with and are skipped when navigating with the keyboard.`Default: false` | | | `checked` $bindable | `boolean` | The checked state of the checkbox.`Default: false` | | | `onCheckedChange` | `function` - (checked: boolean) => void | A callback that is fired when the checked state changes.`Default:  —— undefined` | | | `indeterminate` $bindable | `boolean` | The indeterminate state of the checkbox.`Default: false` | | | `onIndeterminateChange` | `function` - (indeterminate: boolean) => void | A callback that is fired when the indeterminate state changes.`Default:  —— undefined` | | | `value` | `string` | The value of the checkbox item when used in a `*Menu.CheckboxGroup`.`Default:  —— undefined` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `closeOnSelect` | `boolean` | Whether or not the menu item should close when selected.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { checked: boolean; indeterminate: boolean; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; checked: boolean; indeterminate: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | ---------------------------------------------------- | ------------------------------------------ | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-state` | `enum` - 'checked' \| 'unchecked' \| 'indeterminate' | The checkbox menu item's checked state. | | | `data-menubar-checkbox-item` | `''` | Present on the checkbox item element. | | ### Menubar.RadioGroup A group of radio menu items, where only one can be checked at a time. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string` | The value of the currently checked radio menu item.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: string) => void | A callback that is fired when the radio group's value changes.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | ----- | ----------------------------------- | ------- | | `data-menubar-radio-group` | `''` | Present on the radio group element. | | ### Menubar.RadioItem A menu item that can be controlled and toggled like a radio button. It must be a child of a `RadioGroup`. | Property | Type | Description | Details | | ---------------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` required | `string` | The value of the radio item. When checked, the parent `RadioGroup`'s value will be set to this value.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the radio menu item is disabled. Disabled items cannot be interacted with and are skipped when navigating with the keyboard.`Default: false` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `closeOnSelect` | `boolean` | Whether or not the menu item should close when selected.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { checked: boolean; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; checked: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | --------------------------------- | ------------------------------------------ | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-state` | `enum` - 'checked' \| 'unchecked' | The radio menu item's checked state. | | | `data-value` | `''` | The value of the radio item. | | | `data-menubar-radio-item` | `''` | Present on the radio item element. | | ### Menubar.Separator A horizontal line to visually separate menu items. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ---------- | --------------------------------- | ------- | | `data-orientation` | `vertical` | The orientation of the separator. | | | `data-menu-separator` | `''` | Present on the separator element. | | | `data-menubar-separator` | `''` | Present on the separator element. | | ### Menubar.Arrow An optional arrow which points to the dropdown menu's anchor/trigger point. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `width` | `number` | The width of the arrow in pixels.`Default: 8` | | | `height` | `number` | The height of the arrow in pixels.`Default: 8` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-menubar-arrow` | `''` | Present on the arrow element. | | ### Menubar.Group A group of menu items. It should be passed an `aria-label` or have a child `Menu.GroupHeading` component to provide a label for a group of menu items. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----- | ----------------------------- | ------- | | `data-menubar-group` | `''` | Present on the group element. | | ### Menubar.GroupHeading A heading for a group which will be skipped when navigating with the keyboard. It is used to provide a heading for a group of menu items and must be a child of either a `Menubar.Group` or `Menubar.RadioGroup` component. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | ----- | ------------------------------------- | ------- | | `data-menubar-group-heading` | `''` | Present on the group heading element. | | ### Menubar.Sub A submenu belonging to the parent dropdown menu. Responsible for managing the state of the submenu. | Property | Type | Description | Details | | ---------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------- | | `open` $bindable | `boolean` | The open state of the submenu.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### Menubar.SubTrigger A menu item which when pressed or hovered, opens the submenu it is a child of. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the submenu trigger is disabled.`Default: false` | | | `openDelay` | `number` | The amount of time in ms from when the mouse enters the subtrigger until the submenu opens.`Default: 100` | | | `textValue` | `string` | The text value of the checkbox menu item. This is used for typeahead.`Default:  —— undefined` | | | `onSelect` | `function` - () => void | A callback that is fired when the menu item is selected.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-orientation` | `vertical` | The orientation of the menu. | | | `data-highlighted` | `''` | Present when the menu item is highlighted. | | | `data-disabled` | `''` | Present when the menu item is disabled. | | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-menubar-sub-trigger` | `''` | Present on the submenu trigger element. | | ### Menubar.SubContent The submenu content displayed when the parent submenu is open. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not to loop through the menu items in when navigating with the keyboard.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-menubar-sub-content` | `''` | Present on the submenu content element. | | ### Menubar.SubContentStatic The submenu content displayed when the parent submenu menu is open. (Static/No Floating UI) | Property | Type | Description | Details | | ------------------------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not to loop through the menu items when reaching the end of the list when using the keyboard.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { open: boolean; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | --------------------------- | ------------------------------------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The open state of the menu or submenu the element controls or belongs to. | | | `data-menubar-sub-content` | `''` | Present on the submenu content element. | | [Previous Link Preview](/docs/components/link-preview) [Next Meter](/docs/components/meter) ---------------------------------------------------- # Meter Documentation Displays a static measurement within a known range. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
Tokens used {value} / {max}
``` While often visually similar, meters and [Progress](/docs/components/progress) bars serve distinct purposes: **Meter**: - Displays a **static measurement** within a known range (0-100) - Value can fluctuate up/down based on real-time measurements - Examples: CPU usage, battery level, sound volume - Use when showing current state relative to capacity **Progress bar**: - Shows **completion status** of a task - Value only increases as task progresses - Examples: File upload, installation status, form completion - Use when tracking advancement toward completion If a progress bar better fits your requirements, check out the [Progress](/docs/components/progress) component. ## Structure ```svelte ``` ## Reusable Components It's recommended to use the `Meter` primitive to create your own custom meter component that can be used throughout your application. In the example below, we're using the `Meter` primitive to create a more comprehensive meter component. ```svelte
{label} {valueLabel}
``` You can then use the `MyMeter` component in your application like so: +page.svelte ```svelte ``` Of course, you'd want to apply your own styles and other customizations to the `MyMeter` component to fit your application's design. ## Accessibility If a visual label is used, the ID of the label element should be pass via the `aria-labelledby` prop to `Meter.Root`. If no visual label is used, the `aria-label` prop should be used to provide a text description of the progress bar. Assistive technologies often present `aria-valuenow` as a percentage. If conveying the value of the meter only in terms of a percentage would not be user friendly, the `aria-valuetext` property should be set to a string that makes the meter value understandable. For example, a battery meter value might be conveyed as `aria-valuetext="50% (6 hours) remaining"`. \[[source](https://www.w3.org/WAI/ARIA/apg/patterns/meter/)] ## API Reference ### Meter.Root The meter component. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `max` | `number` | The maximum value of the meter.`Default: 100` | | | `min` | `number` | The minimum value of the meter.`Default: 0` | | | `value` | `number` | The current value of the meter.`Default: 0` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------- | ----- | ------------------------------- | ------- | | `data-value` | `''` | The current value of the meter. | | | `data-min` | `''` | The minimum value of the meter. | | | `data-max` | `''` | The maximum value of the meter. | | | `data-meter-root` | `''` | Present on the root element. | | [Previous Menubar](/docs/components/menubar) [Next Navigation Menu](/docs/components/navigation-menu) ---------------------------------------------------- # Navigation Menu Documentation A menu that allows users to navigate between pages of a website. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte {#snippet ListItem({ className, title, content, href }: ListItemProps)}
  • {title}

    {content}

  • {/snippet} Getting started
    • Bits UI

      The headless components for Svelte.

    • {@render ListItem({ href: "/docs", title: "Introduction", content: "Headless components for Svelte and SvelteKit" })} {@render ListItem({ href: "/docs/getting-started", title: "Getting Started", content: "How to install and use Bits UI" })} {@render ListItem({ href: "/docs/styling", title: "Styling", content: "How to style Bits UI components" })}
    Components
      {#each components as component (component.title)} {@render ListItem({ href: component.href, title: component.title, content: component.description })} {/each}
    Docs
    ``` ## Structure ```svelte ``` ## Usage ### Vertical You can create a vertical menu by using the `orientation` prop. ```svelte ``` ### Flexible Layouts Use the `Viewport` component when you need extra control over where `Content` is rendered. This can be useful when your design requires an adjusted DOM structure or if you need flexibility to achieve advanced animations. Tab focus will be managed automatically. ```svelte Item one Item one content Item two Item two content ``` ### With Indicator You can use the optional `Indicator` component to highlight the currently active `Trigger`, which is useful when you want to provide an animated visual cue such as an arrow or highlight to accompany the `Viewport`. ```svelte Item one Item one content Item two Item two content ``` ### Submenus You can create a submenu by nesting your navigation menu and using the `Navigation.Sub` component in place of `NavigationMenu.Root`. ```svelte Item one Subitem one Subitem one content ``` ### Submenus with Viewport You can use the `NavigationMenu.Viewport` component inside of a `NavigationMenu.Sub` to create a viewport dedicated to that submenu. ```svelte Item one Item one content Item two Item two content ``` ### No Viewport The `NavigationMenu.Viewport` component provides a way to transition between `NavigationMenu.Content` without the need for a full close/open animation between them, however, this is completely optional and you don't need to use it. Expand Code ```svelte {#snippet ListItem({ className, title, content, href }: ListItemProps)}
  • {title}

    {content}

  • {/snippet} Getting started
    • Bits UI

      The headless components for Svelte.

    • {@render ListItem({ href: "/docs", title: "Introduction", content: "Headless components for Svelte and SvelteKit" })} {@render ListItem({ href: "/docs/getting-started", title: "Getting Started", content: "How to install and use Bits UI" })} {@render ListItem({ href: "/docs/styling", title: "Styling", content: "How to style Bits UI components" })}
    Components
      {#each components as component (component.title)} {@render ListItem({ href: component.href, title: component.title, content: component.description })} {/each}
    Docs
    ``` ### Advanced Animation We expose `--bits-navigation-menu-viewport-[width|height]` and `data-motion['from-start'|'to-start'|'from-end'|'to-end']` to allow you to animate the `NavigationMenu.Viewport` size and `NavigationMenu.Content` position based on the enter/exit direction. Combining these with `position: absolute;` allows you to create smooth overlapping animation effects when moving between items. ```svelte Item one Item one content Item two Item two content ``` ```css /* app.css */ .NavigationMenuContent { position: absolute; top: 0; left: 0; animation-duration: 250ms; animation-timing-function: ease; } .NavigationMenuContent[data-motion="from-start"] { animation-name: enter-from-left; } .NavigationMenuContent[data-motion="from-end"] { animation-name: enter-from-right; } .NavigationMenuContent[data-motion="to-start"] { animation-name: exit-to-left; } .NavigationMenuContent[data-motion="to-end"] { animation-name: exit-to-right; } .NavigationMenuViewport { position: relative; width: var(--bits-navigation-menu-viewport-width); height: var(--bits-navigation-menu-viewport-height); transition: width, height, 250ms ease; } @keyframes enter-from-right { from { opacity: 0; transform: translateX(200px); } to { opacity: 1; transform: translateX(0); } } @keyframes enter-from-left { from { opacity: 0; transform: translateX(-200px); } to { opacity: 1; transform: translateX(0); } } @keyframes exit-to-right { from { opacity: 1; transform: translateX(0); } to { opacity: 0; transform: translateX(200px); } } @keyframes exit-to-left { from { opacity: 1; transform: translateX(0); } to { opacity: 0; transform: translateX(-200px); } } ``` ### Force Mounting You may wish for the links in the Navigation Menu to persist in the DOM, regardless of whether the menu is open or not. This is particularly useful for SEO purposes. You can achieve this by using the `forceMount` prop on the `NavigationMenu.Content` and `NavigationMenu.Viewport` components. ##### Warning **Note:** Using `forceMount` requires you to manage the visibility of the elements yourself, using the `data-state` attributes on the `NavigationMenu.Content` and `NavigationMenu.Viewport` components. ```svelte ``` Expand Code ```svelte {#snippet ListItem({ className, title, content, href }: ListItemProps)}
  • {title}

    {content}

  • {/snippet} Getting started
    • Bits UI

      The headless components for Svelte.

    • {@render ListItem({ href: "/docs", title: "Introduction", content: "Headless components for Svelte and SvelteKit" })} {@render ListItem({ href: "/docs/getting-started", title: "Getting Started", content: "How to install and use Bits UI" })} {@render ListItem({ href: "/docs/styling", title: "Styling", content: "How to style Bits UI components" })}
    Components
      {#each components as component (component.title)} {@render ListItem({ href: component.href, title: component.title, content: component.description })} {/each}
    Docs
    ``` ### Open on Hover By default, the `NavigationMenu.Item` will open its `NavigationMenu.Content` when the `NavigationMenu.Trigger` is hovered. You can disable this by passing `openOnHover={false}` to the `NavigationMenu.Item`. ##### Note Unlike the default behavior, when `openOnHover` is `false`, the menu will not close when the pointer moves outside of the `NavigationMenu.Content` and will instead require the user to interact outside of the menu or press escape to close it. ```svelte Item one Item one content ``` Expand Code ```svelte {#snippet ListItem({ className, title, content, href }: ListItemProps)}
  • {title}

    {content}

  • {/snippet} Getting started
    • Bits UI

      The headless components for Svelte.

    • {@render ListItem({ href: "/docs", title: "Introduction", content: "Headless components for Svelte and SvelteKit" })} {@render ListItem({ href: "/docs/getting-started", title: "Getting Started", content: "How to install and use Bits UI" })} {@render ListItem({ href: "/docs/styling", title: "Styling", content: "How to style Bits UI components" })}
    Components
      {#each components as component (component.title)} {@render ListItem({ href: component.href, title: component.title, content: component.description })} {/each}
    Docs
    ``` ## API Reference ### NavigationMenu.Root The root navigation menu component which manages & scopes the state of the navigation menu. | Property | Type | Description | Details | | ------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string` | The value of the currently active menu.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: string) => void | A callback function called when the active menu value changes. Called with an empty string when the menu closes.`Default:  —— undefined` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `skipDelayDuration` | `number` | How much time a user has to enter another trigger without incurring a delay again.`Default: 300` | | | `delayDuration` | `number` | The duration from when the mouse enters a trigger until the content opens.`Default: 200` | | | `orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the menu.`Default: 'horizontal'` | | | `ref` $bindable | `HTMLNavElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | ### NavigationMenu.Sub A sub navigation menu component which manages & scopes the state of a submenu, inside the content of a Root menu. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string` | The value of the currently active submenu.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: string) => void | A callback function called when the active menu value changes.`Default:  —— undefined` | | | `orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the menu.`Default: 'horizontal'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | ### NavigationMenu.List A menu within the menubar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLUListElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | ### NavigationMenu.Item A list item within the navigation menu. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `value` | `string` | The value of the item.`Default:  —— undefined` | | | `openOnHover` | `boolean` | Whether or not the item should open its content when the trigger is hovered. Note: When `false`, the menu will not close when the pointer moves outside of the content and will instead require the user to interact outside of the menu or press escape to close it.`Default: true` | | | `ref` $bindable | `HTMLLiElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | ### NavigationMenu.Trigger The button element which toggles the dropdown menu. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the trigger is disabled.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | ### NavigationMenu.Content The content displayed when the dropdown menu is open. | Property | Type | Description | Details | | ------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | ### NavigationMenu.Link A link within the navigation menu. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `active` | `boolean` | Whether or not the link is active.`Default: false` | | | `onSelect` | `function` - () => void | A callback function called when the link is selected.`Default:  —— undefined` | | | `ref` $bindable | `HTMLAnchorElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | ### NavigationMenu.Viewport An optional viewport element for the navigation menu, which renders the content of the menu items if it is present. The content is rendered in place without it. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | ### NavigationMenu.Indicator The indicator element for the navigation menu, which is used to indicate the current active item. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | [Previous Meter](/docs/components/meter) [Next Pagination](/docs/components/pagination) ---------------------------------------------------- # Pagination Documentation Enables users to navigate through a series of pages. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte {#snippet children({ pages, range })}
    {#each pages as page (page.key)} {#if page.type === "ellipsis"}
    ...
    {:else} {page.value} {/if} {/each}

    Showing {range.start} - {range.end}

    {/snippet}
    ``` ## Structure ```svelte {#each pages as page (page.key)} {/each} ``` ## Managing Page State This section covers how to manage the `page` state of the component. ### Two-Way Binding Use `bind:page` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Ellipsis The `pages` snippet prop consists of two types of items: `'page'` and `'ellipsis'`. The `'page'` type represents an actual page number, while the `'ellipsis'` type represents a placeholder for rendering an ellipsis between pages. ## API Reference ### Pagination.Root The root pagination component which contains all other pagination components. | Property | Type | Description | Details | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `count` required | `number` | The total number of items.`Default:  —— undefined` | | | `page` $bindable | `number` | The selected page. You can bind this to a variable to control the selected page from outside the component.`Default:  —— undefined` | | | `onPageChange` | `function` - (page: number) => void | A function called when the selected page changes.`Default:  —— undefined` | | | `perPage` | `number` | The number of items per page.`Default: 1` | | | `siblingCount` | `number` | The number of page triggers to show on either side of the current page.`Default: 1` | | | `loop` | `boolean` | Whether or not the pagination should loop through the items when reaching the end while navigating with the keyboard.`Default: false` | | | `orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the pagination. This determines how keyboard navigation will work with the component.`Default: 'horizontal'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type Page = { type: "page"; value: number; }; type Ellipsis = { type: "ellipsis"; }; type PageItem = (Page \| Ellipsis) & { /\*\* A unique key to be used as the key in a svelte #each block. \*/ key: string; }; type ChildrenSnippetProps = { /\*\* The items to iterate over and render for the pagination component \*/ pages: PageItem\[]; /\*\* The range of pages to render \*/ range: { start: number; end: number }; /\*\* The currently active page \*/ currentPage: number; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type Page = { type: "page"; value: number; }; type Ellipsis = { type: "ellipsis"; }; type PageItem = (Page \| Ellipsis) & { /\*\* A unique key to be used as the key in a svelte #each block. \*/ key: string; }; type ChildSnippetProps = { /\*\* The items to iterate over and render for the pagination component \*/ pages: PageItem\[]; /\*\* The range of pages to render \*/ range: { start: number; end: number }; /\*\* The currently active page \*/ currentPage: number; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | ### Pagination.Page A button that triggers a page change. | Property | Type | Description | Details | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `page` | `PageItem` - export type Page = { type: "page"; /\*\* The page number the 'PageItem' represents \*/ value: number; } export type Ellipsis = { type: "ellipsis"; } export type PageItem = (Page \| Ellipsis) & { /\*\* Unique key for the item, for svelte #each block \*/ key: string; } | The page item this component represents.`Default:  —— undefined` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | ----- | ------------------------------------ | ------- | | `data-selected` | `''` | Present on the current page element. | | | `data-pagination-page` | `''` | Present on the page trigger element. | | ### Pagination.PrevButton The previous button of the pagination. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | --------------------------------------- | ------- | | `data-pagination-prev-button` | `''` | Present on the previous button element. | | ### Pagination.NextButton The next button of the pagination. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | ----------------------------------- | ------- | | `data-pagination-next-button` | `''` | Present on the next button element. | | [Previous Navigation Menu](/docs/components/navigation-menu) [Next PIN Input](/docs/components/pin-input) ---------------------------------------------------- # PIN Input Documentation Enables users to input a sequence of one-character inputs. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte {#snippet children({ cells })}
    {#each cells.slice(0, 3) as cell, i (i)} {@render Cell(cell)} {/each}
    {#each cells.slice(3, 6) as cell, i (i)} {@render Cell(cell)} {/each}
    {/snippet}
    {#snippet Cell(cell: CellProps)} {#if cell.char !== null}
    {cell.char}
    {/if} {#if cell.hasFakeCaret} {/if}
    {/snippet} ``` ## Overview The PIN Input component provides a customizable solution for One-Time Password (OTP), Two-Factor Authentication (2FA), or Multi-Factor Authentication (MFA) input fields. Due to the lack of a native HTML element for these purposes, developers often resort to either basic input fields or custom implementations. This component offers a robust, accessible, and flexible alternative. ##### Credits This component is derived from and would not have been possible without the work done by [Guilherme Rodz](https://x.com/guilhermerodz) with [Input OTP](https://github.com/guilhermerodz/input-otp). ## Key Features - **Invisible Input Technique**: Utilizes an invisible input element for seamless integration with form submissions and browser autofill functionality. - **Customizable Appearance**: Allows for custom designs while maintaining core functionality. - **Accessibility**: Ensures keyboard navigation and screen reader compatibility. - **Flexible Configuration**: Supports various PIN lengths and input types (numeric, alphanumeric). ## Architecture 1. **Root Container**: A relatively positioned root element that encapsulates the entire component. 2. **Invisible Input**: A hidden input field that manages the actual value and interacts with the browser's built-in features. 3. **Visual Cells**: Customizable elements representing each character of the PIN, rendered as siblings to the invisible input. This structure allows for a seamless user experience while providing developers with full control over the visual representation. ## Structure ```svelte {#snippet children({ cells })} {#each cells as cell} {/each} {/snippet} ``` ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Paste Transformation The `pasteTransformer` prop allows you to sanitize/transform pasted text. This can be useful for cleaning up pasted text, like removing hyphens or other characters that should not make it into the input. This function should return the sanitized text, which will be used as the new value of the input. ```svelte text.replace(/-/g, "")}> ``` ## HTML Forms The `PinInput.Root` component is designed to work seamlessly with HTML forms. Simply pass the `name` prop to the `PinInput.Root` component and the input will be submitted with the form. ### Submit On Complete To submit the form when the input is complete, you can use the `onComplete` prop. ```svelte
    form.submit()}>
    ``` ## Patterns You can use the `pattern` prop to restrict the characters that can be entered or pasted into the input. ##### Note! Client-side validation cannot replace server-side validation. Use this in addition to server-side validation for an improved user experience. Bits UI exports a few common patterns that you can import and use in your application. - `REGEXP_ONLY_DIGITS` - Only allow digits to be entered. - `REGEXP_ONLY_CHARS` - Only allow characters to be entered. - `REGEXP_ONLY_DIGITS_AND_CHARS` - Only allow digits and characters to be entered. ```svelte ``` ## API Reference ### PINInput.Root The pin input container component. | Property | Type | Description | Details | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string` | The value of the input.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: string) => void | A callback function that is called when the value of the input changes.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the pin input is disabled.`Default: false` | | | `textalign` | `enum` - 'left' \| 'center' \| 'right' | Where is the text located within the input. Affects click-holding or long-press behavior`Default: 'left'` | | | `maxlength` | `number` | The maximum length of the pin input.`Default: 6` | | | `onComplete` | `function` - (...args: any\[]) => void | A callback function that is called when the input is completely filled.`Default:  —— undefined` | | | `pasteTransformer` | `function` - (text: string) => string | A callback function that is called when the user pastes text into the input. It receives the pasted text as an argument and should return the sanitized text. Useful for cleaning up pasted text, like removing hyphens or other characters that should not make it into the input.`Default:  —— undefined` | | | `inputId` | `string` | Optionally provide an ID to apply to the hidden input element.`Default:  —— undefined` | | | `pushPasswordManagerStrategy` | `enum` - 'increase-width' \| 'none' | Enabled by default, it's an optional strategy for detecting Password Managers in the page and then shifting their badges to the right side, outside the input.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type PinInputCell = { /\*\* The character displayed in the cell. \*/ char: string \| null \| undefined; /\*\* Whether the cell is active. \*/ isActive: boolean; /\*\* Whether the cell has a fake caret. \*/ hasFakeCaret: boolean; }; type SnippetProps = { cells: PinInputCell\[]; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type PinInputCell = { /\*\* The character displayed in the cell. \*/ char: string \| null \| undefined; /\*\* Whether the cell is active. \*/ isActive: boolean; /\*\* Whether the cell has a fake caret. \*/ hasFakeCaret: boolean; }; type SnippetProps = { cells: PinInputCell\[]; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | ----- | ---------------------------- | ------- | | `data-pin-input-root` | `''` | Present on the root element. | | ### PINInput.Cell A single cell of the pin input. | Property | Type | Description | Details | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `cell` | `object` - type Cell = { /\*\* The character displayed in the cell. \*/ char: string \| null \| undefined; /\*\* Whether the cell is active. \*/ isActive: boolean; /\*\* Whether the cell has a fake caret. \*/ hasFakeCaret: boolean; } | The cell object provided by the `cells` snippet prop from the `PinInput.Root` component.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | ----- | ---------------------------------- | ------- | | `data-active` | `''` | Present when the cell is active. | | | `data-inactive` | `''` | Present when the cell is inactive. | | | `data-pin-input-cell` | `''` | Present on the cell element. | | [Previous Pagination](/docs/components/pagination) [Next Popover](/docs/components/popover) ---------------------------------------------------- # Popover Documentation Displays rich content in a floating panel anchored to a trigger element. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte Resize

    Resize image

    Resize your photos easily

    Width
    Height
    ``` ## Structure ```svelte ``` ## Managing Open State This section covers how to manage the `open` state of the component. ### Two-Way Binding Use `bind:open` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Focus ### Focus Trap By default, when a Popover is opened, focus will be trapped within that Popover. You can disable this behavior by setting the `trapFocus` prop to `false` on the `Popover.Content` component. ```svelte ``` ### Open Focus By default, when a Popover is opened, focus will be set to the first focusable element with the `Popover.Content`. This ensures that users navigating my keyboard end up somewhere within the Popover that they can interact with. You can override this behavior using the `onOpenAutoFocus` prop on the `Popover.Content` component. It's *highly* recommended that you use this prop to focus *something* within the Popover's content. You'll first need to cancel the default behavior of focusing the first focusable element by cancelling the event passed to the `onOpenAutoFocus` callback. You can then focus whatever you wish. ```svelte Open Popover { e.preventDefault(); nameInput?.focus(); }} > ``` ### Close Focus By default, when a Popover is closed, focus will be set to the trigger element of the Popover. You can override this behavior using the `onCloseAutoFocus` prop on the `Popover.Content` component. You'll need to cancel the default behavior of focusing the trigger element by cancelling the event passed to the `onCloseAutoFocus` callback, and then focus whatever you wish. ```svelte Open Popover { e.preventDefault(); nameInput?.focus(); }} > ``` ## Scroll Lock By default, when a Popover is opened, users can still scroll the body and interact with content outside of the Popover. If you wish to lock the body scroll and prevent users from interacting with content outside of the Popover, you can set the `preventScroll` prop to `true` on the `Popover.Content` component. ```svelte ``` ## Escape Keydown By default, when a Popover is open, pressing the `Escape` key will close the dialog. Bits UI provides a couple ways to override this behavior. ### escapeKeydownBehavior You can set the `escapeKeydownBehavior` prop to `'ignore'` on the `Popover.Content` component to prevent the dialog from closing when the `Escape` key is pressed. ```svelte ``` ### onEscapeKeydown You can also override the default behavior by cancelling the event passed to the `onEscapeKeydown` callback on the `Popover.Content` component. ```svelte e.preventDefault()}> ``` ## Interact Outside By default, when a Popover is open, pointer down events outside the content will close the popover. Bits UI provides a couple ways to override this behavior. ### interactOutsideBehavior You can set the `interactOutsideBehavior` prop to `'ignore'` on the `Popover.Content` component to prevent the dialog from closing when the user interacts outside the content. ```svelte ``` ### onInteractOutside You can also override the default behavior by cancelling the event passed to the `onInteractOutside` callback on the `Popover.Content` component. ```svelte e.preventDefault()}> ``` ## Custom Anchor By default, the `Popover.Content` is anchored to the `Popover.Trigger` component, which determines where the content is positioned. If you wish to instead anchor the content to a different element, you can pass either a selector `string` or an `HTMLElement` to the `customAnchor` prop of the `Popover.Content` component. ```svelte
    ``` ## Svelte Transitions You can use the `forceMount` prop along with the `child` snippet to forcefully mount the `Popover.Content` component to use Svelte Transitions or another animation library that requires more control. ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
    {/if} {/snippet}
    ``` Of course, this isn't the prettiest syntax, so it's recommended to create your own reusable content component that handles this logic if you intend to use this approach. For more information on using transitions with Bits UI components, see the [Transitions](/docs/transitions) documentation. Expand Code ```svelte Resize {#snippet child({ wrapperProps, props, open })} {#if open}

    Resize image

    Resize your photos easily

    Width
    Height
    {/if} {/snippet}
    ``` ## Overlay Component You can use the `Popover.Overlay` component to create an overlay behind the popover that appears when the popover is open. Expand Code ```svelte Resize

    Resize image

    Resize your photos easily

    Width
    Height
    ``` ## API Reference ### Popover.Root The root component used to manage the state of the state of the popover. | Property | Type | Description | Details | | ---------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------- | | `open` $bindable | `boolean` | The open state of the component.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### Popover.Trigger A component which toggles the opening and closing of the popover on press. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | --------------------------- | -------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | Whether the popover is open or closed. | | | `data-popover-trigger` | `''` | Present on the trigger element. | | ### Popover.Content The contents of the popover which are displayed when the popover is open. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: false` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | --------------------------- | -------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | Whether the popover is open or closed. | | | `data-popover-content` | `''` | Present on the content element. | | | CSS Variable | Description | Details | | ----------------------------------------- | -------------------------------------------- | ------- | | `--bits-popover-content-transform-origin` | The transform origin of the content element. | | | `--bits-popover-content-available-width` | The available width of the content element. | | | `--bits-popover-content-available-height` | The available height of the content element. | | | `--bits-popover-anchor-width` | The width of the anchor element. | | | `--bits-popover-anchor-height` | The height of the anchor element. | | ### Popover.ContentStatic The contents of the popover which are displayed when the popover is open. (Static/No Floating UI) | Property | Type | Description | Details | | ------------------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: false` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | --------------------------- | -------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | Whether the popover is open or closed. | | | `data-popover-content` | `''` | Present on the content element. | | ### Popover.Overlay An overlay that can be used to create a semi-transparent overlay behind the popover when open. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | --------------------------- | -------------------------------------- | ------- | | `data-popover-overlay` | `''` | Present on the overlay element. | | | `data-state` | `enum` - 'open' \| 'closed' | Whether the popover is open or closed. | | ### Popover.Close A button which closes the popover when pressed and is typically placed in the content. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----- | ---------------------------- | ------- | | `data-popover-close` | `''` | Present on the close button. | | ### Popover.Arrow An optional arrow element which points to the trigger when the popover is open. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `width` | `number` | The width of the arrow in pixels.`Default: 8` | | | `height` | `number` | The height of the arrow in pixels.`Default: 8` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----- | ----------------------------- | ------- | | `data-arrow` | `''` | Present on the arrow element. | | | `data-popover-arrow` | `''` | Present on the arrow element. | | ### Popover.Portal When used, will render the popover content into the body or custom `to` element when open | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | [Previous PIN Input](/docs/components/pin-input) [Next Progress](/docs/components/progress) ---------------------------------------------------- # Progress Documentation Shows the completion status of a task. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
    Uploading file... {Math.round(tween.current)}%
    ``` While often visually similar, progress bars and [Meters](/docs/components/meter) serve distinct purposes: **Progress**: - Shows **completion status** of a task - Value only increases as task progresses - Examples: File upload, installation status, form completion - Use when tracking advancement toward completion **Meter**: - Displays a **static measurement** within a known range (0-100) - Value can fluctuate up/down based on real-time measurements - Examples: CPU usage, battery level, sound volume - Use when showing current state relative to capacity If a meter better fits your requirements, check out the [Meter](/docs/components/meter) component. ## Structure ```svelte ``` ## Reusable Components It's recommended to use the `Progress` primitive to create your own custom meter component that can be used throughout your application. In the example below, we're using the `Progress` primitive to create a more comprehensive meter component. ```svelte
    {label} {valueLabel}
    ``` You can then use the `MyProgress` component in your application like so: +page.svelte ```svelte ``` Of course, you'd want to apply your own styles and other customizations to the `MyProgress` component to fit your application's design. ## Accessibility If a visual label is used, the ID of the label element should be pass via the `aria-labelledby` prop to `Progress.Root`. If no visual label is used, the `aria-label` prop should be used to provide a text description of the progress bar. ## API Reference ### Progress.Root The progress bar component. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `max` | `number` | The maximum value of the progress bar.`Default: 100` | | | `min` | `number` | The minimum value of the progress bar.`Default: 0` | | | `value` | `number \| null` | The current value of the progress bar. If set to `null` the progress bar will be indeterminate.`Default: 0` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----------------------------------------- | -------------------------------------- | ------- | | `data-value` | `''` | The current value of the progress bar. | | | `data-state` | `enum` - 'indeterminate' \| 'determinate' | The current state of the progress bar. | | | `data-min` | `''` | The minimum value of the progress bar. | | | `data-max` | `''` | The maximum value of the progress bar. | | | `data-indeterminate` | `''` | Present when the value is `null`. | | | `data-progress-root` | `''` | Present on the root element. | | [Previous Popover](/docs/components/popover) [Next Radio Group](/docs/components/radio-group) ---------------------------------------------------- # Radio Group Documentation Groups multiple radio items under a common name for form submission. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
    Amazing
    Average
    Terrible
    ``` ## Structure ```svelte {#snippet children({ checked })} {#if checked} ✅ {/if} {/snippet} ``` ## Reusable Components It's recommended to use the `RadioGroup` primitives to create your own custom components that can be used throughout your application. In the example below, we're creating a custom `MyRadioGroup` component that takes in an array of items and renders a radio group with those items along with a [`Label`](/docs/components/label) component for each item. MyRadioGroup.svelte ```svelte {#each items as item} {@const id = useId()}
    {#snippet children({ checked })} {#if checked} ✅ {/if} {/snippet} {item.label}
    {/each}
    ``` You can then use the `MyRadioGroup` component in your application like so: +page.svelte ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## HTML Forms If you set the `name` prop on the `RadioGroup.Root` component, a hidden input element will be rendered to submit the value of the radio group to a form. ```svelte ``` ### Required To make the hidden input element `required` you can set the `required` prop on the `RadioGroup.Root` component. ```svelte ``` ## Disabling Items You can disable a radio group item by setting the `disabled` prop to `true`. ```svelte Apple ``` ## Orientation The `orientation` prop is used to determine the orientation of the radio group, which influences how keyboard navigation will work. When the `orientation` is set to `'vertical'`, the radio group will navigate through the items using the `ArrowUp` and `ArrowDown` keys. When the `orientation` is set to `'horizontal'`, the radio group will navigate through the items using the `ArrowLeft` and `ArrowRight` keys. ```svelte ``` ## Examples ### Readonly When a radio group is readonly, users can focus and navigate through the items but cannot change the selection. This is useful for displaying information that should be visible but not editable. Expand Code ```svelte
    Amazing
    Average
    Terrible
    ``` ```svelte ``` ### Disabled When a radio group is disabled, users cannot interact with it at all. The entire group becomes non-focusable and non-interactive. Expand Code ```svelte
    Amazing
    Average
    Terrible
    ``` ```svelte ``` ## API Reference ### RadioGroup.Root The radio group component used to group radio items under a common name for form submission. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string` | The value of the currently selected radio item. You can bind to this value to control the radio group's value from outside the component.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: string) => void | A callback that is fired when the radio group's value changes.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the radio group is disabled. This prevents the user from interacting with it.`Default: false` | | | `required` | `boolean` | Whether or not the radio group is required.`Default: false` | | | `name` | `string` | The name of the radio group used in form submission. If provided, a hidden input element will be rendered to submit the value of the radio group.`Default:  —— undefined` | | | `loop` | `boolean` | Whether or not the radio group should loop through the items when navigating with the arrow keys.`Default: false` | | | `orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the radio group. This will determine how keyboard navigation will work within the component.`Default: 'vertical'` | | | `readonly` | `boolean` | Whether or not the radio group is readonly. When readonly, users can focus and navigate through items but cannot change the value.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----------------------------------- | ----------------------------------------- | ------- | | `data-orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the radio group. | | | `data-disabled` | `''` | Present when the radio group is disabled. | | | `data-readonly` | `''` | Present when the radio group is readonly. | | | `data-radio-group-root` | `''` | Present on the root element. | | ### RadioGroup.Item An radio item, which must be a child of the `RadioGroup.Root` component. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` required | `string` | The value of the radio item. This should be unique for each radio item in the group.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether the radio item is disabled.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | --------------------------------- | ------------------------------------------ | ------- | | `data-disabled` | `''` | Present when the radio item is disabled. | | | `data-readonly` | `''` | Present when the radio group is readonly. | | | `data-value` | `''` | The value of the radio item. | | | `data-state` | `enum` - 'checked' \| 'unchecked' | The radio item's checked state. | | | `data-orientation` | `''` | The orientation of the parent radio group. | | | `data-radio-group-item` | `''` | Present on the radio item element. | | [Previous Progress](/docs/components/progress) [Next Range Calendar](/docs/components/range-calendar) ---------------------------------------------------- # Range Calendar Documentation Enables users to select a range of dates using a calendar interface. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte {#snippet children({ months, weekdays })}
    {#each months as month (month.value.month)} {#each weekdays as day (day)}
    {day.slice(0, 2)}
    {/each}
    {#each month.weeks as weekDates, i (i)} {#each weekDates as date, d (d)} {date.day} {/each} {/each}
    {/each}
    {/snippet}
    ``` ##### Heads up! Before diving into this component, it's important to understand how dates/times work in Bits UI. Please read the [Dates](/docs/dates) documentation to learn more! ## Structure ```svelte {#snippet children({ months, weekdays })} {#each months as month} {#each weekdays as day} {day} {/each} {#each month.weeks as weekDates} {#each weekDates as date} {/each} {/each} {/each} {/snippet} ``` ## Examples ### Min Days You can set the `minDays` prop to limit the minimum number of days that must be selected for a range. ```svelte ``` Expand Code ```svelte {#snippet children({ months, weekdays })}
    {#each months as month (month.value.month)} {#each weekdays as day (day)}
    {day.slice(0, 2)}
    {/each}
    {#each month.weeks as weekDates, i (i)} {#each weekDates as date, d (d)} {date.day} {/each} {/each}
    {/each}
    {/snippet}
    ``` ### Max Days You can set the `maxDays` prop to limit the maximum number of days that can be selected for a range. ```svelte ``` Expand Code ```svelte {#snippet children({ months, weekdays })}
    {#each months as month (month.value.month)} {#each weekdays as day (day)}
    {day.slice(0, 2)}
    {/each}
    {#each month.weeks as weekDates, i (i)} {#each weekDates as date, d (d)} {date.day} {/each} {/each}
    {/each}
    {/snippet}
    ``` ### Min and Max Days You can set both `minDays` and `maxDays` to limit the number of days that can be selected for a range. ```svelte ``` Expand Code ```svelte {#snippet children({ months, weekdays })}
    {#each months as month (month.value.month)} {#each weekdays as day (day)}
    {day.slice(0, 2)}
    {/each}
    {#each month.weeks as weekDates, i (i)} {#each weekDates as date, d (d)} {date.day} {/each} {/each}
    {/each}
    {/snippet}
    ``` ### Exclude Disabled You can set the `excludeDisabled` prop to automatically reset the range if any date within the selected range becomes disabled. ```svelte isWeekend(date, "en-US")} > ``` Expand Code ```svelte isWeekend(date, "en-US")} excludeDisabled > {#snippet children({ months, weekdays })}
    {#each months as month (month.value.month)} {#each weekdays as day (day)}
    {day.slice(0, 2)}
    {/each}
    {#each month.weeks as weekDates, i (i)} {#each weekDates as date, d (d)} {date.day} {/each} {/each}
    {/each}
    {/snippet}
    ``` ## API Reference ### RangeCalendar.Root The root range calendar component which contains all other calendar components. | Property | Type | Description | Details | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `value` $bindable | `DateRange` - import type { DateValue } from "@internationalized/date"; import { createNumberProp } from './helpers'; type DateRange = { start: DateValue \| undefined; end: DateValue \| undefined; }; | The selected date range.`Default:  —— undefined` | | | `onValueChange` | `function` - (range: DateRange) => void | A function that is called when the selected date range changes.`Default:  —— undefined` | | | `placeholder` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The placeholder date, which is used to determine what month to display when no date is selected. This updates as the user navigates the calendar, and can be used to programmatically control the calendar's view.`Default:  —— undefined` | | | `onPlaceholderChange` | `function` - (date: DateValue) => void | A function that is called when the placeholder date changes.`Default:  —— undefined` | | | `pagedNavigation` | `boolean` | Whether or not to use paged navigation for the calendar. Paged navigation causes the previous and next buttons to navigate by the number of months displayed at once, rather than by one month.`Default: false` | | | `preventDeselect` | `boolean` | Whether or not to prevent the user from deselecting a date without selecting another date first.`Default: false` | | | `weekdayFormat` | `enum` - 'narrow' \| 'short' \| 'long' | The format to use for the weekday strings provided via the `weekdays` slot prop.`Default: ''narrow''` | | | `weekStartsOn` | `number` | An absolute day of the week to start the calendar on, regardless of locale. `0` is Sunday, `1` is Monday, etc. If not provided, the calendar will default to the locale's first day of the week.`Default:  —— undefined` | | | `calendarLabel` | `string` | The accessible label for the calendar.`Default:  —— undefined` | | | `fixedWeeks` | `boolean` | Whether or not to always display 6 weeks in the calendar.`Default: false` | | | `isDateDisabled` | `function` - (date: DateValue) => boolean | A function that returns whether or not a date is disabled.`Default:  —— undefined` | | | `isDateUnavailable` | `function` - (date: DateValue) => boolean | A function that returns whether or not a date is unavailable.`Default:  —— undefined` | | | `maxValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The maximum date that can be selected.`Default:  —— undefined` | | | `minValue` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The minimum date that can be selected.`Default:  —— undefined` | | | `locale` | `string` | The locale to use for formatting dates.`Default: 'en'` | | | `numberOfMonths` | `number` | The number of months to display at once.`Default: 1` | | | `disabled` | `boolean` | Whether or not the calendar is disabled.`Default: false` | | | `readonly` | `boolean` | Whether or not the calendar is readonly.`Default: false` | | | `disableDaysOutsideMonth` | `boolean` | Whether or not to disable days outside the current month.`Default: false` | | | `onStartValueChange` | `function` - (value: DateValue) => void | A function that is called when the start date changes.`Default:  —— undefined` | | | `onEndValueChange` | `function` - (value: DateValue) => void | A function that is called when the end date changes.`Default:  —— undefined` | | | `minDays` | `number` | The minimum number of days that can be selected in a range.`Default:  —— undefined` | | | `maxDays` | `number` | The maximum number of days that can be selected in a range.`Default:  —— undefined` | | | `excludeDisabled` | `boolean` | Whether to automatically reset the range if any date within the selected range becomes disabled.`Default: false` | | | `monthFormat` | `union` - short \| long \| narrow \| numeric \| 2-digit \| (month: number) => string | The format to use for the month strings provided via the `months` slot prop.`Default: 'long'` | | | `yearFormat` | `union` - numeric \| 2-digit \| (year: number) => string | The format to use for the year strings provided via the `years` slot prop.`Default: 'numeric'` | | | `child` | `Snippet` - type Month\ = { /\*\* \* A DateValue used to represent the month. Since days \* from the previous and next months may be included in the \* calendar grid, we need a source of truth for the value \* the grid is representing. \*/ value: DateValue; /\*\* \* An array of arrays representing the weeks in the calendar. \* Each sub-array represents a week, and contains the dates for each \* day in that week. This structure is useful for rendering the calendar \* grid using a table, where each row represents a week and each cell \* represents a day. \*/ weeks: T\[]\[]; /\*\* \* An array of all the dates in the current month, including dates from \* the previous and next months that are used to fill out the calendar grid. \* This array is useful for rendering the calendar grid in a customizable way, \* as it provides all the dates that should be displayed in the grid in a flat \* array. \*/ dates: T\[]; }; type ChildSnippetProps = { props: Record\; months: Month\\[]; weekdays: string\[]; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | `children` | `Snippet` - type Month\ = { /\*\* \* A DateValue used to represent the month. Since days \* from the previous and next months may be included in the \* calendar grid, we need a source of truth for the value \* the grid is representing. \*/ value: DateValue; /\*\* \* An array of arrays representing the weeks in the calendar. \* Each sub-array represents a week, and contains the dates for each \* day in that week. This structure is useful for rendering the calendar \* grid using a table, where each row represents a week and each cell \* represents a day. \*/ weeks: T\[]\[]; /\*\* \* An array of all the dates in the current month, including dates from \* the previous and next months that are used to fill out the calendar grid. \* This array is useful for rendering the calendar grid in a customizable way, \* as it provides all the dates that should be displayed in the grid in a flat \* array. \*/ dates: T\[]; }; type ChildrenSnippetProps = { months: Month\\[]; weekdays: string\[]; }; | The children content to render.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | Data Attribute | Value | Description | Details | | -------------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the root element when the calendar is invalid. | | | `data-disabled` | `''` | Present on the root element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the root element when the calendar is readonly. | | | `data-range-calendar-root` | `''` | Present on the root element. | | ### RangeCalendar.Header The header of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | ----- | ------------------------------------------------------------ | ------- | | `data-disabled` | `''` | Present on the header element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the header element when the calendar is readonly. | | | `data-range-calendar-header` | `''` | Present on the header element. | | ### RangeCalendar.Heading The heading of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | ------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the heading element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the heading element when the calendar is readonly. | | | `data-range-calendar-heading` | `''` | Present on the heading element. | | ### RangeCalendar.NextButton The next button of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------------- | ----- | -------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the next button element when the calendar or this button is disabled. | | | `data-range-calendar-next-button` | `''` | Present on the next button element. | | ### RangeCalendar.PrevButton The previous button of the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------------- | ----- | -------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the prev button element when the calendar or this button is disabled. | | | `data-range-calendar-prev-button` | `''` | Present on the prev button element. | | ### RangeCalendar.Cell A cell in the calendar grid. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `date` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The date for the cell.`Default:  —— undefined` | | | `month` | `DateValue` - import type { CalendarDate, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type DateValue = CalendarDate \| CalendarDateTime \| ZonedDateTime | The current month the date is being displayed in.`Default:  —— undefined` | | | `ref` $bindable | `HTMLTableCellElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | ------------------------------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present when the day is disabled. | | | `data-unavailable` | `''` | Present when the day is unavailable. | | | `data-today` | `''` | Present when the day is today. | | | `data-outside-month` | `''` | Present when the day is outside the current month. | | | `data-outside-visible-months` | `''` | Present when the day is outside the visible months. | | | `data-focused` | `''` | Present when the day is focused. | | | `data-selected` | `''` | Present when the day is selected. | | | `data-value` | `''` | The date in the format "YYYY-MM-DD". | | | `data-range-calendar-cell` | `''` | Present on the cell element. | | | `data-range-start` | `''` | Present when the cell is the start of a selection range. | | | `data-range-end` | `''` | Present when the cell is the end of a selection range. | | | `data-range-middle` | `''` | Present when the cell is in the middle of a selection range, but not the start or end of the selection. | | | `data-highlighted` | `''` | Present when the cell is highlighted within a selection range. | | ### RangeCalendar.Day A day in the calendar grid. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------------- | ----- | ------------------------------------------------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present when the day is disabled. | | | `data-unavailable` | `''` | Present when the day is unavailable. | | | `data-today` | `''` | Present when the day is today. | | | `data-outside-month` | `''` | Present when the day is outside the current month. | | | `data-outside-visible-months` | `''` | Present when the day is outside the visible months. | | | `data-focused` | `''` | Present when the day is focused. | | | `data-selected` | `''` | Present when the day is selected. | | | `data-value` | `''` | The date in the format "YYYY-MM-DD". | | | `data-range-calendar-day` | `''` | Present on the day element. | | | `data-range-start` | `''` | Present when the cell is the start of a selection range. | | | `data-range-end` | `''` | Present when the cell is the end of a selection range. | | | `data-range-middle` | `''` | Present when the cell is in the middle of a selection range, but not the start or end of the selection. | | | `data-highlighted` | `''` | Present when the cell is highlighted within a selection range. | | ### RangeCalendar.Grid The grid of dates in the calendar, typically representing a month. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid element when the calendar is readonly. | | | `data-range-calendar-grid` | `''` | Present on the grid element. | | ### RangeCalendar.GridBody The body of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableSectionElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | ----- | ---------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid element when the calendar is readonly. | | | `data-range-calendar-grid-body` | `''` | Present on the grid body element. | | ### RangeCalendar.GridHead The head of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableSectionElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | ----- | --------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid head element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid head element when the calendar is readonly. | | | `data-range-calendar-grid-head` | `''` | Present on the grid head element. | | ### RangeCalendar.GridRow A row in the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableRowElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------ | ----- | -------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the grid row element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the grid row element when the calendar is readonly. | | | `data-range-calendar-grid-row` | `''` | Present on the grid row element. | | ### RangeCalendar.HeadCell A cell in the head of the grid of dates in the calendar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLTableCellElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------- | ----- | --------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the head cell element when the calendar is disabled. | | | `data-readonly` | `''` | Present on the head cell element when the calendar is readonly. | | | `data-range-calendar-head-cell` | `''` | Present on the head cell element. | | ### RangeCalendar.MonthSelect A select you can use to navigate to a specific month in the calendar view. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `months` | `number[]` | The month values to render in the select.`Default: [1-12]` | | | `monthFormat` | `enum` - 'narrow' \| 'short' \| 'long' \| 'numeric' \| '2-digit' \| '(month: number) => string' | The format to use for the month strings provided via the `months` slot prop. If a function is provided, it will be called with the month number as an argument and should return a string.`Default: ''narrow''` | | | `ref` $bindable | `HTMLSelectElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { monthItems: Array<{ value: number; label: string }>; selectedMonthItem: { value: number; label: string }; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; monthItems: Array<{ value: number; label: string }>; selectedMonthItem: { value: number; label: string }; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------------- | ----- | ------------------------------------------------------------------ | ------- | | `data-disabled` | `''` | Present on the month select element when the calendar is disabled. | | | `data-range-calendar-month-select` | `''` | Present on the month select element. | | ### RangeCalendar.YearSelect A select you can use to navigate to a specific year in the calendar view. | Property | Type | Description | Details | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `years` | `number[]` | The year values to render in the select.``Default: The current year or placeholder year (whichever is higher) + 10 and minus 100 years. When a `minValue`/`maxValue` is provided to `Calendar.Root`, those will be used to constrain the range.`` | | | `yearFormat` | `enum` - 'numeric' \| '2-digit' \| '(year: number) => string' | The format to use for the year strings provided via the `years` slot prop. If a function is provided, it will be called with the year as an argument and should return a string.`Default: ''numeric''` | | | `ref` $bindable | `HTMLSelectElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { yearItems: Array<{ value: number; label: string }>; selectedYearItem: { value: number; label: string }; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { props: Record\; yearItems: Array<{ value: number; label: string }>; selectedYearItem: { value: number; label: string }; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------------- | ----- | ----------------------------------------------------------------- | ------- | | `data-disabled` | `''` | Present on the year select element when the calendar is disabled. | | | `data-range-calendar-year-select` | `''` | Present on the year select element. | | [Previous Radio Group](/docs/components/radio-group) [Next Rating Group](/docs/components/rating-group) ---------------------------------------------------- # Rating Group Documentation Enables users to provide ratings using customizable items (like stars). This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte {#snippet children({ items })} {#each items as item (item.index)} {/each} {/snippet} ``` ## Structure ```svelte {#snippet children({ items })} {#each items as item (item.index)} {#if item.state === "active"} ⭐ {:else} ☆ {/if} {/each} {/snippet} ``` ## Reusable Components It's recommended to use the `RatingGroup` primitives to create your own custom rating components that can be used throughout your application. In the example below, we're creating a custom `MyRatingGroup` component that renders a rating group with configurable maximum rating and styling. MyRatingGroup.svelte ```svelte
    {#snippet children({ items })} {#each items as item (item.index)} {#if item.state === "inactive"} {:else if item.state === "active"} {:else if item.state === "partial"} {/if} {/each} {/snippet} {#if showLabel}

    Rating: {value} out of {max} stars

    {/if}
    ``` You can then use the `MyRatingGroup` component in your application like so: +page.svelte ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte {#snippet children({ items })} {#each items as item (item.index)} {#if item.state === "active"}⭐{:else}☆{/if} {/each} {/snippet} ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte {#snippet children({ items })} {#each items as item (item.index)} {#if item.state === "active"}⭐{:else}☆{/if} {/each} {/snippet} ``` ## HTML Forms If you set the `name` prop on the `RatingGroup.Root` component, a hidden input element will be rendered to submit the rating value to a form. ```svelte ``` ### Required To make the hidden input element `required` you can set the `required` prop on the `RatingGroup.Root` component. ```svelte ``` ## Half Ratings The rating group supports half ratings when you set the `allowHalf` prop to `true`. This allows for more precise ratings like 3.5 stars. ```svelte {#snippet children({ items })} {#each items as item (item.index)} {#if item.state === "inactive"} {:else if item.state === "active"} {:else if item.state === "partial"} {/if} {/each} {/snippet} ``` Expand Code ```svelte {#snippet children({ items })} {#each items as item (item.index)} {#if item.state === "inactive"} {:else if item.state === "active"} {:else if item.state === "partial"} {/if} {/each} {/snippet} ``` ## Readonly Mode You can make the rating group readonly by setting the `readonly` prop to `true`. This is useful for displaying existing ratings without allowing user interaction. ```svelte ``` ## Disabled State You can disable the entire rating group by setting the `disabled` prop to `true`. ```svelte ``` ## Hover Preview By default, the rating group shows a preview of the potential rating when hovering over items. You can disable this behavior by setting `hoverPreview` to `false`. ```svelte {#snippet children({ items })} {#each items as item (item.index)} {#if item.state === "active"}⭐{:else}☆{/if} {/each} {/snippet} ``` When disabled, only the currently selected rating will be highlighted, and hovering over items won't show a preview of the potential selection. Expand Code ```svelte

    Hover preview disabled

    Only shows selected rating on hover, no preview of potential selection.

    {#snippet children({ items })} {#each items as item (item.index)} {/each} {/snippet}

    Rating: {value} out of 5 stars

    ``` ## RTL Support The rating group automatically adapts to right-to-left (RTL) text direction. Simply set the `dir="rtl"` attribute on a parent element: ```svelte
    {#snippet children({ items })} {#each items as item (item.index)} {#if item.state === "active"}⭐{:else}☆{/if} {/each} {/snippet}
    ``` In RTL mode, the arrow key navigation is automatically reversed to match the visual direction. Expand Code ```svelte

    تقييم بالنجوم (RTL)

    Rating group with right-to-left text direction.

    {#snippet children({ items })} {#each items as item (item.index)} {#if item.state === "partial"} {:else if item.state === "active"} {:else} {/if} {/each} {/snippet}

    التقييم: {value} من 5 نجوم

    ``` ## Maximum Rating The `max` prop determines the maximum rating value and the number of rating items rendered. (defaults to `5`) ```svelte {#snippet children({ items })} {#each items as item (item.index)} {item.index + 1} {/each} {/snippet} ``` ## Minimum Rating The `min` prop sets a minimum required rating value. When set, users cannot select a rating below this value, and the rating will not go below the minimum when cleared. (defaults to `0`) ```svelte {#snippet children({ items })} {#each items as item (item.index)} {#if item.state === "active"}⭐{:else}☆{/if} {/each} {/snippet} ``` This is useful for scenarios where you require at least a certain rating, such as feedback forms that must have a minimum 1-star rating. ## Accessibility The `RatingGroup` component implements comprehensive accessibility features following WAI-ARIA best practices for rating interfaces. ### ARIA Implementation The component uses the **slider pattern** rather than a radiogroup pattern, which provides better screen reader support for rating interfaces: - **Root element**: `role="slider"` with complete ARIA slider attributes - **Rating items**: `role="presentation"` to avoid redundant announcements - **Value communication**: `aria-valuenow`, `aria-valuemin`, `aria-valuemax` for current state - **Custom descriptions**: `aria-valuetext` for contextual rating descriptions - **State indicators**: `aria-disabled`, `aria-required`, `aria-orientation` When users navigate with arrow keys, screen readers announce the new rating value immediately, providing real-time feedback. ### Keyboard Navigation Strategy The keyboard implementation follows platform conventions while adding rating-specific enhancements: #### Direct Number Input The most efficient way to set ratings - users can type the exact rating they want: - **Integer ratings**: Type `3` to set rating to 3 stars - **Half ratings**: Type `2.5` to set 2.5 stars (when `allowHalf` is enabled) - **Clear rating**: Type `0` to remove rating (respects minimum constraints) - **Input validation**: Invalid numbers are ignored, values are clamped to min/max range #### Arrow Key Navigation Navigation adapts to both rating precision and text direction: - **Standard mode**: Arrow keys increment/decrement by 1 - **Half rating mode**: Arrow keys increment/decrement by 0.5 for finer control - **RTL support**: Left/right arrows automatically reverse in right-to-left layouts - **Bounds respect**: Navigation stops at min/max values #### Quick Navigation - **`Home`**: Jump to minimum rating (or 1 if no minimum set) - **`End`**: Jump to maximum rating - **`PageUp`/`PageDown`**: Increment/decrement by 1 (alternative to arrows) ### Focus Management The component handles focus intelligently: - **Mouse interactions**: Clicking a rating item automatically focuses the root slider - **Keyboard focus**: Single tab stop - the entire rating group acts as one focusable unit - **Visual feedback**: Focus styling applied to the root container - **Disabled state**: Component becomes non-focusable when disabled ### Customizing Accessibility You can enhance the accessibility experience with custom `aria-valuetext`: ```svelte { if (value === 0) return "No rating selected"; return `${value} out of ${max} stars. ${value >= 4 ? "Excellent" : value >= 3 ? "Good" : "Fair"} rating.`; }} > ``` ## API Reference ### RatingGroup.Root The rating group component used to group rating items under a common name for form submission. | Property | Type | Description | Details | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `number` | The value of the rating group. You can bind to this value to control the rating group's value from outside the component.`Default: 0` | | | `onValueChange` | `function` - (value: number) => void | A callback that is fired when the rating group's value changes.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the radio group is disabled. This prevents the user from interacting with it.`Default: false` | | | `required` | `boolean` | Whether or not the radio group is required.`Default: false` | | | `name` | `string` | The name of the rating group used in form submission. If provided, a hidden input element will be rendered to submit the value of the rating group.`Default:  —— undefined` | | | `min` | `number` | The minimum value of the rating group.`Default: 0` | | | `max` | `number` | The maximum value of the rating group.`Default: 5` | | | `allowHalf` | `boolean` | Whether or not the rating group allows half values.`Default: false` | | | `readonly` | `boolean` | Whether or not the rating group is readonly.`Default: false` | | | `orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the rating group. This will determine how keyboard navigation will work within the component.`Default: 'horizontal'` | | | `hoverPreview` | `boolean` | Whether or not the rating group shows a preview of the rating when hovering over the items.`Default: false` | | | `aria-valuetext` | `union` - string \| (value: number, max: number) => string | The text that describes the rating group's value.`` Default: `${value} out of ${max}` `` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type RatingGroupItemState = "active" \| "partial" \| "inactive"; type RatingGroupItemData = { index: number; state: RatingGroupItemState; }; type ChildrenSnippetProps = { items: RatingGroupItemData\[]; value: number; max: number; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type RatingGroupItemState = "active" \| "partial" \| "inactive"; type RatingGroupItemData = { index: number; state: RatingGroupItemState; }; type ChildSnippetProps = { items: RatingGroupItemData\[]; value: number; max: number; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----------------------------------- | ------------------------------------------ | ------- | | `data-orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the rating group. | | | `data-disabled` | `''` | Present when the rating group is disabled. | | | `data-readonly` | `''` | Present when the rating group is readonly. | | | `data-rating-group-root` | `''` | Present on the root element. | | ### RatingGroup.Item An rating item, which must be a child of the `RatingGroup.Root` component. | Property | Type | Description | Details | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `index` required | `number` | The index of the rating item.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether the rating item is disabled.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type RatingGroupItemState = "active" \| "partial" \| "inactive"; type ChildrenSnippetProps = { state: RatingGroupItemState; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type RatingGroupItemState = "active" \| "partial" \| "inactive"; type ChildSnippetProps = { state: RatingGroupItemState; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----------------------------------- | ------------------------------------------- | ------- | | `data-disabled` | `''` | Present when the rating group is disabled. | | | `data-readonly` | `''` | Present when the rating group is readonly. | | | `data-value` | `''` | The value of the rating item. | | | `data-state` | `enum` - 'checked' \| 'unchecked' | The rating item's checked state. | | | `data-orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the parent rating group. | | | `data-rating-group-item` | `''` | Present on the rating item element. | | [Previous Range Calendar](/docs/components/range-calendar) [Next Scroll Area](/docs/components/scroll-area) ---------------------------------------------------- # Scroll Area Documentation Provides a consistent scroll area across platforms. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte

    Scroll Area

    Lorem ipsum dolor sit, amet consectetur adipisicing elit. Dignissimos impedit rem, repellat deserunt ducimus quasi nisi voluptatem cumque aliquid esse ea deleniti eveniet incidunt! Deserunt minus laborum accusamus iusto dolorum. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Blanditiis officiis error minima eos fugit voluptate excepturi eveniet dolore et, ratione impedit consequuntur dolorem hic quae corrupti autem? Dolorem, sit voluptatum.

    ``` ## Structure ```svelte ``` ## Reusable Components If you're planning to use the Scroll Area throughout your application, it's recommended to create a reusable component to reduce the amount of code you need to write each time. This example shows you how to create a Scroll Area component that accepts a few custom props that make it more capable. MyScrollArea.svelte ```svelte {#snippet Scrollbar({ orientation, }: { orientation: "vertical" | "horizontal"; })} {/snippet} {@render children?.()} {#if orientation === "vertical" || orientation === "both"} {@render Scrollbar({ orientation: "vertical" })} {/if} {#if orientation === "horizontal" || orientation === "both"} {@render Scrollbar({ orientation: "horizontal" })} {/if} ``` We'll use this custom component in the following examples to demonstrate how to customize the behavior of the Scroll Area. ## Scroll Area Types ### Hover The `hover` type is the default type of the scroll area, demonstrated in the featured example above. It only shows scrollbars when the user hovers over the scroll area and the content is larger than the viewport. ```svelte ``` ### Scroll The `scroll` type displays the scrollbars when the user scrolls the content. This is similar to the behavior of MacOS. ```svelte ``` ### Auto The `auto` type behaves similarly to your typical browser scrollbars. When the content is larger than the viewport, the scrollbars will appear and remain visible at all times. ```svelte ``` ### Always The `always` type behaves as if you set `overflow: scroll` on the scroll area. Scrollbars will always be visible, even when the content is smaller than the viewport. We've also set the `orientation` prop on the `MyScrollArea` to `'both'` to ensure both scrollbars are rendered. ```svelte ``` ## Customizing the Hide Delay You can customize the hide delay of the scrollbars using the `scrollHideDelay` prop. ```svelte ``` ## API Reference ### ScrollArea.Root The container of all scroll area components. Overflow is hidden on this element to prevent double scrollbars. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `type` | `enum` - 'hover' \| 'scroll' \| 'auto' \| 'always' | The type of scroll area.`Default: 'hover'` | | | `scrollHideDelay` | `number` | The delay in milliseconds before the scroll area hides itself when using `'hover'` or `'scroll'` type.`Default: 600` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | ---------------------------- | ------- | | `data-scroll-area-root` | `''` | Present on the root element. | | ### ScrollArea.Viewport The component which wraps the content and is responsible for computing the scroll area size. | Property | Type | Description | Details | | --------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | ----- | -------------------------------- | ------- | | `data-scroll-area-viewport` | `''` | Present on the viewport element. | | ### ScrollArea.Scrollbar A scrollbar of the scroll area. | Property | Type | Description | Details | | ---------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `orientation` required | `enum` - 'horizontal' \| 'vertical' | The orientation of the scrollbar.`Default:  —— undefined` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------ | ------------------------------ | ------------------------------------------------ | ------- | | `data-state` | `enum` - 'visible' \| 'hidden' | The visibility state of the scrollbar | | | `data-scroll-area-scrollbar-x` | `''` | Present on the `'horizontal'` scrollbar element. | | | `data-scroll-area-scrollbar-y` | `''` | Present on the `'vertical'` scrollbar element. | | ### ScrollArea.Thumb A thumb of a scrollbar in the scroll area. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------- | ------------------------------ | -------------------------------------------- | ------- | | `data-state` | `enum` - 'visible' \| 'hidden' | The visibility state of the scrollbar | | | `data-scroll-area-thumb-x` | `''` | Present on the `'horizontal'` thumb element. | | | `data-scroll-area-thumb-y` | `''` | Present on the `'vertical'` thumb element. | | ### ScrollArea.Corner The corner element between the X and Y scrollbars. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----- | ------------------------------ | ------- | | `data-scroll-area-corner` | `''` | Present on the corner element. | | [Previous Rating Group](/docs/components/rating-group) [Next Select](/docs/components/select) ---------------------------------------------------- # Select Documentation Enables users to pick from a list of options displayed in a dropdown. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte (value = v)} items={themes} allowDeselect={true} > {selectedLabel} {#each themes as theme, i (i + theme.value)} {#snippet children({ selected })} {theme.label} {#if selected}
    {/if} {/snippet}
    {/each}
    ``` ## Overview The Select component provides users with a selectable list of options. It's designed to offer an enhanced selection experience with features like typeahead search, keyboard navigation, and customizable grouping. This component is particularly useful for scenarios where users need to choose from a predefined set of options, offering more functionality than a standard select element. ## Key Features - **Typeahead Search**: Users can quickly find options by typing - **Keyboard Navigation**: Full support for keyboard interactions, allowing users to navigate through options using arrow keys, enter to select, and more. - **Grouped Options**: Ability to organize options into logical groups, enhancing readability and organization of large option sets. - **Scroll Management**: Includes scroll up/down buttons for easy navigation in long lists. - **Accessibility**: Built-in ARIA attributes and keyboard support ensure compatibility with screen readers and adherence to accessibility standards. - **Portal Support**: Option to render the select content in a portal, preventing layout issues in complex UI structures. ## Architecture The Select component is composed of several sub-components, each with a specific role: - **Root**: The main container component that manages the state and context for the combobox. - **Trigger**: The button or element that opens the dropdown list. - **Portal**: Responsible for portalling the dropdown content to the body or a custom target. - **Group**: A container for grouped items, used to group related items. - **GroupHeading**: A heading for a group of items, providing a descriptive label for the group. - **Item**: An individual item within the list. - **Content**: The dropdown container that displays the items. It uses [Floating UI](https://floating-ui.com/) to position the content relative to the trigger. - **ContentStatic** (Optional): An alternative to the Content component, that enables you to opt-out of Floating UI and position the content yourself. - **Viewport**: The visible area of the dropdown content, used to determine the size and scroll behavior. - **ScrollUpButton**: A button that scrolls the content up when the content is larger than the viewport. - **ScrollDownButton**: A button that scrolls the content down when the content is larger than the viewport. - **Arrow**: An arrow element that points to the trigger when using the `Combobox.Content` component. ## Structure Here's an overview of how the Select component is structured in code: ```svelte ``` ## Reusable Components As you can see from the structure above, there are a number of pieces that make up the `Select` component. These pieces are provided to give you maximum flexibility and customization options, but can be a burden to write out everywhere you need to use a select in your application. To ease this burden, it's recommended to create your own reusable select component that wraps the primitives and provides a more convenient API for your use cases. Here's an example of how you might create a reusable `MySelect` component that receives a list of options and renders each of them as an item. MySelect.svelte ```svelte {selectedLabel ? selectedLabel : placeholder} up {#each items as { value, label, disabled } (value)} {#snippet children({ selected })} {selected ? "✅" : ""} {label} {/snippet} {/each} down ``` You can then use the `MySelect` component throughout your application like so: ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Open State This section covers how to manage the `open` state of the component. ### Two-Way Binding Use `bind:open` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Multiple Selection The `type` prop can be set to `'multiple'` to allow multiple items to be selected at a time. ```svelte ``` Expand Code ```svelte {selectedLabel} {#each themes as theme, i (i + theme.value)} {#snippet children({ selected })} {theme.label} {#if selected}
    {/if} {/snippet}
    {/each}
    ``` ## Opt-out of Floating UI When you use the `Select.Content` component, Bits UI uses [Floating UI](https://floating-ui.com/) to position the content relative to the trigger, similar to other popover-like components. You can opt-out of this behavior by instead using the `Select.ContentStatic` component. ```svelte ``` When using this component, you'll need to handle the positioning of the content yourself. Keep in mind that using `Select.Portal` alongside `Select.ContentStatic` may result in some unexpected positioning behavior, feel free to not use the portal or work around it. ## Custom Anchor By default, the `Select.Content` is anchored to the `Select.Trigger` component, which determines where the content is positioned. If you wish to instead anchor the content to a different element, you can pass either a selector string or an `HTMLElement` to the `customAnchor` prop of the `Select.Content` component. ```svelte
    ``` ## What is the Viewport? The `Select.Viewport` component is used to determine the size of the content in order to determine whether or not the scroll up and down buttons should be rendered. If you wish to set a minimum/maximum height for the select content, you should apply it to the `Select.Viewport` component. ## Scroll Up/Down Buttons The `Select.ScrollUpButton` and `Select.ScrollDownButton` components are used to render the scroll up and down buttons when the select content is larger than the viewport. You must use the `Select.Viewport` component when using the scroll buttons. ### Custom Scroll Delay The initial and subsequent scroll delays can be controlled using the `delay` prop on the buttons. For example, we can use the [`cubicOut`](https://svelte.dev/docs/svelte/svelte-easing#cubicOut) easing function from Svelte to create a smooth scrolling effect that speeds up over time. Expand Code ```svelte (value = v)} items={themes}> {selectedLabel} {#each themes as theme, i (i + theme.value)} {#snippet children({ selected })} {theme.label} {#if selected}
    {/if} {/snippet}
    {/each}
    ``` ## Native Scrolling/Overflow If you don't want to use the [scroll buttons](#scroll-updown-buttons) and prefer to use the standard scrollbar/overflow behavior, you can omit the `Select.Scroll[Up|Down]Button` components and the `Select.Viewport` component. You'll need to set a height on the `Select.Content` component and appropriate `overflow` styles to enable scrolling. ## Scroll Lock By default, when a user opens the select, scrolling outside the content will not be disabled. You can override this behavior by setting the `preventScroll` prop to `true`. ```svelte ``` ## Highlighted Items The Select component follows the [WAI-ARIA descendant pattern](https://www.w3.org/TR/wai-aria-practices-1.2/#combobox) for highlighting items. This means that the `Select.Trigger` retains focus the entire time, even when navigating with the keyboard, and items are highlighted as the user navigates them. ### Styling Highlighted Items You can use the `data-highlighted` attribute on the `Select.Item` component to style the item differently when it is highlighted. ### onHighlight / onUnhighlight To trigger side effects when an item is highlighted or unhighlighted, you can use the `onHighlight` and `onUnhighlight` props. ```svelte console.log('I am highlighted!')} onUnhighlight={() => console.log('I am unhighlighted!')} /> ``` ## Svelte Transitions You can use the `forceMount` prop along with the `child` snippet to forcefully mount the `Select.Content` component to use Svelte Transitions or another animation library that requires more control. ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
    {/if} {/snippet}
    ``` Of course, this isn't the prettiest syntax, so it's recommended to create your own reusable content component that handles this logic if you intend to use this approach. For more information on using transitions with Bits UI components, see the [Transitions](/docs/transitions) documentation. Expand Code ```svelte {selectedLabel} {#snippet child({ wrapperProps, props, open })} {#if open}
    {#each themes as theme, i (i + theme.value)} {#snippet children({ selected })} {theme.label} {#if selected}
    {/if} {/snippet}
    {/each}
    {/if} {/snippet}
    ``` ## API Reference ### Select.Root The root select component which manages & scopes the state of the select. | Property | Type | Description | Details | | ---------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `type` required | `enum` - 'single' \| 'multiple' | The type of the component, used to determine the type of the value, when `'multiple'` the value will be an array.`Default:  —— undefined` | | | `value` $bindable | `union` - string \| string\[] | The value of the select. When the type is `'single'`, this should be a string. When the type is `'multiple'`, this should be an array of strings.`Default: string` | | | `onValueChange` | `function` - (value: string) => void \| (value: string\[]) => void | A callback that is fired when the select value changes. When the type is `'single'`, the argument will be a string. When the type is `'multiple'`, the argument will be an array of strings.`Default:  —— undefined` | | | `open` $bindable | `boolean` | The open state of the component.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the select component is disabled.`Default: false` | | | `name` | `string` | The name to apply to the hidden input element for form submission. If provided, a hidden input element will be rendered to submit the value of the select.`Default:  —— undefined` | | | `required` | `boolean` | Whether or not the select menu is required. When `required` is `true`, a `name` attribute must also be provided so that the hidden input is rendered`Default: false` | | | `scrollAlignment` | `enum` - 'nearest' \| 'center' | The alignment of the highlighted item when scrolling.`Default: 'nearest'` | | | `loop` | `boolean` | Whether or not the select menu should loop through items.`Default: false` | | | `allowDeselect` | `boolean` | Whether or not the user can deselect the selected item by pressing it in a single select.`Default: false` | | | `items` | `object` - { value: string; label: string; disabled?: boolean}\[] | Optionally provide an array of `value` and `label` pairs that will be used to match and trigger selection when the trigger is focused and a key is pressed while the content is closed. Additionally, this will be used for form autofill when the type is single.`Default:  —— undefined` | | | `autocomplete` | `string` | The autocomplete attribute to forward to the hidden input element.`Default:  —— undefined` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### Select.Trigger A button which toggles the select's open state. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | --------------------------- | ---------------------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The select's open state. | | | `data-placeholder` | `''` | Present when the select does not have a value. | | | `data-disabled` | `''` | Present when the select is disabled. | | | `data-select-trigger` | `''` | Present on the trigger element. | | ### Select.Content The element which contains the select's items. | Property | Type | Description | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: false` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not the select should loop through items when reaching the end.`Default: false` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | --------------------------- | ------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The select's open state. | | | `data-select-content` | `''` | Present on the content element. | | | CSS Variable | Description | Details | | ---------------------------------------- | -------------------------------------------- | ------- | | `--bits-select-content-transform-origin` | The transform origin of the content element. | | | `--bits-select-content-available-width` | The available width of the content element. | | | `--bits-select-content-available-height` | The available height of the content element. | | | `--bits-select-anchor-width` | The width of the anchor element. | | | `--bits-select-anchor-height` | The height of the anchor element. | | ### Select.ContentStatic The element which contains the select's items. (Static/No Floating UI) | Property | Type | Description | Details | | ------------------------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onOpenAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is opened. Can be prevented.`Default:  —— undefined` | | | `onCloseAutoFocus` | `function` - (event: Event) => void | Event handler called when auto-focusing the content as it is closed. Can be prevented.`Default:  —— undefined` | | | `trapFocus` | `boolean` | Whether or not to trap the focus within the content when open.`Default: true` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `preventOverflowTextSelection` | `boolean` | When `true`, prevents the text selection from overflowing the bounds of the element.`Default: true` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `loop` | `boolean` | Whether or not the select should loop through items when reaching the end.`Default: false` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { open: boolean; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | --------------------------- | ------------------------------- | ------- | | `data-state` | `enum` - 'open' \| 'closed' | The select's open state. | | | `data-select-content` | `''` | Present on the content element. | | ### Select.Portal When used, will render the select content into the body or custom `to` element when open | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### Select.Item A select item, which must be a child of the `select.Content` component. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` required | `string` | The value of the item.`Default:  —— undefined` | | | `label` | `string` | The label of the item, which is what the list will be filtered by using typeahead behavior.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the select item is disabled. This will prevent interaction/selection.`Default: false` | | | `onHighlight` | `function` - () => void | A callback that is fired when the item is highlighted.`Default:  —— undefined` | | | `onUnhighlight` | `function` - () => void | A callback that is fired when the item is unhighlighted.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------ | -------- | --------------------------------------------------------------------------------------------------- | ------- | | `data-value` | `string` | The value of the select item. | | | `data-label` | `string` | The label of the select item. | | | `data-disabled` | `''` | Present when the item is disabled. | | | `data-highlighted` | `''` | Present when the item is highlighted, which is either via keyboard navigation of the menu or hover. | | | `data-selected` | `''` | Present when the item is selected. | | | `data-select-item` | `''` | Present on the item element. | | ### Select.Viewport An optional element to track the scroll position of the select for rendering the scroll up/down buttons. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | ----- | -------------------------------- | ------- | | `data-select-viewport` | `''` | Present on the viewport element. | | ### Select.ScrollUpButton An optional scroll up button element to improve the scroll experience within the select. Should be used in conjunction with the `select.Viewport` component. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `delay` | `function` - (tick: number) => number | Controls the initial delay (tick 0) and delay between auto-scrolls in milliseconds.`Default: () => 50` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------------ | ----- | ---------------------------------------- | ------- | | `data-select-scroll-up-button` | `''` | Present on the scroll up button element. | | ### Select.ScrollDownButton An optional scroll down button element to improve the scroll experience within the select. Should be used in conjunction with the `select.Viewport` component. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `delay` | `function` - (tick: number) => number | Controls the initial delay (tick 0) and delay between auto-scrolls in milliseconds.`Default: () => 50` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------------------- | ----- | ------------------------------------------ | ------- | | `data-select-scroll-down-button` | `''` | Present on the scroll down button element. | | ### Select.Group A group of related select items. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----- | ----------------------------- | ------- | | `data-select-group` | `''` | Present on the group element. | | ### Select.GroupHeading A heading for the parent select group. This is used to describe a group of related select items. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------------- | ----- | ------------------------------------- | ------- | | `data-select-group-heading` | `''` | Present on the group heading element. | | ### Select.Arrow An optional arrow element which points to the content when open. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `width` | `number` | The width of the arrow in pixels.`Default: 8` | | | `height` | `number` | The height of the arrow in pixels.`Default: 8` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------- | ----- | ----------------------------- | ------- | | `data-arrow` | `''` | Present on the arrow element. | | [Previous Scroll Area](/docs/components/scroll-area) [Next Separator](/docs/components/separator) ---------------------------------------------------- # Separator Documentation Visually separates content or UI elements. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte

    Bits UI

    Headless UI components for Svelte.

    Blog
    Docs
    Source
    ``` ## Structure ```svelte ``` ## API Reference ### Separator.Root An element used to separate content. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the separator.`Default: 'horizontal'` | | | `decorative` | `boolean` | Whether the separator is decorative or not, which will determine if it is announced by screen readers.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | ----------------------------------- | --------------------------------- | ------- | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the separator. | | | `data-separator-root` | `''` | Present on the root element. | | [Previous Select](/docs/components/select) [Next Slider](/docs/components/slider) ---------------------------------------------------- # Slider Documentation Enables users to select a value from a continuous range. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
    ``` ## Structure ```svelte ``` ## Reusable Components Bits UI provides primitives that enable you to build your own custom slider component that can be reused throughout your application. Here's an example of how you might create a reusable `MySlider` component. MyMultiSlider.svelte ```svelte {#snippet children({ thumbs, ticks })} {#each thumbs as index} {/each} {#each ticks as index} {/each} {/snippet} ``` You can then use the `MySlider` component in your application like so: ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Value Commit You can use the `onValueCommit` prop to be notified when the user finishes dragging the thumb and the value changes. This is different than the `onValueChange` callback because it waits until the user stops dragging before calling the callback, where the `onValueChange` callback is called as the user dragging. ```svelte { console.log("user is done sliding!", v); }} /> ``` ## RTL Support You can use the `dir` prop to change the reading direction of the slider, which defaults to `"ltr"`. ```svelte ``` ## Auto Sort By default, the slider will sort the values from smallest to largest, so if you drag a smaller thumb to a larger value, the value of that thumb will be updated to the larger value. You can disable this behavior by setting the `autoSort` prop to `false`. ```svelte ``` ## HTML Forms Since there is a near endless number of possible values that a user can select, the slider does not render a hidden input element by default. You'll need to determine how you want to submit the value(s) of the slider with a form. Here's an example of how you might do that: ```svelte
    ``` ## Examples ### Multiple Thumbs and Ticks If the `value` prop has more than one value, the slider will render multiple thumbs. You can also use the `tickItems` and `thumbItems` snippet props to render ticks and thumbs at specific intervals. ```svelte {#snippet children({ tickItems, thumbItems })} {#each thumbItems as { index } (index)} {/each} {#each tickItems as { index } (index)} {/each} {/snippet} ``` To determine the number of ticks that will be rendered, you can simply divide the `max` value by the `step` value. Expand Code ```svelte
    {#snippet children({ tickItems, thumbs })} {#each thumbs as thumb (thumb)} {/each} {#each tickItems as { index } (index)} {/each} {/snippet}
    ``` ### Single Type Set the `type` prop to `"single"` to allow only one slider handle. ```svelte ``` Expand Code ```svelte
    ``` ### Multiple Type Set the `type` prop to `"multiple"` to allow multiple slider handles. ```svelte ``` Expand Code ```svelte
    {#snippet children({ thumbItems })} {#each thumbItems as { index } (index)} {/each} {/snippet}
    ``` ### Vertical Orientation You can use the `orientation` prop to change the orientation of the slider, which defaults to `"horizontal"`. ```svelte ``` Expand Code ```svelte
    ``` ### Tick Labels You can use the `tickItems` snippet prop in combination with the `Slider.TickLabel` to render labels at specific intervals. ```svelte {#snippet children({ tickItems })} {#each tickItems as { value, index } (index)} {value} {/each} {/snippet} ``` Expand Code ```svelte
    {#snippet children({ tickItems, thumbItems })} {#each thumbItems as { index } (index)} {/each} {#each tickItems as { index, value } (index)} {value} {/each} {/snippet}
    ``` ### Discrete Steps Instead of passing a single value to the `step` prop, you can pass an array of discrete values that the slider will snap to. ```svelte ``` Expand Code ```svelte
    {#snippet children({ tickItems })} {#each tickItems as { index, value } (index)} {value}px {/each} {/snippet}
    {#snippet children({ tickItems })} {#each tickItems as { index, value } (index)} {value}px {/each} {/snippet}
    ``` ### Thumb Labels Use the `Slider.ThumbLabel` component to render a label that is positioned relative to the thumb. You can manually specify the index like so: ```svelte Min Max ``` or use the `thumbItems` snippet prop to render a label for each thumb: ```svelte {#snippet children({ thumbItems })} {#each thumbItems as { index, value } (index)} {index === 0 ? "Min" : "Max"}:{value} {/each} {/snippet} ``` Expand Code ```svelte
    {#snippet children({ tickItems })} Check in Dinner Sleep {#each tickItems as { index, value } (index)} {value}pm {/each} {/snippet}
    ``` ## API Reference ### Slider.Root The root slider component which contains the remaining slider components. | Property | Type | Description | Details | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `type` required | `enum` - 'single' \| 'multiple' | The type of the slider. If set to `'multiple'`, the slider will allow multiple thumbs and the `value` will be an array of numbers.`Default:  —— undefined` | | | `value` $bindable | `number` | The current value of the slider. If the `type` is set to `'multiple'`, this should be an array of numbers and will default to an empty array.`Default: 0` | | | `onValueChange` | `function` - (value: number) => void \| (value: number\[]) => void | A callback function called when the value state of the slider changes.`Default:  —— undefined` | | | `onValueCommit` | `function` - (value: number) => void \| (value: number\[]) => void | A callback function called when the user finishes dragging the thumb and the value changes. This is different than the `onValueChange` callback because it waits until the user stops dragging before calling the callback, where the `onValueChange` callback is called immediately after the user starts dragging.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the switch is disabled.`Default: false` | | | `max` | `number` | The maximum value of the slider.`Default: 100` | | | `min` | `number` | The minimum value of the slider.`Default: 0` | | | `orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the slider.`Default: 'horizontal'` | | | `step` $bindable | `union` - number\[] \| number | The step value of the slider. If a single number is provided, the slider will step by that number and use that number to generate the ticks (e.g. `step={1}` will generate ticks at `0, 1, 2, 3, ...`). If an array of numbers is provided, the slider will snap to those values (e.g. `step={[0, 4, 8, 16, 24]}`) and ticks will be generated at those values.`Default:  —— undefined` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `autoSort` | `boolean` | Whether to automatically sort the values in the array when moving thumbs past one another. This is only applicable to the `'multiple'` type.`Default: true` | | | `thumbPositioning` | `enum` - 'exact' \| 'contain' | The positioning of the slider thumb. `'contain'` will ensure that the thumb is always visible within the track, while `'exact'` will ensure that the thumb is always at the same position relative to the track. For an SSR-friendly alternative to `thumbPositioning='contain'`, use the `trackPadding` prop to set the padding between the thumbs/first ticks and the edges of the track.`Default: 'contain'` | | | `trackPadding` | `number` | A percentage of the full track length to pad the start and end of the track. This is useful for creating a visual buffer between the thumbs or beginning/end ticks and the edges of the track. This is an SSR-friendly alternative to `thumbPositioning='contain'`.`Default:  —— undefined` | | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type TickItem = { /\*\* The value this tick represents \*/ value: number; /\*\* The index of this tick \*/ index: number; }; type ChildrenSnippetProps = { /\*\* The tick items to iterate over and render \*/ tickItems: TickItem\[]; /\*\* The currently active thumb \*/ thumbs: number\[]; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type TickItem = { /\*\* The value this tick represents \*/ value: number; /\*\* The index of this tick \*/ index: number; }; type ChildSnippetProps = { /\*\* The tick items to iterate over and render \*/ tickItems: TickItem\[]; /\*\* The currently active thumb \*/ thumbs: number\[]; /\*\* Props to apply to the root element \*/ props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------ | ----------------------------------- | ------------------------------------ | ------- | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the slider. | | | `data-disabled` | `''` | Present when the slider is disabled. | | | `data-slider-root` | `''` | Present on the root element. | | ### Slider.Range The range of the slider. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----------------------------------- | ------------------------------------ | ------- | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the slider. | | | `data-disabled` | `''` | Present when the slider is disabled. | | | `data-slider-range` | `''` | Present on the range elements. | | ### Slider.Thumb A thumb on the slider. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `index` required | `number` | The index of the value this thumb represents.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the thumb is disabled.`Default: false` | | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----------------------------------- | -------------------------------------------------------- | ------- | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the slider. | | | `data-disabled` | `''` | Present when either the thumb or the slider is disabled. | | | `data-active` | `''` | Present when the thumb is active/grabbed. | | | `data-slider-thumb` | `''` | Present on the thumb elements. | | ### Slider.ThumbLabel A label for a thumb on the slider. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `index` required | `number` | The index of the thumb this label represents.`Default:  —— undefined` | | | `position` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The position of the label relative to the thumb.``Default: '`'top'` for horizontal sliders and `'left'` for vertical sliders'`` | | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------ | ------- | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the slider. | | | `data-disabled` | `''` | Present when either the thumb this label represents or the slider is disabled. | | | `data-position` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The position of the label relative to the thumb. | | | `data-active` | `''` | Present when the thumb this label represents is active. | | | `data-value` | `''` | The value of the thumb this label represents. | | | `data-slider-thumb-label` | `''` | Present on the thumb label elements. | | ### Slider.Tick A tick mark on the slider. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `index` required | `number` | The index of the tick in the array of ticks provided by the `ticks` `children` snippet prop.`Default:  —— undefined` | | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------ | ----------------------------------- | -------------------------------------------------------------------------------------------- | ------- | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the slider. | | | `data-disabled` | `''` | Present when the slider is disabled. | | | `data-bounded` | `''` | Present when the tick is bounded (i.e. the tick is less than or equal to the current value). | | | `data-value` | `''` | The value the tick represents. | | | `data-selected` | `''` | Present when the tick is the same value as one of the thumbs. | | | `data-slider-tick` | `''` | Present on the tick elements. | | ### Slider.TickLabel A label for a tick on the slider. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `index` required | `number` | The index of the tick in the array of ticks provided by the `ticks` `children` snippet prop.`Default:  —— undefined` | | | `position` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The position of the tick label.`Default:  —— undefined` | | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the slider. | | | `data-disabled` | `''` | Present when the slider is disabled. | | | `data-position` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The position of the tick label. | | | `data-selected` | `''` | Present when the tick this label represents is the same value as one of the thumbs. | | | `data-value` | `''` | The value of the tick this label represents. | | | `data-bounded` | `''` | Present when the tick this label represents is bounded (i.e. the tick is less than or equal to the current value or within the range of a multiple slider). | | | `data-slider-tick-label` | `''` | Present on the tick label elements. | | [Previous Separator](/docs/components/separator) [Next Switch](/docs/components/switch) ---------------------------------------------------- # Switch Documentation A toggle control that allows users to switch between "on" and "off" states. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
    Do not disturb
    ``` ## Overview The Switch component provides an intuitive and accessible toggle control, allowing users to switch between two states, typically "on" and "off". This component is commonly used for enabling or disabling features, toggling settings, or representing boolean values in forms. The Switch offers a more visual and interactive alternative to traditional checkboxes for binary choices. ## Key Features - **Accessibility**: Built with WAI-ARIA guidelines in mind, ensuring keyboard navigation and screen reader support. - **State Management**: Internally manages the on/off state, with options for controlled and uncontrolled usage. - **Style-able**: Data attributes allow for smooth transitions between states and custom styles. - **HTML Forms**: Can render a hidden input element for form submissions. ## Architecture The Switch component is composed of two main parts: - **Root**: The main container component that manages the state and behavior of the switch. - **Thumb**: The "movable" part of the switch that indicates the current state. ## Structure Here's an overview of how the Switch component is structured in code: ```svelte ``` ## Reusable Components It's recommended to use the `Switch` primitives to create your own custom switch component that can be used throughout your application. In the example below, we're using the `Checkbox` and [`Label`](/docs/components/label) components to create a custom switch component. MySwitch.svelte ```svelte {labelText} ``` You can then use the `MySwitch` component in your application like so: ```svelte ``` ## Managing Checked State This section covers how to manage the `checked` state of the component. ### Two-Way Binding Use `bind:checked` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Disabled State You can disable the switch by setting the `disabled` prop to `true`. ```svelte ``` ## HTML Forms If you pass the `name` prop to `Switch.Root`, a hidden input element will be rendered to submit the value of the switch to a form. By default, the input will be submitted with the default checkbox value of `'on'` if the switch is checked. ```svelte ``` ### Custom Input Value If you'd prefer to submit a different value, you can use the `value` prop to set the value of the hidden input. For example, if you wanted to submit a string value, you could do the following: ```svelte ``` ### Required If you want to make the switch required, you can use the `required` prop. ```svelte ``` This will apply the `required` attribute to the hidden input element, ensuring that proper form submission is enforced. ## API Reference ### Switch.Root The root switch component used to set and manage the state of the switch. | Property | Type | Description | Details | | ------------------- | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `checked` $bindable | `boolean` | The checked state of the checkbox.`Default: false` | | | `onCheckedChange` | `function` - (checked: boolean) => void | A callback that is fired when the checked state changes.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the switch is disabled.`Default: false` | | | `name` | `string` | The name of the hidden input element, used to identify the input in form submissions.`Default:  —— undefined` | | | `required` | `boolean` | Whether or not the switch is required to be checked.`Default: false` | | | `value` | `string` | The value of the hidden input element to be used in form submissions when the switch is checked.`Default:  —— undefined` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { checked: boolean; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { checked: boolean; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------ | --------------------------------- | ------------------------------------ | ------- | | `data-state` | `enum` - 'checked' \| 'unchecked' | The switch's checked state. | | | `data-checked` | `''` | Present when the switch is checked. | | | `data-disabled` | `''` | Present when the switch is disabled. | | | `data-switch-root` | `''` | Present on the root element. | | ### Switch.Thumb The thumb on the switch used to indicate the switch's state. | Property | Type | Description | Details | | --------------- | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - type ChildrenSnippetProps = { checked: boolean; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { checked: boolean; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | --------------------------------- | ----------------------------------- | ------- | | `data-state` | `enum` - 'checked' \| 'unchecked' | The switch's checked state. | | | `data-checked` | `''` | Present when the switch is checked. | | | `data-switch-thumb` | `''` | Present on the thumb element. | | [Previous Slider](/docs/components/slider) [Next Tabs](/docs/components/tabs) ---------------------------------------------------- # Tabs Documentation Organizes content into tabbed sections. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
    Outbound Inbound

    Prague

    06:05

    3h 30m

    Malaga

    06:05


    Malaga

    07:25

    3h 20m

    Prague

    10:45


    ``` ## Structure ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Orientation The `orientation` prop is used to determine the orientation of the `Tabs` component, which influences how keyboard navigation will work. When the `orientation` is set to `'horizontal'`, the `ArrowLeft` and `ArrowRight` keys will move the focus to the previous and next tab, respectively. When the `orientation` is set to `'vertical'`, the `ArrowUp` and `ArrowDown` keys will move the focus to the previous and next tab, respectively. ```svelte ``` ## Activation Mode By default, the `Tabs` component will automatically activate the tab associated with a trigger when that trigger is focused. This behavior can be disabled by setting the `activationMode` prop to `'manual'`. When set to `'manual'`, the user will need to activate the tab by pressing the trigger. ```svelte ``` ## API Reference ### Tabs.Root The root tabs component which contains the other tab components. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `string` | The active tab value.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: string) => void | A callback function called when the active tab value changes.`Default:  —— undefined` | | | `activationMode` | `enum` - 'automatic' \| 'manual' | How the activation of tabs should be handled. If set to `'automatic'`, the tab will be activated when the trigger is focused. If set to `'manual'`, the tab will be activated when the trigger is pressed.`Default: 'automatic'` | | | `disabled` | `boolean` | Whether or not the tabs are disabled.`Default: false` | | | `loop` | `boolean` | Whether or not the tabs should loop when navigating with the keyboard.`Default: true` | | | `orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the tabs.`Default: 'horizontal'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------ | ----------------------------------- | ---------------------------- | ------- | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the tabs. | | | `data-tabs-root` | `''` | Present on the root element. | | ### Tabs.List The component containing the tab triggers. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------ | ----------------------------------- | ---------------------------- | ------- | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the tabs. | | | `data-tabs-list` | `''` | Present on the list element. | | ### Tabs.Trigger The trigger for a tab. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` required | `string` | The value of the tab this trigger represents.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the tab is disabled.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----------------------------------- | --------------------------------------------- | ------- | | `data-state` | `enum` - 'active' \| 'inactive' | The state of the tab trigger. | | | `data-value` | `''` | The value of the tab this trigger represents. | | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the tabs. | | | `data-disabled` | `''` | Present when the tab trigger is disabled. | | | `data-tabs-trigger` | `''` | Present on the trigger elements. | | ### Tabs.Content The panel containing the contents of a tab. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` required | `string` | The value of the tab this content represents.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----- | -------------------------------- | ------- | | `data-tabs-content` | `''` | Present on the content elements. | | [Previous Switch](/docs/components/switch) [Next Time Field](/docs/components/time-field) ---------------------------------------------------- # Time Field Documentation An alternative to the native \`\\` element. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
    Appointment Time {#snippet children({ segments })} {#each segments as { part, value }, i (part + i)}
    {#if part === "literal"} {value} {:else} {value} {/if}
    {/each} {/snippet}
    ``` ##### Heads up! Before diving into this component, it's important to understand how dates/times work in Bits UI. Please read the [Dates/Times](/docs/dates) documentation to learn more! ## Overview The `TimeField` component is an alternative to the native `` element. It provides a more flexible and customizable way to select times within a designated field. ## Structure ```svelte Check-in time {#snippet children({ segments })} {#each segments as { part, value }} {value} {/each} {/snippet} ``` ## Reusable Components It's recommended to use the `TimeField` primitives to build your own custom time field component that can be used throughout your application. The following example shows how you might create a reusable `MyTimeField` component that can be used throughout your application. For style inspiration, reference the featured demo at the top of this page. MyTimeField.svelte ```svelte {labelText} {#snippet children({ segments })} {#each segments as { part, value }} {value} {/each} {/snippet} ``` Expand Code ```svelte
    {labelText} {#snippet children({ segments })} {#each segments as { part, value }, i (i)}
    {#if part === "literal"} {value} {:else} {value} {/if}
    {/each} {/snippet}
    ``` We'll be using this newly created `MyTimeField` component in the following demos and examples to prevent repeating the same code, so be sure to reference it as you go through the documentation. ## Segments A segment of the `TimeField` represents a not only a specific part of the time, such as the hour, minute, second, dayPeriod, or timeZoneName, but can also reference a `"literal"` which is typically a separator between the different parts of the time, and varies based on the `locale`. Notice that in the `MyTimeField` component we created, we're styling the `TimeField.Segment` components differently based on whether they are a `"literal"` or not. ## Placeholder The `placeholder` prop for the `TimeField.Root` component isn't what is displayed when the field is empty, but rather what time our field should start with when the user attempts to cycle through the segments. By default, the `placeholder` will be set to `12:00 AM` or `00:00` depending on the hour cycle. ```svelte ``` If we're collecting a time from the user where we want the timezone to be displayed as well, we can use a `ZonedDateTime` object instead. ```svelte ``` ## Managing Placeholder State This section covers how to manage the `placeholder` state of the Time Field. ### Two-Way Binding Use `bind:placeholder` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the Time Field. The `value` can be a `Time`, `CalendarDateTime`, or `ZonedDateTime` object, and the type in the `value`/`onValueChange` prop will be inferred based on the type of the `value` prop. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled For complete control over the component's state, use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) to manage the value state externally. ```svelte ``` ## Default Value Often, you'll want to start the `TimeField.Root` component with a default value. Likely this value will come from a database in the format of an ISO 8601 string. You can use the `parseDateTime` function from the `@internationalized/date` package to parse the string into a `CalendarDateTime` object. +page.svelte ```svelte ``` Now our input is populated with the default value. In addition to the `parseDateTime` function, you can also use `parseZonedDateTime` to parse the string into a `ZonedDateTime` object if you're working with a timezone. ## Validation ### Minimum Value You can set a minimum value for the `TimeField.Root` component by using the `minValue` prop. If a user selects a time that is less than the minimum value, the time field will be marked as invalid. ```svelte ``` In the example above, we're setting the minimum value to 9:00 AM, and the default value to 8:00 AM. This causes the time field to be marked as invalid, and we can style it accordingly. If you adjust the time to be greater than the minimum value, the invalid state will be cleared. ### Maximum Value You can set a maximum value for the `TimeField.Root` component by using the `maxValue` prop. If a user selects a time that is greater than the maximum value, the time field will be marked as invalid. ```svelte ``` In the example above, we're setting the maximum value to 5:00 PM, and the default value to 6:00 PM. This causes the time field to be marked as invalid, and we can style it accordingly. If you adjust the time to be less than the maximum value, the invalid state will be cleared. ### Custom Validation You can use the `validate` prop to provide a custom validation function for the time field. This function should return a string or array of strings as validation errors if the time is invalid, or undefined/nothing if the time is valid. The strings are then passed to the `onInvalid` callback, which you can use to display an error message to the user. ```svelte ``` ## Granularity The `granularity` prop sets the granularity of the date field, which determines which segments are rendered in the date field. The `granularity` can be set to either `'hour'`, `'minute'`, or `'second'` and defaults to `'minute'`. ```svelte ``` In the example above, we're setting the granularity to `'second'`, which means that the time field will include an additional segment for the seconds. ## Localization You can use the `locale` prop to set the locale of the date field. This will affect the formatting of the date field's segments and placeholders. ```svelte ``` Notice how in the example above, the hour is displayed as `13` (in 24-hour format) and the day period is not displayed, since the locale is set to `de` (German). ## API Reference ### TimeField.Root The root time field component. | Property | Type | Description | Details | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `TimeValue` - import type { Time, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type TimeValue = Time \| CalendarDateTime \| ZonedDateTime | The selected time.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: TimeValue) => void | A function that is called when the selected time changes. The type of value is inferred from the `value` prop if provided.`Default:  —— undefined` | | | `placeholder` $bindable | `TimeValue` - import type { Time, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type TimeValue = Time \| CalendarDateTime \| ZonedDateTime | The placeholder time, which is used to determine what time to start the segments from when no value exists.`Default:  —— undefined` | | | `onPlaceholderChange` | `function` - (value: TimeValue) => void | A function that is called when the placeholder time changes.`Default:  —— undefined` | | | `required` | `boolean` | Whether or not the field is required.`Default: false` | | | `validate` | `function` - (time: TimeValue) => string\[] \| string \| void | A function that returns whether or not a time is unavailable.`Default:  —— undefined` | | | `onInvalid` | `function` - (reason: 'min' \| 'max' \| 'custom', msg?: string \| string\[]) => void | A callback fired when the field's value is invalid.`Default:  —— undefined` | | | `errorMessageId` | `string` | The `id` of the element which contains the error messages for the field when the time is invalid.`Default:  —— undefined` | | | `hourCycle` | `enum` - '12' \| '24' | The hour cycle to use for formatting times. Defaults to the locale preference`Default:  —— undefined` | | | `granularity` | `enum` - 'hour' \| 'minute' \| 'second' | The granularity to use for formatting the field. The field will render segments for each part of the time up to and including the specified granularity.`Default: 'minute'` | | | `hideTimeZone` | `boolean` | Whether or not to hide the time zone segment of the field. This only applies when using a `ZonedDateTime` as the `value` prop.`Default: false` | | | `maxValue` | `TimeValue` - import type { Time, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type TimeValue = Time \| CalendarDateTime \| ZonedDateTime | The maximum valid time that can be entered.`Default:  —— undefined` | | | `minValue` | `TimeValue` - import type { Time, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type TimeValue = Time \| CalendarDateTime \| ZonedDateTime | The minimum valid time that can be entered.`Default:  —— undefined` | | | `locale` | `string` | The locale to use for formatting times.`Default: en-US` | | | `disabled` | `boolean` | Whether or not the field is disabled.`Default: false` | | | `readonly` | `boolean` | Whether or not the field is readonly.`Default: false` | | | `readonlySegments` | `EditableTimeSegmentPart[]` - "hour" \| "minute" \| "second" \| "dayPeriod" | An array of segments that should be readonly, which prevent user input on them.`Default:  —— undefined` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### TimeField.Input The container for the segments of the time field. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `name` | `string` | The name of the time field used for form submission. If provided, a hidden input element will be rendered alongside the time field.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - import type { TimeSegmentPart } from "bits-ui"; type ChildrenSnippetProps = { segments: Array<{ part: TimeSegmentPart; value: string }>; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - import type { TimeSegmentPart } from "bits-ui"; type ChildSnippetProps = { props: Record\; segments: Array<{ part: TimeSegmentPart; value: string }>; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | -------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid. | | | `data-disabled` | `''` | Present on the element when the field is disabled. | | | `data-time-field-input` | `''` | Present on the element. | | ### TimeField.Segment A segment of the time field. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `part` required | `TimeSegmentPart` - "hour" \| "minute" \| "second" \| "dayPeriod" \| "timeZoneName" \| "literal"; | The part of the time to render.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-disabled` | `''` | Present on the element when the field is disabled | | | `data-readonly` | `''` | Present on the element when the field or segment is readonly | | | `data-segment` | `enum` - 'hour' \| 'minute' \| 'second' \| 'dayPeriod' \| 'timeZoneName' \| 'literal' | The part of the time to render. | | | `data-time-field-segment` | `''` | Present on the element. | | ### TimeField.Label The label for the time field. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | ------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-disabled` | `''` | Present on the element when the field is disabled | | | `data-time-field-label` | `''` | Present on the element. | | [Previous Tabs](/docs/components/tabs) [Next Time Range Field](/docs/components/time-range-field) ---------------------------------------------------- # Time Range Field Documentation Enables users to input a range of times within a designated field. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte Hotel dates
    {#each ["start", "end"] as const as type (type)} {#snippet children({ segments })} {#each segments as { part, value }, i (part + i)}
    {#if part === "literal"} {value} {:else} {value} {/if}
    {/each} {/snippet}
    {#if type === "start"} {/if} {/each}
    ``` ##### Heads up! Before diving into this component, it's important to understand how dates/times work in Bits UI. Please read the [Dates/Times](/docs/dates) documentation to learn more! ## Overview The `TimeRangeField` component combines two [Time Field](/docs/components/time-field) components to create a time range field. Check out the [Time Field](/docs/components/time-field) component documentation for information on how to customize this component. ## Structure ```svelte Working Hours {#each ["start", "end"] as const as type} {#snippet children({ segments })} {#each segments as { part, value }} {value} {/each} {/snippet} {/each} ``` ## Managing Placeholder State This section covers how to manage the `placeholder` state of the component. ### Two-Way Binding Use `bind:placeholder` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## API Reference ### TimeRangeField.Root The root time field component. | Property | Type | Description | Details | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` $bindable | `TimeRange` - { start: TimeValue \| undefined; end: TimeValue \| undefined } | The selected time range.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: TimeRange) => void | A function that is called when the selected time range changes.`Default:  —— undefined` | | | `placeholder` $bindable | `TimeValue` - import type { Time, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type TimeValue = Time \| CalendarDateTime \| ZonedDateTime | The placeholder time, which is used to determine what time to start the segments from when no value exists.`Default:  —— undefined` | | | `onPlaceholderChange` | `function` - (value: TimeValue) => void | A function that is called when the placeholder time changes.`Default:  —— undefined` | | | `errorMessageId` | `string` | The `id` of the element which contains the error messages for the field when the time is invalid.`Default:  —— undefined` | | | `validate` | `function` - (time: TimeValue) => string\[] \| string \| void | A function that returns whether or not a time is unavailable.`Default:  —— undefined` | | | `onInvalid` | `function` - (reason: 'min' \| 'max' \| 'custom', msg?: string \| string\[]) => void | A callback fired when the field's value is invalid.`Default:  —— undefined` | | | `minValue` | `TimeValue` - import type { Time, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type TimeValue = Time \| CalendarDateTime \| ZonedDateTime | The minimum valid time that can be entered.`Default:  —— undefined` | | | `maxValue` | `TimeValue` - import type { Time, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type TimeValue = Time \| CalendarDateTime \| ZonedDateTime | The maximum valid time that can be entered.`Default:  —— undefined` | | | `granularity` | `enum` - 'hour' \| 'minute' \| 'second' | The granularity to use for formatting the field. The field will render segments for each part of the time up to and including the specified granularity.`Default: 'minute'` | | | `hideTimeZone` | `boolean` | Whether or not to hide the time zone segment of the field. This only applies when using a `ZonedDateTime` as the `value` prop.`Default: false` | | | `hourCycle` | `enum` - '12' \| '24' | The hour cycle to use for formatting times. Defaults to the locale preference`Default:  —— undefined` | | | `locale` | `string` | The locale to use for formatting times.`Default: en-US` | | | `disabled` | `boolean` | Whether or not the field is disabled.`Default: false` | | | `readonly` | `boolean` | Whether or not the field is readonly.`Default: false` | | | `readonlySegments` | `EditableTimeSegmentPart[]` - "hour" \| "minute" \| "second" \| "dayPeriod" | An array of segments that should be readonly, which prevent user input on them.`Default:  —— undefined` | | | `required` | `boolean` | Whether or not the field is required.`Default: false` | | | `onStartValueChange` | `function` - (value: TimeValue \| undefined) => void | A function that is called when the start time changes.`Default:  —— undefined` | | | `onEndValueChange` | `function` - (value: TimeValue \| undefined) => void | A function that is called when the end time changes.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------------- | ----- | ---------------------------- | ------- | | `data-time-range-field-root` | `''` | Present on the root element. | | ### TimeRangeField.Input The container for the segments of the time field. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `type` required | `enum` - 'start' \| 'end' | The type of field to render (start or end).`Default:  —— undefined` | | | `name` | `string` | The name of the time field used for form submission. If provided, a hidden input element will be rendered alongside the time field.`Default:  —— undefined` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` - import type { TimeSegmentPart } from "bits-ui"; type ChildrenSnippetProps = { segments: Array<{ part: TimeSegmentPart; value: string }>; }; | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - import type { TimeSegmentPart } from "bits-ui"; type ChildSnippetProps = { props: Record\; segments: Array<{ part: TimeSegmentPart; value: string }>; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | -------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid. | | | `data-disabled` | `''` | Present on the element when the field is disabled. | | | `data-time-field-input` | `''` | Present on the element. | | ### TimeRangeField.Segment A segment of the time field. | Property | Type | Description | Details | | --------------- | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `part` required | `TimeSegmentPart` - "hour" \| "minute" \| "second" \| "dayPeriod" \| "timeZoneName" \| "literal" | The part of the time to render.`Default:  —— undefined` | | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------- | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-disabled` | `''` | Present on the element when the field is disabled | | | `data-segment` | `enum` - 'hour' \| 'minute' \| 'second' \| 'dayPeriod' \| 'timeZoneName' \| 'literal' | The type of segment the element represents. | | | `data-time-field-segment` | `''` | Present on the element. | | ### TimeRangeField.Label The label for the time field. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLSpanElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ----------------------- | ----- | ------------------------------------------------ | ------- | | `data-invalid` | `''` | Present on the element when the field is invalid | | | `data-time-field-label` | `''` | Present on the element. | | [Previous Time Field](/docs/components/time-field) [Next Toggle](/docs/components/toggle) ---------------------------------------------------- # Toggle Group Documentation Groups multiple toggle controls, allowing users to enable one or multiple options. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte ``` ## Structure ```svelte bold italic ``` ## Single & Multiple The `ToggleGroup` component supports two `type` props, `'single'` and `'multiple'`. When the `type` is set to `'single'`, the `ToggleGroup` will only allow a single item to be selected at a time, and the type of the `value` prop will be a string. When the `type` is set to `'multiple'`, the `ToggleGroup` will allow multiple items to be selected at a time, and the type of the `value` prop will be an array of strings. ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## API Reference ### ToggleGroup.Root The root component which contains the toggle group items. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `type` required | `enum` - 'single' \| 'multiple' | The type of the component, used to determine the type of the value, when `'multiple'` the value will be an array.`Default:  —— undefined` | | | `value` $bindable | `union` - string \| string\[] | The value of the toggle group. If the `type` is `'multiple'`, this will be an array of strings, otherwise it will be a string.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: string) => void \| (value: string\[]) => void | A callback function called when the value of the toggle group changes. The type of the value is dependent on the type of the toggle group.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the switch is disabled.`Default: false` | | | `loop` | `boolean` | Whether or not the toggle group should loop when navigating.`Default: true` | | | `orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the toggle group.`Default: 'horizontal'` | | | `rovingFocus` | `boolean` | Whether or not the toggle group should use roving focus when navigating.`Default: true` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----------------------------------- | ------------------------------------ | ------- | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the toggle group. | | | `data-toggle-group-root` | `''` | Present on the root element. | | ### ToggleGroup.Item An individual toggle item within the group. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` | `string` | The value of the item.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the switch is disabled.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------------ | ----------------------------------- | -------------------------------------------------- | ------- | | `data-state` | `enum` - 'on' \| 'off' | Whether the toggle item is in the on or off state. | | | `data-value` | `''` | The value of the toggle item. | | | `data-orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the toggle group. | | | `data-disabled` | `''` | Present when the toggle item is disabled. | | | `data-toggle-group-item` | `''` | Present on the toggle group item. | | [Previous Toggle](/docs/components/toggle) [Next Toolbar](/docs/components/toolbar) ---------------------------------------------------- # Toggle Documentation A toggle control that allows users to switch between two states. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
    {code}
    ``` ## Structure ```svelte ``` ## Managing Pressed State This section covers how to manage the `pressed` state of the component. ### Two-Way Binding Use `bind:pressed` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## API Reference ### Toggle.Root The toggle button. | Property | Type | Description | Details | | ------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `pressed` $bindable | `boolean` | Whether or not the toggle button is pressed.`Default: false` | | | `onPressedChange` | `function` - (pressed: boolean) => void | A callback function called when the pressed state of the toggle changes.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the switch is disabled.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------ | ---------------------- | --------------------------------------------- | ------- | | `data-state` | `enum` - 'on' \| 'off' | Whether the toggle is in the on or off state. | | | `data-disabled` | `''` | Present when the toggle is disabled. | | | `data-toggle-root` | `''` | Present on the root element. | | [Previous Time Range Field](/docs/components/time-range-field) [Next Toggle Group](/docs/components/toggle-group) ---------------------------------------------------- # Toolbar Documentation Displays frequently used actions or tools in a compact and easily accessible bar. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
    Ask AI
    ``` ## Structure ```svelte ``` ## Managing Value State This section covers how to manage the `value` state of the component. ### Two-Way Binding Use `bind:value` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## API Reference ### Toolbar.Root The root component which contains the toolbar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `loop` | `boolean` | Whether or not the toolbar should loop when navigating.`Default: true` | | | `orientation` | `enum` - 'horizontal' \| 'vertical' | The orientation of the toolbar.`Default: 'horizontal'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----------------------------------- | --------------------------------- | ------- | | `data-orientation` | `enum` - 'vertical' \| 'horizontal' | The orientation of the component. | | | `data-toolbar-root` | `''` | Present on the root element. | | ### Toolbar.Button A button in the toolbar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the button is disabled.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | --------------------- | ----- | ------------------------------ | ------- | | `data-toolbar-button` | `''` | Present on the button element. | | ### Toolbar.Link A link in the toolbar. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `ref` $bindable | `HTMLAnchorElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ----- | ---------------------------- | ------- | | `data-toolbar-link` | `''` | Present on the link element. | | ### Toolbar.Group A group of toggle items in the toolbar. | Property | Type | Description | Details | | ----------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `type` required | `enum` - 'single' \| 'multiple' | The type of the component, used to determine the type of the value, when `'multiple'` the value will be an array.`Default:  —— undefined` | | | `value` $bindable | `union` - string \| string\[] | The value of the toggle group. If the type is multiple, this will be an array of strings, otherwise it will be a string.`Default:  —— undefined` | | | `onValueChange` | `function` - (value: string) => void \| (value: string\[]) => void | A callback function called when the value changes.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the switch is disabled.`Default: false` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----- | ----------------------------- | ------- | | `data-toolbar-group` | `''` | Present on the group element. | | ### Toolbar.GroupItem A toggle item in the toolbar toggle group. | Property | Type | Description | Details | | ---------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` required | `string` | The value of the toolbar toggle group item. When the toolbar toggle group item is selected, toolbar the toggle group's value will be set to this value if in single mode, or this value will be pushed to the toggle group's array value if in multiple mode.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the item is disabled.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ------------------- | ---------------------- | ---------------------------------------------------------- | ------- | | `data-state` | `enum` - 'on' \| 'off' | Whether the toolbar toggle item is in the on or off state. | | | `data-value` | `''` | The value of the toolbar toggle item. | | | `data-disabled` | `''` | Present when the toolbar toggle item is disabled. | | | `data-toolbar-item` | `''` | Present on the toolbar toggle item. | | [Previous Toggle Group](/docs/components/toggle-group) [Next Tooltip](/docs/components/tooltip) ---------------------------------------------------- # Tooltip Documentation Displays supplementary information when users hover over or interact with an element. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ```svelte
    Make some magic!
    Make some magic!
    Make some magic!
    Make some magic!
    ``` ## Structure ```svelte ``` ## Provider Component The `Tooltip.Provider` component is required to be an ancestor of the `Tooltip.Root` component. It provides shared state for the tooltip components used within it. You can set a single `delayDuration` or `disableHoverableContent` prop on the provider component to apply to all the tooltip components within it. ```svelte ``` It also ensures that only a single tooltip within the same provider can be open at a time. It's recommended to wrap your root layout content with the provider component, setting your sensible default props there. +layout.svelte ```svelte {@render children()} ``` ## Managing Open State This section covers how to manage the `open` state of the component. ### Two-Way Binding Use `bind:open` for simple, automatic state synchronization: ```svelte ``` ### Fully Controlled Use a [Function Binding](https://svelte.dev/docs/svelte/bind#Function-bindings) for complete control over the state's reads and writes. ```svelte ``` ## Mobile Tooltips Tooltips are *not* supported on mobile devices. The intent of a tooltip is to provide a "tip" about a "tool" before the user interacts with that tool (in most cases, a button). This is not possible on mobile devices, because there is no sense of hover on mobile. If a user were to press/touch a button with a tooltip, the action that button triggers would be taken before they were even able to see the tooltip, which renders it useless. If you are using a tooltip on a button without an action, you should consider using a [Popover](/docs/components/popover) instead. If you'd like to learn more about how we came to this decision, here are some useful resources: > The tooltip is not the appropriate role for the more information "i" icon, ⓘ. A tooltip is directly associated with the owning element. The ⓘ isn't 'described by' detailed information; the tool or control is. > > [MDN ARIA Tooltips](https://arc.net/l/quote/zfvjgalg) > Tooltips should only ever contain non-essential content. The best approach to writing tooltip content is to always assume it may never be read. > > [Tooltips in the time of WCAG 2.1](https://arc.net/l/quote/gdrkepxb) ## Reusable Components It's recommended to use the `Tooltip` primitives to build your own custom tooltip component that can be used throughout your application. Below is an example of how you might create a reusable tooltip component that can be used throughout your application. Of course, this isn't the only way to do it, but it should give you a good idea of how to compose the primitives. MyTooltip.svelte ```svelte {@render trigger()} {@render children?.()} ``` You could then use the `MyTooltip` component in your application like so: +page.svelte ```svelte alert("changed to bold!") }}> {#snippet trigger()} {/snippet} Change font to bold ``` ## Delay Duration You can change how long a user needs to hover over a trigger before the tooltip appears by setting the `delayDuration` prop on the `Tooltip.Root` or `Tooltip.Provider` component. ```svelte ``` ## Close on Trigger Click By default, the tooltip will close when the user clicks the trigger. If you want to disable this behavior, you can set the `disableCloseOnTriggerClick` prop to `true`. ```svelte ``` ## Hoverable Content By default, the tooltip will remain open when the user hovers over the content. If you instead want the tooltip to close as the user moves their mouse towards the content, you can set the `disableHoverableContent` prop to `true`. ```svelte ``` ## Non-Keyboard Focus If you want to prevent opening the tooltip when the user focuses the trigger without using the keyboard, you can set the `ignoreNonKeyboardFocus` prop to `true`. ```svelte ``` ## Svelte Transitions You can use the `forceMount` prop along with the `child` snippet to forcefully mount the `Tooltip.Content` component to use Svelte Transitions or another animation library that requires more control. ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
    {/if} {/snippet}
    ``` Of course, this isn't the prettiest syntax, so it's recommended to create your own reusable content components that handles this logic if you intend to use this approach throughout your app. For more information on using transitions with Bits UI components, see the [Transitions](/docs/transitions) documentation. Expand Code ```svelte {#snippet child({ wrapperProps, props, open })} {#if open}
    Make some magic!
    {/if} {/snippet}
    ``` ## Opt-out of Floating UI When you use the `Tooltip.Content` component, Bits UI uses [Floating UI](https://floating-ui.com/) to position the content relative to the trigger, similar to other popover-like components. You can opt-out of this behavior by instead using the `Tooltip.ContentStatic` component. This component does not use Floating UI and leaves positioning the content entirely up to you. ```svelte Hello ``` ##### Note When using the `Tooltip.ContentStatic` component, the `Tooltip.Arrow` component will not be rendered relative to it as it is designed to be used with `Tooltip.Content`. ## Custom Anchor By default, the `Tooltip.Content` is anchored to the `Tooltip.Trigger` component, which determines where the content is positioned. If you wish to instead anchor the content to a different element, you can pass either a selector `string` or an `HTMLElement` to the `customAnchor` prop of the `Tooltip.Content` component. ```svelte
    ``` Expand Code ```svelte
    Custom Anchor
    Make some magic!
    ``` ## API Reference ### Tooltip.Provider A provider component which contains shared state and logic for the tooltips within its subtree. | Property | Type | Description | Details | | ---------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `delayDuration` | `number` | The amount of time in milliseconds to delay opening the tooltip when hovering over the trigger.`Default: 700` | | | `disableHoverableContent` | `boolean` | Whether or not to disable the hoverable content. This is useful when the content contains interactive elements.`Default: false` | | | `disabled` | `boolean` | Whether or not the tooltip is disabled.`Default: false` | | | `disableCloseOnTriggerClick` | `boolean` | Whether or not to close the tooltip when pressing the escape key. This is useful when the content contains interactive elements.`Default: false` | | | `skipDelayDuration` | `number` | The amount of time in milliseconds to delay opening the tooltip when the user has used their mouse to hover over the trigger.`Default: 300` | | | `ignoreNonKeyboardFocus` | `boolean` | Whether or not to ignore the tooltip when the focus is not on the trigger. This is useful when the content contains interactive elements.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### Tooltip.Root The root component containing the parts of the tooltip. Must be a descendant of a `Tooltip.Provider` component. | Property | Type | Description | Details | | ---------------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `open` $bindable | `boolean` | The open state of the component.`Default: false` | | | `onOpenChange` | `function` - (open: boolean) => void | A callback function called when the open state changes.`Default:  —— undefined` | | | `onOpenChangeComplete` | `function` - (open: boolean) => void | A callback function called after the open state changes and all animations have completed.`Default:  —— undefined` | | | `disabled` | `boolean` | Whether or not the tooltip is disabled.`Default: false` | | | `delayDuration` | `number` | The amount of time in milliseconds to delay opening the tooltip when hovering over the trigger.`Default: 700` | | | `disableHoverableContent` | `boolean` | Whether or not to disable the hoverable content. This is useful when the content contains interactive elements.`Default: false` | | | `disableCloseOnTriggerClick` | `boolean` | Whether or not to close the tooltip when pressing the escape key. This is useful when the content contains interactive elements.`Default: false` | | | `ignoreNonKeyboardFocus` | `boolean` | Whether or not to ignore the tooltip when the focus is not on the trigger. This is useful when the content contains interactive elements.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | ### Tooltip.Trigger A component which triggers the opening and closing of the tooltip on hover or focus. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `disabled` | `boolean` | Whether or not the tooltip trigger is disabled.`Default: false` | | | `ref` $bindable | `HTMLButtonElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `data-state` | `enum` - 'delayed-open' \| 'instant-open' \| 'closed' | Whether/how the tooltip is open or closed. When open, if there is a delay, the value will be 'delayed-open', otherwise it will be 'instant-open'. When closed, the value will be 'closed'. | | | `data-tooltip-trigger` | `''` | Present on the tooltip trigger element. | | ### Tooltip.Content The contents of the tooltip which are displayed when the tooltip is open. | Property | Type | Description | Details | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `side` | `enum` - 'top' \| 'bottom' \| 'left' \| 'right' | The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.`Default: 'bottom'` | | | `sideOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `align` | `enum` - 'start' \| 'center' \| 'end' | The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.`Default: 'start'` | | | `alignOffset` | `number` | The distance in pixels from the anchor to the floating element.`Default: 0` | | | `arrowPadding` | `number` | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `avoidCollisions` | `boolean` | When `true`, overrides the `side` and `align` options to prevent collisions with the boundary edges.`Default: true` | | | `collisionBoundary` | `union` - Element \| null | A boundary element or array of elements to check for collisions against.`Default:  —— undefined` | | | `collisionPadding` | `union` - number \| Partial\> | The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.`Default: 0` | | | `sticky` | `enum` - 'partial' \| 'always' | The sticky behavior on the align axis. `'partial'` will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst `'always'` will keep the content in the boundary regardless.`Default: 'partial'` | | | `hideWhenDetached` | `boolean` | When `true`, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.`Default: true` | | | `updatePositionStrategy` | `enum` - 'optimized' \| 'always' | The strategy to use when updating the position of the content. When `'optimized'` the content will only be repositioned when the trigger is in the viewport. When `'always'` the content will be repositioned whenever the position changes.`Default: 'optimized'` | | | `strategy` | `enum` - 'fixed' \| 'absolute' | The positioning strategy to use for the floating element. When `'fixed'` the element will be positioned relative to the viewport. When `'absolute'` the element will be positioned relative to the nearest positioned ancestor.`Default: 'fixed'` | | | `preventScroll` | `boolean` | When `true`, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.`Default: true` | | | `customAnchor` | `union` - string \| HTMLElement \| Measurable \| null | Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.`Default: null` | | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { /\*\* \* Props for the positioning wrapper \* Do not style this element - \* styling should be applied to the content element \*/ wrapperProps: Record\; /\*\* \* Props for your content element \* Apply your custom styles here \*/ props: Record\; /\*\* \* Content visibility state \* Use this for conditional rendering with \* Svelte transitions \*/ open: boolean; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `data-state` | `enum` - 'delayed-open' \| 'instant-open' \| 'closed' | Whether/how the tooltip is open or closed. When open, if there is a delay, the value will be 'delayed-open', otherwise it will be 'instant-open'. When closed, the value will be 'closed'. | | | `data-tooltip-content` | `''` | Present on the tooltip content element. | | | CSS Variable | Description | Details | | ----------------------------------------- | -------------------------------------------- | ------- | | `--bits-tooltip-content-transform-origin` | The transform origin of the content element. | | | `--bits-tooltip-content-available-width` | The available width of the content element. | | | `--bits-tooltip-content-available-height` | The available height of the content element. | | | `--bits-tooltip-anchor-width` | The width of the anchor element. | | | `--bits-tooltip-anchor-height` | The height of the anchor element. | | ### Tooltip.ContentStatic The contents of the tooltip which are displayed when the tooltip is open. (Static/No Floating UI) | Property | Type | Description | Details | | ------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `onInteractOutside` | `function` - (event: PointerEvent) => void | Callback fired when an outside interaction event occurs, which is a `pointerdown` event. You can call `event.preventDefault()` to prevent the default behavior of handling the outside interaction.`Default:  —— undefined` | | | `onFocusOutside` | `function` - (event: FocusEvent) => void | Callback fired when focus leaves the dismissible layer. You can call `event.preventDefault()` to prevent the default behavior on focus leaving the layer.`Default:  —— undefined` | | | `interactOutsideBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an interaction occurs outside of the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `onEscapeKeydown` | `function` - (event: KeyboardEvent) => void | Callback fired when an escape keydown event occurs in the floating content. You can call `event.preventDefault()` to prevent the default behavior of handling the escape keydown event.`Default:  —— undefined` | | | `escapeKeydownBehavior` | `enum` - 'close' \| 'ignore' \| 'defer-otherwise-close' \| 'defer-otherwise-ignore' | The behavior to use when an escape keydown event occurs in the floating content. `'close'` will close the content immediately. `'ignore'` will prevent the content from closing. `'defer-otherwise-close'` will defer to the parent element if it exists, otherwise it will close the content. `'defer-otherwise-ignore'` will defer to the parent element if it exists, otherwise it will ignore the interaction.`Default: 'close'` | | | `forceMount` | `boolean` | Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.`Default: false` | | | `dir` | `enum` - 'ltr' \| 'rtl' | The reading direction of the app.`Default: 'ltr'` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type ChildSnippetProps = { open: boolean; props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | ---------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `data-state` | `enum` - 'delayed-open' \| 'instant-open' \| 'closed' | Whether/how the tooltip is open or closed. When open, if there is a delay, the value will be 'delayed-open', otherwise it will be 'instant-open'. When closed, the value will be 'closed'. | | | `data-tooltip-content` | `''` | Present on the tooltip content element. | | ### Tooltip.Arrow An optional arrow element which points to the trigger when the tooltip is open. | Property | Type | Description | Details | | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `width` | `number` | The width of the arrow in pixels.`Default: 8` | | | `height` | `number` | The height of the arrow in pixels.`Default: 8` | | | `ref` $bindable | `HTMLDivElement` | The underlying DOM element being rendered. You can bind to this to get a reference to the element.`Default: null` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | | `child` | `Snippet` - type SnippetProps = { props: Record\; }; | Use render delegation to render your own element. See [Child Snippet](/docs/child-snippet) docs for more information.`Default:  —— undefined` | | | Data Attribute | Value | Description | Details | | -------------------- | ----------------------------------------------- | --------------------------------------------- | ------- | | `data-arrow` | `''` | Present on the arrow element. | | | `data-tooltip-arrow` | `''` | Present on the arrow element. | | | `data-side` | `enum` - 'top' \| 'right' \| 'bottom' \| 'left' | The side of the tooltip that the arrow is on. | | ### Tooltip.Portal When used, will render the tooltip content into the body or custom `to` element when open | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | [Previous Toolbar](/docs/components/toolbar) [Next BitsConfig](/docs/utilities/bits-config) ---------------------------------------------------- # BitsConfig Documentation A global context provider for configuring default props across all Bits UI components. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ## Overview `BitsConfig` is a global context provider that simplifies managing default prop values across all Bits UI components within its scope. Use it to set defaults like portal targets or locales centrally, and avoid the need to pass the same props to every component. ## Key Features - **Scoped defaults**: Applies defaults only to components within its scope. - **Inheritance**: Child `BitsConfig` instances inherit parent values and can selectively override them. - **Fallback resolution**: Automatically resolves values through the hierarchy of configs. ## Basic Usage Configure default props at the top level: ```svelte Open Dialog Dialog Title Dialog content here ``` ## Inheritance & Overrides Child instances inherit and override parent values: ```svelte
    Main dialog Hover me Tooltip content Nested dialog ``` ## Real-world Examples ### Global Defaults Set app-wide defaults at the root layout: +layout.svelte ```svelte {@render children()} ``` ### Theme-specific Configuration Different portal targets for distinct UI regions: ```svelte
    ``` ### Route-specific Locales Apply specific locales for certain routes: routes/(admin)/+layout.svelte ```svelte {@render children()} ``` ## Component-level Overrides Individual components can override global defaults: ```svelte Uses #main-portal Uses #special-portal ``` ## Value Resolution Order Bits UI resolves default values in this priority: 1. **Direct Component prop** 2. **Nearest parent BitsConfig** 3. **Inherited from parent BitsConfig(s)** 4. **Built-in component default** (e.g., portals default to `"body"`, locales default to `"en"`) ## API Reference ### BitsConfig A global context provider for configuring default props across all Bits UI components. | Property | Type | Description | Details | | ----------------- | --------------------------- | ------------------------------------------------------------------------------------------ | ------- | | `defaultPortalTo` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `defaultLocale` | `string` | The default locale to use for the app.`Default: en` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | [Previous Tooltip](/docs/components/tooltip) [Next IsUsingKeyboard](/docs/utilities/is-using-keyboard) ---------------------------------------------------- # IsUsingKeyboard Documentation A utility to track whether the user is actively using the keyboard or not. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ## Overview `IsUsingKeyboard` is a utility component that tracks whether the user is actively using the keyboard or not. This component is used internally by Bits UI components to provide keyboard accessibility features. It provides global state that is shared across all instances of the class to prevent duplicate event listener registration. ## Usage ```svelte ``` [Previous BitsConfig](/docs/utilities/bits-config) [Next mergeProps](/docs/utilities/merge-props) ---------------------------------------------------- # mergeProps Documentation A utility function to merge props objects. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ## Overview `mergeProps` is a utility function designed to merge multiple props objects. It's particularly useful for composing components with different prop sets or extending the functionality of existing components. It is used internally by Bits UI components to merge the custom `restProps` you pass to a component with the props that Bits UI provides to the component. ## Key Features - Merges multiple props objects - Chains event handlers with cancellation support - Combines class names - Merges style objects and strings - Chains non-event handler functions ## Detailed Behavior ### Event Handlers Event handlers are chained in the order they're passed. If a handler calls `event.preventDefault()`, subsequent handlers in the chain are not executed. ```ts const props1 = { onclick: (e: MouseEvent) => console.log("First click") }; const props2 = { onclick: (e: MouseEvent) => console.log("Second click") }; const mergedProps = mergeProps(props1, props2); mergedProps.onclick(new MouseEvent("click")); // Logs: "First click" then "Second click" ``` If `preventDefault()` is called: ```ts const props1 = { onclick: (e: MouseEvent) => console.log("First click") }; const props2 = { onclick: (e: MouseEvent) => { console.log("Second click"); e.preventDefault(); }, }; const props3 = { onclick: (e: MouseEvent) => console.log("Third click") }; const mergedProps = mergeProps(props1, props2, props3); mergedProps.onclick(new MouseEvent("click")); // Logs: "First click" then "Second click" only ``` Since `props2` called `event.preventDefault()`, `props3`'s `onclick` handler will not be called. ### Non-Event Handler Functions Non-event handler functions are also chained, but without the ability to prevent subsequent functions from executing: ```ts const props1 = { doSomething: () => console.log("Action 1") }; const props2 = { doSomething: () => console.log("Action 2") }; const mergedProps = mergeProps(props1, props2); mergedProps.doSomething(); // Logs: "Action 1" then "Action 2" ``` ### Classes Class names are merged using [`clsx`](https://www.npmjs.com/package/clsx): ```ts const props1 = { class: "text-lg font-bold" }; const props2 = { class: ["bg-blue-500", "hover:bg-blue-600"] }; const mergedProps = mergeProps(props1, props2); console.log(mergedProps.class); // "text-lg font-bold bg-blue-500 hover:bg-blue-600" ``` ### Styles Style objects and strings are merged, with later properties overriding earlier ones: ```ts const props1 = { style: { color: "red", fontSize: "16px" } }; const props2 = { style: "background-color: blue; font-weight: bold;" }; const mergedProps = mergeProps(props1, props2); console.log(mergedProps.style); // "color: red; font-size: 16px; background-color: blue; font-weight: bold;" ``` ```ts import { mergeProps } from "bits-ui"; const props1 = { style: "--foo: red" }; const props2 = { style: { "--foo": "green", color: "blue" } }; const mergedProps = mergeProps(props1, props2); console.log(mergedProps.style); // "--foo: green; color: blue;" ``` [Previous IsUsingKeyboard](/docs/utilities/is-using-keyboard) [Next Portal](/docs/utilities/portal) ---------------------------------------------------- # Portal Documentation A component that renders its children in a portal, preventing layout issues in complex UI structures. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page ## Overview The Portal component is a utility component that renders its children in a portal, preventing layout issues in complex UI structures. This component is used for the various Bits UI component that have a `Portal` sub-component. ## Usage ### Default behavior By default, the `Portal` component will render its children in the `body` element. ```svelte
    This content will be portalled to the body
    ``` ### Custom target You can use the `to` prop to specify a custom target element or selector to render the content to. ```svelte
    This content will be portalled to the #custom-target element
    ``` ### Disable You can use the `disabled` prop to disable the portal behavior. ```svelte
    This content will not be portalled
    ``` ### Overriding the default target The default target can modified using the `defaultPortalTo` prop of the [`BitsConfig`](/docs/utilities/bits-config) component. This will change the default target for all `Portal` components within its scope. Expand Code ```svelte
    ``` ## API Reference ### Portal Renders the children to a different location in the DOM. | Property | Type | Description | Details | | ---------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- | | `to` | `union` - Element \| string | Where to render the content when it is open. Defaults to the body.`Default: document.body` | | | `disabled` | `boolean` | Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.`Default: false` | | | `children` | `Snippet` | The children content to render.`Default:  —— undefined` | | [Previous mergeProps](/docs/utilities/merge-props) [Next useId](/docs/utilities/use-id) ---------------------------------------------------- # useId Documentation A utility function to generate unique IDs. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page The `useId` function is a utility function that can be used to generate unique IDs. This function is used internally by all Bits UI components and is exposed for your convenience. ## Usage ```svelte ``` [Previous Portal](/docs/utilities/portal) [Next WithElementRef](/docs/type-helpers/with-element-ref) ---------------------------------------------------- # WithElementRef Documentation A type helper to enable the \`ref\` prop on a component. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page The `WithElementRef` type helper is a convenience type that enables you to follow the same [`ref`](/docs/ref) prop pattern as used by Bits UI components when crafting your own. ```ts type WithElementRef = T & { ref?: U | null; }; ``` This type helper is used internally by Bits UI components to enable the `ref` prop on a component. ## Usage Example CustomButton.svelte ```svelte ``` [Previous useId](/docs/utilities/use-id) [Next WithoutChild](/docs/type-helpers/without-child) ---------------------------------------------------- # WithoutChild Documentation A type helper to exclude the child snippet prop from a component. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page The `WithoutChild` type helper is used to exclude the `child` snippet prop from a component. This is useful when you're building custom component wrappers that populate the `children` prop of a component and don't provide a way to pass a custom `child` snippet. To learn more about the `child` snippet prop, check out the [delegation](/docs/child-snippet) documentation. CustomAccordionHeader.svelte ```svelte {@render children?.()} ``` [Previous WithElementRef](/docs/type-helpers/with-element-ref) [Next WithoutChildren](/docs/type-helpers/without-children) ---------------------------------------------------- # WithoutChildrenOrChild Documentation A type helper to exclude the child ad children snippet props from a component. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page The `WithoutChildrenOrChild` type helper is used to exclude the `child` and `children` props from a component. This is useful when you're building custom component wrappers that populate the `children` prop of a component and don't provide a way to pass a custom `children` or `child` snippet. To learn more about the `child` snippet prop, check out the [delegation](/docs/child-snippet) documentation. CustomAccordionTrigger.svelte ```svelte {title} ``` Now, the `CustomAccordionTrigger` component won't expose `children` or `child` props to the user, but will expose the other root component props. [Previous WithoutChildren](/docs/type-helpers/without-children) ---------------------------------------------------- # WithoutChildren Documentation A type helper to exclude the children snippet prop from a component. This is a documentation section that potentially contains examples, demos, and other useful information related to a specific part of Bits UI. When helping users with this documentation, you can ignore the classnames applied to the demos unless they are relevant to the user's issue. Copy Page The `WithoutChildren` type helper is used to exclude the `children` snippet prop from a component. This is useful when you're building custom component wrappers that populate the `children` prop of a component. CustomAccordion.svelte ```svelte ``` In the example above, we're using the `WithoutChildren` type helper to exclude the `children` snippet prop from the `Accordion.Root` component. This ensures our exposed props are consistent with what is being used internally. [Previous WithoutChild](/docs/type-helpers/without-child) [Next WithoutChildrenOrChild](/docs/type-helpers/without-children-or-child) ----------------------------------------------------