# Carbon Components Svelte A complete [Svelte](https://github.com/sveltejs/svelte) component library that implements the [IBM Carbon Design System](https://www.carbondesignsystem.com/). Ship accessible, consistent, production-ready interfaces. - **90+ components** -- from inputs to data tables - **5 built-in themes** -- two light, three dark - **Fully typed TypeScript API** -- props, events, and slots - **WCAG 2.1 AA** -- keyboard and screen-reader ready ## Quick start Install the library, pick a theme, and render your first component. Three steps to a running app, plus customization options below. ### 1. Install the package ```sh # npm npm i carbon-components-svelte # pnpm pnpm add carbon-components-svelte # Yarn yarn add carbon-components-svelte # Bun bun add carbon-components-svelte ``` ### 2. Apply a theme stylesheet Import one precompiled Carbon theme. The Carbon Design System supports five themes (2 light, 3 dark): White, Gray 10, Gray 80, Gray 90, Gray 100. Import this once at the top-level, like `index.js` or `src/+layout.svelte`. ```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 (for dynamic theming) import "carbon-components-svelte/css/all.css"; ``` ### 3. Import a component ```svelte ``` Explore the full [component index](/component-index). ## Dynamic theming To switch themes at runtime, import the combined `all.css` stylesheet instead of a single theme. It bundles all five themes and toggles between them through a `theme` attribute on the HTML element. Import the stylesheet once, at the top-level entry point of your app: ```javascript import "carbon-components-svelte/css/all.css"; ``` Then set the theme reactively in Svelte: ```svelte ``` Or statically in your HTML: ```html ``` Or use the [Theme component](/components/Theme) to manage the theme reactively. ## Faster builds, smaller bundles The fast path is enough to build. [carbon-preprocess-svelte](https://github.com/carbon-design-system/carbon-preprocess-svelte) trims build times and bundle size with two drop-in tools for faster HMR in development and leaner CSS when you ship. Add carbon-preprocess-svelte as a dev dependency: ```sh # npm npm i -D carbon-preprocess-svelte # pnpm pnpm add -D carbon-preprocess-svelte # Yarn yarn add -D carbon-preprocess-svelte # Bun bun add -D carbon-preprocess-svelte ``` ### optimizeImports Rewrites barrel imports to direct source paths, dramatically cutting cold build and HMR times. ### optimizeCss Tree-shakes unused Carbon CSS at build time, often removing hundreds of kilobytes from production bundles. ### Configure your bundler Add `optimizeImports` to your Svelte preprocessor and `optimizeCss` to your bundler plugins. **Vite:** ```javascript // vite.config.js import { svelte, vitePreprocess } from "@sveltejs/vite-plugin-svelte"; import { optimizeCss, optimizeImports } from "carbon-preprocess-svelte"; export default { plugins: [ svelte({ preprocess: [vitePreprocess(), optimizeImports()], }), optimizeCss(), ], }; ``` **SvelteKit:** ```javascript // svelte.config.js import adapter from "@sveltejs/adapter-static"; import { vitePreprocess } from "@sveltejs/vite-plugin-svelte"; import { optimizeImports } from "carbon-preprocess-svelte"; const config = { preprocess: [vitePreprocess(), optimizeImports()], kit: { adapter: adapter() }, }; export default 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()], }); ``` **Rollup:** ```javascript // rollup.config.js import svelte from "rollup-plugin-svelte"; import { optimizeCss, optimizeImports } from "carbon-preprocess-svelte"; const production = !process.env.ROLLUP_WATCH; export default { plugins: [ svelte({ preprocess: [optimizeImports()], }), production && optimizeCss(), ], }; ``` **Webpack:** ```javascript // webpack.config.mjs import { OptimizeCssPlugin, optimizeImports } from "carbon-preprocess-svelte"; export default { module: { rules: [ { test: /\.svelte$/, use: { loader: "svelte-loader", options: { preprocess: [optimizeImports()], }, }, }, ], }, plugins: [new OptimizeCssPlugin()], }; ``` ## Icons and pictograms The icon and pictogram sets ship as separate packages of individual Svelte components. Both are professionally designed, original iconography crafted to complement the scale and grid of Carbon components. Each is optional, so install only what you need. ### Icons 2,700+ icons designed for product UI, in four sizes (16, 20, 24, and 32 pixels), set with a single prop. ```sh # npm npm i carbon-icons-svelte # pnpm pnpm add carbon-icons-svelte # Yarn yarn add carbon-icons-svelte # Bun bun add carbon-icons-svelte ``` ```svelte ``` ### Pictograms 1,500+ illustrative pictograms for empty states, onboarding, hero sections, and feature callouts. Larger than icons, 64px by default. ```sh # npm npm i carbon-pictograms-svelte # pnpm pnpm add carbon-pictograms-svelte # Yarn yarn add carbon-pictograms-svelte # Bun bun add carbon-pictograms-svelte ``` ```svelte ``` ## Documentation for LLMs Documentation is available in LLM-friendly plain text for use with coding assistants, plus a standalone Markdown document for every component. Append `.md` to any component's URL to read it. - **[llms.txt](/llms.txt)** -- A component index where each entry links to its per-component Markdown doc, sized for model context windows. - **[llms-full.txt](/llms-full.txt)** -- The full component documentation in a single plain-text file. ## Collection The Carbon Svelte collection includes packages for icons, pictograms, and data visualization: - **Carbon Components Svelte** -- 90+ components -- [GitHub](https://github.com/carbon-design-system/carbon-components-svelte) - **Carbon Icons Svelte** -- 2,700+ 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 ### Basic 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 Align the chevron icon to the left side of the accordion item by setting `align` to `"start"`. ```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.

``` ### Flush Set `flush` to remove the accordion's gutter, aligning it flush with the edges of its container. This works well in full-bleed layouts and side panels. `flush` has no effect when `align` is `"start"`. ```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 with the title slot instead of the title prop for more complex 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 `open` on an 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.

``` ### Single-open Set `type` to `"single"` so that opening an item automatically closes any other open item. This is useful for FAQs, step-by-step wizards, or settings panels where only one section should be expanded at a time. The default is `"multiple"`, which allows any number of items to be open simultaneously. ```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.

``` ### Nested Put an `Accordion` inside an `AccordionItem` to compose nested clusters. Nested items keep their own open state, independent of the parent. ```svelte 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. Region us-south Analyzes text to extract meta-data from content such as concepts, entities, emotion, relations, sentiment and more. Region eu-de ``` ### Programmatic example Programmatically control the accordion items with the `bind:open` directive, expanding and collapsing items based on user interactions or application state. ```svelte {#each items as item}

{item.description}

{/each}
``` ### Sizes Set `size` to control row height. The default is `md`. #### Extra-large Display the accordion in an extra-large size by setting `size` to `"xl"`. ```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 Set `size` to `"sm"` for a smaller accordion in compact layouts or when space is limited. ```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 Disable the whole accordion or individual items. #### All Set `disabled` on the accordion to disable all items at once. Users can no longer expand or collapse any 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.

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

{item.description}

{/each}
``` #### Item Disable an individual item by setting `disabled` on a specific accordion item for finer 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 Set `skeleton` to show a loading placeholder while content loads. ```svelte ``` #### Left-aligned chevron Combine skeleton state with left-aligned chevron by enabling `skeleton` and setting `align` to `"start"`. ```svelte ``` #### Custom count By default, the skeleton state displays 4 items. Set `count` to specify the number of skeleton items to display. ```svelte ``` #### Closed By default, the first skeleton item is open. Set `open={false}` to render the skeleton collapsed. ```svelte ``` #### Extra-large Set `size` to `"xl"` for an extra-large skeleton. ```svelte ``` #### Small Set `size` to `"sm"` for a small skeleton. ```svelte ``` #### Flush Set `flush` to remove the skeleton's gutter, matching the flush variant. ```svelte ``` ### Lazy loading Set `lazy` on an accordion item to defer mounting its panel content until the item first opens. Use it for panels with heavy content, such as API-fetched data or charts, so they mount only when needed. The content stays mounted after the item collapses. ```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.

``` --- ### 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_ | | `flush` | `boolean` | Set to `true` to remove the gutter around the accordion, aligning it flush with its container.
Has no effect when `align` is `"start"`. | `false` | | `disabled` | `boolean` | Set to `true` to disable the accordion | `false` | | `skeleton` | `boolean` | Set to `true` to display the skeleton state | `false` | | `type` | `"single" \| "multiple"` | Specify the expansion behavior of the accordion.
Set to `"single"` so that opening an item closes all other items. | `"multiple"` | #### `Accordion` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `Accordion` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `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` | | `ref` (Reactive) | `null \| HTMLButtonElement` | Obtain a reference to the heading button HTML element. | `null` | | `title` | `string` | Specify the title of the accordion item heading.
Alternatively, use the "title" slot. | `"title"` | | `ariaLabel` | `string` | Specify a custom label for the accordion button.
This is important for accessibility when the accordion has no visible title. | _undefined_ | | `lazy` | `boolean` | Set to `true` to defer mounting the panel content until the item is first opened.
Once mounted, the content stays mounted for subsequent collapses. | `false` | #### `AccordionItem` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | | `title` | `Record` | #### `AccordionItem` forwarded events | Event | | ----------------- | | `on:animationend` | | `on:click` | | `on:keydown` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `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_ | | `flush` | `boolean` | Set to `true` to remove the gutter around the accordion, aligning it flush with its container.
Has no effect when `align` is `"start"`. | `false` | | `open` | `boolean` | Set to `false` to close the first accordion item | `true` | #### `AccordionSkeleton` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `AccordionSkeleton` $$restProps `AccordionSkeleton` spreads `$$restProps` to the `ul` element. ## AspectRatio ### Basic Display a 2:1 aspect ratio container by default. ```svelte 2x1 ``` ### Ratios Supported aspect ratios include `2x1`, `2x3`, `16x9`, `4x3`, `1x1`, `3x4`, `3x2`, `9x16`, and `1x2`. #### 2x3 Display content with a 2:3 aspect ratio. ```svelte 2x3 ``` #### 16x9 Display content with a 16:9 aspect ratio. ```svelte 16x9 ``` #### 4x3 Display content with a 4:3 aspect ratio. ```svelte 4x3 ``` #### 1x1 Display content with a 1:1 (square) aspect ratio. ```svelte 1x1 ``` #### 3x4 Display content with a 3:4 aspect ratio. ```svelte 3x4 ``` #### 3x2 Display content with a 3:2 aspect ratio. ```svelte 3x2 ``` #### 9x16 Display content with a 9:16 aspect ratio. ```svelte 9x16 ``` #### 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. ## BadgeIndicator ### Basic Omit count to render an empty dot that signals presence without a number. ```svelte ``` ### Count Set count to a number. Values greater than 999 display as 999+. ```svelte ``` ### Formatted count Pass a string to count to override the built-in numeric display. String values bypass the 999+ cap. ```svelte ``` ### In UI Shell Use the [UI Shell](/components/UIShell) for header notifications and other utility indicators. ```svelte

Dashboard

``` --- ### Component API #### `BadgeIndicator` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `ref` (Reactive) | `null \| HTMLDivElement` | Obtain a reference to the HTML element. | `null` | | `count` | `number \| string` | Specify the badge count.
Omit or set to `0` to render an empty dot.
A numeric count greater than `999` displays as "999+".
Pass a string to override the displayed value (e.g. `"1.2k"`). | _undefined_ | #### `BadgeIndicator` $$restProps `BadgeIndicator` spreads `$$restProps` to the `div` element. #### `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.
When the `badge` slot is used, size is set to `lg` per Carbon design guidelines. | `"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` | `Icon` | Specify the icon to render.
Alternatively, use the named slot "icon". | _undefined_ | | `iconDescription` | `string` | Specify the ARIA label for the button icon.
On an icon-only button, this also drives Carbon's tooltip. If omitted,
the icon-only button renders without a tooltip; supply your own
`aria-label` or `aria-labelledby` for accessibility in that case. | _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` | `number \| string \| undefined` | Specify the tabindex | `"0"` | | `type` | `string` | Specify the `type` attribute for the button element | `"button"` | | `portalTooltip` | `boolean \| undefined` | Set to `true` to render the icon-only tooltip in a portal,
preventing it from being clipped by `overflow: hidden` containers
and enabling auto-flipping when the preferred direction lacks space.
By default, the tooltip is portalled when inside a `Modal`. | _undefined_ | #### `Button` slots | Slot | Detail | | --- | --- | | `default` | `{
props: {
role: "button";
type?: string;
tabindex: any;
disabled: boolean;
href?: string;
class: string;
[key: string]: any;
};
}` | | `badge` | `Record` | | `icon` | `{
style: undefined \| string;
}` | #### `Button` forwarded events | Event | | --------------- | | `on:blur` | | `on:click` | | `on:focus` | | `on:mousedown` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `Button` $$restProps `Button` spreads `$$restProps` to the `button | a | div` element. #### `HeaderGlobalAction` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `ref` (Reactive) | `HTMLButtonElement` | Obtain a reference to the HTML button element. | `null` | | `isActive` | `boolean` | Set to `true` to use the active variant | `false` | | `icon` | `Icon` | Specify the icon to render. | _undefined_ | #### `HeaderGlobalAction` slots | Slot | Detail | | ------- | ----------------------- | | `badge` | `Record` | #### `HeaderGlobalAction` forwarded events | Event | | ---------- | | `on:click` | #### `HeaderGlobalAction` $$restProps `HeaderGlobalAction` spreads `$$restProps` to the `Button` component. ## Box ### Basic The default component renders a `
` with no modifiers. ```svelte Content inside a box. ``` ### Tokens Apply Carbon fill, inset, and border tokens. #### Fill Set `fill` to a Carbon background token. Tokens use v11 names and resolve through the active theme. | Token | Description | | ------------ | -------------------------- | | `background` | Default page background | | `layer-01` | First layer surface | | `layer-02` | Second layer surface | | `layer-03` | Third layer surface | | `field` | Form field background | | `inverse` | Inverse surface background | ```svelte background layer-01 layer-02 layer-03 ``` Nested fills stack Carbon layer surfaces. Contrast depends on the active theme: on white, layer-02 matches the page background, so pair a darker outer fill with border to show depth. ```svelte layer-03 inside layer-01. ``` #### Inset Set inset and margin props using the shared layout scale 1-13 (same values as [Stack](/components/Stack) gap). Pass a string for any CSS length. | Scale | Size | | ----- | -------------- | | 1 | 0.125rem (2px) | | 2 | 0.25rem (4px) | | 3 | 0.5rem (8px) | | 4 | 0.75rem (12px) | | 5 | 1rem (16px) | | 6 | 1.5rem (24px) | | 7 | 2rem (32px) | | 8 | 2.5rem (40px) | | 9 | 3rem (48px) | | 10 | 4rem (64px) | | 11 | 5rem (80px) | | 12 | 6rem (96px) | | 13 | 10rem (160px) | ```svelte Scale padding (5) Custom padding (`2rem`) Axis padding Vertical margin ``` #### Border Set `border` to a Carbon border token. Each utility applies `1px solid`. | Token | Description | | ------------- | -------------------------- | | `subtle` | Subtle divider border | | `strong` | Strong divider border | | `interactive` | Interactive element border | | `disabled` | Disabled element border | ```svelte subtle strong interactive ``` ### Width Set width, maxWidth, or minWidth to any CSS length. Numbers are treated as pixels. Use `fullWidth` to span the container (`width: 100%`). ```svelte Max width in rem (`20rem`). Max width in pixels (`480`). ``` ```svelte
Full width up to a custom max width.
``` ### Composition ```svelte API keys API keys authenticate programmatic access to your workspace. Store secrets in IBM Cloud Secrets Manager and rotate them on a schedule your security team defines. ``` ### Utility classes Apply Box utilities directly when you do not need the component. Classes use the `bx--` prefix. | Class | Description | | ---------------------------- | ----------------------------- | | `bx--box-fill-background` | Default page background | | `bx--box-fill-layer-01` | First layer surface | | `bx--box-fill-layer-02` | Second layer surface | | `bx--box-fill-layer-03` | Third layer surface | | `bx--box-fill-field` | Form field background | | `bx--box-fill-inverse` | Inverse surface background | | `bx--box-border-subtle` | Subtle 1px border | | `bx--box-border-strong` | Strong 1px border | | `bx--box-border-interactive` | Interactive 1px border | | `bx--box-border-disabled` | Disabled 1px border | | `bx--box-p-{1-13}` | Padding on all sides | | `bx--box-px-{1-13}` | Horizontal padding | | `bx--box-py-{1-13}` | Vertical padding | | `bx--box-m-{1-13}` | Margin on all sides | | `bx--box-mx-{1-13}` | Horizontal margin | | `bx--box-my-{1-13}` | Vertical margin | | `bx--box-full-width` | Span the full container width | ```svelte
Styled with utility classes
``` --- ### Component API #### `Box` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `fill` | `"background" \| "layer-01" \| "layer-02" \| "layer-03" \| "field" \| "inverse"` | Set the background fill using a Carbon theme token. | _undefined_ | | `padding` | `SpacingValue \| undefined` | Set padding on all sides. Numbers `1`-`13` use the shared layout scale; strings accept any CSS length. | _undefined_ | | `paddingX` | `SpacingValue \| undefined` | Set horizontal padding. Numbers `1`-`13` use the shared layout scale; strings accept any CSS length. | _undefined_ | | `paddingY` | `SpacingValue \| undefined` | Set vertical padding. Numbers `1`-`13` use the shared layout scale; strings accept any CSS length. | _undefined_ | | `margin` | `SpacingValue \| undefined` | Set margin on all sides. Numbers `1`-`13` use the shared layout scale; strings accept any CSS length. | _undefined_ | | `marginX` | `SpacingValue \| undefined` | Set horizontal margin. Numbers `1`-`13` use the shared layout scale; strings accept any CSS length. | _undefined_ | | `marginY` | `SpacingValue \| undefined` | Set vertical margin. Numbers `1`-`13` use the shared layout scale; strings accept any CSS length. | _undefined_ | | `border` | `"subtle" \| "strong" \| "interactive" \| "disabled"` | Set the border using a Carbon border token. | _undefined_ | | `width` | `number \| string \| undefined` | Set the width. Numbers are treated as pixels; strings accept any CSS length. | _undefined_ | | `maxWidth` | `number \| string \| undefined` | Set the max width. Numbers are treated as pixels; strings accept any CSS length. | _undefined_ | | `minWidth` | `number \| string \| undefined` | Set the min width. Numbers are treated as pixels; strings accept any CSS length. | _undefined_ | | `fullWidth` | `boolean` | Set to `true` to span the full width of the container | `false` | | `tag` | `keyof HTMLElementTagNameMap` | Specify the tag name. | `"div"` | #### `Box` typedefs ```ts type SpacingScale = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13; type SpacingValue = SpacingScale | string; ``` #### `Box` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `Box` $$restProps `Box` spreads `$$restProps` to the `any` element. ## Breadcrumb ### Basic 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 item with `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 ``` ### Small Use `size="sm"` for a compact breadcrumb. This pairs with an overflow menu when space is tight. ```svelte Home API 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} ``` ### Custom link element Omit href and use `let:props` to render a custom link element (for example, a router link). Spread props onto the element to apply the Carbon link class and forward aria-current when isCurrentPage is set. ```svelte Dashboard Annual reports 2019 ``` ### Skeleton Display a loading state with `skeleton`. Use `count` to specify the number of items. ```svelte ``` #### Small Use `skeleton` with `size="sm"` for a compact loading state. ```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` | | `labelText` | `string` | Specify the ARIA label for the nav | `"Breadcrumb"` | | `size` | `"sm" \| "md"` | Specify the size of the breadcrumb. | `"md"` | #### `Breadcrumb` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `Breadcrumb` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `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:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `BreadcrumbItem` $$restProps `BreadcrumbItem` spreads `$$restProps` to the `li` element. #### `BreadcrumbSkeleton` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `noTrailingSlash` | `boolean` | Set to `true` to hide the breadcrumb trailing slash | `false` | | `count` | `number` | Specify the number of breadcrumb items to render | `3` | | `size` | `"sm" \| "md"` | Specify the size of the breadcrumb. | `"md"` | #### `BreadcrumbSkeleton` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `BreadcrumbSkeleton` $$restProps `BreadcrumbSkeleton` spreads `$$restProps` to the `div` element. ## Breakpoint ### Breakpoints The Carbon Design System [grid implementation](https://carbondesignsystem.com/guidelines/2x-grid/implementation#responsive-options) defines five responsive breakpoints. 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. | Breakpoint | Width range | | ----------- | ------------------- | | **Small** | Less than 672px | | **Medium** | 672px - 1056px | | **Large** | 1056px - 1312px | | **X-Large** | 1312px - 1584px | | **Max** | Greater than 1584px | ### Basic Bind to `size` to determine the current breakpoint. Possible values include `"sm"`, `"md"`, `"lg"`, `"xlg"`, and `"max"`. The on:change event fires when the size is initially determined and when a breakpoint change occurs (for example, when the browser 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 or 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}

``` ### use:hideAtBreakpoint Use the `hideAtBreakpoint` action to hide an element outside a breakpoint range, without wrapping it in `Breakpoint`. Set `above`, `below`, or both. Resize the browser to see the elements toggle. ```svelte
Hidden at md and up
Hidden below lg
``` --- ### 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 ### Kinds Set the `kind` prop to match the importance of the action. #### Primary The default button style is primary. Use it for the main action on a page. ```svelte ``` #### Secondary Set `kind="secondary"` for secondary actions. ```svelte ``` #### Tertiary Set `kind="tertiary"` for tertiary actions. ```svelte ``` #### Ghost Set `kind="ghost"` for ghost-style buttons. ```svelte ``` #### Danger Set `kind="danger"` for destructive actions. ```svelte ``` #### Danger tertiary Set `kind="danger-tertiary"` for less prominent destructive actions. ```svelte ``` #### Danger tertiary (icon-only) Create an icon-only danger tertiary button by omitting the label text and providing an icon description for accessibility. ```svelte ``` ### Icons Add an icon, or render an icon-only button with a tooltip. #### With icon Add an icon to the button using the `icon` prop. ```svelte ``` #### Icon-only Omit the label and provide an `iconDescription` for accessibility. This text is used as the button's tooltip and screen reader label. ```svelte ``` #### With icon Similarly, link buttons can have icons. ```svelte ``` ### Custom element By default, the button renders either a button or anchor element. To render a different element, set `as` to `true` and spread `let:props` to the element. ```svelte ``` ### Sizes Set the `size` prop. The default is medium. #### Field Set `size="field"` for field-sized buttons that align with form input heights. ```svelte ``` #### Small Set `size="small"` for small buttons. ```svelte ``` #### Large Set `size="lg"` for large buttons. ```svelte ``` #### Extra-large Set `size="xl"` for extra-large buttons. ```svelte ``` ### Disabled 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.
When the `badge` slot is used, size is set to `lg` per Carbon design guidelines. | `"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` | `Icon` | Specify the icon to render.
Alternatively, use the named slot "icon". | _undefined_ | | `iconDescription` | `string` | Specify the ARIA label for the button icon.
On an icon-only button, this also drives Carbon's tooltip. If omitted,
the icon-only button renders without a tooltip; supply your own
`aria-label` or `aria-labelledby` for accessibility in that case. | _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` | `number \| string \| undefined` | Specify the tabindex | `"0"` | | `type` | `string` | Specify the `type` attribute for the button element | `"button"` | | `portalTooltip` | `boolean \| undefined` | Set to `true` to render the icon-only tooltip in a portal,
preventing it from being clipped by `overflow: hidden` containers
and enabling auto-flipping when the preferred direction lacks space.
By default, the tooltip is portalled when inside a `Modal`. | _undefined_ | #### `Button` slots | Slot | Detail | | --- | --- | | `default` | `{
props: {
role: "button";
type?: string;
tabindex: any;
disabled: boolean;
href?: string;
class: string;
[key: string]: any;
};
}` | | `badge` | `Record` | | `icon` | `{
style: undefined \| string;
}` | #### `Button` forwarded events | Event | | --------------- | | `on:blur` | | `on:click` | | `on:focus` | | `on:mousedown` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `Button` $$restProps `Button` spreads `$$restProps` to the `button | a | div` element. #### `ButtonSkeleton` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `href` | `string` | Set the `href` to use an anchor link. | _undefined_ | | `size` | `"default" \| "field" \| "small" \| "lg" \| "xl"` | Specify the size of button skeleton. | `"default"` | #### `ButtonSkeleton` forwarded events | Event | | --------------- | | `on:blur` | | `on:click` | | `on:focus` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `ButtonSkeleton` $$restProps `ButtonSkeleton` spreads `$$restProps` to the `a` element. ## ButtonSet ### Basic Place buttons side by side in a horizontal layout. ```svelte ``` ### Stacked Stack buttons vertically with `stacked`. ```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 ### Basic 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 Hide the label visually by setting `hideLabel` to `true`. The label remains available to screen readers. ```svelte ``` ### Helper text Use `helperText` to provide additional context or instructions below the checkbox. ```svelte ``` ### States Reflect interaction states. #### Disabled Set `disabled` to `true` to prevent user interaction. ```svelte ``` #### Read-only 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 ``` #### Invalid Set `invalid` to `true` and provide `invalidText` to show a validation error. ```svelte ``` #### Warning Set `warn` to `true` and provide `warnText` to show a warning message. `invalid` takes precedence over `warn` when both are set. ```svelte ``` ### Reactive Bind to track and update the checkbox state. #### bind:checked Use two-way binding with `bind:checked` to track the checkbox state. ```svelte
checked: {checked}
``` #### 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 ``` #### Reactive Use two-way binding with `bind:selected` to track and update the selected values. ```svelte
selected: {JSON.stringify(selected)}
``` #### Hidden legend Hide the legend visually by setting `hideLegend` to `true`. The legend remains available to screen readers. ```svelte ``` #### Custom label Use the `legendChildren` slot to provide custom label content instead of `legendText`. ```svelte Notification preferences

You can change these settings at any time.

``` #### Helper text Use `helperText` to provide additional context below the checkbox group. ```svelte ``` #### Disabled Disable all checkboxes in the group. ```svelte ``` #### Read-only Set `readonly` to `true` on CheckboxGroup to display non-editable values. Unlike disabled, the readonly state keeps labels readable. You can also set readonly on individual checkboxes when needed. ```svelte ``` #### Invalid Set `invalid` to `true` and provide `invalidText` to show a validation error for the group. The group's state takes precedence over any invalid/warn state set on an individual checkbox. ```svelte ``` #### Warning Set `warn` to `true` and provide `warnText` to show a warning message for the group. ```svelte ``` --- ### Component API #### `Checkbox` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `checked` (Reactive) | `boolean` | Specify whether the checkbox is checked. | `false` | | `group` (Reactive) | `ReadonlyArray \| undefined` | Specify the bound group. | _undefined_ | | `indeterminate` (Reactive) | `boolean` | Specify whether the checkbox is indeterminate. | `false` | | `ref` (Reactive) | `null \| HTMLInputElement` | Obtain a reference to the input HTML element. | `null` | | `value` | `T` | 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 | `""` | | `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 | `""` | | `title` | `string` | Specify the title attribute for the label element. | _undefined_ | | `id` | `string` | Set an id for the input label | `uniqueId()` | | `tabindex` | `number \| string \| undefined` | Set the tabindex for the input element. | _undefined_ | | `decorative` | `boolean` | Set to `true` to hide the input from the accessibility tree via CSS
(not just tabindex/aria-hidden, which axe-core's nested-interactive
check does not treat as sufficient). Use when this Checkbox is
nested inside another interactive/widget-role element that already
owns the checked-state semantics (e.g. a listbox option) and the
checkbox itself is purely decorative. | `false` | #### `Checkbox` slots | Slot | Detail | | --------------- | ----------------------- | | `labelChildren` | `Record` | #### `Checkbox` forwarded events | Event | | --------------- | | `on:blur` | | `on:change` | | `on:click` | | `on:focus` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `Checkbox` dispatched events | Event | Detail | | ---------- | --------- | | `on:check` | `boolean` | #### `Checkbox` $$restProps `Checkbox` spreads `$$restProps` to the `div` element. #### `CheckboxGroup` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `selected` (Reactive) | `ReadonlyArray` | Set the selected checkbox values. | `[]` | | `disabled` | `boolean` | Set to `true` to disable all checkboxes | `false` | | `required` | `boolean` | Set to `true` to require at least one selection. | _undefined_ | | `name` | `string` | Specify a name attribute for the checkbox inputs. | _undefined_ | | `legendText` | `string` | Specify the legend text.
Alternatively, use the named slot "legendChildren". | `""` | | `hideLegend` | `boolean` | Set to `true` to visually hide the legend | `false` | | `helperText` | `string` | Specify the helper 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 | `""` | | `readonly` | `boolean` | Set to `true` to use the read-only variant | `false` | | `id` | `string` | Set an id for the container div element. | _undefined_ | #### `CheckboxGroup` slots | Slot | Detail | | ---------------- | ----------------------- | | `default` | `Record` | | `legendChildren` | `Record` | #### `CheckboxGroup` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `CheckboxGroup` dispatched events | Event | Detail | | ----------- | ----------------------------------------------- | | `on:change` | `ReadonlyArray<
string \| number
>` | #### `CheckboxGroup` $$restProps `CheckboxGroup` spreads `$$restProps` to the `div` element. #### `CheckboxSkeleton` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `CheckboxSkeleton` $$restProps `CheckboxSkeleton` spreads `$$restProps` to the `div` element. ## ClickableTile ### Basic Create a clickable tile with an href to link to another page. ```svelte Carbon Design System ``` ### Reactive example Bind to `clicked` to read whether the tile has been activated. ```svelte
Clicked: {clicked}
Click this tile
``` ### Prevent default Handle the `click` event to override default link behavior. Call `e.preventDefault()` to stop navigation. ```svelte { e.preventDefault(); // custom behavior }} > Carbon Design System ``` ### Light Use the light color scheme with `light`. ```svelte Carbon Design System ``` ### Disabled Prevent interaction with `disabled`. ```svelte Carbon Design System ``` --- ### Component API #### `ClickableTile` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `clicked` (Reactive) | `boolean` | Whether the tile has been clicked.
Toggles on click and on Space/Enter. | `false` | | `ref` (Reactive) | | Obtain a reference to the underlying anchor HTML element. | `null` | | `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:blur` | | `on:click` | | `on:focus` | | `on:keydown` | | `on:keyup` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `ClickableTile` $$restProps `ClickableTile` spreads `$$restProps` to the `a | p` element. ## CodeSnippet ### Basic Display a single-line code snippet by default. By default, the copy button uses the native [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText) to copy text, with a `document.execCommand("copy")` fallback when that API is unavailable or rejects (for example in an insecure context). Pass a function to `copy` to replace it. See [Override](#override). ```svelte ``` ### Async copy Pass an async function to `copy` when clipboard text is not ready at render time, such as a longer install command fetched on click. The copy feedback text appears after `copy()` resolves. During the request, the copy control sets `aria-busy="true"` and ignores further clicks. A rejected copy shows `errorFeedback` (default `"Failed to copy"`) in the same tooltip slot as the success message and emits `copy:error`. Prefetch on hover with `on:mouseenter:copy-button` on the copy control. The example below shows async copy for each variant (`single`, `inline`, `multi`). ```svelte
{ console.error("copy:error", e.detail.error); }} />
{ console.error("copy:error", e.detail.error); }} /> { console.error("copy:error", e.detail.error); }} />
``` ### Copy behavior Replace or disable the default clipboard behavior. #### Override Pass a custom function to `copy` to override the default copy behavior. This example uses [clipboard-copy](https://github.com/feross/clipboard-copy) to copy the text instead of the default Clipboard API. ```svelte copy(text)} /> ``` #### Prevent Pass a no-op function to `copy` to disable copying. ```svelte {}} /> ## Inline Set `type="inline"` to display code inline with text. ## Multi-line Set `type="multi"` to display multiple lines of code with expand/collapse functionality. ``` ```svelte ``` #### Overflow detection The "Show more"/"Show less" button only appears when the multi-line snippet content exceeds the collapsed height. Because the visibility is based on the snippet's measured height, it adapts to the consumer's font size and line height, and updates automatically if the content or layout changes. Toggle the example below to grow the content past the threshold and reveal the expand button. ```svelte ``` #### Collapsed row count Set `maxCollapsedNumberOfRows` to shorten the collapsed preview. Each row is 16px tall; the default is `15` (240px). Use `minCollapsedNumberOfRows`, `minExpandedNumberOfRows`, and `maxExpandedNumberOfRows` for the matching minimum and expanded limits. ```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 feedback Customize the message and icon shown after copying. #### Text Set `feedback` to customize the copy button feedback text. Set `errorFeedback` to customize the message shown when copying fails (default `"Failed to copy"`). ```svelte ``` #### Icon Set `feedbackIcon` to swap the copy button icon during the feedback window. Applies to `"single"` and `"multi"` types; has no effect on `"inline"`. ```svelte ``` ### Hidden buttons Hide the copy or show-more controls. #### Copy Set `hideCopyButton` to `true` to hide the copy button. ```svelte ``` #### Show more Set `showMoreLess` to `false` to hide the expand/collapse button on multi-line snippets. Overflowing content scrolls inside the collapsed container instead of being clipped with no way to reach the rest. ```svelte ``` #### Copy and show more 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 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 ``` ### Syntax highlighting CodeSnippet does not ship a syntax highlighter. Pass the plain source to `code` so copy uses unstyled text, and render highlighted HTML from Prism, Shiki, or another highlighter in the default slot with `{@html}`. Load language grammars and token theme CSS in your app. ```svelte {@html highlighted} ``` ### Dynamic multi-line code Use `code` 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}
``` ### Tooltip position Set `tooltipPosition` to place the feedback tooltip relative to the copy button. It applies to every variant, including the inline snippet. ```svelte ``` ### Tooltip alignment Set `tooltipAlignment` to align the feedback tooltip relative to the copy button. ```svelte ``` ### Portal tooltip The "Copied!" feedback tooltip is rendered in a floating portal by default, so it is never clipped by a parent container with hidden overflow or a z-index stacking context. Set `portalTooltip` to `false` to use Carbon's inline feedback caret instead. The example renders each variant inside a container with hidden overflow. ```svelte
``` ### Inside a modal Because the feedback tooltip is portalled by default, it is not clipped inside a [Modal](/components/Modal). Set `portalTooltip` to `false` to use the inline caret. ```svelte (open = false)} > ``` ### Skeleton Set `skeleton` to `true` to show a loading state. Defaults to `"single"` type. ```svelte ``` #### 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` | | `ref` (Reactive) | `null \| HTMLPreElement` | Obtain a reference to the pre HTML element. | `null` | | `copyRef` (Reactive) | `null \| HTMLButtonElement` | Obtain a reference to the underlying copy button 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 \| Promise` | By default, this component uses `navigator.clipboard.writeText` API to copy text to the user's clipboard,
with a `document.execCommand("copy")` fallback. Failures reject so the component can show
`errorFeedback` and dispatch `copy:error`.

Provide a custom function to override this behavior. | `copyText` | | `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. | `"Copy code"` | | `codeLabel` | `string` | Specify the ARIA label of the code snippet container (single/multi variants). | `"Code snippet"` | | `feedback` | `string` | Specify the feedback text displayed when clicking the snippet | `"Copied!"` | | `errorFeedback` | `string` | Specify the feedback text displayed when copying fails | `"Failed to copy"` | | `feedbackTimeout` | `number` | Set the timeout duration (ms) to display feedback text | `2000` | | `feedbackIcon` | `Icon` | Specify an icon to render on the copy button during the feedback window
(e.g. after copying). When unset, the copy icon is always shown.

NOTE: this prop does not apply to the `type="inline"` variant. | _undefined_ | | `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"` | | `showMoreLess` | `boolean` | Set to `false` to hide the show more/less button.

When hidden, overflowing multi-line content scrolls inside the
collapsed container instead of being clipped with no affordance.

NOTE: this prop only works with the `type="multi"` variant. | `true` | | `maxCollapsedNumberOfRows` | `number` | Specify the maximum number of rows shown when collapsed.
Set to `0` for no maximum.

NOTE: this prop only works with the `type="multi"` variant.
Row height is 16px. | `15` | | `maxExpandedNumberOfRows` | `number` | Specify the maximum number of rows shown when expanded.
Set to `0` for no maximum (default).

NOTE: this prop only works with the `type="multi"` variant.
Row height is 16px. | `0` | | `minCollapsedNumberOfRows` | `number` | Specify the minimum number of rows shown when collapsed.
Set to `0` for no minimum.

NOTE: this prop only works with the `type="multi"` variant.
Row height is 16px. | `3` | | `minExpandedNumberOfRows` | `number` | Specify the minimum number of rows shown when expanded.
Set to `0` for no minimum.

NOTE: this prop only works with the `type="multi"` variant.
Row height is 16px. | `16` | | `id` | `string` | Set an id for the code element | `uniqueId()` | | `portalTooltip` | `boolean \| undefined` | Set how the "Copied!" feedback tooltip is rendered.
By default, it is rendered in a portal so it is never clipped by an
`overflow: hidden` container. Set to `false` to use Carbon's inline
feedback caret instead. | _undefined_ | | `tooltipPosition` | `"top" \| "right" \| "bottom" \| "left"` | Set the position of the feedback tooltip relative to the copy button. | `"bottom"` | | `tooltipAlignment` | `"start" \| "center" \| "end"` | Set the alignment of the feedback tooltip relative to the copy button. | `"center"` | #### `CodeSnippet` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `CodeSnippet` forwarded events | Event | | ----------------- | | `on:animationend` | | `on:click` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `CodeSnippet` dispatched events | Event | Detail | | --------------------------- | -------------------- | | `on:collapse` | `null` | | `on:copy` | `null` | | `on:copy:error` | `{ error: unknown }` | | `on:expand` | `null` | | `on:mouseenter:copy-button` | `MouseEvent` | | `on:mouseleave:copy-button` | `MouseEvent` | #### `CodeSnippet` $$restProps `CodeSnippet` spreads `$$restProps` to the `button | span` element. #### `CodeSnippetSkeleton` props | Prop | Type | Description | Default | | ------ | --------------------- | ----------------------------- | ---------- | | `type` | `"single" \| "multi"` | Set the type of code snippet. | `"single"` | #### `CodeSnippetSkeleton` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `CodeSnippetSkeleton` $$restProps `CodeSnippetSkeleton` spreads `$$restProps` to the `div` element. ## ComboBox ### Basic Create a combobox with a title and placeholder text. Each item needs a unique id and display text. Combo boxes key items by id for performance. ```svelte ``` ### Reactive See how the combobox responds to user input and selection changes. ```svelte
``` ### Content Customize how items render and how the label and helper text appear. #### Custom slot Override the default slot to customize how each item displays. Use `let:item`, `let:index`, `let:selected`, and `let:highlighted` to style highlighted and selected rows. ```svelte
{item.text}
id: {item.id} - index: {index} - selected: {selected} - highlighted: {highlighted}
``` #### Item icons Set icon on an item for a left icon. The label sits between the icon and the checkmark. Use the icon slot for custom markup. ```svelte ``` Use the `iconRight` slot to replace the checkmark. ```svelte {#if selected}{:else}{/if} ``` #### Hidden label Hide the label visually by setting `hideLabel` to `true`. The label remains available to screen readers. ```svelte ``` #### Helper text Add descriptive text below the combobox with `helperText`. ```svelte ``` ### Selection Pre-select items, clear the current selection, and coordinate multiple combo boxes. #### Initial selection Set `selectedId` to pre-select an item when the combobox loads. ```svelte ``` #### Clear selection Use `bind:this` to access the component instance and call `ComboBox.clear()` to clear the selection. Pass `focus: false` in the options to prevent re-focusing the input. ```svelte
``` #### Open on clear By default, the dropdown menu is closed after clearing the selection. Set `openOnClear` to `true` to reopen the dropdown menu after clearing the selection. This lets users immediately browse all available items without needing to click the input again. ```svelte ``` #### Multiple combo boxes See how to manage multiple comboboxes in a form. ```svelte
Primary: {primary}
Secondary: {secondary}
``` ### Auto-highlight By default, no item is automatically highlighted when typing. Set `autoHighlight` to `"first-match"` to highlight the first matching item as you type. #### First match Set `autoHighlight` to `"first-match"` to automatically highlight the first matching item as you type. Select it by pressing Enter without using arrow keys. The default filter is case-insensitive substring matching (for example, "app" matches "Apple"). ```svelte ``` #### Case-sensitive filter Use `autoHighlight="first-match"` with a custom `shouldFilterItem` to control which items appear. The auto-highlight respects the custom filter; only items that pass the filter are considered for highlighting. In this example, the filter is case-sensitive. ```svelte item.text.startsWith(value)} labelText="Item" placeholder="Select an item" items={[ { id: "0", text: "Apple" }, { id: "1", text: "Apricot" }, { id: "2", text: "Banana" }, { id: "3", text: "Blueberry" }, { id: "4", text: "Blackberry" }, { id: "5", text: "Cherry" }, { id: "6", text: "Cranberry" }, { id: "7", text: "Grape" }, { id: "8", text: "Mango" }, { id: "9", text: "Pineapple" }, ]} /> ``` #### With typeahead Combine `typeahead` and `autoHighlight="first-match"` for the full autocomplete experience: the input text is completed and the matching item is visually highlighted. ```svelte ``` ### Typeahead Set `typeahead` to `true` to enable autocomplete. As users type, the input suggests and completes matching items. By default, typeahead uses case-insensitive prefix matching. When a match is found, the suggestion shows the untyped portion highlighted so users can accept it or keep typing. Pressing Enter or Tab accepts the suggestion: it selects the matching item, normalizes the value to the item's casing, and closes the dropdown. Tab still moves focus to the next control. Clicking away accepts the suggestion the same way. When the typed text matches no item, the suggestion is not committed. Pressing or End accepts the inline suggestion in place: it commits the completed text into the value (keeping your casing) and collapses the cursor to the end, but keeps focus in the input and leaves the dropdown open so you can continue editing. Unlike Enter and Tab, it does not select an item or close the menu. You can provide a custom `shouldFilterItem` to change the filtering logic. See the [fuzzy filter](#fuzzy-filter) example below. ```svelte
``` #### Fuzzy filter Provide a custom `shouldFilterItem` to override the default prefix matching used by typeahead. This example reuses the built-in `fuzzyMatch` utility, exported from `carbon-components-svelte`, as the predicate. It matches items whose text contains the typed characters in order (for example, "bl" matches "Blueberry" and "Blackberry"). Only the `matched` boolean is used here; the `score` and `indices` it also returns rank and highlight matches, as shown in [Highlight matches](#highlight-matches) below. Inline completion only fills in the input when the top match starts with the typed text, so a fuzzy match like "api" against "Apricot" filters the list without completing the input. Pair the custom filter with `autoHighlight="first-match"` so the matched item is highlighted and Enter or Tab selects it. ```svelte ``` #### Highlight matches Besides `matched`, `fuzzyMatch` returns the `indices` of the characters that matched. Pass them to the `highlightSegments` utility (also exported from `carbon-components-svelte`) to split the item text into matched and unmatched runs, then bold the matched runs in the default slot. Bind `value` to read the typed query inside the slot. ```svelte {#each highlightSegments(item.text, fuzzyMatch(item.text, value).indices) as segment} {#if segment.match} {segment.text} {:else} {segment.text} {/if} {/each} ``` ### Filtering By default, combobox filtering is synchronous and client-side. Customize the filter logic, label rendering, and when results reset. #### Filterable Enable filtering to let users search through the options. ```svelte ``` #### Filter mode By default (`filterMode="remove"`), filtering unmounts non-matching options and recreates them when they match again. Set `filterMode` to `"hide"` to keep every option mounted and hide non-matching ones with the `hidden` attribute. Keyboard navigation, `aria-setsize`, and `aria-posinset` still follow the matching items only. `"hide"` falls back to `"remove"` when virtualization is enabled. For typical ComboBox lists, `"remove"` is faster per keystroke because it only updates matching option nodes. #### Custom label Set `itemToString` to customize how items display in the filterable combobox. ```svelte ``` #### Clear filter on open After selecting an item in a filterable combobox, reopening the dropdown normally shows only the results matching that selection. Set `clearFilterOnOpen` to `true` to clear the filter on open, showing all items so you can browse and change the selection. The original value is automatically restored if you close the dropdown without making a new selection. ```svelte ``` #### Async For async (for example, server-side) filtering, bind to `value` and update `items` when input changes. This example simulates async behavior with a debounced input value change. ```svelte ``` #### Load more `scrollend` fires when the menu is scrolled near the bottom. Use it to append the next page of `items`. The component does not fetch or mutate `items` for you. This is a library load-more signal, named like Modal's lowercase `transitionend`. It is not the browser's native `scrollend` (scroll stopped). Keep prior items visible while the next page loads. Track in-flight status in local state, or surface it with the `empty` slot when the list is temporarily empty. `scrollend` fires once per approach to the bottom. It re-arms after the user scrolls away, and when `items` grows so another page can be requested. Holding the scrollbar at the bottom does not spam the handler. The raw DOM `scroll` event is still forwarded via `on:scroll`. ```svelte true} virtualize={{ containerHeight: 240, threshold: 1 }} on:scrollend={loadMore} /> {#if loading} {:else if !hasMore}

Loaded all {TOTAL} items.

{:else}

{items.length} of {TOTAL} loaded. Scroll the menu to fetch the next page.

{/if}
``` #### Allow custom value Set `allowCustomValue` to `true` to let users enter custom text that is not in the predefined list. By default, user-entered text is cleared when the combobox loses focus without selecting an item. With allowCustomValue 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"}
``` #### Select text on focus Set `selectTextOnFocus` to `true` to select all text in the input when it receives focus (for example, on tab or click). Users can replace the value by typing without manually selecting first. An alternative is [clear filter on open](#clear-filter-on-open), which clears the filter when opening so all options are visible. ```svelte ``` ### Virtualization Virtualization renders only the items currently visible in the viewport, improving performance for large lists. By default, the combo box virtualizes lists with more than 100 items. #### Large lists 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 the [custom threshold](#custom-threshold) example below. ```svelte item.text.toLowerCase().includes(value.toLowerCase())} bind:selectedId bind:value />
Selected: {selectedItem?.text}
``` #### 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 render above and below the viewport for smoother scrolling. 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 /> ``` #### 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 render normally without virtualization. ```svelte item.text.toLowerCase().includes(value.toLowerCase())} bind:selectedId bind:value /> ``` #### Custom item height By default, item height matches the menu row for each size: 24px (`xs`), 32px (`sm`), 40px (`md`), 48px (`lg`, `xl`). Set `itemHeight` when custom slots change row height. ```svelte item.text.toLowerCase().includes(value.toLowerCase())} bind:selectedId bind:value let:item > {item.text} {item.description} ``` ### Top direction Set `direction` to `"top"` to make the dropdown menu appear above the input. ```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. Without `portalMenu`, the dropdown in the example below would be clipped by its container's hidden overflow. 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.
``` ### Light Set `light` to `true` to use the light color scheme. ```svelte ``` ### Sizes The `size` prop sets the height. The default is `medium`. #### Extra-small Set `size` to `"xs"` for an extra-small combobox. ```svelte ``` #### Small Set `size` to `"sm"` for a small combobox. ```svelte ``` #### Extra-large Set `size` to `"xl"` for an extra-large combobox. ```svelte ``` ### States Surface validation, warning, disabled, and read-only states. #### Invalid Set `invalid` to `true` and provide `invalidText` to show an error message. ```svelte ``` #### Warning Set `warn` to `true` and provide `warnText` to show a warning message. ```svelte ``` #### Disabled Set `disabled` to `true` to prevent interaction with the combobox. ```svelte ``` #### Disabled items Mark individual items with `disabled: true` to disable specific options. ```svelte ``` #### Read-only Set `readonly` to `true` to display a non-editable value. ```svelte ``` ### Fluid Set `fluid` to `true` to use the fluid variant, which embeds the label inside the field. Fluid combo boxes can be used standalone or inside [FluidForm](/components/FluidForm), where the fluid variant is applied automatically. ```svelte ``` #### Custom label Use the `labelChildren` slot to render custom label content, such as a tooltip icon. ```svelte Contact ``` #### Condensed By default, the fluid variant renders taller menu items to match the taller field. Set `condensed` to `true` to render menu items at their default height instead. ```svelte ``` #### Invalid Fluid combo boxes display the error message inside the field boundary. Long messages wrap to multiple lines. ```svelte ``` #### Warning ```svelte ``` #### Disabled Invalid and warning states are not displayed while the combo box is disabled. ```svelte ``` #### Read-only Invalid and warning states are not displayed while the combo box is read-only. ```svelte ``` #### Skeleton Display a loading skeleton for the fluid combo box variant. ```svelte ``` ### Form name Set `name` so the combo box participates in native form submission (for example SvelteKit form actions and `FormData`). Unlike [Dropdown](/components/Dropdown#form-name), `name` lands directly on the always-mounted text input, so it submits the displayed text (`value`), not `selectedId`, empty string when nothing is selected. ```svelte
``` --- ### 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. | `(item) => item.text ?? item.id` | | `direction` | `"bottom" \| "top"` | Specify the direction of the combobox dropdown menu. | `"bottom"` | | `size` | `"xs" \| "sm" \| "lg" \| "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` | | `readonly` | `boolean` | Set to `true` to use the read-only variant | `false` | | `fluid` | `boolean` | Set to `true` to use the fluid variant.
Inherited from the parent `FluidForm` context,
so it does not need to be set when used inside `FluidForm`. | `false` | | `condensed` | `boolean` | Set to `true` to render condensed menu items in the fluid variant.
Menu items use the default height instead of the taller fluid height.
Only applies when the fluid variant is active. | `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` | | `selectTextOnFocus` | `boolean` | Set to `true` to select all text in the input when it receives focus (e.g. on tab or click). | `false` | | `openOnClear` | `boolean` | Set to `true` to reopen the dropdown menu after clearing the selection.
This allows users to immediately see all available items after clearing. | `false` | | `typeahead` | `boolean` | Set to `true` to enable autocomplete with typeahead | `false` | | `autoHighlight` | `"none" \| "first-match"` | Control whether the first matching item is automatically highlighted as the user types.
- `"none"`: No auto-highlighting (default). The user must use arrow keys or hover to highlight items.
- `"first-match"`: Automatically highlight the first non-disabled filtered item on each input change. | `"none"` | | `shouldFilterItem` | `(item: Item, value: string) => boolean` | Determine if an item should be filtered given the current combobox value.
When `typeahead` is enabled and no custom function is provided,
the default case-insensitive prefix matching is used.
When a custom function is provided, it is used even with `typeahead`. | `() => true` | | `filterMode` | `"remove" \| "hide"` | Set the filtering strategy used while the menu is open.
- `"remove"`: unmount non-matching options and recreate them when they
match again.
- `"hide"`: keep all options mounted and hide non-matching ones with the
`hidden` attribute.

`"hide"` falls back to `"remove"` when virtualization is enabled. | `"remove"` | | `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 | `uniqueId()` | | `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: size-based, or 64px for fluid unless `condensed`): Height of each item in pixels. Override when custom slots change row height.
- `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; open?: boolean; }) => Promise` | Clear the combo box programmatically.
By default, focuses the combo box after clearing. Set `options.focus` to `false` to prevent focusing.
Set `options.open` to `true` to keep the dropdown open after clearing. | _undefined_ | #### `ComboBox` typedefs ```ts type ComboBoxItem = { id: Id; text: string; /** Whether the item is disabled */ disabled?: boolean; /** Icon component shown left of the item text */ icon?: any; }; ``` #### `ComboBox` slots | Slot | Detail | | --- | --- | | `default` | `{
item: Item;
index: number;
selected: boolean;
highlighted: boolean;
}` | | `icon` | `{
item: Item;
index: number;
selected: boolean;
highlighted: boolean;
}` | | `iconRight` | `{
item: Item;
index: number;
selected: boolean;
highlighted: boolean;
}` | | `labelChildren` | `Record` | #### `ComboBox` forwarded events | Event | | ------------ | | `on:blur` | | `on:clear` | | `on:focus` | | `on:input` | | `on:keydown` | | `on:keyup` | | `on:paste` | | `on:scroll` | #### `ComboBox` dispatched events | Event | Detail | Description | | --- | --- | --- | | `on:close` | `{
trigger:
\| "escape-key"
\| "outside-click"
\| "select";
}` | | | `on:scrollend` | `{
scrollTop: number;
scrollHeight: number;
clientHeight: number;
}` | Dispatched when the menu is scrolled near the bottom (load-more signal).
Not the browser's native `scrollend` (scroll stopped). | | `on:select` | `{
selectedId: Item["id"];
selectedItem: Item;
}` | | #### `ComboBox` $$restProps `ComboBox` spreads `$$restProps` to the `input` element. #### `FluidComboBoxSkeleton` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `FluidComboBoxSkeleton` $$restProps `FluidComboBoxSkeleton` spreads `$$restProps` to the `div` element. ## ComboButton ### Basic Wrap `MenuItem` components in `ComboButton` and set `labelText` for the primary action button. Use the `labelChildren` slot for custom button content. Clicking the label fires `on:click`; clicking the chevron trigger opens the menu and fires the separate `on:click:trigger` event. The trigger's other native events (`mousedown`, `focus`, `blur`, `mouseover`, `mouseenter`, `mouseleave`) dispatch the same way, each with a `:trigger`-suffixed counterpart alongside the shared, unscoped event. ```svelte console.log("Save as")}>Save as console.log("Save a copy")}>Save a copy console.log("Save and close")} >Save and close ``` ### Icon description The icon-only trigger needs its own accessible label, since it has no visible text. Override `iconDescription` to change it; the default is `"Additional actions"`. ```svelte console.log("Save as")}>Save as console.log("Save a copy")}>Save a copy ``` #### Tooltip position Set `tooltipPosition` to control where the trigger's tooltip appears. This is independent of `direction`, which controls where the menu opens - the two are separate concerns and can point different ways. ```svelte console.log("Save as")}>Save as console.log("Save a copy")}>Save a copy ``` #### No tooltip Set `iconDescription` to an empty string to render the trigger without Carbon's tooltip, the same way [Button](/components/Button#icons) handles an empty `iconDescription`. The trigger then has no accessible name of its own, so only do this when something else in the surrounding context labels it. ```svelte console.log("Save as")}>Save as console.log("Save a copy")}>Save a copy ``` ### Size Set `size` to scale both buttons and each menu item's row height together. The default is `"md"`. `ComboButton` only supports the `"primary"` kind, matching Carbon React. #### Extra small ```svelte console.log("Save as")}>Save as console.log("Save a copy")}>Save a copy ``` #### Small ```svelte console.log("Save as")}>Save as console.log("Save a copy")}>Save a copy ``` #### Large ```svelte console.log("Save as")}>Save as console.log("Save a copy")}>Save a copy ``` ### Direction Set `direction` to `"top"` or `"bottom"` (default) for which side of the trigger the menu opens on. The menu flips to the opposite side when there isn't room on the preferred side. See [Menu placement](/components/Menu#placement) for gap and offset props. #### Top ```svelte console.log("Save as")}>Save as console.log("Save a copy")}>Save a copy ``` #### Alignment Set `intrinsicAlign` to `"start"`, `"center"`, or `"end"` (default) to align the menu edge with the trigger. ```svelte console.log("Save as")}>Save as console.log("Save a copy")}>Save a copy ``` ### Disabled Set `disabled` to `true` to disable both the primary action and trigger buttons. ```svelte console.log("Save as")}>Save as ``` ### Menu items `MenuItem` takes `disabled`, an `icon`, `kind="danger"` for destructive rows, and nested children for submenus. Use `MenuDivider` between groups. See [MenuButton](/components/MenuButton#menu-items) for the full set of examples and keyboard/hover behavior for submenus. #### Disabled Set `disabled` on a `MenuItem` to make it non-interactive. ```svelte console.log("Save as")}>Save as console.log("Save a copy")} >Save a copy ``` #### Icons Pass a Carbon icon to `icon`. ```svelte console.log("Save a copy")} >Save a copy console.log("Save as")}>Save as ``` #### Danger Set `kind="danger"` on `MenuItem` for a destructive action. ```svelte console.log("Save as")}>Save as console.log("Save a copy")}>Save a copy console.log("Delete draft")} > Delete draft ``` #### Nested Set `labelText` on a `MenuItem` and nest child `MenuItem` rows to get a submenu. ```svelte console.log("Save as")}>Save as console.log("PDF")}>PDF console.log("JPG")}>JPG console.log("PNG")}>PNG ``` --- ### Component API #### `ComboButton` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `labelText` (Required) | `string` | Required. Specify the primary action button text.
Alternatively, use the "labelChildren" slot for custom button content;
`labelText` is still used as the accessible name in that case. | _undefined_ | | `open` (Reactive) | `boolean` | Set to `true` to open the menu. | `false` | | `ref` (Reactive) | `null \| HTMLDivElement` | Obtain a reference to the outer HTML element. | `null` | | `disabled` | `boolean` | Set to `true` to disable both the primary action and trigger buttons. | `false` | | `size` | `"xs" \| "sm" \| "md" \| "lg"` | Specify the size of both buttons and the menu row height. | `"md"` | | `direction` | `"top" \| "bottom"` | Set the preferred direction the menu opens toward.
The menu flips to the opposite direction if there is not enough space. | `"bottom"` | | `intrinsicAlign` | `"start" \| "center" \| "end"` | Align the menu to the trigger button's intrinsic width. | `"end"` | | `iconDescription` | `string` | Specify the accessible label for the icon-only trigger button.
Set to an empty string to render the trigger without a tooltip, the
same way `Button` handles an empty `iconDescription` - the trigger then
has no accessible name of its own, so only do this when something else
in the surrounding context labels it. | `"Additional actions"` | | `tooltipPosition` | `"top" \| "right" \| "bottom" \| "left"` | Set the position of the icon-only trigger's tooltip.
Independent of `direction`, which controls where the menu opens. | `"bottom"` | #### `ComboButton` slots | Slot | Detail | | --------------- | ----------------------- | | `default` | `Record` | | `labelChildren` | `Record` | #### `ComboButton` forwarded events | Event | | --------------- | | `on:blur` | | `on:click` | | `on:close` | | `on:focus` | | `on:mousedown` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `ComboButton` dispatched events | Event | Detail | Description | | --- | --- | --- | | `on:blur:trigger` | `FocusEvent` | | | `on:click:trigger` | `MouseEvent` | Fires when the menu trigger button is clicked, separate from the primary action's `click` event. | | `on:focus:trigger` | `FocusEvent` | | | `on:mousedown:trigger` | `MouseEvent` | | | `on:mouseenter:trigger` | `MouseEvent` | | | `on:mouseleave:trigger` | `MouseEvent` | | | `on:mouseover:trigger` | `MouseEvent` | | #### `ComboButton` $$restProps `ComboButton` spreads `$$restProps` to the `div` element. #### `MenuItem` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `selected` (Reactive) | `boolean` | Set to `true` to select the item.
Only applies to a selectable item or one inside
`MenuItemGroup` or `MenuItemRadioGroup`. | `false` | | `ref` (Reactive) | `null \| HTMLLIElement` | Obtain a reference to the list item HTML element. | `null` | | `kind` | `"default" \| "danger"` | Specify the kind of item. | `"default"` | | `disabled` | `boolean` | Set to `true` to disable the item | `false` | | `icon` | `Icon` | Specify the icon to render.
Icon is rendered to the left of the label text. | _undefined_ | | `labelText` | `string \| undefined` | Specify the label text.
Required to nest `MenuItem` children and create a submenu: once set,
the default slot holds the nested items instead of the label.
Alternatively, use the "labelChildren" slot for custom label content;
`labelText` is still used as the accessible name and title in that case. | _undefined_ | | `shortcutText` | `string` | Specify the shortcut text.
Alternatively, use the "shortcutText" slot.
Display only; does not register a keybinding. | `""` | | `selectable` | `boolean` | Set to `true` to make the item a standalone checkbox.
Automatically enabled when `selected` is `true` or when the item
is inside `MenuItemGroup`. | `false` | | `id` | `string` | Specify the id.
It's recommended to provide an id as a value to bind to
within a selectable or radio menu group. | `uniqueId()` | #### `MenuItem` slots | Slot | Detail | | --------------- | ----------------------- | | `default` | `Record` | | `labelChildren` | `Record` | | `shortcutText` | `Record` | #### `MenuItem` forwarded events | Event | | ------------ | | `on:keydown` | #### `MenuItem` dispatched events | Event | Detail | Description | | --- | --- | --- | | `on:click` | `MouseEvent` | Dispatched on selection. Cancelable: call `preventDefault()` to keep
the menu open. A selectable or radio item's selection still updates. | #### `MenuItem` $$restProps `MenuItem` spreads `$$restProps` to the `li` element. ## ComposedModal ### 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). ### Basic Create a modal with a header, body, and footer. Each section can be customized independently. ```svelte ``` ### Full width Remove modal body padding so content spans edge to edge with `fullWidth`. Use it for content that supplies its own layout, such as a table or fluid form. ```svelte (open = false)} /> ``` ### 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. Call `e.preventDefault()` to keep the modal open. The event includes a trigger property indicating what triggered the close attempt: `"escape-key"` (Escape), `"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; }} />
``` ### Hide close button Set `hideCloseButton` on `ModalHeader` to remove the header close button. Use this for forced-choice dialogs such as auth walls or terms acceptance. Always provide an alternative dismiss path -- typically footer actions -- and pair with `preventCloseOnClickOutside` when outside clicks should not dismiss the dialog. Escape still closes the modal unless you cancel the `close` event. ```svelte (open = false)} >

You must accept or decline the terms. The header close button is hidden, so use the footer actions to leave this dialog.

(open = false)} />
``` ### Prevent secondary button close `secondaryButtonText` closes the modal by default. The footer dispatches a cancelable `click:button--secondary` event first. Call `e.preventDefault()` to keep the modal open -- for example when Cancel should stay put for a dirty form. ```svelte { name = draft; open = false; }} > {#if showWarning} {/if} { if (isDirty) { e.preventDefault(); showWarning = true; } }} /> ``` ### Danger Display critical or destructive actions 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 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 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"); }} /> ``` ### Primary button loading Set `primaryButtonLoading` on `ModalFooter` while an async submit is in progress. The primary button shows an [InlineLoading](/components/InlineLoading) spinner, becomes non-interactive, and suppresses `submit` until loading finishes. The modal stays open. ```svelte

Save your changes to the Cloudant database configuration.

``` --- ### 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` | | `fullWidth` | `boolean` | Set to `true` to remove the modal body padding so content spans edge to edge | `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:click` | | `on:keydown` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `ComposedModal` dispatched events | Event | Detail | | --- | --- | | `on:click:button--primary` | `null` | | `on:close` | `{
trigger:
\| "escape-key"
\| "outside-click"
\| "close-button"
\| "programmatic";
}` | | `on:open` | `null` | | `on:submit` | `null` | | `on:transitionend` | `{
open: boolean;
}` | #### `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"` | | `hideCloseButton` | `boolean` | Set to `true` to hide the header close button.
Provide an alternative dismiss path (footer actions or Escape). | `false` | #### `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` | `Icon` | Specify the primary button icon. | _undefined_ | | `primaryButtonDisabled` | `boolean` | Set to `true` to disable the primary button | `false` | | `primaryButtonLoading` | `boolean` | Set to `true` to show a loading state on the primary button.
While loading, the button is non-interactive and submit is suppressed. | `false` | | `primaryButtonLoadingDescription` | `string` | Specify the description for the primary button loading state.
Passed to `InlineLoading` as `description`. | `"Loading"` | | `primaryClass` | `string` | Specify a class for the primary button. | _undefined_ | | `secondaryButtonText` | `string` | Specify the secondary button text | `""` | | `secondaryButtons` | `ReadonlyArray<{ text: string; kind?: string; disabled?: boolean }>` | One or two secondary buttons for the modal footer.
Supersedes `secondaryButtonText`. Each entry needs `text`; optional
`kind` (defaults to `"secondary"`) and `disabled` pass through to Button.
With two entries plus a primary button, the footer uses the three-button layout. | `[]` | | `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 | Description | | --- | --- | --- | | `on:click:button--secondary` | `{ text: string }` | Dispatched when a secondary button is clicked. For `secondaryButtonText`, the event is cancelable: call `preventDefault()` to keep the modal open. If not cancelled, the modal closes. Array `secondaryButtons` never auto-close. | #### `ModalFooter` $$restProps `ModalFooter` spreads `$$restProps` to the `div` element. ## ContainedList ### Basic Display a basic contained list with a header label and list items. The default size is medium. ```svelte Item 1 Item 2 Item 3 ``` ### Custom label Use the `labelChildren` slot for custom label content instead of plain label text. ```svelte Custom label Item 1 Item 2 Item 3 ``` ### Sizes The default size is medium. See variants below for compact and larger layouts. #### Small Use the small size variant for more compact list items with reduced padding and height. ```svelte Item 1 Item 2 Item 3 ``` #### Large Use the large size variant for larger list items with increased padding and height. ```svelte Item 1 Item 2 Item 3 ``` #### Extra-large Use the extra-large size variant for the largest list items with maximum padding and height. ```svelte Item 1 Item 2 Item 3 ``` ### Inset rulers Set `inset` to inset divider lines from the edges for a more refined appearance. ```svelte Item 1 Item 2 Item 3 ``` ### Disclosed Set `kind` to `"disclosed"` for a compact header that sticks while scrolling. In long lists, the header stays visible at the top of the container. ```svelte
{#each Array.from({ length: 6 }) as i} Item {/each} {#each Array.from({ length: 6 }) as i} Item {/each}
``` ### Icons Add icons using the `icon` prop. Icons appear to the left of each item. ```svelte Item 1 Item 2 Item 3 ``` ### Search Add a search input to filter list items. #### Expandable Use the `action` slot on the list to add an expandable search control in the header. ```svelte Item 1 Item 2 Item 3 ``` #### Persistent Place the search as a direct child (not in the action slot) for a persistent filter below the title. The input is styled for list headers and works with sticky headers. ```svelte {#each filteredResults as item} {item} {/each} ``` ### Interactive items Set `interactive` on a list item to render it as a clickable button with keyboard support. Combine with `disabled` to prevent interaction. ```svelte console.log("click")}> Item 1 Item 2 Item 3 ``` #### With actions Use the `action` slot on an item for trailing controls such as buttons or icons. Actions sit on the trailing edge and do not block the item click target. ```svelte console.log("click")}> Item 1
selectedId: {selectedId}
{#each visibleSwitches as sw (sw.id)} {/each} ``` ### Manual selection mode By default, the content switcher changes the selection when the user moves focus with the arrow keys. Set `selectionMode` to `"manual"` so that arrow keys only move focus without changing the selection. The user must press Enter or Space to select a switch. ```svelte ``` ### Reactive example Programmatically control the content switcher with the `bind:selectedIndex` directive, updating the selected index based on user interactions or application state. ```svelte
Selected index: {selectedIndex}
``` ### Conditional switches Switches can be conditionally rendered using Svelte's `{#if}` blocks. The component automatically maintains correct indices even when switches are dynamically added or removed. ```svelte
Selected index: {selectedIndex}
{#if showAdmin} {/if} {#if showSettings} {/if}
``` ### Custom switch slot Override the default slot in the switch to customize how each option displays. ```svelte Latest news Trending ``` ### Icon-only Set `icon` on every switch for compact, icon-only controls. The switcher becomes icon-only when all switches include an icon. Use `text` for the accessible label and tooltip. ```svelte ``` #### Custom tooltip alignment Pass `tooltipAlignment` to individual icon-only switches to adjust tooltip alignment. ```svelte ``` ### Low contrast Set `lowContrast` for the low contrast variant. The selected switch uses a light surface instead of the default inverse (dark) background, reducing the contrast between the switcher and surrounding content. ```svelte ``` #### Disabled switches Combine low contrast with disabled switches. ```svelte ``` #### Sizes The low contrast variant supports all sizes. Set `size` to `"sm"`, `"xl"`, or leave it unset for the default size. ```svelte ``` #### Icon-only Combine low contrast with icon-only switches. ```svelte ``` #### Icon-only (custom tooltip alignment) Pass `tooltipAlignment` to individual icon-only switches to adjust tooltip alignment. ```svelte ``` #### Icon-only (sizes) The low contrast, icon-only variant supports all sizes. Set `size` to `"sm"`, `"xl"`, or leave it unset for the default size. ```svelte ``` ### Sizes Set `size` to control height. The default is `md`. #### Extra-large Set `size` to `"xl"` for an extra-large content switcher. ```svelte ``` #### Small Set `size` to `"sm"` for a small content switcher. ```svelte ``` ### Disabled Disable individual switches with `disabled`. ```svelte ``` --- ### Component API #### `ContentSwitcher` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `selectedIndex` (Reactive) | `number` | Set the selected index of the switch item.
Ignored when `selectedId` is set. | `0` | | `selectedId` (Reactive) | `string \| undefined` | Specify the selected switch by id.
When set, takes precedence over `selectedIndex` and stays on the same
logical switch as switches are added or removed. Pair with a stable `id`
on each `Switch`. | _undefined_ | | `ref` (Reactive) | `null \| HTMLDivElement` | Obtain a reference to the tablist HTML element. | `null` | | `size` | `"sm" \| "xl"` | Specify the size of the content switcher. | _undefined_ | | `selectionMode` | `"automatic" \| "manual"` | Choose whether or not to automatically change selection
on focus when using arrow keys. Defaults to "automatic". | `"automatic"` | | `lowContrast` | `boolean` | Set to `true` to use the low contrast variant | `false` | #### `ContentSwitcher` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ContentSwitcher` forwarded events | Event | | --------------- | | `on:blur` | | `on:click` | | `on:focus` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `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"` | | `icon` | `Icon` | Render an icon-only switch.
The parent `ContentSwitcher` becomes icon-only when every `Switch` sets `icon`.
`text` is used as the accessible label and the tooltip shown on hover and focus. | _undefined_ | | `disabled` | `boolean` | Set to `true` to disable the switch | `false` | | `tooltipAlignment` | `"start" \| "center" \| "end"` | Align the portalled tooltip to the switch. | `"center"` | | `id` | `string` | Set an id for the button element | `uniqueId()` | #### `Switch` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `Switch` forwarded events | Event | | --------------- | | `on:blur` | | `on:click` | | `on:focus` | | `on:keydown` | | `on:keyup` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `Switch` $$restProps `Switch` spreads `$$restProps` to the `button` element. ## ContextMenu ### Basic In the examples, right click anywhere within the iframe. The context menu appears when right-clicking anywhere in the window. Use ContextMenuOption for menu items and ContextMenuDivider for visual separation. The root element has `role="menu"`. Set `labelText` or `aria-label` on ContextMenu so assistive technologies get a meaningful name. This matters most for the default window-wide behavior (target unset), where there is no visible trigger to label the menu with `aria-labelledby`. ```svelte

Right click anywhere on this page

``` ### Context menu options `ContextMenuOption` supports the following props: | Prop | Description | | --- | --- | | `labelText` | Primary label (or use the `labelChildren` slot; see the API reference). | | `shortcutText` | Keyboard hint shown on the right, with or without an icon. Pass the shortcut as a string, for example `"CmdC"`. | | `icon` | Carbon icon component to the left of the label. When an icon is set, the option is indented automatically so rows align; you do not need to pass `indented` for icon rows. | | `indented` | Indent the label without an icon, for example to align with submenu parents or nested items (see [Nested menu](#nested-menu), [Custom target](#custom-target), and [Multiple targets](#multiple-targets)). | | `disabled` | Non-interactive, dimmed row. | | `kind` | `"default"` or `"danger"` for destructive actions. | For options inside `ContextMenuGroup`, see [Selectable](#selectable), [Selectable (nested)](#selectable-nested), and [Radio group](#radio-group). ```svelte

Right click anywhere on this page

``` ### Nested menu Put children inside a parent `ContextMenuOption` to open a flyout submenu. Use `indented` on the parent when it has no icon so the label aligns with other rows. Submenus can contain: | Kind | Description | | --- | --- | | Plain options | Nested `ContextMenuOption` rows for ordinary actions (no selection state). This page's example below mixes plain rows with a selectable group; see **Open with** → Preview / Editor. | | Selectable group | A nested `ContextMenuGroup` with an accessible label; options act as checkboxes and share `bind:selectedIds`. See [Selectable (nested)](#selectable-nested); the **Export as** branch in this example shows the same pattern alongside plain items. | | Radio group | A nested `ContextMenuRadioGroup` with `bind:selectedId` so only one choice is active. See [Radio group (nested)](#radio-group-nested). | Selecting an option closes only that option's own menu level. At the root, that closes the whole menu. Inside a submenu, it closes just that flyout and leaves the rest open. Call `event.preventDefault()` to keep a flyout open across several picks; see [Prevent menu from closing](#prevent-menu-from-closing). ```svelte

Right click anywhere on this page

``` ### Targets Control which element triggers the menu. #### Custom target By default, the context menu triggers when you right-click 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

``` ### Selection Let options act as checkboxes or radios, standalone or grouped. #### Selectable Use selectable for a single toggle item, or wrap options in ContextMenuGroup with `bind:selectedIds` for a checkbox-style group. Provide an id on each option in the group. The standalone toggle and the group items are independent, and the group tracks every chosen option in selectedIds. ```svelte

Right click anywhere on this page

``` #### Selectable (nested) Put ContextMenuGroup inside a parent ContextMenuOption to show the checkbox-style group in a flyout submenu. Use `bind:selectedIds` for the chosen values. See [Nested menu](#nested-menu) for a full submenu example, and [Prevent menu from closing](#prevent-menu-from-closing) to keep the flyout open while changing several checkboxes. ```svelte

Right click anywhere on this page

``` #### Radio group Use ContextMenuRadioGroup to organize related options as a radio set: only one option can be selected at a time, and `bind:selectedId` reflects the active choice. ```svelte

Right click anywhere on this page

``` #### Radio group (nested) Put ContextMenuRadioGroup inside a parent ContextMenuOption to show the radio set in a flyout submenu, similar to the nested checkbox group in [Nested menu](#nested-menu). Use `bind:selectedId` for the active choice. Selecting an option closes that flyout. Call `event.preventDefault()` in the option's `on:click` handler to leave it open; `selectedId` still updates. See [Prevent menu from closing](#prevent-menu-from-closing). ```svelte e.preventDefault()} /> e.preventDefault()} /> e.preventDefault()} />

Right click anywhere on this page

``` ### Prevent menu from closing An option's `click` event is cancelable. Call `event.preventDefault()` in its `on:click` handler to keep the menu open. For a selectable or radio option, selection still updates; only the close is canceled. That is how you leave a nested submenu open while changing several choices. See [Radio group (nested)](#radio-group-nested). ```svelte { e.preventDefault(); copyToClipboard(); }} />

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` | | `labelText` | `string \| undefined` | Accessible name for the menu.
Prefer setting this (or `aria-label`) when the menu is opened from the window
(`target` unset), where there is no visible trigger for `aria-labelledby`. | _undefined_ | #### `ContextMenu` slots | Slot | Detail | | --------- | ----------------------- | | `default` | `Record` | #### `ContextMenu` forwarded events | Event | | ------------ | | `on:click` | | `on:keydown` | #### `ContextMenu` dispatched events | Event | Detail | | --- | --- | | `on:close` | `{
trigger:
\| "escape-key"
\| "outside-click"
\| "select";
}` | | `on:open` | `HTMLElement` | #### `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 | | --- | --- | --- | --- | | `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` | | `indented` | `boolean` | Set to `true` to indent the label.
Rendered indented regardless when `icon` is set, or when the option is selectable or part of a radio group. | `false` | | `icon` | `Icon` | Specify the icon to render.
Icon is rendered to the left of the label text.
Overridden with a checkmark icon when the option is selectable or part of a radio group. | _undefined_ | | `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. | `uniqueId()` | #### `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 | Description | | --- | --- | --- | | `on:click` | `Event` | Dispatched on selection. Cancelable: call `preventDefault()` to keep
this menu level open. A selectable or radio option's selection still
updates. | #### `ContextMenuOption` $$restProps `ContextMenuOption` spreads `$$restProps` to the `li` element. ## CopyButton ### Basic Set `text` to the string to copy. By default, the copy button uses the native [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText), with a `document.execCommand("copy")` fallback when that API is unavailable or rejects (for example in an insecure context); pass a function to `copy` to replace it (see [Override](#override)). For code examples, use [CodeSnippet](/components/CodeSnippet); for content not ready at render time, see [Async copy](#async-copy). ```svelte ``` ### Async copy Pass an async `copy` function when the text is not available at render time, for example markdown fetched on click. Feedback appears after `copy()` resolves. While `copy()` is pending, the button sets `aria-busy` and ignores clicks. On failure, the button shows `errorFeedback` (default `"Failed to copy"`) and emits `copy:error`. Prefetch on hover with `on:mouseenter`. ```svelte { console.error("Copy failed", e.detail.error); }} /> ``` ### Ghost kind Set `kind` to `"ghost"` to render a transparent button that matches a [Button](/components/Button) with `kind="ghost"`. The default `kind` (`"primary"`) keeps Carbon's filled square. ```svelte ``` ### Sizes Set `size` to scale the square. Sizes align with the heights used by [Button](/components/Button). #### Small ```svelte ``` #### Medium The default size (`md`) matches Carbon's native copy button. ```svelte ``` #### Large ```svelte ``` #### Extra large ```svelte ``` ### Custom feedback Customize the message and icon shown after copying. #### Text Set `feedback` to customize the message shown after copying. Set `errorFeedback` to customize the message shown when copying fails (default `"Failed to copy"`). ```svelte ``` #### Icon Set `feedbackIcon` to show a different icon while feedback is visible. The copy icon returns when feedback closes. ```svelte ``` #### Duration Set `feedbackTimeout` to change how long the feedback stays visible, in milliseconds. Defaults to `2000`. ```svelte ``` ### Copy behavior Replace or disable the default clipboard behavior. #### Override Pass a function to `copy` to replace the default Clipboard API behavior. This example uses the [clipboard-copy](https://github.com/feross/clipboard-copy) package instead of the Clipboard API. ```svelte copy(text)} tooltipAlignment="start" /> ``` #### Prevent Set `copy` to a no-op function to disable copying. ```svelte {}} /> ## Hover tooltip On hover or focus, the button shows a proactive tooltip with the `iconDescription`. It renders in a floating portal so it is never clipped and flips when space is tight. ### Directions Set `tooltipPosition` to place the tooltip relative to the button. ### Alignment Set `tooltipAlignment` to align the tooltip relative to the button. ## Portal tooltip The "Copied!" feedback tooltip is rendered in a floating portal by default, so it shares the same surface as the hover tooltip (the text swaps in place) and is never clipped by an `overflow: hidden` container. Set `portalTooltip` to `false` to use Carbon's inline feedback caret instead. A non-default `tooltipPosition` or `tooltipAlignment` is always portalled because the inline caret only supports the default placement. ``` ```svelte ``` ### Inside a modal Because the feedback tooltip is portalled by default, it is not clipped inside a [Modal](/components/Modal). Set `portalTooltip` to `false` to use the inline caret. ```svelte (open = false)} > ``` --- ### Component API #### `CopyButton` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `ref` (Reactive) | `null \| HTMLButtonElement` | Obtain a reference to the underlying button element. | `null` | | `feedback` | `string` | Set the feedback text shown after clicking the button | `"Copied!"` | | `errorFeedback` | `string` | Set the feedback text shown when copying fails | `"Failed to copy"` | | `feedbackTimeout` | `number` | Set the timeout duration (ms) to display feedback text | `2000` | | `feedbackIcon` | `Icon` | Specify an icon to render during the feedback window (for example, after copying).
When unset, the copy icon is always shown. | _undefined_ | | `iconDescription` | `string` | Set the title and ARIA label for the copy button | `"Copy to clipboard"` | | `kind` | `"primary" \| "ghost"` | Specify the kind of copy button.
Use `"ghost"` to match a `Button` with `kind="ghost"`. | `"primary"` | | `size` | `"sm" \| "md" \| "lg" \| "xl"` | Specify the size of the copy button.
`"md"` keeps Carbon's native 2.5rem square; the other sizes match `Button`. | `"md"` | | `text` | `string` | Specify the text to copy. | _undefined_ | | `copy` | `(text: string) => void \| Promise` | Override the default copy behavior (`navigator.clipboard.writeText` with
a `document.execCommand("copy")` fallback). Failures reject so the button
can show `errorFeedback` and dispatch `copy:error`. | `copyText` | | `portalTooltip` | `boolean \| undefined` | Set how the "Copied!" feedback tooltip is rendered.
By default, it is rendered in a portal so it shares the same surface as the
hover tooltip (the text swaps in place) and is never clipped by an
`overflow: hidden` container. Set to `false` to use Carbon's inline feedback
caret instead; a non-default `tooltipPosition`/`tooltipAlignment` still
portals because the inline caret only supports the default placement. | _undefined_ | | `tooltipPosition` | `"top" \| "right" \| "bottom" \| "left"` | Set the position of the tooltip relative to the button. | `"bottom"` | | `tooltipAlignment` | `"start" \| "center" \| "end"` | Set the alignment of the tooltip relative to the button. | `"center"` | #### `CopyButton` forwarded events | Event | | ----------------- | | `on:animationend` | | `on:blur` | | `on:click` | | `on:focus` | | `on:mouseenter` | | `on:mouseleave` | #### `CopyButton` dispatched events | Event | Detail | | --------------- | -------------------- | | `on:copy` | `null` | | `on:copy:error` | `{ error: unknown }` | #### `CopyButton` $$restProps `CopyButton` spreads `$$restProps` to the `button` element. ## CopyInput ### Basic Set `value` to the string to show and copy. For install commands, see [CodeSnippet](/components/CodeSnippet); for display-only values, use [TextInput](/components/TextInput#read-only). ```svelte ``` ### Select on focus Set `selectOnFocus` to select the full value when the field receives focus. ```svelte ``` ### Async copy Pass an async `copy` function when the text is not available at render time, for example a token fetched on click. Feedback appears after `copy()` resolves. While `copy()` is pending, the copy button shows a busy state and ignores clicks. On failure, the button shows `errorFeedback` (default `"Failed to copy"`) and emits `copy:error`. Prefetch on hover with `on:mouseenter:copy-button`. ```svelte { console.error("Copy failed", e.detail.error); }} /> ``` ### Obscured value Set `type` to `"password"` to obscure the value. By default the value stays obscured; the copy button still copies the full value. ```svelte ``` Set `revealMode` to opt into revealing the value on interaction. Use `"focus"` to reveal while the input is focused. ```svelte ``` Use `"hover-focus"` to reveal while the input is hovered or focused. ```svelte ``` ### Truncation Long values truncate with an ellipsis when the field is narrower than the text. Focus or select the field to see the full value. Copy always uses the complete value. ```svelte
``` ### Helper text ```svelte ``` ### Sizes Set `size` to `"sm"` or `"xl"`. ```svelte

``` ### Inline label ```svelte ``` ### Custom feedback Customize the message and icon shown after copying. #### Text Set `feedback` to customize the message shown after copying. Set `errorFeedback` to customize the message shown when copying fails (default `"Failed to copy"`). ```svelte ``` #### Icon Set `feedbackIcon` to show a different icon while feedback is visible. The copy icon returns when feedback closes. ```svelte ``` ### Light ```svelte ``` ### Tooltip On hover or focus, the copy button shows a tooltip with `iconDescription`. It renders in a floating portal so it is not clipped and flips when space is tight. #### Direction Set `tooltipPosition` to place the tooltip relative to the copy button. Accepts `"top"`, `"right"`, `"bottom"` (default), and `"left"`. ```svelte ``` #### Alignment Set `tooltipAlignment` to align the tooltip relative to the copy button. Accepts `"start"`, `"center"` (default), and `"end"`. ```svelte ``` ### Portal tooltip The copy feedback tooltip is rendered in a floating portal by default, so it shares the same surface as the hover tooltip (the text swaps in place) and is never clipped by an `overflow: hidden` container. Set `portalTooltip` to `false` to use Carbon's inline feedback caret instead. A non-default `tooltipPosition` or `tooltipAlignment` is always portalled because the inline caret only supports the default placement. ```svelte ``` ### Inside a modal Because the feedback tooltip is portalled by default, it is not clipped inside a [Modal](/components/Modal). Set `portalTooltip` to `false` to use the inline caret. ```svelte (open = false)} > ``` ### Fluid Use the fluid variant with `fluid`, which embeds the label inside the field. Fluid copy inputs can be used standalone or inside [FluidForm](/components/FluidForm), where the fluid variant is applied automatically. The fluid variant cannot be combined with the inline variant. ```svelte ``` #### Custom label Use the `labelChildren` slot to render custom label content, such as a tooltip icon. ```svelte API token ``` #### Disabled ```svelte ``` #### Skeleton Display a loading skeleton for the fluid copy input variant. ```svelte ``` ### Skeleton Show a loading state with the default skeleton variant. ```svelte ``` #### Without label Set `hideLabel` to hide the skeleton label. ```svelte ``` --- ### Component API #### `CopyInput` props | Prop | Type | Description | Default | | --- | --- | --- | --- | | `ref` (Reactive) | `null \| HTMLInputElement` | Obtain a reference to the input HTML element. | `null` | | `value` | `string` | Specify the value to display and copy. | `""` | | `type` | `"text" \| "password"` | Set to `"password"` to obscure the value.
Use `revealMode` to reveal the value on interaction. | `"text"` | | `revealMode` | `"focus" \| "hover-focus"` | Control when a `type="password"` value is revealed.
Has no effect unless `type` is `"password"`.
- `"focus"`: reveal while the input is focused.
- `"hover-focus"`: reveal while the input is hovered or focused.
When unset, the value stays obscured; the copy button still copies the full value. | _undefined_ | | `selectOnFocus` | `boolean` | Set to `true` to select the full value when the input receives focus. | `false` | | `size` | `"sm" \| "xl"` | Set the size of the input. | _undefined_ | | `light` | `boolean` | Set to `true` to enable the light variant | `false` | | `disabled` | `boolean` | Set to `true` to disable the input and copy button | `false` | | `inline` | `boolean` | Set to `true` to use the inline variant | `false` | | `fluid` | `boolean` | Set to `true` to use the fluid variant.
Inherited from the parent `FluidForm` context,
so it does not need to be set when used inside `FluidForm`.
Cannot be combined with the inline variant. | `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 | `""` | | `id` | `string` | Set an id for the input element | `uniqueId()` | | `name` | `string` | Specify a name attribute for the input. | _undefined_ | | `feedback` | `string` | Set the feedback text shown after clicking the copy button | `"Copied!"` | | `errorFeedback` | `string` | Set the feedback text shown when copying fails | `"Failed to copy"` | | `feedbackIcon` | `Icon` | Specify an icon to render during the feedback window (for example, after copying).
When unset, the copy icon is always shown. | _undefined_ | | `feedbackTimeout` | `number` | Set the timeout duration (ms) to display the feedback text | `2000` | | `iconDescription` | `string` | Set the title and ARIA label for the copy button | `"Copy to clipboard"` | | `copy` | `(text: string) => void \| Promise` | Override the default copy behavior (`navigator.clipboard.writeText` with
a `document.execCommand("copy")` fallback). Failures reject so the control
can show `errorFeedback` and dispatch `copy:error`. | `copyText` | | `portalTooltip` | `boolean \| undefined` | Set to `true` to render the feedback tooltip in a portal,
preventing it from being clipped by `overflow: hidden` containers.
By default, the tooltip is portalled when inside a `Modal`. | _undefined_ | | `tooltipPosition` | `"top" \| "right" \| "bottom" \| "left"` | Set the position of the copy button's tooltip. | `"bottom"` | | `tooltipAlignment` | `"start" \| "center" \| "end"` | Set the alignment of the copy button's tooltip. | `"center"` | #### `CopyInput` slots | Slot | Detail | | --------------- | ----------------------- | | `labelChildren` | `Record` | #### `CopyInput` forwarded events | Event | | --------------- | | `on:blur` | | `on:click` | | `on:copy` | | `on:copy:error` | | `on:focus` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `CopyInput` dispatched events | Event | Detail | | --------------------------- | ------------ | | `on:mouseenter:copy-button` | `MouseEvent` | | `on:mouseleave:copy-button` | `MouseEvent` | #### `CopyInput` $$restProps `CopyInput` spreads `$$restProps` to the `input` element. #### `CopyInputSkeleton` props | Prop | Type | Description | Default | | ----------- | --------- | ------------------------------------ | ------- | | `hideLabel` | `boolean` | Set to `true` to hide the label text | `false` | #### `CopyInputSkeleton` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `CopyInputSkeleton` $$restProps `CopyInputSkeleton` spreads `$$restProps` to the `div` element. #### `FluidCopyInputSkeleton` forwarded events | Event | | --------------- | | `on:click` | | `on:mouseenter` | | `on:mouseleave` | | `on:mouseover` | #### `FluidCopyInputSkeleton` $$restProps `FluidCopyInputSkeleton` spreads `$$restProps` to the `div` element. ## DataTable ### Basic Create a basic table using `headers` and `rows`. Match each header key with the corresponding row property. Every header needs a unique key and every row a unique id. ```svelte ``` ### Cells Customize cell rendering with `cell` and `cellHeader` slots. #### Slotted Use the `cell` slot to customize cell content. Access row and cell data through `let:row` and `let:cell`. Use the `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"}

Distributes requests evenly across servers. Read more on Wikipedia

{:else} {cell.value} {/if}
``` #### Row state The `cell` slot provides rowSelected and rowExpanded 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)" : ""}
``` #### Editable Use the `cell` slot to render form inputs that edit row values inline. Bind the input to the row field--for example `bind:value={row.qty}`--to update the rows array. The table rebuilds cells only when the rows array reference changes. After an in-place edit, call `refreshRow(id)` to update columns whose display reads other fields on the same row. Use `bind:this` to obtain a reference to the component instance. ```svelte `$${row.unitPrice * row.qty}`, }, ]} {rows} > {#if cell.key === "qty"} { // Rebuild cells so the Total column picks up the new qty. dataTable.refreshRow(row.id); }} /> {:else} {cell.display ? cell.display(cell.value, row) : cell.value} {/if} ``` When you edit multiple painted rows in place, call `refreshCells()` once to rebuild derived columns for the visible window. Offscreen rows are computed when they scroll into view. ```svelte `$${row.unitPrice * row.qty}`, }, ]} {rows} > {#if cell.key === "qty"} {:else} {cell.display ? cell.display(cell.value, row) : cell.value} {/if} ``` ### Title and description Add a title and description above the table. #### Props Add a title and description to provide context for the table data. ```svelte ``` #### Slottable By default, the title renders as an `

` and the description as a `

`. Use slots to customize the elements and styles. Destructure the original classes with `let:props`. ```svelte

Load balancers

Your organization's active load balancers.
``` ### Width Control the table and column widths. #### Static Set `useStaticWidth` to `true` to render the table with an auto width instead of 100%. ```svelte ``` #### Custom columns Specify width or minWidth in `headers` to set column dimensions. This applies a fixed table layout. 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", }))} /> ``` #### Alignment Set `columnAlign` in `headers` to align a column's header and cells. Values are logical: `end` is the right edge in left-to-right text and the left edge in right-to-left text; the default, `start`, is the left edge. Sortable columns keep their sort affordance. ```svelte "$" + cost, }, ]} rows={[ { id: "a", name: "Load Balancer 3", protocol: "HTTP", port: 3000, cost: 1240, }, { id: "b", name: "Load Balancer 1", protocol: "HTTP", port: 443, cost: 865, }, { id: "c", name: "Load Balancer 2", protocol: "HTTP", port: 80, cost: 310 }, ]} /> ``` ### Column visibility Control which columns render without editing the `headers` definition. #### Hidden columns Set `columnHidden` to `true` on a header to skip that column in render while keeping it in `headers`. A single canonical header list keeps column order and definitions stable across toggles. Hidden columns are excluded from toolbar search, since a match the reader cannot see is a result they cannot explain. An active sort on a hidden column still applies, because hiding is presentational. ```svelte ``` #### Toggling columns Flip `columnHidden` on a bound `headers` array from a `ToolbarMenu` to build a column picker. ```svelte {#each headers as header (header.key)} toggleColumn(header.key)}> {header.columnHidden ? "Show" : "Hide"} {header.value} {/each} ``` ### Sticky header Set `stickyHeader` to fix the header in place while the body scrolls. #### Scrolling 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", }))} /> ``` #### Empty column A header with `empty: true` has no label, but body cells can still render content. For row-actions overflow menus, also set `columnMenu: true` so the column stays narrow and the menu trigger stays centered. With stickyHeader enabled, the empty column stays aligned with its body cells. ```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", }))} > {#if cell.key === "overflow"} {:else} {cell.value} {/if} ``` #### Max height By default, stickyHeader caps the table height at 300px. Override the cap with `stickyHeaderMaxHeight`. Pass a number (interpreted as px) or a CSS length string such as `"24rem"`. ```svelte ``` ### Virtualization Set `virtualize` to render only the visible rows, improving performance for large datasets. #### Large datasets Virtualization renders only rows visible in the viewport, improving performance for large datasets. Set `virtualize` to `true` to enable. The header stays visible while scrolling--sticky positioning is applied automatically. Use `stickyHeader` when you need the full sticky-header layout. 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 ``` #### Custom overscan Overscanning renders extra rows above and below the viewport for smoother scrolling. The default overscan is 3. Set `overscan` to control how many extra rows are rendered. ```svelte ``` #### Custom row height By default, virtual row height matches the table size variant (48px medium, 24px compact, 32px short, 64px tall). Use `rowClass` for a custom row height via CSS, and set matching `itemHeight` for correct virtualization. ```svelte ``` #### Custom max visible rows By default, the table shows 10 rows in the viewport. Set `maxVisibleRows` to control how many rows are visible at once. Container height is itemHeight × maxVisibleRows, or use `containerHeight` for pixel-based control. ```svelte ``` ### Toolbar Add a Toolbar above the table for search, menus, and actions. #### Search & actions Add a toolbar with search, menu, and actions above the table. ```svelte Restart all API documentation Stop all ``` #### Small Use `size="short"` for a more compact table. The toolbar inherits a matching size from the parent DataTable: short uses the small toolbar and compact uses the [extra small toolbar](#compact). Set `size` on the toolbar to override the inherited value (see [toolbar size override](#size-override)). ```svelte Restart all API documentation Stop all ``` #### Size override Set `size` on the toolbar to override the size inherited from the DataTable. Here, `size="tall"` on the table pairs with `size="sm"` on the toolbar. ```svelte Restart all API documentation Stop all ``` #### Compact Use `size="compact"` for the table. The toolbar inherits the extra small (xs) size to match the compact row height. ```svelte Restart all API documentation Stop all ``` #### Selectable rows Set `selectable` to `true` to enable selectable rows. Here, the toolbar is used standalone. For batch actions on selected rows, see [batch selection with toolbar](#actions-toolbar). ```svelte ``` ### Toolbar search with typeahead Compose [SearchMenu](/components/SearchMenu) in the toolbar for a search typeahead with suggestions. `SearchMenu` does not read the `DataTable` context, so bind to `value` and filter the rows in the consumer. Selecting a suggestion sets `value`. For built-in row filtering without a menu, use [ToolbarSearch](#filtering). ```svelte {#each rows as row (row.id)} {/each} ``` ### Export Serialize headers and rows to a CSV string with `toCsv`. It applies each column's `display` formatting and skips empty columns, so the export matches what the table renders. It returns a string instead of triggering a download; pass the result to [`downloadFile`](/components/Link#download-link) (or wire it into [`LinkDownload`](/components/Link#download-link)) when you want a file. Export the current view by passing the rows matching `filteredRowIds`; values a spreadsheet would read as formulas are prefixed with a single quote unless `escapeFormulas` is `false`. ```svelte ``` ### Filtering Filter rows with `shouldFilterRows`. #### Client-side Set `shouldFilterRows` to `true` to enable client-side filtering. The default filter compares cell values as strings. For pagination with filtering, bind to `filteredRowIds` and pass its length to the pagination totalItems. ```svelte ``` #### 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 /> ``` #### Strategy By default (`filterMode="remove"`), filtering unmounts non-matching rows, resetting focus, draft inputs, and open menus. This keeps the DOM small for large tables. Set `filterMode` to `"hide"` to keep every row mounted and hide non-matching rows instead, preserving row state when cells hold inputs or other widgets. Type a note in the example, filter the row away, then clear the search--the note remains. Setting `filterMode` to `"hide"` has no effect when pageSize is set or virtualization is enabled. Selection, select all, and filteredRowIds still reflect matching rows only. ```svelte {#if cell.key === "note"} {:else} {cell.value} {/if} ``` ### Row styling Apply alternating colors or custom row classes. #### Zebra Set `zebra` to `true` to add alternating row colors. ```svelte ``` #### Custom 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, and 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)}
``` ### Footer Use the `footerCell` slot to render a summary row aligned to the table columns. The slot receives each header, so it can decide what to render per column and leave the rest blank. Compute totals, averages, and counts yourself; the table does not aggregate. The footer renders once for the whole table rather than once per page, and it stays in place while virtualized rows scroll. ```svelte {#if header.key === "requests"} {totalRequests.toLocaleString()} {:else if index === 0} Total {/if} ``` ### Sizes Set `size` to control row height. The default is medium. #### Medium Set `size="medium"` for standard row height. ```svelte ``` #### Tall Set `size="tall"` for increased row height. ```svelte ``` #### Short Set `size="short"` for compact row height. ```svelte ``` #### Compact Set `size="compact"` for minimal row height. ```svelte ``` ### Sorting Set `sortable` to enable column sorting. #### Sortable columns Set `sortable` to `true` to enable column sorting. Disable sorting on specific columns by setting `sort: false` in the header object. When a sortable header is clicked, the table dispatches a cancelable `sort` event with `event.detail` shaped like `{ key, direction }`. The detail key is the header key (or null when unsorted); direction is `"none"`, `"ascending"`, or `"descending"`. Listen with `on:sort`. ```svelte console.log(e.detail.key, e.detail.direction)} /> ``` #### Server-side When rows and sort order come from an API, the canonical order is usually defined on the server (collation, nullable fields, joined columns, security filters). Client-side sorting on the same payload can disagree with that behavior or waste work on large datasets. In those cases, call `preventDefault()` on the `sort` event so the table does not reorder rows or apply its own sort for that click. Use event.detail.key and event.detail.direction as your sort parameters (query string, GraphQL variables, RPC args), wait for the response, then assign the new rows. The sort indicators should match what the server applied: bind sortKey and sortDirection from the parent and set them after the response (as in the example), or pass them as one-way props if you do not need child-to-parent sync. The framed example uses setTimeout to simulate a network request; `preventDefault()` runs first, then simulated sorted rows replace rows and the bound sort props update the header. ```svelte { e.preventDefault(); const { key, direction } = e.detail; rows = await fakeServerSort(key, direction); sortKey = key; sortDirection = direction; }} /> ``` #### Sort always Sortable columns support three directions: none (unsorted, original row order), ascending, and descending. Clicking a column header cycles through them in order. By default, a third click on a sorted column unsorts it (none restores the original row order). Set `sortAlways` to `true` to skip the unsorted state so the column always remains sorted. The first click sorts ascending; subsequent clicks alternate ascending and descending (no unsorted state). ```svelte ``` #### Per-column sort always Use `sortAlways` on individual headers to control which columns allow unsorting. In this transaction log, the Date column always stays sorted (chronological order is required for audit trails), while Amount and Status can be unsorted. ```svelte ``` #### Custom display and sort Use display and sort functions in headers 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", }, ]} /> ``` #### Top-level sort Define a default comparator for all sortable columns with top-level `sort`. Per-header sort functions take precedence. The comparator receives `(a, b, { key, ascending, row_a, row_b })`, enabling key-aware and row-level sorting logic. ```svelte { switch (key) { case "expireDate": return new Date(a) - new Date(b); case "port": return a - b; default: return String(a).localeCompare(String(b)); } }} headers={[ { key: "name", value: "Name" }, { key: "protocol", value: "Protocol" }, { key: "port", value: "Port" }, { key: "expireDate", value: "Expire date", display: (date) => new Date(date).toLocaleDateString(), }, ]} rows={[ { id: "a", name: "Load Balancer 3", protocol: "HTTP", port: 3000, expireDate: "2020-10-21", }, { id: "b", name: "Load Balancer 1", protocol: "HTTP", port: 443, expireDate: "2020-09-10", }, { id: "c", name: "Load Balancer 2", protocol: "HTTP", port: 80, expireDate: "2020-11-24", }, { id: "d", name: "Load Balancer 6", protocol: "HTTP", port: 3000, expireDate: "2020-12-01", }, { id: "e", name: "Load Balancer 4", protocol: "HTTP", port: 443, expireDate: "2021-03-21", }, { id: "f", name: "Load Balancer 5", protocol: "HTTP", port: 80, expireDate: "2020-11-14", }, ]} /> ``` #### Nested 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 Control sorting programmatically with `sortKey` and `sortDirection`. Set sortKey to a valid header key and sortDirection to "none", "ascending", or "descending". ```svelte
``` ### Pagination Combine the table with Pagination. #### Page bindings Bind pageSize and page on Pagination and pass them to the data table. ```svelte ``` #### Matching size Match Pagination size to DataTable size for consistent heights. Pair a short table with small (sm) pagination. ```svelte ``` Pair a tall table with large (lg) pagination. ```svelte ``` Pair a compact table with extra small (xs) pagination. ```svelte ``` ### Empty column (overflow menu) Set `empty: true` in a header to create an empty column--for overflow menus without a header label. ```svelte {#if cell.key === "overflow"} {:else} {cell.value} {/if} ``` ### Highlighted row Pass row ids in `highlightedRowIds` to keep a row visually highlighted. Bind each overflow menu open state to track which row is open. Highlighted rows use the bx--data-table--highlighted-row class, styled with the same theme tokens as row hover. ```svelte {#if cell.key === "overflow"} {:else} {cell.value} {/if} ``` ### Selection Enable row selection with checkboxes or radios, with optional batch actions. #### Checkbox Set `selectable` to `true` for multi-select. Bind selectedRowIds to track selections. Use inputName to customize checkbox names. Hold Shift while clicking a checkbox to select every row between it and the last row clicked. ```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 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 (initial 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", }))} /> ``` #### Actions toolbar Add a toolbar for batch actions when rows are selected. ```svelte Restart all API documentation Stop all ``` #### Controlled toolbar Control the batch actions toolbar with `active`. Prevent default cancel behavior with `on:cancel`. ```svelte { e.preventDefault(); active = false; }} > ``` #### Radio Set `radio` to `true` for single-row selection. Bind selectedRowIds to track the selected row. Use inputName to customize radio button names. ```svelte ``` #### Non-selectable 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} /> ``` ### Expansion Set `expandable` to reveal additional content per row. #### Expandable rows Set `expandable` to `true` to make rows expandable. Use `expandedRow` to customize expanded content. ```svelte
{JSON.stringify(row, null, 2)}
``` #### Custom icon Use the `expandIcon` slot to customize the expand/collapse icon. The slot receives expanded (whether the row is expanded), row (the row data, or undefined for the header expand-all button), and props (with aria-hidden and class to spread onto your icon). ```svelte
{JSON.stringify(row, null, 2)}
``` #### Non-expandable 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)}
``` #### Zebra Combine expandable rows with zebra striping. ```svelte
{JSON.stringify(row, null, 2)}
``` #### Compact Set `size="compact"` for expandable rows with minimal height. ```svelte
{JSON.stringify(row, null, 2)}
``` #### Short Set `size="short"` for expandable rows with compact height. ```svelte
{JSON.stringify(row, null, 2)}
``` #### Tall Set `size="tall"` for expandable rows with increased height. ```svelte
{JSON.stringify(row, null, 2)}
``` #### Batch Set `batchExpansion` to `true` to expand and collapse all rows at once. ```svelte
{JSON.stringify(row, null, 2)}
``` #### With selection Combine `batchExpansion` and `batchSelection` for expandable, selectable tables. ```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 Show a loading state with `DataTableSkeleton`. #### Loading state Use the data table skeleton to show a loading state. ```svelte ``` #### Headers and rows Specify headers and row count for the skeleton. ```svelte ``` #### Object headers Pass header objects to customize the skeleton. ```svelte ``` #### Empty header Add an empty header column with `empty: true`. ```svelte ``` #### No header or toolbar Hide the header and toolbar in the skeleton. ```svelte ``` #### Tall Set `size="tall"` for a taller skeleton. ```svelte ``` #### Short Set `size="short"` for a shorter skeleton. ```svelte ``` #### Compact 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. | `[]` | | `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. | `uniqueId()` | | `zebra` | `boolean` | Set to `true` to use zebra styles | `false` | | `sortable` | `boolean` | Set to `true` for the sortable variant | `false` | | `sortAlways` | `boolean` | Set to `true` to only toggle between "ascending" and
"descending" sort directions, skipping "none". | `false` | | `sort` | `(a: DataTableSortValue, b: DataTableSortValue, context: { key: DataTableKey; ascending: boolean; row_a: Row; row_b: Row }) => number` | Specify a default sort comparator for all sortable columns.
Per-header `sort` functions take precedence over this prop.

With a typed row generic, `a` and `b` are {@link DataTableSortValue} (the union of cell value types over every {@link DataTableKey} on `Row`). Narrow using `context.key` (typed as {@link DataTableKey}) or runtime checks. | _undefined_ | | `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.
Row selection is enabled regardless of `selectable`. | `false` | | `selectable` | `boolean` | Set to `true` for the selectable variant.
Shift-clicking a row checkbox extends selection to every row between it and the last row clicked (not supported with `radio`). | `false` | | `batchSelection` | `boolean` | Set to `true` to enable batch selection.
Row selection is enabled regardless of `selectable`. | `false` | | `nonSelectableRowIds` | `ReadonlyArray` | Specify the ids of rows that should not be selectable. | `[]` | | `highlightedRowIds` | `ReadonlyArray` | Specify the row ids to highlight.
Adds `bx--data-table--highlighted-row`. The highlighted row class is themed by default. | `[]` | | `stickyHeader` | `boolean` | Set to `true` to enable a sticky header | `false` | | `stickyHeaderMaxHeight` | `number \| string` | Override the maximum height of the sticky header table, replacing the
default `300px`. Only applies when `stickyHeader` is `true`. Pass a number
(interpreted as `px`) or a CSS length string (e.g. `"100%"`, `"24rem"`). | _undefined_ | | `useStaticWidth` | `boolean` | Set to `true` to use static width | `false` | | `filterMode` | `"remove" \| "hide"` | Set the filtering strategy used by `ToolbarSearch`.
- `"remove"`: remove non-matching rows from the DOM and recreate them when the
filter clears.
- `"hide"`: keep all rows mounted and hide non-matching rows with the `hidden`
attribute, preserving focus, inputs, and open menus.

`"hide"` falls back to `"remove"` when `pageSize` is set or `virtualize` is enabled.

Because `"hide"` keeps every row mounted, each keystroke re-renders all
rows, not just matching ones. For large row counts (hundreds or more),
prefer `"remove"`, pagination, or virtualization. | `"remove"` | | `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.
Virtualization assumes a uniform row height; combining it with `expandable` rows is not supported and may cause incorrect scroll-spacer sizing when rows are expanded mid-list.

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_ | | `refreshRow` | `(id: Row["id"]) => void` | Rebuild cells for a single row after an in-place edit to `rows`. | _undefined_ | | `refreshCells` | `() => void` | Rebuild cells for currently painted rows after batch in-place edits to
`rows`. Offscreen rows are computed when they enter the window. | _undefined_ | #### `DataTable` typedefs ```ts type DataTableValue = any; interface DataTableRow { id: Id; [key: string]: DataTableValue; } type DataTableKey = [ keyof import("./data-table-utils.d.ts").KeysWithoutIndexSignature, ] extends [never] ? import("./data-table-utils.d.ts").PropertyPath : keyof import("./data-table-utils.d.ts").KeysWithoutIndexSignature extends "id" ? import("./data-table-utils.d.ts").PropertyPath : Row extends DataTableRow ? import("./data-table-utils.d.ts").PropertyPathIgnoringIndexSignatures : import("./data-table-utils.d.ts").PropertyPath; type DataTableSortValue = import("./data-table-utils.d.ts").DataTableSortValue; type DataTableEmptyHeader = { key: DataTableKey | (string & {}); /** Whether the header is empty */ empty: true; display?: (item: DataTableValue, row: Row) => DataTableValue; sort?: | false | ((a: DataTableSortValue, b: DataTableSortValue) => number); /** Override table-level sortAlways for this column */ sortAlways?: boolean; /** Whether the column menu is enabled */ columnMenu?: boolean; /** Whether the column is skipped in render while remaining in `headers` */ columnHidden?: boolean; width?: string; minWidth?: string; }; type DataTableNonEmptyHeader = { key: DataTableKey; empty?: false; value: DataTableValue; display?: (item: DataTableValue, row: Row) => DataTableValue; sort?: | false | ((a: DataTableSortValue, b: DataTableSortValue) => number); /** Override table-level sortAlways for this column */ sortAlways?: boolean; /** Whether the column menu is enabled */ columnMenu?: boolean; /** Whether the column is skipped in render while remaining in `headers` */ columnHidden?: boolean; width?: string; minWidth?: string; /** Horizontal alignment of the column header and cells. Logical, so `end` is the right edge in LTR and the left edge in RTL. Defaults to `"start"`. */ columnAlign?: "start" | "end"; }; type DataTableHeader = DataTableNonEmptyHeader | DataTableEmptyHeader; 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";
};
}` | | `expandIcon` | `{
expanded: boolean;
row: Row \| undefined;
props: {
"aria-hidden": "true" \| "false";
class: string;
};
}` | | `expandedRow` | `{
row: Row;
rowSelected: boolean;
}` | | `footerCell` | `{
header: DataTableNonEmptyHeader;
index: number;
}` | | `titleChildren` | `{
props: {
class: "bx--data-table-header__title";
};
}` | #### `DataTable` dispatched events | Event | Detail | Description | | --- | --- | --- | | `on:click` | `{
header?: DataTableHeader;
row?: Row;
cell?: DataTableCell;
}` | | | `on:click:cell` | `{
cell: DataTableCell;
target: EventTarget;
currentTarget: EventTarget;
rowClass?: DataTableRowClass;
}` | | | `on:click:header` | `{
header: DataTableHeader;
/** The intended next sort direction for this click, reported regardless of whether the `sort` event was cancelled. */
sortDirection?:
"ascending" \| "descending" \| "none";
target: EventTarget;
currentTarget: EventTarget;
}` | | | `on:click:header--expand` | `{
expanded: boolean;
}` | | | `on:click:header--select` | `{
indeterminate: boolean;
selected: boolean;
}` | | | `on:click:row` | `{
row: Row;
target: EventTarget;
currentTarget: EventTarget;
}` | | | `on:click:row--expand` | `{
expanded: boolean;
row: Row;
}` | | | `on:click:row--select` | `{
selected: boolean;
row: Row;
}` | | | `on:mouseenter:row` | `Row` | | | `on:mouseleave:row` | `Row` | | | `on:sort` | `type EventDetail =
\| { key: null; direction: "none" }
\| {
key: DataTableKey;
direction:
"ascending" \| "descending";
}` | Dispatched when a sortable column header would change the active sort. The event is cancelable: call `preventDefault()` to skip updating `sortKey` / `sortDirection` and skip client side sorting for that click (for example full server side sorting while still reading `detail.key` / `detail.direction` for your API). If not cancelled, the table applies the new sort and sorts the current `rows` client side. Typical uses: server side sorting, URL or query string sync, analytics, and persisting sort preferences. | #### `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 page `