Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 28 additions & 28 deletions COMPONENT_INDEX.md

Large diffs are not rendered by default.

16 changes: 11 additions & 5 deletions docs/src/COMPONENT_API.json
Original file line number Diff line number Diff line change
Expand Up @@ -2040,6 +2040,17 @@
"constant": false,
"reactive": true
},
{
"name": "virtualize",
"kind": "let",
"description": "Enable virtualization for large lists",
"type": "undefined | boolean | { itemHeight?: number, containerHeight?: number, overscan?: number, threshold?: number, maxItems?: number }",
"isFunction": false,
"isFunctionDeclaration": false,
"isRequired": false,
"constant": false,
"reactive": false
},
{
"name": "clear",
"kind": "function",
Expand Down Expand Up @@ -2108,11 +2119,6 @@
"type": "forwarded",
"name": "paste",
"element": "input"
},
{
"type": "forwarded",
"name": "scroll",
"element": "ListBoxMenu"
}
],
"typedefs": [
Expand Down
14 changes: 14 additions & 0 deletions docs/src/pages/components/ComboBox.svx
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,20 @@ Set `itemToString` to customize how items display in the filterable combobox.

<FileSource src="/framed/ComboBox/FilterableComboBoxCustomLabel" />

## Filtering (async)

By default, combobox filtering is synchronous and client-side.

For async (e.g., server-side) filtering, bind to `value` and update `items` when input changes. This example simulates async/await behavior with a debounced input value change.

<FileSource src="/framed/ComboBox/AsyncComboBox" />

## Virtualized (large lists)

Enable virtualization for large lists to improve performance. Only visible items are rendered in the DOM.

<FileSource src="/framed/ComboBox/VirtualizedComboBox" />

## Top direction

Set `direction` to `"top"` to make the dropdown menu appear above the input.
Expand Down
58 changes: 58 additions & 0 deletions docs/src/pages/framed/ComboBox/AsyncComboBox.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<script>
import { onMount } from "svelte";
import { ComboBox } from "carbon-components-svelte";

let items = [];
let timeoutId;
let inputValue = "";

// Simulate fetching data from a remote server.
async function fetchItems(query) {
if (!query) {
return [];
}

await new Promise((resolve) => setTimeout(resolve, 300));

const allItems = [
{ id: "0", text: "Slack" },
{ id: "1", text: "Email" },
{ id: "2", text: "Fax" },
{ id: "3", text: "Phone" },
{ id: "4", text: "SMS" },
{ id: "5", text: "WhatsApp" },
{ id: "6", text: "Teams" },
{ id: "7", text: "Discord" },
{ id: "8", text: "Zoom" },
{ id: "9", text: "Skype" },
];

return allItems.filter((item) =>
item.text.toLowerCase().includes(query.toLowerCase())
);
}

onMount(() => {
// Fetch initial items.
fetchItems("").then((data) => (items = data));

return () => {
clearTimeout(timeoutId);
};
});

$: {
clearTimeout(timeoutId);
timeoutId = setTimeout(async () => {
items = await fetchItems(inputValue);
// Debounce input value changes.
}, 150);
}
</script>

<ComboBox
titleText="Contact"
placeholder="Type to search..."
bind:value={inputValue}
{items}
/>
31 changes: 31 additions & 0 deletions docs/src/pages/framed/ComboBox/VirtualizedComboBox.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<script>
import { ComboBox } from "carbon-components-svelte";

// Generate large dataset
const items = Array.from({ length: 5000 }, (_, i) => ({
id: String(i),
text: "Item " + (i + 1),
}));

let selectedId = undefined;
let value = "";
</script>

<ComboBox
titleText="Virtualized ComboBox (5,000 items)"
placeholder="Filter..."
helperText="Only visible items are rendered in the DOM"
{items}
shouldFilterItem={(item, value) =>
item.text.toLowerCase().includes(value.toLowerCase())}
bind:selectedId
bind:value
virtualize={true}
/>

<div style="margin-top: 1rem;">
{#if selectedId !== undefined}
<strong>Selected:</strong>
{items.find((item) => item.id === selectedId)?.text}
{/if}
</div>
142 changes: 111 additions & 31 deletions src/ComboBox/ComboBox.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,12 @@
*/
export let listRef = null;

/**
* Enable virtualization for large lists
* @type {undefined | boolean | { itemHeight?: number, containerHeight?: number, overscan?: number, threshold?: number, maxItems?: number }}
*/
export let virtualize = undefined;

import { createEventDispatcher, afterUpdate, tick } from "svelte";
import Checkmark from "../icons/Checkmark.svelte";
import WarningFilled from "../icons/WarningFilled.svelte";
Expand All @@ -120,12 +126,14 @@
import ListBoxMenuIcon from "../ListBox/ListBoxMenuIcon.svelte";
import ListBoxMenuItem from "../ListBox/ListBoxMenuItem.svelte";
import ListBoxSelection from "../ListBox/ListBoxSelection.svelte";
import { virtualize as virtualizeUtil } from "../utils/virtualize.js";

const dispatch = createEventDispatcher();

let selectedItem = undefined;
let prevSelectedId = null;
let highlightedIndex = -1;
let listScrollTop = 0;

function change(dir) {
let index = highlightedIndex + dir;
Expand Down Expand Up @@ -216,6 +224,29 @@
$: comboId = `combo-${id}`;
$: highlightedId = items[highlightedIndex] ? items[highlightedIndex].id : 0;
$: filteredItems = items.filter((item) => shouldFilterItem(item, value));

$: virtualConfig = virtualize
? {
itemHeight: 40, // TODO: adjust based on size
containerHeight: 300,
overscan: 3,
threshold: 100,
maxItems: undefined,
...(typeof virtualize === "object" ? virtualize : {}),
}
: null;

$: virtualData = virtualConfig
? virtualizeUtil({
items: filteredItems,
scrollTop: listScrollTop,
...virtualConfig,
})
: null;

$: itemsToRender = virtualData?.isVirtualized
? virtualData.visibleItems
: filteredItems;
</script>

<svelte:window
Expand Down Expand Up @@ -380,38 +411,87 @@
/>
</div>
{#if open}
<ListBoxMenu aria-label={ariaLabel} {id} on:scroll bind:ref={listRef}>
{#each filteredItems as item, i (item.id)}
<ListBoxMenuItem
id={item.id}
active={selectedId === item.id}
highlighted={highlightedIndex === i}
disabled={item.disabled}
on:click={(e) => {
if (item.disabled) {
e.stopPropagation();
return;
}
selectedId = item.id;
open = false;
<ListBoxMenu
aria-label={ariaLabel}
{id}
on:scroll={(e) => {
listScrollTop = e.target.scrollTop;
}}
bind:ref={listRef}
style={virtualConfig
? `max-height: ${virtualConfig.containerHeight}px; overflow-y: auto;`
: undefined}
>
{#if virtualData?.isVirtualized}
<div style="height: {virtualData.totalHeight}px; position: relative;">
<div style="transform: translateY({virtualData.offsetY}px);">
{#each itemsToRender as item, i (item.id)}
{@const actualIndex = virtualData.startIndex + i}
<ListBoxMenuItem
id={item.id}
active={selectedId === item.id}
highlighted={highlightedIndex === actualIndex}
disabled={item.disabled}
on:click={(e) => {
if (item.disabled) {
e.stopPropagation();
return;
}
selectedId = item.id;
open = false;

if (filteredItems[actualIndex]) {
value = itemToString(filteredItems[actualIndex]);
}
}}
on:mouseenter={() => {
if (item.disabled) return;
highlightedIndex = actualIndex;
}}
>
<slot {item} index={actualIndex}>
{itemToString(item)}
</slot>
{#if selectedItem && selectedItem.id === item.id}
<Checkmark class="bx--list-box__menu-item__selected-icon" />
{/if}
</ListBoxMenuItem>
{/each}
</div>
</div>
{:else}
{#each itemsToRender as item, i (item.id)}
<ListBoxMenuItem
id={item.id}
active={selectedId === item.id}
highlighted={highlightedIndex === i}
disabled={item.disabled}
on:click={(e) => {
if (item.disabled) {
e.stopPropagation();
return;
}
selectedId = item.id;
open = false;

if (filteredItems[i]) {
value = itemToString(filteredItems[i]);
}
}}
on:mouseenter={() => {
if (item.disabled) return;
highlightedIndex = i;
}}
>
<slot {item} index={i}>
{itemToString(item)}
</slot>
{#if selectedItem && selectedItem.id === item.id}
<Checkmark class="bx--list-box__menu-item__selected-icon" />
{/if}
</ListBoxMenuItem>
{/each}
if (filteredItems[i]) {
value = itemToString(filteredItems[i]);
}
}}
on:mouseenter={() => {
if (item.disabled) return;
highlightedIndex = i;
}}
>
<slot {item} index={i}>
{itemToString(item)}
</slot>
{#if selectedItem && selectedItem.id === item.id}
<Checkmark class="bx--list-box__menu-item__selected-icon" />
{/if}
</ListBoxMenuItem>
{/each}
{/if}
</ListBoxMenu>
{/if}
</ListBox>
Expand Down
1 change: 0 additions & 1 deletion src/MultiSelect/MultiSelect.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,6 @@
name={item.id}
title={useTitleInItem ? itemToString(item) : undefined}
{...itemToInput(item)}
readonly
tabindex="-1"
id="checkbox-{item.id}"
checked={item.checked}
Expand Down
35 changes: 35 additions & 0 deletions src/utils/virtualize.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export interface VirtualizeConfig {
/** Full array of items to virtualize */
items: any[];
/** Height of each item in pixels */
itemHeight: number;
/** Visible container height in pixels */
containerHeight: number;
/** Current scroll position */
scrollTop: number;
/** Extra items to render above/below viewport (default: 3) */
overscan?: number;
/** Cap maximum rendered items */
maxItems?: number;
/** Minimum items before virtualization activates (default: 100) */
threshold?: number;
}

export interface VirtualizeResult<T = any> {
/** Items to render in the current viewport */
visibleItems: T[];
/** Index of first visible item */
startIndex: number;
/** Index after last visible item */
endIndex: number;
/** Y offset for positioning visible items */
offsetY: number;
/** Total height of all items */
totalHeight: number;
/** Whether virtualization is active */
isVirtualized: boolean;
}

export function virtualize<T = any>(
config: VirtualizeConfig,
): VirtualizeResult<T>;
Loading