# Carbon Components Svelte Carbon Components Svelte is a [Svelte](https://github.com/sveltejs/svelte) component library that implements the [Carbon Design System](https://www.carbondesignsystem.com/), an open source design system by IBM. ## Installation ```sh # npm npm i carbon-components-svelte # pnpm pnpm i carbon-components-svelte # Yarn yarn add carbon-components-svelte # Bun bun add carbon-components-svelte ``` ## Styling Before importing components, you will need to first apply Carbon component styles. The Carbon Design System supports five themes (2 light, 3 dark): White, Gray 10, Gray 80, Gray 90, Gray 100. This CSS needs only to be imported once, preferably at the root of your application. ```javascript // White theme import "carbon-components-svelte/css/white.css"; // Gray 10 theme import "carbon-components-svelte/css/g10.css"; // Gray 80 theme import "carbon-components-svelte/css/g80.css"; // Gray 90 theme import "carbon-components-svelte/css/g90.css"; // Gray 100 theme import "carbon-components-svelte/css/g100.css"; // All themes import "carbon-components-svelte/css/all.css"; ``` The `all.css` StyleSheet uses CSS variables to dynamically switch between themes. ## Optimization For smaller bundles and faster builds, use [carbon-preprocess-svelte](https://github.com/carbon-design-system/carbon-preprocess-svelte) with `optimizeImports` and `optimizeCss` below. Install [carbon-preprocess-svelte](https://github.com/carbon-design-system/carbon-preprocess-svelte) as a development dependency: ```bash npm i -D carbon-preprocess-svelte # pnpm pnpm i -D carbon-preprocess-svelte # Yarn yarn add -D carbon-preprocess-svelte # Bun bun add -D carbon-preprocess-svelte ``` ### optimizeImports `optimizeImports` is a Svelte preprocessor that rewrites barrel imports from Carbon components/icons/pictograms packages to their source Svelte code paths. This speeds up development and production build compile times while preserving IDE typeahead and autocompletion. It optimizes imports from `carbon-components-svelte`, `carbon-icons-svelte`, and `carbon-pictograms-svelte`. Example transformation: ```diff - import { Button } from "carbon-components-svelte"; + import Button from "carbon-components-svelte/src/Button/Button.svelte"; - import { Add } from "carbon-icons-svelte"; + import Add from "carbon-icons-svelte/lib/Add.svelte"; ``` **SvelteKit:** add it to `svelte.config.js`. If you use Vite, `vitePreprocess` should run before `optimizeImports`: ```javascript // svelte.config.js (SvelteKit) import { vitePreprocess } from "@sveltejs/vite-plugin-svelte"; import { optimizeImports } from "carbon-preprocess-svelte"; export default { preprocess: [vitePreprocess(), optimizeImports()], }; ``` **Plain Vite:** pass the preprocessor in `vite.config.js` when calling the Svelte plugin: ```javascript // vite.config.js (plain Vite + Svelte) import { svelte } from "@sveltejs/vite-plugin-svelte"; import { optimizeCss, optimizeImports } from "carbon-preprocess-svelte"; export default { plugins: [svelte({ preprocess: [optimizeImports()] }), optimizeCss()], }; ``` ### optimizeCss `optimizeCss` is a Vite plugin that removes unused Carbon styles at build time. `carbon-components-svelte@0.85.0` or greater is required. Add it to your Vite config: ```javascript // vite.config.js import { sveltekit } from "@sveltejs/kit/vite"; import { optimizeCss } from "carbon-preprocess-svelte"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [sveltekit(), optimizeCss()], }); ``` ## Dynamic theming Use the `all.css` StyleSheet for dynamic, client-side theming: ```javascript import "carbon-components-svelte/css/all.css"; ``` Programmatically switch between each of the five Carbon themes by setting the "theme" attribute on the HTML element: ```svelte ``` You can use the `Theme` component to update the theme at runtime. ## Collection The Carbon Svelte collection includes packages for icons, pictograms, and data visualization: - **Carbon Components Svelte** — 50+ components — [GitHub](https://github.com/carbon-design-system/carbon-components-svelte) - **Carbon Icons Svelte** — 2,600+ icons — [GitHub](https://github.com/carbon-design-system/carbon-icons-svelte) - **Carbon Pictograms Svelte** — 1,500+ pictograms — [GitHub](https://github.com/carbon-design-system/carbon-pictograms-svelte) - **Carbon Charts Svelte** — 25+ charts, powered by d3 — [GitHub](https://github.com/carbon-design-system/carbon-charts/tree/master/packages/svelte) - **Carbon Preprocess Svelte** — Collection of Carbon Svelte preprocessors — [GitHub](https://github.com/carbon-design-system/carbon-preprocess-svelte) ## Accordion Accordions create a vertically stacked list of expandable sections that show or hide content. They support custom titles, different sizes, and various states including disabled and skeleton loading. ### Default Use the accordion and accordion item components to compose a collapsible list of items. By default, the chevron icon is on the right side of the accordion item. ```svelte

Natural Language Classifier uses advanced natural language processing and machine learning techniques to create custom classification models. Users train their data and the service predicts the appropriate category for the inputted text.

Analyze text to extract meta-data from content such as concepts, entities, emotion, relations, sentiment and more.

Translate text, documents, and websites from one language to another. Create industry or region-specific translations via the service's customization capability.

``` ### Left-aligned chevron The chevron icon can be aligned to the left side of the accordion item by setting the `align` prop to "start". This provides an alternative visual style while maintaining the same functionality. ```svelte

Natural Language Classifier uses advanced natural language processing and machine learning techniques to create custom classification models. Users train their data and the service predicts the appropriate category for the inputted text.

Analyze text to extract meta-data from content such as concepts, entities, emotion, relations, sentiment and more.

Translate text, documents, and websites from one language to another. Create industry or region-specific translations via the service's customization capability.

``` ### Custom title slot Customize the title content by using the `title` slot instead of the `title` prop. This allows for more complex title layouts with multiple elements. ```svelte
Natural Language Classifier
AI / Machine Learning

Natural Language Classifier uses advanced natural language processing and machine learning techniques to create custom classification models. Users train their data and the service predicts the appropriate category for the inputted text.

Natural Language Understanding
AI / Machine Learning

Analyze text to extract meta-data from content such as concepts, entities, emotion, relations, sentiment and more.

Language Translator
AI / Machine Learning

Translate text, documents, and websites from one language to another. Create industry or region-specific translations via the service's customization capability.

``` ### First item open Set the `open` prop on an accordion item to have it expanded by default when the accordion is first rendered. ```svelte

Natural Language Classifier uses advanced natural language processing and machine learning techniques to create custom classification models. Users train their data and the service predicts the appropriate category for the inputted text.

Analyze text to extract meta-data from content such as concepts, entities, emotion, relations, sentiment and more.

Translate text, documents, and websites from one language to another. Create industry or region-specific translations via the service's customization capability.

``` ### Programmatic example This example demonstrates how to programmatically control the accordion items using the `bind:open` directive. Expand and collapse items based on user interactions or application state. ```svelte {#each items as item}

{item.description}

{/each}
``` ### Extra-large size The accordion can be displayed in an extra-large size by setting the `size` prop to "xl". This provides more visual emphasis and is suitable for prominent content sections. ```svelte

Natural Language Classifier uses advanced natural language processing and machine learning techniques to create custom classification models. Users train their data and the service predicts the appropriate category for the inputted text.

Analyze text to extract meta-data from content such as concepts, entities, emotion, relations, sentiment and more.

Translate text, documents, and websites from one language to another. Create industry or region-specific translations via the service's customization capability.

``` ### Small size For more compact layouts, set the `size` prop to "sm" to display the accordion in a smaller size. This is useful when space is limited or when the accordion is used as a secondary UI element. ```svelte

Natural Language Classifier uses advanced natural language processing and machine learning techniques to create custom classification models. Users train their data and the service predicts the appropriate category for the inputted text.

Analyze text to extract meta-data from content such as concepts, entities, emotion, relations, sentiment and more.

Translate text, documents, and websites from one language to another. Create industry or region-specific translations via the service's customization capability.

``` ### Disabled state Set the `disabled` prop on the accordion to disable all items at once. This prevents users from expanding or collapsing any items in the accordion. ```svelte

Natural Language Classifier uses advanced natural language processing and machine learning techniques to create custom classification models. Users train their data and the service predicts the appropriate category for the inputted text.

Analyze text to extract meta-data from content such as concepts, entities, emotion, relations, sentiment and more.

Translate text, documents, and websites from one language to another. Create industry or region-specific translations via the service's customization capability.

``` ### Batch disable Programmatically toggle the disabled state of all accordion items using the `disabled` prop. In this example, disabling all items also collapses them. ```svelte {#each items as item}

{item.description}

{/each}
``` ### Disabled (item) Individual accordion items can be disabled by setting the `disabled` prop on specific accordion item components. This allows for more granular control over which items are interactive. ```svelte

Natural Language Classifier uses advanced natural language processing and machine learning techniques to create custom classification models. Users train their data and the service predicts the appropriate category for the inputted text.

Analyze text to extract meta-data from content such as concepts, entities, emotion, relations, sentiment and more.

Translate text, documents, and websites from one language to another. Create industry or region-specific translations via the service's customization capability.

``` ### Skeleton The skeleton state provides a loading placeholder for the accordion. It displays a simplified version of the component while content is being loaded. ```svelte ``` ### Skeleton (left-aligned chevron) The skeleton state can be combined with the left-aligned chevron style by setting both the `skeleton` and `align="start"` props. ```svelte ``` ### Skeleton (custom count) By default, the skeleton state displays 4 items. Specify the number of skeleton items to display using the `count` prop. This is useful when you know the exact number of items that will be loaded. ```svelte ``` ### Skeleton (closed) By default, the first skeleton item is open. The skeleton state can be displayed in a collapsed state by setting `open={false}`. ```svelte ``` ### Skeleton (extra-large) The skeleton state supports the extra-large size variant, maintaining visual consistency with the active component states. ```svelte ``` ### Skeleton (small) The skeleton state also supports the small size variant, providing a compact loading placeholder for space-constrained layouts. ```svelte ``` --- ### Component API #### `Accordion` props | Prop | Type | Description | Default | | ---------- | ------------------ | ------------------------------------------------- | ----------- | | `align` | `"start" \| "end"` | Specify alignment of accordion item chevron icon. | `"end"` | | `size` | `"sm" \| "xl"` | Specify the size of the accordion. | _undefined_ | | `disabled` | `boolean` | Set to `true` to disable the accordion | `false` | | `skeleton` | `boolean` | Set to `true` to display the skeleton state | `false` | #### `Accordion` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `Accordion` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `Accordion` $$restProps `Accordion` spreads `$$restProps` to the `AccordionSkeleton` component. #### `AccordionItem` props | Prop | Type | Description | Default | | --------------------- | --------- | ------------------------------------------------------------------------------------------ | ------------------- | | `open` (Reactive) | `boolean` | Set to `true` to open the first accordion item | `false` | | `disabled` (Reactive) | `boolean` | Set to `true` to disable the accordion item | `false` | | `title` | `string` | Specify the title of the accordion item heading.
Alternatively, use the "title" slot. | `"title"` | | `iconDescription` | `string` | Specify the ARIA label for the accordion item chevron icon | `"Expand/Collapse"` | #### `AccordionItem` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | | `title` | `Record` | #### `AccordionItem` forwarded events | Event | | ----------------- | | `on:animationend` | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | | `on:keydown` | #### `AccordionItem` $$restProps `AccordionItem` spreads `$$restProps` to the `li` element. #### `AccordionSkeleton` props | Prop | Type | Description | Default | | ------- | ------------------ | ------------------------------------------------- | ----------- | | `count` | `number` | Specify the number of accordion items to render | `4` | | `align` | `"start" \| "end"` | Specify alignment of accordion item chevron icon. | `"end"` | | `size` | `"sm" \| "xl"` | Specify the size of the accordion. | _undefined_ | | `open` | `boolean` | Set to `false` to close the first accordion item | `true` | #### `AccordionSkeleton` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `AccordionSkeleton` $$restProps `AccordionSkeleton` spreads `$$restProps` to the `ul` element. ## AspectRatio Aspect ratios maintain consistent proportions for content across different screen sizes. They are particularly useful for images, videos, and other media that need to preserve their aspect ratio when resizing. Supported aspect ratios include `"2x1"`, `"2x3"`, `"16x9"`, `"4x3"`, `"1x1"`, `"3x4"`, `"3x2"`, `"9x16"` and `"1x2"`. ### Default Display a 2:1 aspect ratio container by default. ```svelte 2x1 ``` ### Ratio 2x3 Display content with a 2:3 aspect ratio. ```svelte 2x3 ``` ### Ratio 16x9 Display content with a 16:9 aspect ratio. ```svelte 16x9 ``` ### Ratio 4x3 Display content with a 4:3 aspect ratio. ```svelte 4x3 ``` ### Ratio 1x1 Display content with a 1:1 (square) aspect ratio. ```svelte 1x1 ``` ### Ratio 3x4 Display content with a 3:4 aspect ratio. ```svelte 3x4 ``` ### Ratio 3x2 Display content with a 3:2 aspect ratio. ```svelte 3x2 ``` ### Ratio 9x16 Display content with a 9:16 aspect ratio. ```svelte 9x16 ``` ### Ratio 1x2 Display content with a 1:2 aspect ratio. ```svelte 1x2 ``` ### Tile (16x9) Wrap a tile or other content in an aspect ratio container to maintain proportions. ```svelte Content ``` --- ### Component API #### `AspectRatio` props | Prop | Type | Description | Default | | ------- | --------------------------------------------------------------------------------- | ------------------------- | ------- | | `ratio` | `"2x1" \| "2x3" \| "16x9" \| "4x3" \| "1x1" \| "3x4" \| "3x2" \| "9x16" \| "1x2"` | Specify the aspect ratio. | `"2x1"` | #### `AspectRatio` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `AspectRatio` $$restProps `AspectRatio` spreads `$$restProps` to the `div` element. ## Breadcrumb Breadcrumbs display a hierarchical navigation trail that shows users their current location within an application. They support current page indication, trailing slash customization, and overflow handling for long navigation paths. ### Default Display a hierarchical navigation trail with slashes between items. Mark the current page with `isCurrentPage`. ```svelte Dashboard Annual reports 2019 ``` ### No trailing slash Remove the trailing slash from the last breadcrumb item using `noTrailingSlash`. ```svelte Home Profile ``` ### Overflow menu Add an overflow menu to handle long breadcrumb trails. Use overflow menu item components for menu options. ```svelte Home API documentation Usage ``` ### Breadcrumb trail Build a full breadcrumb trail with multiple items and a current page indicator. ```svelte {#each items as item, i} {item.text} {/each} ``` ### Skeleton Display a loading state with `skeleton` prop. Use `count` to specify the number of items. ```svelte ``` --- ### Component API #### `Breadcrumb` props | Prop | Type | Description | Default | | ----------------- | --------- | --------------------------------------------------- | ------- | | `noTrailingSlash` | `boolean` | Set to `true` to hide the breadcrumb trailing slash | `false` | | `skeleton` | `boolean` | Set to `true` to display skeleton state | `false` | #### `Breadcrumb` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `Breadcrumb` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `Breadcrumb` $$restProps `Breadcrumb` spreads `$$restProps` to the `BreadcrumbSkeleton` component. #### `BreadcrumbItem` props | Prop | Type | Description | Default | | --------------- | --------- | ---------------------------------------------------------------- | ----------- | | `href` | `string` | Set the `href` to use an anchor link. | _undefined_ | | `isCurrentPage` | `boolean` | Set to `true` if the breadcrumb item represents the current page | `false` | #### `BreadcrumbItem` slots | Slot | Detail | | --------- | ------------------------------------------------------------------------------------------- | | `default` | `{
props?: {
"aria-current"?: string;
class: "bx--link";
};
}` | #### `BreadcrumbItem` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `BreadcrumbItem` $$restProps `BreadcrumbItem` spreads `$$restProps` to the `li` element. ## Breakpoint The Carbon Design System [grid implementation](https://carbondesignsystem.com/guidelines/2x-grid/implementation#responsive-options) defines five responsive breakpoints: - **Small**: less than 672px - **Medium**: 672 - 1056px - **Large**: 1056 - 1312px - **X-Large**: 1312 - 1584px - **Max**: greater than 1584px This utility component uses the [Window.matchMedia API](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) to declaratively determine the current Carbon breakpoint size. ### Default Bind to the `size` prop to determine the current breakpoint size. Possible values include: `"sm" | "md" | "lg" | "xlg" | "max"`. The `"on:change"` event will fire when the size is initially determined and when a breakpoint change event occurs (e.g., the browser width is resized). ```svelte (events = [...events, e.detail])} />

Resize the width of your browser.

Breakpoint size

{size}

on:change
{JSON.stringify(events, null, 2)}
``` ### Store and Breakpoint Values Use `breakpointObserver` as an alternative to the component to get the current size as a Svelte store. The store provides two additional functions that create derived stores returning a `boolean` indicating whether the size is smaller/larger than a certain breakpoint. Access the `breakpoints` dictionary to map from `BreakpointSize` to `BreakpointValue`. ```svelte

Current breakpoint size: {$size}

Current breakpoint value: {breakpoints[$size]}px

Smaller than medium: {$smaller}

Larger than medium: {$larger}

``` --- ### Component API #### `Breakpoint` props | Prop | Type | Description | Default | | ------------------ | --------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `size` (Reactive) | `BreakpointSize` | Determine the current Carbon grid breakpoint size. | _undefined_ | | `sizes` (Reactive) | `Record` | Carbon grid sizes as an object. | `{
sm: false,
md: false,
lg: false,
xlg: false,
max: false,
}` | #### `Breakpoint` typedefs ```ts type BreakpointSize = "sm" | "md" | "lg" | "xlg" | "max"; type BreakpointValue = 320 | 672 | 1056 | 1312 | 1584; ``` #### `Breakpoint` slots | Slot | Detail | | --------- | -------------------------------------------------------------------------------------------------------- | | `default` | `{
size: BreakpointSize;
sizes: Record<
BreakpointSize,
boolean
>;
}` | #### `Breakpoint` dispatched events | Event | Detail | | ----------- | ------------------------------------------------------------------------------ | | `on:change` | `{
size: BreakpointSize;
breakpointValue: BreakpointValue;
}` | ## Button Buttons trigger actions in the interface. Use them to submit forms, navigate between pages, or perform specific tasks. Choose from different styles and sizes to match the importance and context of each action. ### Primary button The default button style is primary. This should be used for primary actions. ```svelte ``` ### Secondary button Set `kind="secondary"` for secondary actions. ```svelte ``` ### Tertiary button Set `kind="tertiary"` for tertiary actions. ```svelte ``` ### Ghost button Set `kind="ghost"` for ghost-style buttons. ```svelte ``` ### Danger button Set `kind="danger"` for destructive actions. ```svelte ``` ### Danger tertiary button Set `kind="danger-tertiary"` for less prominent destructive actions. ```svelte ``` ### Danger tertiary, icon-only button Create an icon-only danger tertiary button by omitting the label text and providing an icon description for accessibility. ```svelte ``` ### Button with icon Add an icon to the button using the `icon` prop. ```svelte ``` ### Icon-only button > [!NOTE] Provide an **iconDescription** for accessibility. This text will be > used as the button's tooltip and screen reader label. ```svelte ``` ### Link button with icon Similarly, link buttons can have icons. ```svelte ``` ### Custom element By default, the button will render either a `button` or `a` element. To render a different element, set `as` to `true` and spread `let:props` to the element. ```svelte ``` ### Field size Set `size="field"` for field-sized buttons that align with form input heights. ```svelte ``` ### Small size Set `size="small"` for small buttons. ```svelte ``` ### Large size Set `size="lg"` for large buttons. ```svelte ``` ### Extra-large size Set `size="xl"` for extra-large buttons. ```svelte ``` ### Disabled state Set `disabled` to disable the button. ```svelte



``` ### Skeleton Set `skeleton` to show a loading state. ```svelte ``` --- ### Component API #### `Button` props | Prop | Type | Description | Default | | ------------------ | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | `ref` (Reactive) | `null \| HTMLAnchorElement \| HTMLButtonElement` | Obtain a reference to the HTML element | `null` | | `kind` | `"primary" \| "secondary" \| "tertiary" \| "ghost" \| "danger" \| "danger-tertiary" \| "danger-ghost"` | Specify the kind of button. | `"primary"` | | `size` | `"default" \| "field" \| "small" \| "lg" \| "xl"` | Specify the size of button. | `"default"` | | `expressive` | `boolean` | Set to `true` to use Carbon's expressive typesetting | `false` | | `isSelected` | `boolean` | Set to `true` to enable the selected state for an icon-only, ghost button. | `false` | | `icon` | `any` | Specify the icon to render.
Alternatively, use the named slot "icon". | _undefined_ | | `iconDescription` | `string` | Specify the ARIA label for the button icon. | _undefined_ | | `tooltipAlignment` | `"start" \| "center" \| "end"` | Set the alignment of the tooltip relative to the icon.
Only applies to icon-only buttons. | `"center"` | | `tooltipPosition` | `"top" \| "right" \| "bottom" \| "left"` | Set the position of the tooltip relative to the icon. | `"bottom"` | | `hideTooltip` | `boolean` | Set to `true` to hide the tooltip while maintaining accessibility.
Only applies to icon-only buttons.
When `true`, the tooltip is visually hidden but the `iconDescription` remains accessible to screen readers. | `false` | | `as` | `boolean` | Set to `true` to render a custom HTML element.
Props are destructured as `props` in the default slot. | `false` | | `skeleton` | `boolean` | Set to `true` to display the skeleton state | `false` | | `disabled` | `boolean` | Set to `true` to disable the button | `false` | | `href` | `string` | Set the `href` to use an anchor link. | _undefined_ | | `tabindex` | `string` | Specify the tabindex | `"0"` | | `type` | `string` | Specify the `type` attribute for the button element | `"button"` | #### `Button` slots | Slot | Detail | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `default` | `{
props: {
role: "button";
type?: string;
tabindex: any;
disabled: boolean;
href?: string;
class: string;
[key: string]: any;
};
}` | | `icon` | `{
style: undefined \| string;
}` | #### `Button` forwarded events | Event | | --------------- | | `on:click` | | `on:focus` | | `on:blur` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `Button` $$restProps `Button` spreads `$$restProps` to the `button | a | div` element. ## ButtonSet Group related buttons together in a set. Use this component to create consistent spacing and alignment between multiple buttons. ### Default Place buttons side by side in a horizontal layout. ```svelte ``` ### Stacked Set `stacked` to `true` to arrange buttons vertically. ```svelte ``` --- ### Component API #### `ButtonSet` props | Prop | Type | Description | Default | | --------- | --------- | --------------------------------------------- | ------- | | `stacked` | `boolean` | Set to `true` to stack the buttons vertically | `false` | #### `ButtonSet` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ButtonSet` $$restProps `ButtonSet` spreads `$$restProps` to the `div` element. ## Checkbox Checkboxes let users select one or more options from a list. Use them for multiple-choice questions, settings, or to confirm actions. ### Default Create a checkbox with a label using `labelText`. By default, the checkbox is unchecked. ```svelte ``` ### Checked Set `checked` to `true` to pre-select the checkbox. ```svelte ``` ### Indeterminate Set `indeterminate` to `true` to show a mixed state, typically used in parent checkboxes with some children selected. ```svelte ``` ### Hidden label Set `hideLabel` to `true` to visually hide the label while keeping it accessible to screen readers. ```svelte ``` ### Helper text Use `helperText` to provide additional context or instructions below the checkbox. ```svelte ``` ### Disabled state Set `disabled` to `true` to prevent user interaction. ```svelte ``` ### Read-only state Set `readonly` to `true` to make the checkbox non-interactive while keeping the label text readable. Unlike `disabled`, the readonly state is intended for displaying checkbox values that can only be changed programmatically. ```svelte ``` ### Reactive example (bind:checked) Use two-way binding with `bind:checked` to track the checkbox state. ```svelte
checked: {checked}
``` ### Reactive example (bind:group) Bind an array to `group` so each checkbox adds or removes its `value` when toggled. This API is inspired by Svelte [group inputs](https://svelte.dev/tutorial/svelte/group-inputs). When using `bind:group`, the checked state is derived from the group array: use `bind:group` (not `bind:checked`) to control selection, since updating `checked` directly will be overwritten. ```svelte
{#each values as value} {/each}
Selected: {JSON.stringify(group)}
``` ### Skeleton Set `skeleton` to `true` to show a loading state. ```svelte ``` ### CheckboxGroup Use a checkbox group to wrap multiple checkbox components with a shared legend, layout, and validation. This mirrors the [RadioButtonGroup](/components/RadioButton) API but supports multiple selections. ```svelte ``` ### CheckboxGroup (reactive example) Use two-way binding with `bind:selected` to track and update the selected values. ```svelte
selected: {JSON.stringify(selected)}
``` ### CheckboxGroup (hidden legend) Visually hide the legend while maintaining accessibility. ```svelte ``` ### CheckboxGroup (custom label content) Use the `legendChildren` slot to provide custom label content instead of using the `legendText` prop. ```svelte Notification preferences

You can change these settings at any time.

``` ### CheckboxGroup (helper text) Use `helperText` to provide additional context below the checkbox group. ```svelte ``` ### CheckboxGroup (disabled) Disable all checkboxes in the group. ```svelte ``` ### CheckboxGroup (read-only) Set `readonly` on each checkbox to display selected values without allowing user interaction. Unlike `disabled`, the readonly state keeps labels readable. ```svelte ``` --- ### Component API #### `Checkbox` props | Prop | Type | Description | Default | | -------------------------- | -------------------------- | -------------------------------------------------- | ----------------------------------- | | `checked` (Reactive) | `boolean` | Specify whether the checkbox is checked | `false` | | `group` (Reactive) | `ReadonlyArray` | Specify the bound group. | _undefined_ | | `indeterminate` (Reactive) | `boolean` | Specify whether the checkbox is indeterminate | `false` | | `title` (Reactive) | `string` | Specify the title attribute for the label element. | _undefined_ | | `ref` (Reactive) | `null \| HTMLInputElement` | Obtain a reference to the input HTML element | `null` | | `value` | `any` | Specify the value of the checkbox. | `""` | | `skeleton` | `boolean` | Set to `true` to display the skeleton state | `false` | | `required` | `boolean` | Set to `true` to mark the field as required | `false` | | `readonly` | `boolean` | Set to `true` for the checkbox to be read-only | `false` | | `disabled` | `boolean` | Set to `true` to disable the checkbox | `false` | | `labelText` | `string` | Specify the label text | `""` | | `hideLabel` | `boolean` | Set to `true` to visually hide the label text | `false` | | `helperText` | `string` | Specify the helper text | `""` | | `name` | `string` | Set a name for the input element | `""` | | `id` | `string` | Set an id for the input label | `ccs-${Math.random().toString(36)}` | #### `Checkbox` slots | Slot | Detail | | --------------- | ----------------------- | | `labelChildren` | `Record` | #### `Checkbox` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | | `on:change` | | `on:focus` | | `on:blur` | #### `Checkbox` dispatched events | Event | Detail | | ---------- | --------- | | `on:check` | `boolean` | #### `Checkbox` $$restProps `Checkbox` spreads `$$restProps` to the `div` element. ## ClickableTile Clickable tiles create interactive content areas that link to other pages or trigger actions. Use them to group related content and provide clear navigation targets. ### Default Create a clickable tile with an `href` to link to another page. ```svelte Carbon Design System ``` ### Prevent default behavior Handle the `click` event to override the default link behavior. Use `e.preventDefault()` to stop navigation. ```svelte { e.preventDefault(); // custom behavior }} > Carbon Design System ``` ### Light variant Set `light` to `true` to use the light color scheme. ```svelte Carbon Design System ``` ### Disabled state Set `disabled` to `true` to prevent interaction. ```svelte Carbon Design System ``` --- ### Component API #### `ClickableTile` props | Prop | Type | Description | Default | | -------------------- | --------- | ----------------------------------------- | ----------- | | `clicked` (Reactive) | `boolean` | Set to `true` to click the tile | `false` | | `light` | `boolean` | Set to `true` to enable the light variant | `false` | | `disabled` | `boolean` | Set to `true` to disable the tile | `false` | | `href` | `string` | Set the `href`. | _undefined_ | #### `ClickableTile` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ClickableTile` forwarded events | Event | | --------------- | | `on:click` | | `on:keydown` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `ClickableTile` $$restProps `ClickableTile` spreads `$$restProps` to the `a | p` element. ## CodeSnippet Code snippets display and copy code examples. They support single-line, multi-line, and inline formats with customizable copy and expand functionality. This component uses the native, asynchronous [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText) to copy text. You can override the default copy functionality with your own implementation. See [Overriding copy functionality](#overriding-copy-functionality). ### Default Display a single-line code snippet by default. ```svelte ``` ### Overriding copy functionality Pass a custom function to the `copy` prop to override the default copy behavior. In this example, we use the open source module [clipboard-copy](https://github.com/feross/clipboard-copy) to copy the text instead of the default Clipboard API. ```svelte copy(text)} /> ``` ### Preventing copy functionality Pass a no-op function to the `copy` prop to disable copying. ```svelte {}} /> ``` ### Inline Set `type="inline"` to display code inline with text. ```svelte ``` ### Multi-line Set `type="multi"` to display multiple lines of code with expand/collapse functionality. ```svelte ``` ### Expanded by default Set `expanded` to `true` to show the full multi-line code snippet. ```svelte ``` ### Reactive example The multi-line code snippet dispatches "expand" and "collapse" events. ```svelte i + 1).join("\n")} bind:expanded on:expand={() => { console.log("on:expand"); }} on:collapse={() => { console.log("on:collapse"); }} /> ``` ### Custom copy feedback text Set `feedback` to customize the copy button feedback text. ```svelte ``` ### Hidden copy button Set `hideCopyButton` to `true` to hide the copy button. ```svelte ``` ### Hidden show more button Set `showMoreLess` to `false` to hide the expand/collapse button on multi-line snippets. ```svelte ``` ### Hidden copy, show more buttons Hide both the copy and expand/collapse buttons. ```svelte ``` ### Custom show more/less text Set `showMoreText` and `showLessText` to customize the expand/collapse button text. ```svelte ``` ### Disabled state Set `disabled` to `true` to disable interaction. This only applies to `"single"` and `"multi"` types. ```svelte ``` ### Wrapped text By default, the code snippet preserves text formatting and does not wrap text. Set `wrapText` to `true` to wrap long lines in multi-line snippets. ```svelte ``` ### Dynamic multi-line code Use the `code` prop instead of the default slot for dynamically updated code. ```svelte ``` ### Hidden multi-line code The "Show more" button relies on the element's computed height. For hidden content, the button won't appear because the height is `0`. Re-render the component to fix this issue. ```svelte {#if toggled}
"Show more" will not render

{/if}
{#if toggled}

"Show more" will render

{/if} ``` ### Skeleton Set `skeleton` to `true` to show a loading state. Defaults to `"single"` type. ```svelte ``` ### Skeleton (multi-line) Set `type="multi"` with `skeleton` to show a multi-line loading state. ```svelte ``` --- ### Component API #### `CodeSnippet` props | Prop | Type | Description | Default | | ------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | `expanded` (Reactive) | `boolean` | Set to `true` to expand a multi-line code snippet (type="multi") | `false` | | `showMoreLess` (Reactive) | `boolean` | Set to `false` to hide the show more/less button.

NOTE: this prop only works with the `type="multi"` variant. | `true` | | `ref` (Reactive) | `null \| HTMLPreElement` | Obtain a reference to the pre HTML element | `null` | | `type` | `"single" \| "inline" \| "multi"` | Set the type of code snippet. | `"single"` | | `code` | `string` | Set the code snippet text.
Alternatively, use the default slot.

NOTE: you _must_ use the `code` prop for the copy-to-clipboard functionality. | _undefined_ | | `copy` | `(code: string) => void` | By default, this component uses `navigator.clipboard.writeText` API to copy text to the user's clipboard.

Provide a custom function to override this behavior. | _undefined_ | | `hideCopyButton` | `boolean` | Set to `true` to hide the copy button | `false` | | `disabled` | `boolean` | Set to `true` for the disabled variant.
Only applies to the "single", "multi" types. | `false` | | `wrapText` | `boolean` | Set to `true` to wrap the text.

NOTE: this prop only works with the `type="multi"` variant. | `false` | | `light` | `boolean` | Set to `true` to enable the light variant | `false` | | `skeleton` | `boolean` | Set to `true` to display the skeleton state | `false` | | `copyButtonDescription` | `string` | Specify the ARIA label for the copy button icon. | _undefined_ | | `copyLabel` | `string` | Specify the ARIA label of the copy button. | _undefined_ | | `feedback` | `string` | Specify the feedback text displayed when clicking the snippet | `"Copied!"` | | `feedbackTimeout` | `number` | Set the timeout duration (ms) to display feedback text | `2000` | | `showLessText` | `string` | Specify the show less text.

NOTE: this prop only works with the `type="multi"` variant. | `"Show less"` | | `showMoreText` | `string` | Specify the show more text.

NOTE: this prop only works with the `type="multi"` variant. | `"Show more"` | | `id` | `string` | Set an id for the code element | `ccs-${Math.random().toString(36)}` | #### `CodeSnippet` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `CodeSnippet` forwarded events | Event | | ----------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | | `on:animationend` | #### `CodeSnippet` dispatched events | Event | Detail | | ------------- | ------ | | `on:expand` | `null` | | `on:collapse` | `null` | | `on:copy` | `null` | #### `CodeSnippet` $$restProps `CodeSnippet` spreads `$$restProps` to the `button | span` element. ## ComboBox Combo boxes combine a text input with a dropdown menu to let users select from predefined options or enter custom values. They support filtering, custom item rendering, and various states. Combo boxes are keyed for performance reasons. > [!NOTE] Every `items` object must have a unique "id" property. ### Default Create a combobox with a title and placeholder text. Each item requires a unique `id` and `text`. ```svelte ``` ### Custom slot Override the default slot to customize how each item displays. Access the item and index through the `let:` directive. ```svelte
{item.text}
id: {item.id} - index: {index}
``` ### Hidden label Set `hideLabel` to `true` to visually hide the label while keeping it accessible to screen readers. ```svelte ``` ### Initial selected id Set `selectedId` to pre-select an item when the combobox loads. ```svelte ``` ### Reactive example See how the combobox responds to user input and selection changes. ```svelte
``` ### Autocomplete with typeahead Set `typeahead` to `true` to enable autocomplete with typeahead functionality. As users type, the input automatically suggests and completes matching items. The typeahead feature uses prefix matching (case-insensitive) to filter items that start with the entered text. When a match is found, the suggestion is displayed with the untyped portion highlighted, allowing users to accept it or continue typing. Note that when `typeahead` is enabled, the `shouldFilterItem` prop is ignored as the typeahead functionality provides its own filtering logic. ```svelte
``` ### Clear selection Use `bind:this` to access the component instance and call `ComboBox.clear()` to programmatically clear the selection. Set `focus: false` in the method options to prevent re-focusing the input. ```svelte
``` ### Multiple combo boxes See how to manage multiple comboboxes in a form. ```svelte
Primary: {primary}
Secondary: {secondary}
``` ### Filterable Enable filtering to let users search through the options. ```svelte ``` ### Filterable with custom label Set `itemToString` to customize how items display in the filterable combobox. ```svelte ``` ### Clear filter on open When using a filterable combobox, reopening the dropdown after making a selection will normally show only the filtered results matching the selected item. Set `clearFilterOnOpen` to `true` to temporarily clear the filter when opening, showing all available items. This makes it easier to browse and change selections. The original value is automatically restored if you close the dropdown without making a new selection. ```svelte ``` ### Filtering (async) By default, combobox filtering is synchronous and client-side. For async (e.g., server-side) filtering, bind to `value` and update `items` when input changes. This example simulates async/await behavior with a debounced input value change. ```svelte ``` ### Allow custom value Set `allowCustomValue` to `true` to let users enter custom text that isn't in the predefined list. By default, user-entered text is cleared when the combobox loses focus without selecting an item. When `allowCustomValue` is enabled, custom text is preserved. ```svelte { if (!value) return true; return item.text.toLowerCase().includes(value.toLowerCase()); }} on:select={(e) => { console.log("Selected item:", e.detail); }} />
Selected ID: {selectedId ?? "none"}
Current value: {value || "empty"}
``` ### Top direction Set `direction` to `"top"` to make the dropdown menu appear above the input. ```svelte ``` ### Light variant Set `light` to `true` to use the light color scheme. ```svelte ``` ### Portal menu Set `portalMenu` to `true` to render the dropdown menu in a floating portal. This prevents the menu from being clipped by parent containers with `overflow: hidden` or z-index stacking contexts. The example below shows a container with hidden overflow. Without `portalMenu`, the dropdown would be clipped. When inside a [Modal](/components/Modal#modal-with-dropdowns), `portalMenu` defaults to `true` unless explicitly set to `false`. ```svelte
This container has hidden overflow. Without portalMenu, the dropdown would be clipped.
``` ### Extra-large size Set `size` to `"xl"` for an extra-large combobox. ```svelte ``` ### Small size Set `size` to `"sm"` for a small combobox. ```svelte ``` ### Invalid state Set `invalid` to `true` and provide `invalidText` to show an error message. ```svelte ``` ### Warning state Set `warn` to `true` and provide `warnText` to show a warning message. ```svelte ``` ### Disabled state Set `disabled` to `true` to prevent interaction with the combobox. ```svelte ``` ### Disabled items Set `disabled: true` in an item object to disable specific options. ```svelte ``` ### Virtualized items (large lists) Virtualization is a technique that allows only the items currently visible in the viewport to be rendered in the DOM, improving performance for large lists. By default, the combo box will virtualize lists with more than 100 items. In the example below, 10,000 items are provided to the combobox but only 11 items (8 visible items + 3 overscan items) are rendered in the DOM. Set `virtualize={false}` to explicitly disable virtualization, even for large lists. Or, customize the threshold at which virtualization activates. See [Virtualized items (custom threshold)](#virtualized-items-custom-threshold). ```svelte item.text.toLowerCase().includes(value.toLowerCase())} bind:selectedId bind:value />
Selected: {selectedItem?.text}
``` ### Virtualized items (custom overscan) Overscanning is the process of rendering extra items above and below the viewport to ensure smooth scrolling. The default overscan value is 3. Specify a custom value for `overscan` to control how many extra items are rendered above/below the viewport for smoother scrolling. > [!NOTE] During very fast scrolling, higher overscan values may cause more > flickering due to increased DOM updates. For fast scrolling scenarios, use a > lower overscan value. ```svelte item.text.toLowerCase().includes(value.toLowerCase())} bind:selectedId bind:value /> ``` ### Virtualized items (custom threshold) The threshold is the minimum number of items required before virtualization activates. The default threshold value is 100, meaning lists with fewer than 100 items will not be virtualized and all items will be rendered normally. Specify a custom value for `threshold` to control when virtualization activates. Below the threshold, all items are rendered normally without virtualization. ```svelte item.text.toLowerCase().includes(value.toLowerCase())} bind:selectedId bind:value /> ``` ### Virtualized items (custom item height) The default item height for virtualization is 40 pixels. When using custom slots to render items with different heights (e.g., multi-line items with descriptions), specify a custom `itemHeight` value to match your item's actual height. ```svelte item.text.toLowerCase().includes(value.toLowerCase())} bind:selectedId bind:value let:item > {item.text} {item.description} ``` --- ### Component API #### `ComboBox` props | Prop | Type | Description | Default | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | `selectedId` (Reactive) | `Item["id"]` | Set the selected item by value id. | _undefined_ | | `value` (Reactive) | `string` | Specify the selected combobox value | `""` | | `open` (Reactive) | `boolean` | Set to `true` to open the combobox menu dropdown | `false` | | `ref` (Reactive) | `null \| HTMLInputElement` | Obtain a reference to the input HTML element | `null` | | `listRef` (Reactive) | `null \| HTMLDivElement` | Obtain a reference to the list HTML element. | `null` | | `items` | `ReadonlyArray` | Set the combobox items. | `[]` | | `itemToString` | `(item: Item) => string` | Override the display of a combobox item. | _undefined_ | | `direction` | `"bottom" \| "top"` | Specify the direction of the combobox dropdown menu. | `"bottom"` | | `size` | `"sm" \| "xl"` | Set the size of the combobox. | _undefined_ | | `disabled` | `boolean` | Set to `true` to disable the combobox | `false` | | `labelText` | `string` | Specify the title text of the combobox | `""` | | `hideLabel` | `boolean` | Set to `true` to visually hide the label text | `false` | | `placeholder` | `string` | Specify the placeholder text | `""` | | `helperText` | `string` | Specify the helper text | `""` | | `invalidText` | `string` | Specify the invalid state text | `""` | | `invalid` | `boolean` | Set to `true` to indicate an invalid state | `false` | | `warn` | `boolean` | Set to `true` to indicate a warning state | `false` | | `warnText` | `string` | Specify the warning state text | `""` | | `light` | `boolean` | Set to `true` to enable the light variant | `false` | | `allowCustomValue` | `boolean` | Set to `true` to allow custom values that are not in the items list.
By default, user-entered text is cleared when the combobox loses focus without selecting an item.
When enabled, custom text is preserved. | `false` | | `clearFilterOnOpen` | `boolean` | Set to `true` to clear the input value when opening the dropdown.
This allows users to see all available items instead of only filtered results.
The original value is restored if the dropdown is closed without making a selection. | `false` | | `typeahead` | `boolean` | Set to `true` to enable autocomplete with typeahead | `false` | | `shouldFilterItem` | `(item: Item, value: string) => boolean` | Determine if an item should be filtered given the current combobox value.
Will be ignored if `typeahead` is enabled. | _undefined_ | | `translateWithId` | `(id: import("../ListBox/ListBoxMenuIcon.svelte").ListBoxMenuIconTranslationId) => string` | Override the chevron icon label based on the open state.
Defaults to "Open menu" when closed and "Close menu" when open. | _undefined_ | | `translateWithIdSelection` | `(id: "clearSelection") => string` | Override the label of the clear button when the input has a selection.
Defaults to "Clear selected item" since a combo box can only have one selection. | _undefined_ | | `id` | `string` | Set an id for the list box component | `ccs-${Math.random().toString(36)}` | | `name` | `string` | Specify a name attribute for the input. | _undefined_ | | `virtualize` | `undefined \| boolean \| { itemHeight?: number, containerHeight?: number, overscan?: number, threshold?: number, maxItems?: number }` | Enable virtualization for large lists. Virtualization renders only the items currently visible in the viewport, improving performance for large lists.

By default, virtualization is automatically enabled for lists with more than 100 items.

Set `virtualize={false}` to explicitly disable virtualization, even for large lists.

Set `virtualize={true}` to explicitly enable virtualization with default settings.

Provide an object to customize virtualization behavior:
- `itemHeight` (default: 40): The height in pixels of each item. Specify a custom value when using custom slots with multi-line items or different heights.
- `containerHeight` (default: 300): The maximum height in pixels of the dropdown container.
- `overscan` (default: 3): The number of extra items to render above and below the viewport for smoother scrolling. Higher values may cause more flickering during very fast scrolling.
- `threshold` (default: 100): The minimum number of items required before virtualization activates. Lists with fewer items will render all items normally without virtualization.
- `maxItems` (default: undefined): The maximum number of items to render. When undefined, all visible items are rendered. | _undefined_ | | `portalMenu` | `boolean \| undefined` | Set to `true` to render the dropdown menu in a portal,
allowing it to escape containers with `overflow: hidden`.
When inside a Modal, defaults to `true` unless explicitly set to `false`. | _undefined_ | | `clear` | `(options?: { focus?: boolean; }) => Promise` | Clear the combo box programmatically.
By default, focuses the combo box after clearing. Set `options.focus` to `false` to prevent focusing. | _undefined_ | #### `ComboBox` typedefs ```ts type ComboBoxItem = { id: Id; text: string; /** Whether the item is disabled */ disabled?: boolean; }; ``` #### `ComboBox` slots | Slot | Detail | | --------------- | ------------------------------------------------- | | `default` | `{
item: Item;
index: number;
}` | | `labelChildren` | `Record` | #### `ComboBox` forwarded events | Event | | ------------ | | `on:clear` | | `on:input` | | `on:keydown` | | `on:keyup` | | `on:focus` | | `on:blur` | | `on:paste` | | `on:scroll` | #### `ComboBox` dispatched events | Event | Detail | | ----------- | ------------------------------------------------------------------ | | `on:select` | `{
selectedId: Item["id"];
selectedItem: Item;
}` | #### `ComboBox` $$restProps `ComboBox` spreads `$$restProps` to the `input` element. ## ComposedModal Composed modals let you build custom modals by combining modal header, modal body, and modal footer components. Use them to create focused interactions that require user attention or input. **ComposedModal vs Modal** The composed modal provides a composition-based approach with modal header, modal body, and modal footer sub-components for maximum flexibility. For simpler use cases, use [Modal](/components/Modal) instead. Both components share the same events, accessibility features, and [focus behavior](/components/Modal#focus-behavior). ### Composed modal Create a modal with a header, body, and footer. Each section can be customized independently. ```svelte ``` ### With Portal Wrap the composed modal in a portal to ensure it renders above all z-index stacking contexts and parent overflow constraints, preventing visual clipping and layering issues. ```svelte

This container hides overflowing content. Without a portal, the modal would be clipped.

This composed modal is rendered in a portal, ensuring it appears above all z-index stacking contexts and parent overflow constraints.

(open = false)} />
``` ### Prevent default close behavior The modal dispatches a cancelable `close` event, allowing you to prevent the modal from closing using `e.preventDefault()`. The event includes a `trigger` property indicating what triggered the close attempt: `"escape-key"`, `"outside-click"`, or `"close-button"`. ```svelte { console.log("Close triggered by:", e.detail.trigger); if (hasUnsavedChanges) { e.preventDefault(); showWarning = true; } }} on:submit={() => { hasUnsavedChanges = false; open = false; }} > {#if showWarning} {/if}

You have unsaved changes. Click "Save" to apply them.

{ hasUnsavedChanges = false; showWarning = false; open = false; }} />
``` ### Danger modal Display critical actions or destructive operations with the danger variant. Set `danger` on both `ComposedModal` and `ModalFooter` for the red danger styling. By default, the cancel button receives focus instead of the critical button to prevent accidental destructive actions. ```svelte

This is a permanent action and cannot be undone.

(open = false)} />
``` ### Progress modal Combine the composed modal with a progress indicator to create a multi-step flow within a modal. Use the modal footer's default slot to render Cancel (ghost), Previous (secondary), and Next (primary) buttons. Track the current step to control which content is displayed and update the button label on the final step. ```svelte
0} label="General" /> 1} label="Configure" /> {#if step === 0} {:else if step === 1} {:else}

Review your workspace configuration before creating.

{#if name || region}

Name: {name || "(not set)"} · Region: {region || "(not set)"}

{/if} {/if}
``` ### Multiple secondary buttons Set `secondaryButtons` in the modal footer to create a 3-button modal. This prop replaces `secondaryButtonText` and takes a tuple of two button configurations. ```svelte (open = false)}> { if (detail.text === "Cancel") open = false; if (detail.text === "Review") console.log("Review"); }} /> ``` --- ### Component API #### `ComposedModal` props | Prop | Type | Description | Default | | ---------------------------- | ------------------------ | --------------------------------------------------------------------- | ------------------------------ | | `open` (Reactive) | `boolean` | Set to `true` to open the modal | `false` | | `ref` (Reactive) | `null \| HTMLDivElement` | Obtain a reference to the top-level HTML element | `null` | | `size` | `"xs" \| "sm" \| "lg"` | Set the size of the composed modal. | _undefined_ | | `danger` | `boolean` | Set to `true` to use the danger variant | `false` | | `preventCloseOnClickOutside` | `boolean` | Set to `true` to prevent the modal from closing when clicking outside | `false` | | `containerClass` | `string` | Specify a class for the inner modal | `""` | | `selectorPrimaryFocus` | `null \| string` | Specify a selector to be focused when opening the modal. | `"[data-modal-primary-focus]"` | #### `ComposedModal` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ComposedModal` forwarded events | Event | | --------------- | | `on:keydown` | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `ComposedModal` dispatched events | Event | Detail | | -------------------------- | ------------------------------------------------------------------------------------------------- | | `on:close` | `{
trigger:
\| "escape-key"
\| "outside-click"
\| "close-button";
}` | | `on:transitionend` | `{
open: boolean;
}` | | `on:submit` | `null` | | `on:click:button--primary` | `null` | | `on:open` | `null` | #### `ComposedModal` $$restProps `ComposedModal` spreads `$$restProps` to the `div` element. #### `ModalHeader` props | Prop | Type | Description | Default | | ----------------- | -------- | ----------------------------------------- | --------- | | `title` | `string` | Specify the modal title | `""` | | `label` | `string` | Specify the modal label | `""` | | `labelClass` | `string` | Specify the label class | `""` | | `titleClass` | `string` | Specify the title class | `""` | | `closeClass` | `string` | Specify the close class | `""` | | `closeIconClass` | `string` | Specify the close icon class | `""` | | `iconDescription` | `string` | Specify the ARIA label for the close icon | `"Close"` | #### `ModalHeader` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ModalHeader` forwarded events | Event | | ---------- | | `on:click` | #### `ModalHeader` $$restProps `ModalHeader` spreads `$$restProps` to the `div` element. #### `ModalBody` props | Prop | Type | Description | Default | | --------------------- | --------- | ----------------------------------------------------- | ------- | | `hasForm` | `boolean` | Set to `true` if the modal contains form elements | `false` | | `hasScrollingContent` | `boolean` | Set to `true` if the modal contains scrolling content | `false` | #### `ModalBody` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ModalBody` $$restProps `ModalBody` spreads `$$restProps` to the `div` element. #### `ModalFooter` props | Prop | Type | Description | Default | | ----------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ----------- | | `primaryButtonText` | `string` | Specify the primary button text | `""` | | `primaryButtonIcon` | `any` | Specify the primary button icon. | _undefined_ | | `primaryButtonDisabled` | `boolean` | Set to `true` to disable the primary button | `false` | | `primaryClass` | `string` | Specify a class for the primary button. | _undefined_ | | `secondaryButtonText` | `string` | Specify the secondary button text | `""` | | `secondaryButtons` | `[] \| [{ text: string; }, { text: string; }]` | 2-tuple prop to render two secondary buttons for a 3 button modal.
Supersedes `secondaryButtonText`. | `[]` | | `secondaryClass` | `string` | Specify a class for the secondary button. | _undefined_ | | `danger` | `boolean` | Set to `true` to use the danger variant | `false` | #### `ModalFooter` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ModalFooter` dispatched events | Event | Detail | | ---------------------------- | ------------------------------ | | `on:click:button--secondary` | `{
text: string;
}` | #### `ModalFooter` $$restProps `ModalFooter` spreads `$$restProps` to the `div` element. ## ContainedList Contained lists provide a structured way to display a list of items within a container. They support various sizes, interactive items, icons, actions, and search functionality. They are useful for displaying hierarchical or grouped content with consistent spacing and styling. ### Default Display a basic contained list with a header label and list items. The default size is `md`. ```svelte Item 1 Item 2 Item 3 ``` ### Custom label Use the `labelChildren` slot to provide custom label content instead of using the `labelText` prop. ```svelte Custom label Item 1 Item 2 Item 3 ``` ### Small size Use the `sm` size variant for more compact list items with reduced padding and height. ```svelte Item 1 Item 2 Item 3 ``` ### Large size Use the `lg` size variant for larger list items with increased padding and height. ```svelte Item 1 Item 2 Item 3 ``` ### Extra-large size Use the `xl` size variant for the largest list items with maximum padding and height. ```svelte Item 1 Item 2 Item 3 ``` ### Inset rulers Set the `inset` prop to `true` to make the divider lines between list items inset from the edges, creating a more refined visual appearance. ```svelte Item 1 Item 2 Item 3 ``` ### Disclosed variant Set `kind="disclosed"` to use a more compact header style with sticky positioning. When scrolling, the list header will stick to the top of the container, making it useful for long lists where you want to keep the context visible. The header in the disclosed variant has a fixed height. ```svelte
{#each Array.from({ length: 6 }) as i} Item {/each} {#each Array.from({ length: 6 }) as i} Item {/each}
``` ### With icons Add icons to list items by passing an icon component to the `icon` prop. Icons are displayed to the left of the item content. ```svelte Item 1 Item 2 Item 3 ``` ### With expandable search Use the `action` slot on the contained list to add interactive elements like an expandable search component. The search will be positioned in the header and can be used to filter list items. ```svelte Item 1 Item 2 Item 3 ``` ### With persistent search Pass the search component as a direct child (not in the `action` slot) to create a persistent search that appears below the title. The search input is styled specifically for use within the list and is adapted to work with the sticky list headers. ```svelte {#each filteredResults as item} {item} {/each} ``` ### Interactive items Set the `interactive` prop to `true` on a contained list item to render the item as a clickable button element. This enables keyboard navigation and click event handling. You can also set `disabled` to prevent interaction. ```svelte console.log("click")}> Item 1 Item 2 Item 3 ``` ### Interactive items with actions Add interactive elements to individual list items using the `action` slot on a contained list item. This is useful for adding buttons, icons, or other controls that appear on the right side of each item. Actions are positioned absolutely and don't interfere with the item's clickable area. ```svelte console.log("click")}> Item 1
Selected index: {selectedIndex}
``` ### Custom switch slot Override the default slot in the switch to customize how each option displays. ```svelte Latest news Trending ``` ### Extra-large size Set `size` to `"xl"` for an extra-large content switcher. ```svelte ``` ### Small size Set `size` to `"sm"` for a small content switcher. ```svelte ``` ### Disabled state Set `disabled` to `true` on individual switches to prevent interaction. ```svelte ``` --- ### Component API #### `ContentSwitcher` props | Prop | Type | Description | Default | | -------------------------- | -------------- | ----------------------------------------- | ----------- | | `selectedIndex` (Reactive) | `number` | Set the selected index of the switch item | `0` | | `size` | `"sm" \| "xl"` | Specify the size of the content switcher. | _undefined_ | #### `ContentSwitcher` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ContentSwitcher` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `ContentSwitcher` dispatched events | Event | Detail | | ----------- | -------- | | `on:change` | `number` | #### `ContentSwitcher` $$restProps `ContentSwitcher` spreads `$$restProps` to the `div` element. #### `Switch` props | Prop | Type | Description | Default | | --------------------- | --------------------------- | ------------------------------------------------------------------ | ----------------------------------- | | `selected` (Reactive) | `boolean` | Set to `true` for the switch to be selected | `false` | | `ref` (Reactive) | `null \| HTMLButtonElement` | Obtain a reference to the button HTML element | `null` | | `text` | `string` | Specify the switch text.
Alternatively, use the default slot. | `"Provide text"` | | `disabled` | `boolean` | Set to `true` to disable the switch | `false` | | `id` | `string` | Set an id for the button element | `ccs-${Math.random().toString(36)}` | #### `Switch` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `Switch` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | | `on:keydown` | #### `Switch` $$restProps `Switch` spreads `$$restProps` to the `button` element. ## ContextMenu Context menus display a menu when users right-click. Use them to provide quick access to contextual actions or options. In the examples, right click anywhere within the iframe. ### Default The context menu appears when right-clicking anywhere in the window. Use context menu option for menu items and context menu divider for visual separation. ```svelte

Right click anywhere on this page

``` ### Custom target By default, the context menu will trigger when right clicking anywhere in the `window`. Set `target` to specify which element triggers the context menu. ```svelte console.log(e.detail)}>

Right click this element

``` ### Multiple targets Set `target` to an array of elements to trigger the context menu from multiple sources. ```svelte console.log(e.detail)}>

Right click this element

... or this one

``` ### Radio groups Use context menu group and context menu radio group to organize related options and create radio button selections. ```svelte

Right click anywhere on this page

``` --- ### Component API #### `ContextMenu` props | Prop | Type | Description | Default | | ----------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `open` (Reactive) | `boolean` | Set to `true` to open the menu.
Either `x` and `y` must be greater than zero. | `false` | | `x` (Reactive) | `number` | Specify the horizontal offset of the menu position | `0` | | `y` (Reactive) | `number` | Specify the vertical offset of the menu position | `0` | | `ref` (Reactive) | `null \| HTMLUListElement` | Obtain a reference to the unordered list HTML element | `null` | | `target` | `null \| ReadonlyArray` | Specify an element or list of elements to trigger the context menu.
If no element is specified, the context menu applies to the entire window. | `null` | #### `ContextMenu` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ContextMenu` forwarded events | Event | | ------------ | | `on:click` | | `on:keydown` | #### `ContextMenu` dispatched events | Event | Detail | | ---------- | ------------- | | `on:open` | `HTMLElement` | | `on:close` | `null` | #### `ContextMenu` $$restProps `ContextMenu` spreads `$$restProps` to the `ul` element. #### `ContextMenuGroup` props | Prop | Type | Description | Default | | ------------------------ | ----------------------- | ---------------------- | ------- | | `selectedIds` (Reactive) | `ReadonlyArray` | | `[]` | | `labelText` | `string` | Specify the label text | `""` | #### `ContextMenuGroup` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ContextMenuRadioGroup` props | Prop | Type | Description | Default | | ----------------------- | -------- | ------------------------------- | ------- | | `selectedId` (Reactive) | `string` | Set the selected radio group id | `""` | | `labelText` | `string` | Specify the label text | `""` | #### `ContextMenuRadioGroup` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ContextMenuOption` props | Prop | Type | Description | Default | | ----------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------- | | `indented` (Reactive) | `boolean` | Set to `true` to indent the label | `false` | | `icon` (Reactive) | `any` | Specify the icon to render.
Icon is rendered to the left of the label text. | _undefined_ | | `selected` (Reactive) | `boolean` | Set to `true` to use the selected variant | `false` | | `selectable` (Reactive) | `boolean` | Set to `true` to enable the selectable variant.
Automatically set to `true` if `selected` is `true`. | `false` | | `ref` (Reactive) | `null \| HTMLLIElement` | Obtain a reference to the list item HTML element | `null` | | `kind` | `"default" \| "danger"` | Specify the kind of option. | `"default"` | | `disabled` | `boolean` | Set to `true` to enable the disabled state | `false` | | `labelText` | `string` | Specify the label text.
Alternatively, use the "labelChildren" slot. | `""` | | `shortcutText` | `string` | Specify the shortcut text.
Alternatively, use the "shortcutText" slot. | `""` | | `id` | `string` | Specify the id.
It's recommended to provide an id as a value to bind to within a selectable/radio menu group. | `ccs-${Math.random().toString(36)}` | #### `ContextMenuOption` slots | Slot | Detail | | --------------- | ----------------------- | | `default` | `Record` | | `icon` | `Record` | | `labelChildren` | `Record` | | `shortcutText` | `Record` | #### `ContextMenuOption` forwarded events | Event | | --------------- | | `on:keydown` | | `on:mouseenter` | | `on:mouseleave` | #### `ContextMenuOption` dispatched events | Event | Detail | | ---------- | ------ | | `on:click` | `null` | #### `ContextMenuOption` $$restProps `ContextMenuOption` spreads `$$restProps` to the `li` element. ## CopyButton Copy buttons let users copy text to their clipboard with a single click. Use them to provide quick access to code snippets, links, or other text content. This component uses the native [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText) to copy text. Override the default copy functionality with your own implementation. See [Overriding copy functionality](#overriding-copy-functionality). ### Default Create a copy button with the `text` prop to specify what to copy. ```svelte ``` ### Custom feedback text Set `feedback` to customize the message shown after copying. ```svelte ``` ### Overriding copy functionality Pass a custom function to the `copy` prop to override the default copy behavior. This example uses the NPM package [clipboard-copy](https://github.com/feross/clipboard-copy) to copy the text instead of the default Clipboard API. ```svelte copy(text)} /> ``` ### Preventing copy functionality Pass a no-op function to the `copy` prop to disable copying. ```svelte {}} /> ``` --- ### Component API #### `CopyButton` props | Prop | Type | Description | Default | | ----------------- | ------------------------ | ----------------------------------------------------------------------------------------------- | --------------------- | | `text` (Required) | `string` | Specify the text to copy. | _undefined_ | | `feedback` | `string` | Set the feedback text shown after clicking the button | `"Copied!"` | | `feedbackTimeout` | `number` | Set the timeout duration (ms) to display feedback text | `2000` | | `iconDescription` | `string` | Set the title and ARIA label for the copy button | `"Copy to clipboard"` | | `copy` | `(text: string) => void` | Override the default copy behavior of using the navigator.clipboard.writeText API to copy text. | _undefined_ | #### `CopyButton` forwarded events | Event | | ----------------- | | `on:click` | | `on:animationend` | #### `CopyButton` dispatched events | Event | Detail | | --------- | ------ | | `on:copy` | `null` | #### `CopyButton` $$restProps `CopyButton` spreads `$$restProps` to the `button` element. ## DataTable Data tables display structured data in a tabular format. Use them to present large datasets with features like sorting, filtering, pagination, virtualization, and row selection. > [!NOTE] This component is keyed for performance. Every **headers** object must > have a unique "key" property. Every **rows** object must have a unique "id" > property. ### Default Create a basic table by providing `headers` and `rows` data. Match the `key` in headers with the corresponding property in rows. ```svelte ``` ### Slotted cells Use the `"cell"` slot to customize cell content. Access row and cell data through `let:row` and `let:cell` directives. Use `"cellHeader"` slot for header cells. ```svelte {#if header.key === "port"} {header.value} (network) {:else} {header.value} {/if} {#if cell.key === "rule" && cell.value === "Round robin"} {cell.value} {:else} {cell.value} {/if} ``` ### Custom cell rendering with row state The `"cell"` slot provides `rowSelected` and `rowExpanded` props to conditionally render content based on row state. ```svelte {#if cell.key === "status"} {cell.value} {rowExpanded ? "(expanded)" : ""} {:else} {cell.value} {/if}
Additional details for {row.name} {rowSelected ? "(Currently selected)" : ""}
``` ### With title, description Add a title and description to provide context for the table data. ```svelte ``` ### Slottable title, description By default, the title is rendered as a `

` element and the description is rendered as a `

` element. Use slots to customize the elements and styles. The original classes can be destructured using `let:props`. ```svelte

Load balancers

Your organization's active load balancers.
``` ### Static width Set `useStaticWidth` to `true` to render the table with an auto width instead of 100%. ```svelte ``` ### Custom column widths Specify `width` or `minWidth` in the `headers` object to set column dimensions. This applies a fixed table layout. > [!WARNING] Custom column widths do not work with a > [sticky header](#sticky-header). ```svelte ({ id: i, name: "Load Balancer " + (i + 1), protocol: "HTTP", port: i % 3 ? (i % 2 ? 3000 : 80) : 443, rule: i % 3 ? "Round robin" : "DNS delegation", }))} /> ``` ### Sticky header Set `stickyHeader` to `true` to fix the header in place. This adds a maximum height to force scrolling. ```svelte ({ id: i, name: "Load Balancer " + (i + 1), protocol: "HTTP", port: i % 3 ? (i % 2 ? 3000 : 80) : 443, rule: i % 3 ? "Round robin" : "DNS delegation", }))} /> ``` ### Virtualized rows (large datasets) Virtualization renders only the rows currently visible in the viewport, improving performance for large datasets. Set `virtualize={true}` to enable. The header stays visible while scrolling (sticky positioning is applied automatically). Use `stickyHeader={true}` for the intended layout, if necessary. Container height defaults to 10 rows (`itemHeight * maxVisibleRows`). The example below shows 10,000 rows with a filterable toolbar; only visible rows are rendered in the DOM. ```svelte ``` ### Virtualized rows (custom overscan) Overscanning renders extra rows above and below the viewport for smoother scrolling. The default overscan value is 3. Specify a custom `overscan` to control how many extra rows are rendered. ```svelte ``` ### Virtualized rows (custom row height) By default, the virtual row height matches the table size variant (48px medium, 24px compact, 32px short, 64px tall). Use `rowClass` to apply a custom row height via CSS and set `itemHeight` to match for correct virtualization. ```svelte ``` ### Virtualized rows (custom max visible rows) By default, the table shows 10 rows in the viewport. Customize `maxVisibleRows` to control how many rows are visible at once. Container height is calculated as `itemHeight * maxVisibleRows`, or use `containerHeight` for pixel-based control. ```svelte ``` ### With toolbar Add a toolbar with search, menu, and actions above the table. ```svelte Restart all API documentation Stop all ``` ### With toolbar (small size) Use `size="short"` to create a more compact table with a small toolbar. ```svelte Restart all API documentation Stop all ``` ### With toolbar and selectable rows Set `selectable` to `true` to enable selectable rows. Here, the toolbar is used standalone. For batch actions for selected rows, see the [batch selection with toolbar](#batch-selection-with-batch-actions-toolbar) example. ```svelte ``` ### Filterable Set `shouldFilterRows` to `true` to enable client-side filtering. The default filter performs string comparisons on cell values. For pagination with filtering, bind to `filteredRowIds` and pass its length to the pagination component's `totalItems`. ```svelte ``` ### Filterable (custom) Pass a function to `shouldFilterRows` to implement custom filtering logic. ```svelte { return ( /(6|8)$/.test(row.name) && row.rule.toLowerCase().includes(value.toLowerCase()) ); }} bind:filteredRowIds /> ``` ### Zebra stripes Set `zebra` to `true` to add alternating row colors. ```svelte ``` ### Custom row classes Use `rowClass` to apply custom CSS classes to rows. Pass a string for a static class, or a function that receives `{ row, rowIndex, selected, expanded }` and returns conditional classes. Try selecting and expanding rows to see the custom styles. ```svelte { const classes = []; if (row.protocol === "HTTPS") classes.push("secure"); if (selected) classes.push("selected"); if (expanded) classes.push("expanded"); return classes.join(" ") || undefined; }} >
{JSON.stringify(row, null, 2)}
``` ### Tall rows Set `size="tall"` for increased row height. ```svelte ``` ### Medium rows Set `size="medium"` for standard row height. ```svelte ``` ### Short rows Set `size="short"` for compact row height. ```svelte ``` ### Compact rows Set `size="compact"` for minimal row height. ```svelte ``` ### Sortable Set `sortable` to `true` to enable column sorting. Disable sorting on specific columns by setting `sort: false` in the header object. ```svelte ``` ### Sortable with pagination Bind to `pageSize` and `page` props of the pagination component and pass them to the data table. ```svelte ``` ### Sortable with custom display and sort methods Use `display` and `sort` functions in header objects to customize cell rendering and sorting. ```svelte cost + " €" }, { key: "expireDate", value: "Expire date", display: (date) => new Date(date).toLocaleString(), sort: (a, b) => new Date(a) - new Date(b), }, ]} rows={[ { id: "a", name: "Load Balancer 3", protocol: "HTTP", port: 3000, cost: 100, expireDate: "2020-10-21", }, { id: "b", name: "Load Balancer 1", protocol: "HTTP", port: 443, cost: 200, expireDate: "2020-09-10", }, { id: "c", name: "Load Balancer 2", protocol: "HTTP", port: 80, cost: 150, expireDate: "2020-11-24", }, { id: "d", name: "Load Balancer 6", protocol: "HTTP", port: 3000, cost: 250, expireDate: "2020-12-01", }, { id: "e", name: "Load Balancer 4", protocol: "HTTP", port: 443, cost: 550, expireDate: "2021-03-21", }, { id: "f", name: "Load Balancer 5", protocol: "HTTP", port: 80, cost: 400, expireDate: "2020-11-14", }, ]} /> ``` ### Sortable with nested object values Access nested object properties using dot notation in the header key. ```svelte cost + " €" }, { key: "expireDate", value: "Expire date", display: (date) => new Date(date).toLocaleString(), sort: (a, b) => new Date(a) - new Date(b), }, ]} rows={[ { id: "a", name: "Load Balancer 3", network: { protocol: "HTTP", port: 3000, }, cost: 100, expireDate: "2020-10-21", }, { id: "b", name: "Load Balancer 1", network: { protocol: "HTTP", port: 443, }, cost: 200, expireDate: "2020-09-10", }, { id: "c", name: "Load Balancer 2", network: { protocol: "HTTP", port: 80, }, cost: 150, expireDate: "2020-11-24", }, { id: "d", name: "Load Balancer 6", network: { protocol: "HTTP", port: 3000, }, cost: 250, expireDate: "2020-12-01", }, { id: "e", name: "Load Balancer 4", network: { protocol: "HTTP", port: 443, }, cost: 550, expireDate: "2021-03-21", }, { id: "f", name: "Load Balancer 5", network: { protocol: "HTTP", port: 80, }, cost: 400, expireDate: "2020-11-14", }, ]} /> ``` ### Programmatic sorting Use `sortKey` and `sortDirection` props to control sorting programmatically. Set `sortKey` to a valid header key and `sortDirection` to "none", "ascending", or "descending". ```svelte
``` ### Empty column with overflow menu Set `empty: true` in a header object to create an empty column. Use this for overflow menus without a header. ```svelte {#if cell.key === "overflow"} {:else}{cell.value}{/if} ``` ### Selectable rows (checkbox) Set `selectable` to `true` for multi-select functionality. Bind to `selectedRowIds` to track selections. Use `inputName` to customize checkbox names. ```svelte ({ id: i, name: "Load Balancer " + (i + 1), protocol: "HTTP", port: i % 3 ? (i % 2 ? 3000 : 80) : 443, rule: i % 3 ? "Round robin" : "DNS delegation", }))} /> ``` ### Batch selection Set `batchSelection` to `true` to add a checkbox for selecting all rows. The checkbox shows an indeterminate state when some rows are selected. ```svelte ({ id: i, name: "Load Balancer " + (i + 1), protocol: "HTTP", port: i % 3 ? (i % 2 ? 3000 : 80) : 443, rule: i % 3 ? "Round robin" : "DNS delegation", }))} /> ``` ### Batch selection with initial selected rows Use `selectedRowIds` to specify initially selected rows. ```svelte ({ id: i, name: "Load Balancer " + (i + 1), protocol: "HTTP", port: i % 3 ? (i % 2 ? 3000 : 80) : 443, rule: i % 3 ? "Round robin" : "DNS delegation", }))} /> ``` ### Batch selection with batch actions toolbar Add a toolbar for batch actions when rows are selected. ```svelte Restart all API documentation Stop all ``` ### Batch selection with controlled toolbar Control the batch actions toolbar with the `active` prop. Prevent default cancel behavior in the `on:cancel` event. ```svelte { e.preventDefault(); active = false; }} > ``` ### Selectable rows (radio) Set `radio` to `true` for single-row selection. Bind to `selectedRowIds` to track the selected row. Use `inputName` to customize radio button names. ```svelte ``` ### Non-selectable rows Use `nonSelectableRowIds` to prevent selection of specific rows. ```svelte row.port === 3000) .map((row) => row.id)} headers={[ { key: "name", value: "Name" }, { key: "protocol", value: "Protocol" }, { key: "port", value: "Port" }, { key: "rule", value: "Rule" }, ]} {rows} /> ``` ### Expandable rows Set `expandable` to `true` to make rows expandable. Use the `expanded-row` slot to customize expanded content. ```svelte
{JSON.stringify(row, null, 2)}
``` ### Non-expandable rows Use `nonExpandableRowIds` to prevent expansion of specific rows. ```svelte row.port < 3000) .map((row) => row.id)} headers={[ { key: "name", value: "Name" }, { key: "protocol", value: "Protocol" }, { key: "port", value: "Port" }, { key: "rule", value: "Rule" }, ]} {rows} >
{JSON.stringify(row, null, 2)}
``` ### Expandable (zebra styles) Combine expandable rows with zebra striping. ```svelte
{JSON.stringify(row, null, 2)}
``` ### Expandable (compact size) Set `size="compact"` for expandable rows with minimal height. ```svelte
{JSON.stringify(row, null, 2)}
``` ### Expandable (short size) Set `size="short"` for expandable rows with compact height. ```svelte
{JSON.stringify(row, null, 2)}
``` ### Expandable (tall size) Set `size="tall"` for expandable rows with increased height. ```svelte
{JSON.stringify(row, null, 2)}
``` ### Batch expansion Set `batchExpansion` to `true` to expand and collapse all rows at once. ```svelte
{JSON.stringify(row, null, 2)}
``` ### Expandable and selectable rows Combine `batchExpansion` and `batchSelection` for tables with both expandable and selectable rows. ```svelte ({ id: i, name: "Load Balancer " + (i + 1), protocol: "HTTP", port: i % 3 ? (i % 2 ? 3000 : 80) : 443, rule: i % 3 ? "Round robin" : "DNS delegation", }))} >
 {JSON.stringify(row, null, 2)}
``` ### Skeleton Use the data table skeleton to show a loading state. ```svelte ``` ### Skeleton with headers, row count Specify headers and row count for the skeleton. ```svelte ``` ### Skeleton with object headers Pass header objects to customize the skeleton. ```svelte ``` ### Skeleton with empty header Add an empty header column with `empty: true`. ```svelte ``` ### Skeleton without header, toolbar Hide the header and toolbar in the skeleton. ```svelte ``` ### Skeleton (tall size) Set `size="tall"` for a taller skeleton. ```svelte ``` ### Skeleton (short size) Set `size="short"` for a shorter skeleton. ```svelte ``` ### Skeleton (compact size) Set `size="compact"` for a minimal skeleton. ```svelte ``` --- ### Component API #### `DataTable` props | Prop | Type | Description | Default | | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | `sortKey` (Reactive) | `DataTableKey` | Specify the header key to sort by. | `null` | | `sortDirection` (Reactive) | `"none" \| "ascending" \| "descending"` | Specify the sort direction. | `"none"` | | `expandable` (Reactive) | `boolean` | Set to `true` for the expandable variant.
Automatically set to `true` if `batchExpansion` is `true`. | `false` | | `expandedRowIds` (Reactive) | `ReadonlyArray` | Specify the row ids to be expanded. | `[]` | | `selectable` (Reactive) | `boolean` | Set to `true` for the selectable variant.
Automatically set to `true` if `radio` or `batchSelection` are `true`. | `false` | | `selectedRowIds` (Reactive) | `ReadonlyArray` | Specify the row ids to be selected. | `[]` | | `scrollContainerRef` (Reactive) | `null \| HTMLDivElement` | Obtain a reference to the table wrapper element. When virtualization is enabled and `stickyHeader` is false, this element is the scroll container—use `bind:scrollContainerRef` to programmatically control scroll position (e.g. `scrollContainerRef.scrollTop = 0`). | `null` | | `headers` | `ReadonlyArray>` | Specify the data table headers. | `[]` | | `rows` | `ReadonlyArray` | Specify the rows the data table should render.
Keys defined in `headers` are used for the row ids. | `[]` | | `size` | `"compact" \| "short" \| "medium" \| "tall"` | Set the size of the data table. | _undefined_ | | `title` | `string` | Specify the title of the data table | `""` | | `description` | `string` | Specify the description of the data table | `""` | | `rowClass` | `DataTableRowClass` | Specify a custom class name for each row.
Provide a function to return a class name based
on row properties, allowing conditional classes
based on selected/expanded state. | _undefined_ | | `inputName` | `string` | Specify a name attribute for the input elements
in a selectable data table (radio or checkbox).
When the table is inside a form, this name will
be included in the form data on submit. | `ccs-${Math.random().toString(36)}` | | `zebra` | `boolean` | Set to `true` to use zebra styles | `false` | | `sortable` | `boolean` | Set to `true` for the sortable variant | `false` | | `batchExpansion` | `boolean` | Set to `true` to enable batch expansion. | `false` | | `nonExpandableRowIds` | `ReadonlyArray` | Specify the ids for rows that should not be expandable. | `[]` | | `radio` | `boolean` | Set to `true` for the radio selection variant | `false` | | `batchSelection` | `boolean` | Set to `true` to enable batch selection | `false` | | `nonSelectableRowIds` | `ReadonlyArray` | Specify the ids of rows that should not be selectable. | `[]` | | `stickyHeader` | `boolean` | Set to `true` to enable a sticky header | `false` | | `useStaticWidth` | `boolean` | Set to `true` to use static width | `false` | | `pageSize` | `number` | Specify the number of items to display in a page | `0` | | `page` | `number` | Set to `number` to set current page | `0` | | `virtualize` | `undefined \| boolean \| { itemHeight?: number, maxVisibleRows?: number, containerHeight?: number, overscan?: number, threshold?: number, maxItems?: number }` | Enable virtualization for large row lists. Virtualization renders only the rows currently visible in the viewport, improving performance for large datasets.

Virtualization is opt-in. Set `virtualize={true}` to enable with default settings, or pass a configuration object to customize.
Virtualized tables are intended for use with `stickyHeader={true}` so the header stays visible while scrolling. Pagination is ignored when virtualization is enabled.

Provide an object to customize virtualization behavior:
- `itemHeight` (default: 48 for medium size, adjusted for size variant): The height in pixels of each row. Specify a custom value when using custom slots with multi-line content or different heights.
- `maxVisibleRows` (default: 10): The maximum number of rows to display in the viewport. The container height will be calculated as `itemHeight * maxVisibleRows`. Overridden by `containerHeight` if explicitly provided.
- `containerHeight` (default: calculated from maxVisibleRows): The maximum height in pixels of the table body container. If not provided, calculated from `itemHeight * maxVisibleRows`.
- `overscan` (default: 3): The number of extra rows to render above and below the viewport for smoother scrolling. Higher values may cause more flickering during very fast scrolling.
- `threshold` (default: 100): The minimum number of rows required before virtualization activates. Tables with fewer rows will render all rows normally without virtualization.
- `maxItems` (default: undefined): The maximum number of rows to render. When undefined, all visible rows are rendered. | _undefined_ | | `tableHeaderTranslateWithId` | `(id: import("./TableHeader.svelte").TableHeaderTranslationId) => string` | Override the default table header translation ids. | _undefined_ | #### `DataTable` typedefs ```ts type DataTableKey = import("./data-table-utils.d.ts").PropertyPath; type DataTableValue = any; type DataTableEmptyHeader = { key: DataTableKey | (string & {}); /** Whether the header is empty */ empty: boolean; display?: (item: DataTableValue, row: Row) => DataTableValue; sort?: false | ((a: DataTableValue, b: DataTableValue) => number); /** Whether the column menu is enabled */ columnMenu?: boolean; width?: string; minWidth?: string; }; type DataTableNonEmptyHeader = { key: DataTableKey; value: DataTableValue; display?: (item: DataTableValue, row: Row) => DataTableValue; sort?: false | ((a: DataTableValue, b: DataTableValue) => number); /** Whether the column menu is enabled */ columnMenu?: boolean; width?: string; minWidth?: string; }; type DataTableHeader = | DataTableNonEmptyHeader | DataTableEmptyHeader; interface DataTableRow { id: Id; [key: string]: DataTableValue; } type DataTableCell = { key: DataTableKey | (string & {}); value: DataTableValue; display?: (item: DataTableValue, row: DataTableRow) => DataTableValue; }; interface DataTableRowClassArgs { row: Row; rowIndex: number; selected: boolean; expanded: boolean; } type DataTableRowClass = | string | ((row: DataTableRowClassArgs) => string | undefined); ``` #### `DataTable` slots | Slot | Detail | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `default` | `Record` | | `cell` | `{
row: Row;
cell: DataTableCell;
rowIndex: number;
cellIndex: number;
rowSelected: boolean;
rowExpanded: boolean;
}` | | `cellHeader` | `{
header: DataTableNonEmptyHeader;
}` | | `descriptionChildren` | `{
props: {
class: "bx--data-table-header__description";
};
}` | | `expanded-row` | `{
row: Row;
rowSelected: boolean;
}` | | `titleChildren` | `{
props: {
class: "bx--data-table-header__title";
};
}` | #### `DataTable` dispatched events | Event | Detail | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `on:click` | `{
header?: DataTableHeader;
row?: Row;
cell?: DataTableCell;
}` | | `on:click:header--expand` | `{
expanded: boolean;
}` | | `on:click:header` | `{
header: DataTableHeader;
sortDirection?:
\| "ascending"
\| "descending"
\| "none";
target: EventTarget;
currentTarget: EventTarget;
}` | | `on:click:header--select` | `{
indeterminate: boolean;
selected: boolean;
}` | | `on:click:row` | `{
row: Row;
target: EventTarget;
currentTarget: EventTarget;
}` | | `on:mouseenter:row` | `Row` | | `on:mouseleave:row` | `Row` | | `on:click:row--expand` | `{
expanded: boolean;
row: Row;
}` | | `on:click:row--select` | `{
selected: boolean;
row: Row;
}` | | `on:click:cell` | `{
cell: DataTableCell;
target: EventTarget;
currentTarget: EventTarget;
rowClass?: DataTableRowClass;
}` | #### `DataTable` $$restProps `DataTable` spreads `$$restProps` to the `div` element. #### `Pagination` props | Prop | Type | Description | Default | | ----------------------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | `page` (Reactive) | `number` | Specify the current page index | `1` | | `pageSize` (Reactive) | `number` | Specify the number of items to display in a page | `10` | | `totalItems` | `number` | Specify the total number of items | `0` | | `pageWindow` | `number` | If `totalItems` is a large number, it can affect the
rendering performance of this component since its value
is used to calculate the number of pages in the native
select dropdown. This value creates a small window of
pages rendered around the current page. By default,
a maximum of 1000 select items are rendered. | `1000` | | `disabled` | `boolean` | Set to `true` to disable the pagination | `false` | | `forwardText` | `string` | Specify the forward button text | `"Next page"` | | `backwardText` | `string` | Specify the backward button text | `"Previous page"` | | `itemsPerPageText` | `string` | Specify the items per page text | `"Items per page:"` | | `itemText` | `(min: number, max: number) => string` | Override the item text. | _undefined_ | | `itemRangeText` | `(min: number, max: number, total: number) => string` | Override the item range text. | _undefined_ | | `pageInputDisabled` | `boolean` | Set to `true` to disable the page input | `false` | | `pageSizeInputDisabled` | `boolean` | Set to `true` to disable the page size input | `false` | | `pageSizes` | `ReadonlyArray` | Specify the available page sizes. | `[10]` | | `dynamicPageSizes` | `boolean` | Set to `true` to dynamically filter page sizes based on total items.
Page sizes larger than needed to display all items on a single page are hidden. | `false` | | `pagesUnknown` | `boolean` | Set to `true` if the number of pages is unknown | `false` | | `pageText` | `(page: number) => string` | Override the page text. | _undefined_ | | `pageRangeText` | `(current: number, total: number) => string` | Override the page range text. | _undefined_ | | `id` | `string` | Set an id for the top-level element | `ccs-${Math.random().toString(36)}` | #### `Pagination` dispatched events | Event | Detail | Description | | --------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------- | | `on:change` | `{
page?: number;
pageSize?: number;
}` | Dispatched when the user changes the page or page size through any interaction. | | `on:click:button--previous` | `{
page: number;
}` | Dispatched when the user clicks the previous page button. | | `on:click:button--next` | `{
page: number;
}` | Dispatched when the user clicks the next page button. | | `on:update` | `{
pageSize: number;
page: number;
}` | Dispatched reactively whenever the page or page size changes. | #### `Pagination` $$restProps `Pagination` spreads `$$restProps` to the `div` element. #### `Toolbar` props | Prop | Type | Description | Default | | ------ | ------------------- | ------------------------- | ----------- | | `size` | `"sm" \| "default"` | Specify the toolbar size. | `"default"` | #### `Toolbar` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `Toolbar` $$restProps `Toolbar` spreads `$$restProps` to the `section` element. #### `ToolbarContent` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ToolbarSearch` props | Prop | Type | Description | Default | | --------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `value` (Reactive) | `number \| string` | Specify the value of the search input. | `""` | | `expanded` (Reactive) | `boolean` | Set to `true` to expand the search bar | `false` | | `filteredRowIds` (Reactive) | `ReadonlyArray` | The filtered row ids. | `[]` | | `ref` (Reactive) | `null \| HTMLInputElement` | Obtain a reference to the input HTML element. | `null` | | `persistent` | `boolean` | Set to `true` to keep the search bar expanded | `false` | | `disabled` | `boolean` | Set to `true` to disable the search bar | `false` | | `shouldFilterRows` | `boolean \| ((row: Row, value: number \| string) => boolean)` | Set to `true` to filter table rows using the search value.

If `true`, the default search excludes `id`, `cells` fields and
only does a basic comparison on string and number type cell values.

To implement your own client-side filtering, pass a function
that accepts a row and value and returns a boolean. | `false` | | `tabindex` | `string` | Specify the tabindex | `"0"` | #### `ToolbarSearch` forwarded events | Event | | ------------ | | `on:clear` | | `on:change` | | `on:input` | | `on:focus` | | `on:blur` | | `on:keyup` | | `on:keydown` | | `on:paste` | #### `ToolbarSearch` $$restProps `ToolbarSearch` spreads `$$restProps` to the `input` element. #### `ToolbarMenu` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ToolbarMenu` $$restProps `ToolbarMenu` spreads `$$restProps` to the `OverflowMenu` component. #### `ToolbarMenuItem` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ToolbarMenuItem` forwarded events | Event | | ------------ | | `on:click` | | `on:keydown` | #### `ToolbarMenuItem` $$restProps `ToolbarMenuItem` spreads `$$restProps` to the `OverflowMenuItem` component. #### `ToolbarBatchActions` props | Prop | Type | Description | Default | | --------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ----------- | | `active` (Reactive) | `undefined \| boolean` | Use a boolean to show or hide the toolbar. | _undefined_ | | `formatTotalSelected` | `(totalSelected: number) => string` | Override the total items selected text. | _undefined_ | | `selectedIds` | `ReadonlyArray` | Specify the selected IDs for standalone usage.
This is unnecessary if using this component with `DataTable`. | `[]` | #### `ToolbarBatchActions` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | | `cancel` | `Record` | #### `ToolbarBatchActions` dispatched events | Event | Detail | | ----------- | ------ | | `on:cancel` | `null` | #### `ToolbarBatchActions` $$restProps `ToolbarBatchActions` spreads `$$restProps` to the `div` element. ## DatePicker Date pickers let users select a date or date range using a calendar interface. They use the [flatpickr](https://github.com/flatpickr/flatpickr) library for their calendar implementation. > [!NOTE] If using Rollup, specify **inlineDynamicImports: true** in your > **rollup.config.js**. ### Single Set `datePickerType` to `"single"` for single date selection. ```svelte ``` ### Range Set `datePickerType` to `"range"` to enable date range selection. ```svelte ``` ### Programmatic range update Use `bind:valueFrom` and `bind:valueTo` to programmatically update the date range from outside the component. ```svelte ``` ### Custom date format Use the `dateFormat` prop to customize the date format (default: `"m/d/Y"`). The input `pattern` attribute is automatically derived to match, ensuring native form validation works correctly. ```svelte
(submittedValue = value)}>
``` ### Portal menu Set `portalMenu` to `true` to render the calendar in a floating portal. This prevents the calendar from being clipped by parent containers with `overflow: hidden` or z-index stacking contexts. When inside a Modal, `portalMenu` defaults to `true` unless explicitly set to `false`. ```svelte (open = false)} > ``` ### Simple Create a simple date picker without a dropdown calendar. ```svelte ``` ### With helper text Add helper text to provide additional context or formatting instructions. ```svelte ``` ### Hidden label Hide the label while maintaining accessibility. ```svelte ``` ### Light variant Use the light variant for light backgrounds. ```svelte ``` ### Extra-large size Use the extra-large size for more prominent date pickers. ```svelte ``` ### Small size Use the small size for compact date pickers. ```svelte ``` ### Invalid state Show an invalid state when the input value is not valid. ```svelte ``` ### Warning state Show a warning state to indicate potential issues with the input. ```svelte ``` ### Disabled state Disable the date picker to prevent user interaction. ```svelte ``` ### Skeleton Show a loading state with the skeleton component. ```svelte ``` --- ### Component API #### `DatePicker` props | Prop | Type | Description | Default | | ---------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | `value` (Reactive) | `number \| string` | Specify the date picker input value. | `""` | | `valueFrom` (Reactive) | `string` | Specify the date picker start date value (from).
Only works with the "range" date picker type. | `""` | | `valueTo` (Reactive) | `string` | Specify the date picker end date value (to).
Only works with the "range" date picker type. | `""` | | `datePickerType` | `"simple" \| "single" \| "range"` | Specify the date picker type. | `"simple"` | | `dateFormat` | `string` | Specify the date format | `"m/d/Y"` | | `maxDate` | `null \| string \| Date` | Specify the maximum date. | `null` | | `minDate` | `null \| string \| Date` | Specify the minimum date. | `null` | | `locale` | `import("flatpickr/dist/types/locale").CustomLocale \| import("flatpickr/dist/types/locale").key` | Specify the locale. | `"en"` | | `short` | `boolean` | Set to `true` to use the short variant | `false` | | `light` | `boolean` | Set to `true` to enable the light variant | `false` | | `portalMenu` | `boolean \| undefined` | Set to `true` to render the calendar in a portal to prevent clipping.
When inside a Modal, defaults to `true` unless explicitly set to `false`. | _undefined_ | | `id` | `string` | Set an id for the date picker element | `ccs-${Math.random().toString(36)}` | | `flatpickrProps` | `import("flatpickr/dist/types/options").Options` | Override the options passed to the Flatpickr instance.
@see https://flatpickr.js.org/options | `{ static: true }` | #### `DatePicker` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `DatePicker` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `DatePicker` dispatched events | Event | Detail | | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `on:change` | `type EventDetail =
\| string
\| {
selectedDates: [
dateFrom: Date,
dateTo?: Date,
];
dateStr:
\| string
\| { from: string; to: string };
}` | #### `DatePicker` $$restProps `DatePicker` spreads `$$restProps` to the `div` element. #### `DatePickerInput` props | Prop | Type | Description | Default | | ----------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | `ref` (Reactive) | `null \| HTMLInputElement` | Obtain a reference to the input HTML element | `null` | | `size` | `"sm" \| "xl"` | Set the size of the input. | _undefined_ | | `type` | `string` | Specify the input type | `"text"` | | `placeholder` | `string` | Specify the input placeholder text | `""` | | `pattern` | `string` | Specify the Regular Expression for the input value.
By default, the pattern is derived from the parent
`DatePicker`'s `dateFormat` prop. | _undefined_ | | `disabled` | `boolean` | Set to `true` to disable the input | `false` | | `helperText` | `string` | Specify the helper text | `""` | | `iconDescription` | `string` | Specify the ARIA label for the calendar icon | `""` | | `id` | `string` | Set an id for the input element | `ccs-${Math.random().toString(36)}` | | `labelText` | `string` | Specify the label text | `""` | | `hideLabel` | `boolean` | Set to `true` to visually hide the label text | `false` | | `invalid` | `boolean` | Set to `true` to indicate an invalid state | `false` | | `invalidText` | `string` | Specify the invalid state text | `""` | | `warn` | `boolean` | Set to `true` to indicate a warning state | `false` | | `warnText` | `string` | Specify the warning state text | `""` | | `name` | `string` | Set a name for the input element. | _undefined_ | #### `DatePickerInput` slots | Slot | Detail | | --------------- | ----------------------- | | `labelChildren` | `Record` | #### `DatePickerInput` forwarded events | Event | | ------------ | | `on:input` | | `on:keydown` | | `on:keyup` | | `on:blur` | | `on:paste` | #### `DatePickerInput` $$restProps `DatePickerInput` spreads `$$restProps` to the `input` element. #### `DatePickerSkeleton` props | Prop | Type | Description | Default | | ------- | --------- | ----------------------------------------- | ----------------------------------- | | `range` | `boolean` | Set to `true` to use the range variant | `false` | | `id` | `string` | Set an id to be used by the label element | `ccs-${Math.random().toString(36)}` | #### `DatePickerSkeleton` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `DatePickerSkeleton` $$restProps `DatePickerSkeleton` spreads `$$restProps` to the `div` element. ## Dropdown Dropdowns provide a select input with a dropdown menu. They support various states, sizes, and customization options. Each item in the dropdown must have a unique `id` property for proper functionality. > [!NOTE] Every `items` object must have a unique "id" property. ### Default Use the dropdown to create a select input with a dropdown menu. Each item must have a unique `id` property. ```svelte ``` ### Custom label Use the `labelChildren` slot to provide custom label content instead of using the `labelText` prop. ```svelte Custom label ``` ### Custom slot Override the default slot to customize the display of each item. Access the item and index through the `let:` directive. ```svelte
{item.text}
id: {item.id} - index: {index}
``` ### Hidden label Hide the label while maintaining accessibility by setting the `hideLabel` prop to `true`. The label will still be available to screen readers. ```svelte ``` ### Format item display text Format the display text of items using the `itemToString` prop. This function receives the item object and returns the formatted string. ```svelte { return item.text + " (" + item.id + ")"; }} labelText="Contact" selectedId="0" items={[ { id: "0", text: "Slack" }, { id: "1", text: "Email" }, { id: "2", text: "Fax" }, ]} /> ## Multiple dropdowns Create multiple dropdowns that work together. This example demonstrates how to manage the state of multiple dropdowns. ``` ```svelte
Primary: {primary}
Secondary: {secondary}
``` ### Top direction Display the dropdown menu above the input by setting the `direction` prop to `"top"`. This is useful when there's limited space below the input. ```svelte ``` ### Light variant Use the light variant for dropdowns on dark backgrounds by setting the `light` prop to `true`. ```svelte ``` ### Portal menu Set `portalMenu` to `true` to render the dropdown menu in a floating portal. This prevents the menu from being clipped by parent containers with `overflow: hidden` or z-index stacking contexts. The example below shows a container with hidden overflow. Without `portalMenu`, the dropdown would be clipped. When inside a [Modal](/components/Modal#modal-with-dropdowns), `portalMenu` defaults to `true` unless explicitly set to `false`. ```svelte
This container has hidden overflow. Without portalMenu, the dropdown would be clipped.
``` ### Inline variant Display the dropdown inline with other content by setting the `type` prop to `"inline"`. This variant removes the background and border. ```svelte ``` ### Extra-large size Increase the size of the dropdown by setting the `size` prop to `"xl"`. This provides more visual emphasis for important selections. ```svelte ``` ### Small size Decrease the size of the dropdown by setting the `size` prop to `"sm"`. This is useful for compact layouts or secondary selections. ```svelte ``` ### Invalid state Indicate an invalid selection by setting the `invalid` prop to `true`. Provide feedback to users with the `invalidText` prop. ```svelte ``` ### Warning state Indicate a warning state by setting the `warn` prop to `true`. Provide additional context with the `warnText` prop. ```svelte ``` ### Disabled state Disable the entire dropdown by setting the `disabled` prop to `true`. This prevents user interaction with the component. ```svelte ``` ### Disabled items Disable specific items in the dropdown by setting the `disabled` property to `true` in the item object. This allows for more granular control over available selections. ```svelte ``` ### Virtualized items (large lists) Virtualization is a technique that allows only the items currently visible in the viewport to be rendered in the DOM, improving performance for large lists. By default, the dropdown will virtualize lists with more than 100 items. In the example below, 10,000 items are provided to the dropdown but only 11 items (8 visible items + 3 overscan items) are rendered in the DOM. Set `virtualize={false}` to explicitly disable virtualization, even for large lists. Or, customize the threshold at which virtualization activates. See [Virtualized items (custom threshold)](#virtualized-items-custom-threshold). ```svelte
Selected: {selectedItem?.text}
``` ### Virtualized items (custom overscan) Overscanning is the process of rendering extra items above and below the viewport to ensure smooth scrolling. The default overscan value is 3. Specify a custom value for `overscan` to control how many extra items are rendered above/below the viewport for smoother scrolling. > [!NOTE] During very fast scrolling, higher overscan values may cause more > flickering due to increased DOM updates. For fast scrolling scenarios, use a > lower overscan value. ```svelte ``` ### Virtualized items (custom threshold) The threshold is the minimum number of items required before virtualization activates. The default threshold value is 100, meaning lists with fewer than 100 items will not be virtualized and all items will be rendered normally. Specify a custom value for `threshold` to control when virtualization activates. Below the threshold, all items are rendered normally without virtualization. ```svelte ``` ### Virtualized items (custom item height) The default item height for virtualization is 40 pixels. When using custom slots to render items with different heights (e.g., multi-line items with descriptions), specify a custom `itemHeight` value to match your item's actual height. ```svelte {item.text} {item.description} ``` ### Skeleton Display a loading state using the dropdown skeleton. This provides visual feedback while the dropdown content is being loaded. ```svelte ``` --- ### Component API #### `Dropdown` props | Prop | Type | Description | Default | | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | `selectedId` (Reactive, Required) | `Item["id"]` | Specify the selected item id. | _undefined_ | | `open` (Reactive) | `boolean` | Set to `true` to open the dropdown | `false` | | `ref` (Reactive) | `null \| HTMLButtonElement` | Obtain a reference to the button HTML element | `null` | | `listRef` (Reactive) | `null \| HTMLDivElement` | Obtain a reference to the list HTML element. | `null` | | `items` | `ReadonlyArray` | Set the dropdown items. | `[]` | | `itemToString` | `(item: Item) => string` | Override the display of a dropdown item. | _undefined_ | | `type` | `"default" \| "inline"` | Specify the type of dropdown. | `"default"` | | `direction` | `"bottom" \| "top"` | Specify the direction of the dropdown menu. | `"bottom"` | | `size` | `"sm" \| "lg" \| "xl"` | Specify the size of the dropdown field. | _undefined_ | | `light` | `boolean` | Set to `true` to enable the light variant | `false` | | `disabled` | `boolean` | Set to `true` to disable the dropdown | `false` | | `labelText` | `string` | Specify the title text | `""` | | `invalid` | `boolean` | Set to `true` to indicate an invalid state | `false` | | `invalidText` | `string` | Specify the invalid state text | `""` | | `warn` | `boolean` | Set to `true` to indicate a warning state | `false` | | `warnText` | `string` | Specify the warning state text | `""` | | `helperText` | `string` | Specify the helper text | `""` | | `label` | `string` | Specify the list box label. | _undefined_ | | `hideLabel` | `boolean` | Set to `true` to visually hide the label text | `false` | | `translateWithId` | `(id: import("../ListBox/ListBoxMenuIcon.svelte").ListBoxMenuIconTranslationId) => string` | Override the chevron icon label based on the open state.
Defaults to "Open menu" when closed and "Close menu" when open. | _undefined_ | | `virtualize` | `undefined \| boolean \| { itemHeight?: number, containerHeight?: number, overscan?: number, threshold?: number, maxItems?: number }` | Enable virtualization for large lists. Virtualization renders only the items currently visible in the viewport, improving performance for large lists.

By default, virtualization is automatically enabled for lists with more than 100 items.

Set `virtualize={false}` to explicitly disable virtualization, even for large lists.

Set `virtualize={true}` to explicitly enable virtualization with default settings.

Provide an object to customize virtualization behavior:
- `itemHeight` (default: 40): The height in pixels of each item. Specify a custom value when using custom slots with multi-line items or different heights.
- `containerHeight` (default: 300): The maximum height in pixels of the dropdown container.
- `overscan` (default: 3): The number of extra items to render above and below the viewport for smoother scrolling. Higher values may cause more flickering during very fast scrolling.
- `threshold` (default: 100): The minimum number of items required before virtualization activates. Lists with fewer items will render all items normally without virtualization.
- `maxItems` (default: undefined): The maximum number of items to render. When undefined, all visible items are rendered. | _undefined_ | | `portalMenu` | `boolean \| undefined` | Set to `true` to render the dropdown menu in a portal,
allowing it to escape containers with `overflow: hidden`.
When inside a Modal, defaults to `true` unless explicitly set to `false`. | _undefined_ | | `id` | `string` | Set an id for the list box component | `ccs-${Math.random().toString(36)}` | | `name` | `string` | Specify a name attribute for the list box. | _undefined_ | #### `Dropdown` typedefs ```ts type DropdownItem = { id: Id; text: string; /** Whether the item is disabled */ disabled?: boolean; }; ``` #### `Dropdown` slots | Slot | Detail | | --------------- | ------------------------------------------------- | | `default` | `{
item: Item;
index: number;
}` | | `labelChildren` | `Record` | #### `Dropdown` forwarded events | Event | | ----------- | | `on:scroll` | #### `Dropdown` dispatched events | Event | Detail | | ----------- | ------------------------------------------------------------------ | | `on:select` | `{
selectedId: Item["id"];
selectedItem: Item;
}` | #### `Dropdown` $$restProps `Dropdown` spreads `$$restProps` to the `div` element. #### `DropdownSkeleton` props | Prop | Type | Description | Default | | -------- | --------- | --------------------------------------- | ------- | | `inline` | `boolean` | Set to `true` to use the inline variant | `false` | #### `DropdownSkeleton` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `DropdownSkeleton` $$restProps `DropdownSkeleton` spreads `$$restProps` to the `div` element. ## ExpandableTile Expandable tiles create a collapsible content container that can show and hide content with a smooth animation. They are ideal for managing content overflow and progressive disclosure of information. They automatically measure content height using a resize observer. ### Default Create an expandable tile that shows and hides content. The component uses a [resize observer](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) to determine the height of the above-the-fold content. By default, the tile is collapsed. Use the `above` and `below` slots to define the content that appears before and after expansion. ```svelte
Above the fold content here


More above the fold content
Below the fold content here
``` ### Custom tile heights Set custom heights for the tile content using CSS. This is useful when you need to control the exact dimensions of the visible and hidden content. ```svelte
Above the fold content here
Below the fold content here
``` ### Expanded Display the tile in its expanded state by default by setting the `expanded` prop to `true`. ```svelte
Above the fold content here
Below the fold content here
``` ### Light variant Use the light variant for expandable tiles on dark backgrounds by setting the `light` prop to `true`. ```svelte
Above the fold content here
Below the fold content here
``` ### With icon labels Customize the expand/collapse button labels using the `tileExpandedLabel` and `tileCollapsedLabel` props. ```svelte
Above the fold content here
Below the fold content here
``` ### With interactive content By default, the tile uses a `
Below the fold content here
``` --- ### Component API #### `ExpandableTile` props | Prop | Type | Description | Default | | -------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------- | | `expanded` (Reactive) | `boolean` | Set to `true` to expand the tile | `false` | | `tileMaxHeight` (Reactive) | `number` | Specify the max height of the tile (number of pixels) | `0` | | `tilePadding` (Reactive) | `number` | Specify the padding of the tile (number of pixels) | `0` | | `ref` (Reactive) | `null \| HTMLElement` | Obtain a reference to the top-level element | `null` | | `light` | `boolean` | Set to `true` to enable the light variant | `false` | | `tileCollapsedIconText` | `string` | Specify the icon text of the collapsed tile | `"Interact to expand Tile"` | | `tileExpandedIconText` | `string` | Specify the icon text of the expanded tile | `"Interact to collapse Tile"` | | `tileExpandedLabel` | `string` | Specify the icon label of the expanded tile | `""` | | `tileCollapsedLabel` | `string` | Specify the icon label of the collapsed tile | `""` | | `tabindex` | `string` | Specify the tabindex | `"0"` | | `id` | `string` | Set an id for the top-level div element | `ccs-${Math.random().toString(36)}` | | `hasInteractiveContent` | `boolean` | Set to `true` if the tile contains interactive content
(e.g., links, buttons, inputs). The tile will render as
a `div` instead of a `button` to avoid invalid HTML nesting,
and the expand/collapse toggle moves to the chevron button. | `false` | #### `ExpandableTile` slots | Slot | Detail | | ------- | ----------------------- | | `above` | `Record` | | `below` | `Record` | #### `ExpandableTile` forwarded events | Event | | --------------- | | `on:click` | | `on:keypress` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `ExpandableTile` $$restProps `ExpandableTile` spreads `$$restProps` to the `svelte:element` element. ## FileUploader File uploaders provide a complete solution for file uploads, including a button trigger, drag-and-drop container, and file list display. They support various states, file validation, and customization options. ### File uploader (button-only) Create a simple file upload button using the file uploader button. By default, it accepts a single file. Set `multiple` to `true` to allow multiple file selection. ```svelte ``` ### Multiple files Enable multiple file selection by setting the `multiple` prop to `true`. This allows users to select multiple files at once. ```svelte ``` ### Custom button kind, size Customize the button appearance using the `kind` and `size` props. The default is a small primary button. ```svelte ``` ### Button with icon Add an icon to the file uploader button using the `icon` prop. ```svelte ``` ### Icon-only button > [!NOTE] Provide an **iconDescription** for accessibility. This text will be > used as the button's tooltip and screen reader label. Set **labelText=""** to > render an icon-only button. ```svelte ``` ### Icon-only button (custom tooltip position) Control the tooltip position and alignment with `tooltipPosition` and `tooltipAlignment`. ```svelte ``` ### Icon-only button (hidden tooltip) Set `hideTooltip` to `true` to visually hide the tooltip while maintaining accessibility for screen readers. > [!NOTE] Use this when tooltips cause layout issues, interfere with > interactions, or when multiple icon buttons are densely packed (e.g., > toolbars). The **iconDescription** remains accessible to screen readers. ```svelte ``` ### File uploader The file uploader combines a button trigger with a list of uploaded files. It supports file type restrictions, multiple file selection, and various upload states. This example accepts multiple JPEG files and displays them in a completed state. ```svelte ``` ### Clear files Remove uploaded files from the file uploader in two ways: - programmatically using the **clearFiles** accessor - two-way binding by setting **files** to **[]** ```svelte
``` ### Maximum file size Limit the size of uploaded files using the `maxFileSize` prop. Files exceeding the limit (in bytes) will be automatically filtered out. The `maxFileSize` prop accepts values in bytes. File sizes use binary (base 2) units, where 1024 bytes = 1 KiB (kibibyte), not 1000 bytes. This matches how operating systems and file systems measure file sizes. This example accepts files up to 1 MB (1,048,576 bytes): ```svelte ``` ### File uploader (disabled state) Disable the file uploader by setting the `disabled` prop to `true`. This prevents user interaction with the component. ```svelte ``` ### Item (uploading) Display a file upload in progress using the `uploading` status. This shows a loading indicator and the file name. ```svelte ``` ### Item (complete) Show a successfully uploaded file using the `complete` status. This displays a checkmark icon next to the file name. ```svelte ``` ### Item (edit) Enable file deletion by setting the status to `"edit"`. Clicking the close icon dispatches a `delete` event with the item's ID. ```svelte { console.log(e.detail); // "readme" }} /> ## Item (edit status, invalid state) Mark a file as invalid while keeping it editable. This shows an error icon and allows the user to remove the file. ## Item (edit status, invalid state with subject, body) Provide detailed error messages for invalid files using the `errorSubject` and `errorBody` props. This helps users understand and resolve upload issues. ## Item sizes Customize the size of file uploader items using the `size` prop. The default size is "default". ## Drop container Use the file uploader drop container for drag-and-drop file uploads. It supports file validation and multiple file selection. This example accepts files smaller than 1 kB and logs the selected files to the console. { return files.filter((file) => file.size < 1_024); }} on:change={(e) => { console.log("files", e.detail); }} /> ## Skeleton Display a loading state using the file uploader skeleton. This provides visual feedback while the file uploader content is being loaded. ``` --- ### Component API #### `FileUploaderButton` props | Prop | Type | Description | Default | | ---------------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | `files` (Reactive) | `ReadonlyArray` | Obtain a reference to the uploaded files. | `[]` | | `labelText` (Reactive) | `string` | Specify the label text | `"Add file"` | | `ref` (Reactive) | `null \| HTMLInputElement` | Obtain a reference to the input HTML element | `null` | | `accept` | `ReadonlyArray` | Specify the accepted file types. | `[]` | | `multiple` | `boolean` | Set to `true` to allow multiple files | `false` | | `disabled` | `boolean` | Set to `true` to disable the input | `false` | | `disableLabelChanges` | `boolean` | Set to `true` to disable label changes | `false` | | `kind` | `import("../Button/Button.svelte").ButtonProps["kind"]` | Specify the kind of file uploader button. | `"primary"` | | `size` | `import("../Button/Button.svelte").ButtonProps["size"]` | Specify the size of the file uploader button. | `"small"` | | `id` | `string` | Set an id for the input element | `ccs-${Math.random().toString(36)}` | | `name` | `string` | Specify a name attribute for the input | `""` | | `icon` | `any` | Specify the icon to render. | _undefined_ | | `iconDescription` | `string` | Specify the ARIA label for the button icon. | _undefined_ | | `tooltipAlignment` | `"start" \| "center" \| "end"` | Set the alignment of the tooltip relative to the icon.
Only applies to icon-only buttons. | `"center"` | | `tooltipPosition` | `"top" \| "right" \| "bottom" \| "left"` | Set the position of the tooltip relative to the icon. | `"bottom"` | | `hideTooltip` | `boolean` | Set to `true` to hide the tooltip while maintaining accessibility.
Only applies to icon-only buttons.
When `true`, the tooltip is visually hidden but the `iconDescription` remains accessible to screen readers. | `false` | #### `FileUploaderButton` slots | Slot | Detail | | --------------- | ----------------------- | | `labelChildren` | `Record` | #### `FileUploaderButton` forwarded events | Event | | ------------ | | `on:keydown` | | `on:click` | #### `FileUploaderButton` dispatched events | Event | Detail | | ----------- | --------------------- | | `on:change` | `ReadonlyArray` | #### `FileUploaderButton` $$restProps `FileUploaderButton` spreads `$$restProps` to the `input` element. #### `FileUploader` props | Prop | Type | Description | Default | | ------------------ | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | | `files` (Reactive) | `ReadonlyArray` | Obtain a reference to the uploaded files. | `[]` | | `status` | `"uploading" \| "edit" \| "complete"` | Specify the file uploader status. | `"uploading"` | | `disabled` | `boolean` | Set to `true` to disable the file uploader | `false` | | `accept` | `ReadonlyArray` | Specify the accepted file types. | `[]` | | `maxFileSize` | `number \| undefined` | Specify the maximum file size in bytes.
Files exceeding this limit will be filtered out.
File sizes use binary (base 2) units: 1024 bytes = 1 KiB, not 1000 bytes. | _undefined_ | | `multiple` | `boolean` | Set to `true` to allow multiple files | `false` | | `clearFiles` | `() => void` | Programmatically clear the uploaded files. | _undefined_ | | `labelTitle` | `string` | Specify the label title.
Alternatively, use the named slot "labelTitle". | `""` | | `labelDescription` | `string` | Specify the label description.
Alternatively, use the named slot "labelDescription". | `""` | | `kind` | `import("../Button/Button.svelte").ButtonProps["kind"]` | Specify the kind of file uploader button. | `"primary"` | | `size` | `import("../Button/Button.svelte").ButtonProps["size"]` | Specify the size of the file uploader button. | `"small"` | | `buttonLabel` | `string` | Specify the button label | `""` | | `iconDescription` | `string` | Specify the ARIA label used for the status icons | `"Provide icon description"` | | `name` | `string` | Specify a name attribute for the file button uploader input | `""` | #### `FileUploader` slots | Slot | Detail | | ------------------ | ----------------------- | | `labelDescription` | `Record` | | `labelTitle` | `Record` | #### `FileUploader` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | | `on:keydown` | #### `FileUploader` dispatched events | Event | Detail | | ----------- | --------------------- | | `on:add` | `ReadonlyArray` | | `on:remove` | `ReadonlyArray` | | `on:change` | `ReadonlyArray` | #### `FileUploader` $$restProps `FileUploader` spreads `$$restProps` to the `div` element. #### `FileUploaderDropContainer` props | Prop | Type | Description | Default | | ------------------ | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------- | | `files` (Reactive) | `ReadonlyArray` | Obtain a reference to the uploaded files. | `[]` | | `ref` (Reactive) | `null \| HTMLInputElement` | Obtain a reference to the input HTML element | `null` | | `accept` | `ReadonlyArray` | Specify the accepted file types. | `[]` | | `multiple` | `boolean` | Set to `true` to allow multiple files | `false` | | `validateFiles` | `(files: ReadonlyArray) => ReadonlyArray` | Override the default behavior of validating uploaded files.
By default, files are not validated. | _undefined_ | | `labelText` | `string` | Specify the label text | `"Add file"` | | `role` | `string` | Specify the `role` attribute of the drop container | `"button"` | | `disabled` | `boolean` | Set to `true` to disable the input | `false` | | `tabindex` | `string` | Specify `tabindex` attribute | `"0"` | | `id` | `string` | Set an id for the input element | `ccs-${Math.random().toString(36)}` | | `name` | `string` | Specify a name attribute for the input | `""` | #### `FileUploaderDropContainer` slots | Slot | Detail | | --------------- | ----------------------- | | `labelChildren` | `Record` | #### `FileUploaderDropContainer` forwarded events | Event | | -------------- | | `on:dragover` | | `on:dragleave` | | `on:drop` | | `on:keydown` | | `on:click` | #### `FileUploaderDropContainer` dispatched events | Event | Detail | | ----------- | --------------------- | | `on:add` | `ReadonlyArray` | | `on:change` | `ReadonlyArray` | #### `FileUploaderDropContainer` $$restProps `FileUploaderDropContainer` spreads `$$restProps` to the `div` element. #### `FileUploaderItem` props | Prop | Type | Description | Default | | ----------------- | ------------------------------------- | ------------------------------------------------ | ----------------------------------- | | `status` | `"uploading" \| "edit" \| "complete"` | Specify the file uploader status. | `"uploading"` | | `size` | `"default" \| "field" \| "small"` | Specify the size of button skeleton. | `"default"` | | `iconDescription` | `string` | Specify the ARIA label used for the status icons | `""` | | `invalid` | `boolean` | Set to `true` to indicate an invalid state | `false` | | `errorSubject` | `string` | Specify the error subject text | `""` | | `errorBody` | `string` | Specify the error body text | `""` | | `id` | `string` | Set an id for the top-level element | `ccs-${Math.random().toString(36)}` | | `name` | `string` | Specify the file uploader name | `""` | #### `FileUploaderItem` forwarded events | Event | | --------------- | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `FileUploaderItem` dispatched events | Event | Detail | | ----------- | -------- | | `on:delete` | `string` | #### `FileUploaderItem` $$restProps `FileUploaderItem` spreads `$$restProps` to the `span` element. #### `FileUploaderSkeleton` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `FileUploaderSkeleton` $$restProps `FileUploaderSkeleton` spreads `$$restProps` to the `div` element. ## FloatingPortal Floating portals build on [Portal](/components/Portal) by rendering content into `document.body` and positioning it relative to an anchor element. The `anchor` prop is required and specifies the element to position the floating content relative to. They automatically flip direction when there is not enough space and reposition on scroll and resize. Use a portal when you only need to escape overflow and z-index stacking contexts. Use floating portals when you need anchored, positioned content such as dropdowns, popovers, or overflow menus. In the examples below, click the button to toggle the floating content and drag the tile to move the anchor. The floating content will track the anchor position. ### Default Position floating content below an anchor element. ```svelte
e.key === "Enter" && (open = !open)} title="Drag to move, click to toggle" >
Content ``` ### Direction Set the `direction` prop to `"top"` or `"bottom"` to control the preferred direction. The component will flip to the opposite direction if there is not enough space. The default direction is `"bottom"`. ```svelte
e.key === "Enter" && (openBottom = !openBottom)} title="Drag to move, click to toggle" >
Content
e.key === "Enter" && (openTop = !openTop)} title="Drag to move, click to toggle" >
Content
``` ### Escaping overflow Because the floating content is rendered into `document.body`, it escapes parent containers with `overflow: hidden`. ```svelte
This container has hidden overflow.
e.key === "Enter" && (open = !open)} title="Drag to move, click to toggle" >
Content ``` ### Slot direction By default, the floating content is rendered below the anchor element. However, if there is not enough space below the anchor element, the component will automatically flip to the opposite direction. Use the `direction` slot prop to read the actual rendered direction after auto-flipping for conditional logic, like styles. ```svelte
e.key === "Enter" && (open = !open)} title="Drag to move, click to toggle" >
Actual direction: {direction} ``` --- ### Component API #### `FloatingPortal` props | Prop | Type | Description | Default | | ------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | `anchor` (Required) | `null \| HTMLElement` | Required. Specify the anchor element to position the floating content relative to.
When using `bind:this`, this may be `null` initially until the element is mounted. | _undefined_ | | `ref` (Reactive) | `null \| HTMLElement` | Obtain a reference to the floating portal element. | `null` | | `direction` | `"bottom" \| "top"` | Set the preferred direction of the floating content.
The component will flip to the opposite direction
if there is not enough space. | `"bottom"` | | `open` | `boolean` | Set to `true` to open the floating content. | `false` | | `zIndex` | `number` | Specify the z-index of the floating portal.
By default, this value supersedes the z-index
of modals (9000) and list box menus (9100). | `9200` | #### `FloatingPortal` slots | Slot | Detail | | --------- | ---------------------------------------------- | | `default` | `{
direction: "bottom" \| "top";
}` | #### `FloatingPortal` $$restProps `FloatingPortal` spreads `$$restProps` to the `Portal` component. ## FluidForm Fluid forms provide a fluid-width form layout that adapts to their container. They are designed for full-width form layouts and work with most Carbon input components. Note that inline input variants cannot be used within a fluid form. ### Fluid form Create a fluid-width form layout using the fluid form component. This example shows a basic login form with required fields. ```svelte ``` ### Invalid state Handle form validation and display error states using the `invalid` and `invalidText` props on form inputs. This example demonstrates how to show validation errors in a fluid form. ```svelte ``` --- ### Component API #### `FluidForm` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `FluidForm` forwarded events | Event | | --------------- | | `on:click` | | `on:keydown` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | | `on:submit` | #### `FluidForm` $$restProps `FluidForm` spreads `$$restProps` to the `form` element. ## Form Forms provide a structured way to collect user input. They work with various form controls like checkboxes, radio buttons, and select menus. Form groups help organize related form controls with a legend. ### Form Create a form with grouped controls using the form and form group. This example shows a form with checkboxes, radio buttons, and a select menu. ```svelte
``` ### Prevent default behavior Handle form submission by preventing the default browser behavior. Use `e.preventDefault()` to stop the native form submission and handle the event programmatically. ```svelte
{ e.preventDefault(); console.log("submit", e); }} > ``` --- ### Component API #### `Form` props | Prop | Type | Description | Default | | ---------------- | ------------------------- | -------------------------------------- | ------- | | `ref` (Reactive) | `null \| HTMLFormElement` | Obtain a reference to the form element | `null` | #### `Form` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `Form` forwarded events | Event | | --------------- | | `on:click` | | `on:keydown` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | | `on:submit` | #### `Form` $$restProps `Form` spreads `$$restProps` to the `form` element. #### `FormGroup` props | Prop | Type | Description | Default | | ------------- | --------- | --------------------------------------------- | ------- | | `noMargin` | `boolean` | Set to `true` for to remove the bottom margin | `false` | | `invalid` | `boolean` | Set to `true` to indicate an invalid state | `false` | | `message` | `boolean` | Set to `true` to render a form requirement | `false` | | `messageText` | `string` | Specify the message text | `""` | | `legendText` | `string` | Specify the legend text | `""` | | `legendId` | `string` | Specify an id for the legend element | `""` | #### `FormGroup` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `FormGroup` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseover` | | `on:mouseenter` | | `on:mouseleave` | #### `FormGroup` $$restProps `FormGroup` spreads `$$restProps` to the `fieldset` element. ## Grid The [Carbon grid system](https://carbondesignsystem.com/elements/2x-grid/overview/) provides a responsive layout structure that adapts to different screen sizes. Use row and column components to create flexible layouts. The grid supports various spacing options and column configurations. The system uses a responsive column structure where the total number of columns changes based on screen size: - **Small (sm)**: 0-671px — 4 columns - **Medium (md)**: 672-1055px — 8 columns - **Large (lg)**: 1056-1311px — 16 columns - **X-Large (xlg)**: 1312-1583px — 16 columns - **Max (max)**: 1584px and above — 16 columns > [!NOTE] Column spans are relative to the total columns at each breakpoint. For > example, to create a full-width column, use `sm={4} md={8} lg={16}` instead of > the same value across all breakpoints. ### Default Create a basic grid layout with equal-width columns. This example demonstrates the default grid behavior. ```svelte Column Column Column Column ``` ### Full width Use the full-width grid variant for layouts that span the entire viewport width. This removes the default max-width constraint. ```svelte Column Column Column Column ``` ### Narrow Create a more compact grid layout using the narrow variant. This reduces the spacing between columns. ```svelte Column Column Column Column ``` ### Condensed Use the condensed variant for even tighter spacing between columns. This is ideal for dense data displays. ```svelte Column Column Column Column ``` ### Responsive Build responsive layouts by specifying different column widths for different breakpoints. The grid automatically adjusts based on screen size. **Key concept:** Since each breakpoint has a different total number of columns, you need to scale your column spans proportionally. Here are common patterns: **Full width column:** ```svelte ``` **Half width (50/50 split):** ```svelte ``` **Two-thirds / One-third split:** ```svelte ``` ```svelte sm: 1, md: 4, lg: 8 sm: 1, md: 2, lg: 2 sm: 1, md: 1, lg: 1 sm: 1, md: 1, lg: 1 ``` ### Offset columns Create space between columns using the offset feature. This allows for more flexible layouts without empty columns. ```svelte Offset 3 Offset 2 Offset 1 Offset 0 ``` ### Aspect ratio columns Maintain consistent column heights using aspect ratio columns. This ensures content alignment across different column widths. ```svelte 2x1 2x1 ``` ### Padding Add vertical padding (top/bottom) to grid elements using the `padding` prop. You can apply padding at the grid, row, or column level to control spacing between rows of content. This is useful for creating vertical rhythm without manually adding margins. ```svelte
Adding padding to Grid applies it to columns in all rows:
Column Column Column Column
Adding padding to a Row only applies to its columns:
Column Column Column Column Column Column Column Column
Adding padding to a specific column only applies it to the column:
Column Column Column Column ``` ### Breakpoints Reference Understanding [breakpoints](/components/Breakpoint) is critical for creating responsive layouts. Each breakpoint has specific pixel ranges and column counts: - **Small (sm)**: 0-671px — 4 columns — Mobile phones - **Medium (md)**: 672-1055px — 8 columns — Tablets, small laptops - **Large (lg)**: 1056-1311px — 16 columns — Desktop monitors, laptops - **X-Large (xlg)**: 1312-1583px — 16 columns — Large desktop monitors - **Max (max)**: 1584px and above — 16 columns — Extra-large displays When designing responsive layouts, start with mobile (sm) and work your way up to ensure your content works well at all sizes. --- ### Component API #### `Grid` props | Prop | Type | Description | Default | | --------------- | --------- | ---------------------------------------------------------------------------------------------------------- | ------- | | `as` | `boolean` | Set to `true` to render a custom HTML element.
Props are destructured as `props` in the default slot. | `false` | | `condensed` | `boolean` | Set to `true` to use the condensed variant | `false` | | `narrow` | `boolean` | Set to `true` to use the narrow variant | `false` | | `fullWidth` | `boolean` | Set to `true` to use the fullWidth variant | `false` | | `noGutter` | `boolean` | Set to `true` to remove the gutter | `false` | | `noGutterLeft` | `boolean` | Set to `true` to remove the left gutter | `false` | | `noGutterRight` | `boolean` | Set to `true` to remove the right gutter | `false` | | `padding` | `boolean` | Set to `true` to add top and bottom padding to all columns | `false` | #### `Grid` slots | Slot | Detail | | --------- | --------------------------------------------------------------------------------- | | `default` | `{
props: {
class: string;
[key: string]: any;
};
}` | #### `Grid` $$restProps `Grid` spreads `$$restProps` to the `div` element. #### `Row` props | Prop | Type | Description | Default | | --------------- | --------- | ---------------------------------------------------------------------------------------------------------- | ------- | | `as` | `boolean` | Set to `true` to render a custom HTML element.
Props are destructured as `props` in the default slot. | `false` | | `condensed` | `boolean` | Set to `true` to use the condensed variant | `false` | | `narrow` | `boolean` | Set to `true` to use the narrow variant | `false` | | `noGutter` | `boolean` | Set to `true` to remove the gutter | `false` | | `noGutterLeft` | `boolean` | Set to `true` to remove the left gutter | `false` | | `noGutterRight` | `boolean` | Set to `true` to remove the right gutter | `false` | | `padding` | `boolean` | Set to `true` to add top and bottom padding to all columns | `false` | #### `Row` slots | Slot | Detail | | --------- | --------------------------------------------------------------------------------- | | `default` | `{
props: {
class: string;
[key: string]: any;
};
}` | #### `Row` $$restProps `Row` spreads `$$restProps` to the `div` element. #### `Column` props | Prop | Type | Description | Default | | --------------- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ----------- | | `as` | `boolean` | Set to `true` to render a custom HTML element.
Props are destructured as `props` in the default slot. | `false` | | `noGutter` | `boolean` | Set to `true` to remove the gutter | `false` | | `noGutterLeft` | `boolean` | Set to `true` to remove the left gutter | `false` | | `noGutterRight` | `boolean` | Set to `true` to remove the right gutter | `false` | | `padding` | `boolean` | Set to `true` to add top and bottom padding to the column | `false` | | `aspectRatio` | `"2x1" \| "16x9" \| "9x16" \| "1x2" \| "4x3" \| "3x4" \| "1x1"` | Specify the aspect ratio of the column. | _undefined_ | | `sm` | `ColumnBreakpoint` | Set the small breakpoint. | _undefined_ | | `md` | `ColumnBreakpoint` | Set the medium breakpoint. | _undefined_ | | `lg` | `ColumnBreakpoint` | Set the large breakpoint. | _undefined_ | | `xlg` | `ColumnBreakpoint` | Set the extra large breakpoint. | _undefined_ | | `max` | `ColumnBreakpoint` | Set the maximum breakpoint. | _undefined_ | #### `Column` typedefs ```ts type ColumnSize = boolean | number; type ColumnSizeDescriptor = { span?: ColumnSize; offset: number; }; type ColumnBreakpoint = ColumnSize | ColumnSizeDescriptor; ``` #### `Column` slots | Slot | Detail | | --------- | --------------------------------------------------------------------------------- | | `default` | `{
props: {
class: string;
[key: string]: any;
};
}` | #### `Column` $$restProps `Column` spreads `$$restProps` to the `div` element. ## Heading Heading and section components work together to automatically manage semantic heading hierarchy in your application. The heading component automatically adjusts its heading level (h1–h6) based on the nesting depth of section components, ensuring proper document structure and accessibility without manual level management. ### Default A top-level heading inside a section renders as an `h1` element. This provides a semantic starting point for your document structure. ```svelte
Heading 1
``` ### Nested sections As you nest section components, the heading levels automatically increment to maintain proper hierarchy. Each nested section increases the heading level by one (h1 → h2 → h3, etc.). Heading levels are automatically capped at `h6` to ensure valid HTML structure, even if you nest deeper than six levels. ```svelte
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
Capped at Heading 6
``` ### Custom level Use the `level` prop on the section to specify a custom starting heading level. This is useful when you need to start a section at a specific level, such as when embedding content that should begin at a higher heading level. Child sections will continue to increment from this custom level. ```svelte
Starts at Heading 5
Heading 6
``` ### Custom section element By default, the section renders a semantic `
` element. Use the `tag` prop to render a different HTML element while maintaining the heading level context functionality. This is useful when you need to use a different semantic element (like `
`, `
`, or `