Files
heroui-vue/packages/vue/src/components/list-box/ListBox.vue
T
maoyingjie 9e8d89e48d feat(collections): virtual row layout with variable heights, headings, loader and gap/padding
ListBox virtualized mode grows a full row stream (padding spacers, data-driven
heading rows, item rows, #loader row) with px semantics mapped from the pinned
ListLayout contract: rowHeight may be a per-index function falling back to
estimatedRowHeight, gap sits between content rows only, padding is end
spacers, and every input is re-read per layout pass. Scroll ownership resolves
to the list root or the nearest scrolling ancestor so popovers scroll as a
whole with a sticky search field (data-virtualized hook; the historical 320px
self-scroll rule stays for non-virtualized lists).

Table gains the public useVirtualRows/bindVirtualRows pure geometry helpers
(prefix sums + binary search, no state kernel): variable heights, estimated
fallback, gap/padding and a loader reservation that stays consistent with the
rendered spacers. headingHeight and dropIndicatorThickness remain unavailable
(no sectioned header model, no drag-and-drop) and are recorded as such.

Pinned demo values stay explicit (table 42px, list-box/autocomplete 50px);
the table demo scrolls an outer viewport div because a native table cannot be
a scroll container (verified: 300px height blown out to 45036px).
2026-10-29 16:21:09 +08:00

831 lines
26 KiB
Vue

<script setup lang="ts" generic="T extends ListBoxDataItem = ListBoxDataItem">
import {
computed,
inject,
getCurrentInstance,
mergeProps,
nextTick,
onBeforeUpdate,
onBeforeUnmount,
onMounted,
provide,
ref,
shallowRef,
useAttrs,
useSlots,
watch,
watchEffect,
} from "vue";
import { useVirtualList } from "@vueuse/core";
import { listboxVariants } from "@heroui-vue/styles";
import { useConfig } from "../../providers/context";
import Header from "../header/HeaderRoot.vue";
import { useInheritedDisabled, disabledContextKey } from "../field/disabled";
import { useCollectionSelection } from "../collection/selection";
import { useCollectionRegistry } from "../collection/registry";
import { collectionOwnerKey } from "../collection/owner";
import { assertKey } from "../collection/keys";
import {
listBoxKey,
type ListBoxDataItem,
type ListBoxOptions,
type ListBoxKey,
type ListBoxMember,
} from "./context";
defineOptions({ name: "ListBox", inheritAttrs: false });
const props = withDefaults(defineProps<ListBoxOptions<T>>(), {
selectionMode: "single",
selectionBehavior: "toggle",
orientation: "vertical",
variant: "default",
as: "div",
rowHeight: 50,
headingHeight: 48,
loaderHeight: 48,
gap: 0,
padding: 0,
overscan: 5,
});
const owner = inject(collectionOwnerKey, undefined);
provide(collectionOwnerKey, undefined);
const mode = computed(() => owner?.mode.value ?? props.selectionMode);
const behavior = computed(() =>
owner
? mode.value === "single"
? "replace"
: "toggle"
: props.selectionBehavior,
);
const readOnly = computed(() => props.isReadOnly || !!owner?.readOnly.value);
const disabledKeys = computed(() => [
...(props.disabledKeys ?? []),
...(owner?.disabledKeys.value ?? []),
]);
const emit = defineEmits<{
"update:modelValue": [keys: ListBoxKey[]];
selectionChange: [keys: ListBoxKey[]];
action: [key: ListBoxKey];
}>();
defineSlots<{
default?: (props: { item: T; index: number }) => unknown;
empty?: () => unknown;
loader?: () => unknown;
}>();
const slots = useSlots();
const attrs = useAttrs();
const instance = getCurrentInstance()!;
const modelPresence = () =>
["modelValue", "model-value"].some((key) =>
Object.hasOwn(instance.vnode.props ?? {}, key),
);
const selectedPresence = () =>
["selectedKeys", "selected-keys"].some((key) =>
Object.hasOwn(instance.vnode.props ?? {}, key),
);
const controlled = ref(modelPresence() || selectedPresence());
const hasModel = ref(modelPresence());
onBeforeUpdate(() => {
hasModel.value = modelPresence();
controlled.value = hasModel.value || selectedPresence();
});
const config = useConfig();
const disabled = useInheritedDisabled(
() => props.isDisabled || owner?.disabled.value,
);
provide(disabledContextKey, disabled);
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
// Optional owner-driven view: filtering and virtual focus stay off unless the
// composite asks for them, so standalone ListBox and Select are unchanged.
const virtualFocus = computed(() => !!owner?.virtualFocus?.());
const ownerFilter = computed(() => owner?.filter);
const registry = useCollectionRegistry<ListBoxMember>();
const mounted = ref(false);
let disconnectOwner: (() => void) | undefined;
onMounted(() => {
mounted.value = true;
if (owner)
disconnectOwner = owner.connect({
items: known,
optionId,
reveal,
focus: async (edge) => {
const available = eligible();
const key =
edge === "last"
? available.at(-1)?.key
: edge === "first"
? available[0]?.key
: (available.find((item) => selection.selected(item.key))?.key ??
available[0]?.key);
if (key !== undefined) await focus(key);
else root.value?.focus();
},
});
});
const data = computed(() => {
const seen = new Set<ListBoxKey>();
return props.items?.map((item) => {
assertKey(item.id);
if (seen.has(item.id))
throw new Error(`Duplicate collection key: ${item.id}`);
seen.add(item.id);
return {
key: item.id,
disabled: !!item.isDisabled || !!disabledKeys.value.includes(item.id),
text: item.textValue ?? "",
};
});
});
const keyDisabled = (key: ListBoxKey) =>
disabled.value ||
!!disabledKeys.value.includes(key) ||
!!data.value?.find((item) => item.key === key)?.disabled;
const known = () => {
const members = registry.ordered();
return (
data.value?.map((item) => ({
...item,
text:
item.text ||
members.find((member) => member.key() === item.key)?.textValue() ||
"",
disabled:
item.disabled ||
!!members.find((member) => member.key() === item.key)?.disabled(),
})) ??
members.map((member) => ({
key: member.key(),
disabled: member.disabled(),
text: member.textValue(),
}))
);
};
/** Full data set with the owner filter applied: display and navigation only. */
const visibleKnown = () => {
const filter = ownerFilter.value;
const items = known();
return filter ? items.filter((item) => filter(item)) : items;
};
const visibleKeys = computed(
() => new Set(visibleKnown().map((item) => item.key)),
);
const eligible = () => visibleKnown().filter((item) => !item.disabled);
/** Empty channel needs a settled collection: static children register on mount. */
const visibleIsEmpty = computed(
() => visibleKeys.value.size === 0 && (!!props.items || mounted.value),
);
// A removed, disabled or filtered-out row cannot stay active. The collection
// clears the shared active key (it never invents a value) and leaves the next
// candidate to the composite; a closed collection has no active row at all.
watchEffect(() => {
if (!virtualFocus.value || !mounted.value) return;
const activeRef = owner?.activeKey;
if (!activeRef || activeRef.value === undefined) return;
const key = activeRef.value;
void visibleKeys.value;
if (
owner?.isOpen?.() === false ||
!eligible().some((item) => item.key === key)
)
activeRef.value = undefined;
});
const blockedKeys = computed(() =>
known()
.filter((item) => item.disabled)
.map((item) => item.key),
);
const selection = useCollectionSelection({
mode: () => mode.value,
controlled: () => !!owner || controlled.value,
value: () =>
owner?.keys.value ??
(hasModel.value ? props.modelValue : props.selectedKeys),
defaultValue: props.defaultValue ?? props.defaultSelectedKeys,
disabled: () => disabled.value,
readOnly: () => readOnly.value,
disabledKeys: () => blockedKeys.value,
disallowEmptySelection: () => props.disallowEmptySelection,
onChange: (keys) => {
owner?.request(keys);
emit("update:modelValue", [...keys]);
emit("selectionChange", [...keys]);
},
});
const focused = ref<ListBoxKey>();
const lastFocused = ref<ListBoxKey>();
const pressed = ref<ListBoxKey>();
// Pointer presses clear keyboard intent; the composite sets it again on keys.
const keyboard = owner?.keyboardIntent ?? ref(true);
const active = computed(() => {
if (virtualFocus.value && owner?.activeKey) return owner.activeKey.value;
if (!mounted.value) return undefined;
const items = eligible();
return (
items.find((item) => item.key === lastFocused.value)?.key ??
items.find((item) => mode.value !== "none" && selection.selected(item.key))
?.key ??
items[0]?.key
);
});
/**
* Items as the caller passed them, restricted to the visible subset. The full
* data set stays available through `known()` for text and accepted values.
*/
const visibleItems = computed(() => {
const items = props.items ? [...props.items] : [];
const filter = ownerFilter.value;
if (!items.length || !filter) return items;
const visible = visibleKeys.value;
return items.filter((item) => visible.has(item.id));
});
const source = computed(() => visibleItems.value);
/**
* Virtualized row stream: padding spacers, optional heading rows (from the
* item `heading` field), the item rows themselves and an optional loader row.
* Row heights are px and re-read on every layout pass, so reactive heights or
* props update the window without a remount. `gap` is the spacing between
* content rows (item/heading/loader), counted into the earlier row's wrapper
* height to keep one geometry source; padding spacers carry no gap.
* `padding` renders as spacer rows at both ends.
*/
type VirtualRow =
| { key: string; kind: "pad"; height: number }
| { key: string; kind: "heading"; height: number; text: string }
| { key: string; kind: "item"; height: number; item: T; index: number }
| { key: string; kind: "loader"; height: number };
const fallbackRowHeight = computed(
() =>
props.estimatedRowHeight ??
(typeof props.rowHeight === "number" ? props.rowHeight : 50),
);
const virtualRows = computed<VirtualRow[]>(() => {
const items = source.value as T[];
const gap = props.gap > 0 ? props.gap : 0;
const rows: VirtualRow[] = [];
const push = (row: VirtualRow) => {
// Gap sits between content rows only (pinned ListLayout semantics).
const prev = rows[rows.length - 1];
if (row.kind !== "pad" && prev && prev.kind !== "pad") prev.height += gap;
rows.push(row);
};
if (props.padding > 0)
push({ key: "pad-top", kind: "pad", height: props.padding });
items.forEach((item, index) => {
if (item.heading)
push({
key: `heading-${index}`,
kind: "heading",
height: props.headingHeight,
text: item.heading,
});
const height =
(typeof props.rowHeight === "function"
? props.rowHeight(index)
: props.rowHeight) ?? fallbackRowHeight.value;
push({ key: `item-${item.id}`, kind: "item", height, item, index });
});
if (slots.loader)
push({ key: "loader", kind: "loader", height: props.loaderHeight });
if (props.padding > 0)
push({ key: "pad-bottom", kind: "pad", height: props.padding });
return rows;
});
/** Row stream index for a logical item index (headings/pads shift the row). */
function rowIndexOfItem(index: number): number {
return virtualRows.value.findIndex(
(row) => row.kind === "item" && row.index === index,
);
}
// VueUse owns measurement, scroll range and cleanup; one logical collection
// remains available for select-all/typeahead even while most rows are unmounted.
const {
list: windowItems,
containerProps,
wrapperProps,
scrollTo,
} = useVirtualList(virtualRows, {
itemHeight: (rowIndex: number) =>
virtualRows.value[rowIndex]?.height ?? fallbackRowHeight.value,
overscan: props.overscan,
});
const root = shallowRef<HTMLElement | null>(null);
/**
* The scroll container drives the virtual window: the list root when it
* scrolls itself (fixed rows inside a sized box) and the nearest scrolling
* ancestor otherwise (popover-wide scrolling with sticky chrome, like the
* pinned autocomplete example).
*/
function resolveScrollParent(): HTMLElement | null {
const el = root.value;
if (!el) return null;
const scrolls = (node: HTMLElement) => {
const overflowY = getComputedStyle(node).overflowY;
return (
(overflowY === "auto" || overflowY === "scroll") &&
node.scrollHeight > node.clientHeight + 1
);
};
if (scrolls(el)) return el;
for (let node = el.parentElement; node; node = node.parentElement)
if (scrolls(node)) return node;
return el;
}
let scrollParent: HTMLElement | null = null;
function onVirtualScroll() {
containerProps.onScroll();
}
watch(
root,
(el) => {
scrollParent?.removeEventListener("scroll", onVirtualScroll);
scrollParent = null;
if (!el || !props.virtualized) return;
const parent = resolveScrollParent();
if (!parent) return;
scrollParent = parent;
containerProps.ref.value = parent;
parent.addEventListener("scroll", onVirtualScroll, { passive: true });
},
{ flush: "post" },
);
onBeforeUnmount(() => {
scrollParent?.removeEventListener("scroll", onVirtualScroll);
scrollParent = null;
});
let restoringFocus = false;
function restoreFocus() {
restoringFocus = true;
root.value?.focus({ preventScroll: true });
restoringFocus = false;
}
let focusRequest = 0;
let disposing = false;
onBeforeUnmount(() => {
disconnectOwner?.();
disposing = true;
focusRequest++;
});
/** Mounted DOM id of an option; undefined while a virtualized row is unmounted. */
function optionId(key: ListBoxKey): string | undefined {
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
return element?.id || undefined;
}
const nextFrame = (): Promise<void> =>
typeof requestAnimationFrame === "function"
? new Promise((resolve) => requestAnimationFrame(() => resolve()))
: nextTick();
/** A virtualized row mounts after the window moves; wait for real DOM, bounded. */
async function waitForMountedRow(key: ListBoxKey, valid: () => boolean) {
for (let attempt = 0; attempt < 3; attempt++) {
if (!valid()) return;
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
if (element?.isConnected) return;
await nextFrame();
}
}
/** Row stream top offset in px (sum of the heights before the row). */
function rowOffsetOf(rowIndex: number): number {
let top = 0;
for (let i = 0; i < rowIndex; i++) top += virtualRows.value[i]!.height;
return top;
}
/**
* Bring a row into view without taking DOM focus. Virtualized lists move the
* window by row offset (item rows may sit behind heading/padding rows); the
* scroll container may be any scrolling ancestor; ordinary lists scroll the
* mounted row (the row itself may sit inside any scroll container supplied by
* the caller).
*/
async function revealRow(key: ListBoxKey, valid: () => boolean) {
// Every side effect is guarded: filtering, closing, unmounting or a newer
// request invalidates the work that is still awaiting.
if (!valid()) return;
if (props.virtualized) {
const index = source.value.findIndex((item) => item.id === key);
if (index < 0 || !valid()) return;
const rowIndex = rowIndexOfItem(index);
if (rowIndex < 0) return;
const row = virtualRows.value[rowIndex]!;
const rowTop = rowOffsetOf(rowIndex);
const element = scrollParent ?? root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + row.height > element.scrollTop + element.clientHeight)
) {
if (!valid()) return;
scrollTo(rowIndex);
}
await waitForMountedRow(key, valid);
return;
}
await nextTick();
if (!valid()) return;
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
if (!valid() || !element?.isConnected) return;
element.scrollIntoView?.({ block: "nearest" });
}
let revealRequest = 0;
/**
* A request stays valid only while it is the newest one, the row is still
* visible/enabled, the collection is open and the component is alive.
*/
function revealToken(key: ListBoxKey) {
const request = ++revealRequest;
return () =>
!disposing &&
request === revealRequest &&
!disabled.value &&
owner?.isOpen?.() !== false &&
eligible().some((item) => item.key === key);
}
/** Reveal a row without taking DOM focus (virtual focus / activedescendant). */
async function reveal(key: ListBoxKey) {
const valid = revealToken(key);
if (!valid()) return;
lastFocused.value = key;
await revealRow(key, valid);
}
async function focus(key: ListBoxKey) {
if (
disposing ||
disabled.value ||
!eligible().some((item) => item.key === key)
)
return;
const request = ++focusRequest;
lastFocused.value = key;
if (virtualFocus.value) {
const valid = revealToken(key);
if (!valid()) return;
if (owner?.activeKey && owner.activeKey.value !== key)
owner.activeKey.value = key;
await revealRow(key, valid);
return;
}
await revealRow(
key,
() => !disposing && !disabled.value && request === focusRequest,
);
if (disposing || request !== focusRequest || disabled.value) return;
const element = registry
.available()
.find((member) => member.key() === key)
?.element();
element?.focus({ preventScroll: true });
element?.scrollIntoView?.({ block: "nearest" });
}
let anchor: ListBoxKey | undefined;
function activate(key: ListBoxKey, event: MouseEvent | KeyboardEvent) {
const item = known().find((entry) => entry.key === key);
if (
event.defaultPrevented ||
disabled.value ||
readOnly.value ||
!item ||
item.disabled
)
return;
if (mode.value === "multiple" && event.shiftKey) {
anchor ??= selection.keys.value[0] ?? active.value ?? key;
selectRange(anchor, key);
} else if (behavior.value === "replace" && !event.ctrlKey && !event.metaKey)
selection.replace(key);
else selection.toggle(key);
if (!event.shiftKey) anchor = key;
owner?.action(key);
emit("action", key);
}
function selectRange(startKey: ListBoxKey, endKey: ListBoxKey) {
const items = eligible();
const start = items.findIndex((item) => item.key === startKey),
end = items.findIndex((item) => item.key === endKey);
if (start < 0 || end < 0) return;
selection.request([
...selection.keys.value.filter(selection.disabled),
...items
.slice(Math.min(start, end), Math.max(start, end) + 1)
.map((item) => item.key),
]);
}
let search = "",
lastSearch = 0;
let pendingSpace: ListBoxKey | undefined;
function keydown(event: KeyboardEvent) {
if (
virtualFocus.value ||
event.defaultPrevented ||
event.isComposing ||
event.keyCode === 229 ||
disabled.value ||
(event.target as Element).closest("[data-hv-listbox]") !== root.value
)
return;
if (
owner &&
event.key === "Tab" &&
!event.altKey &&
!event.ctrlKey &&
!event.metaKey
) {
owner.leave();
return;
}
keyboard.value = true;
const items = eligible();
if (!items.length) return;
if (
(event.ctrlKey || event.metaKey) &&
event.key.toLowerCase() === "a" &&
mode.value === "multiple"
) {
event.preventDefault();
selection.selectAll(items.map((item) => item.key));
return;
}
if (event.altKey) return;
if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) return;
const index = items.findIndex((item) => item.key === active.value);
let target: number | undefined;
const backward =
props.orientation === "vertical"
? "ArrowUp"
: dir.value === "rtl"
? "ArrowRight"
: "ArrowLeft";
const forward =
props.orientation === "vertical"
? "ArrowDown"
: dir.value === "rtl"
? "ArrowLeft"
: "ArrowRight";
if (event.key === "Home") target = 0;
else if (event.key === "End") target = items.length - 1;
else if (event.key === "PageUp" || event.key === "PageDown") {
const current = registry
.ordered()
.find((member) => member.key() === active.value)
?.element();
const activeHeight =
(typeof props.rowHeight === "function"
? props.rowHeight(index)
: props.rowHeight) ?? fallbackRowHeight.value;
const height = props.virtualized
? activeHeight
: current?.getBoundingClientRect().height || activeHeight;
const page = Math.max(
1,
Math.floor((root.value?.clientHeight ?? 0) / height),
);
target = index + (event.key === "PageDown" ? page : -page);
} else if (event.key === backward) target = index - 1;
else if (event.key === forward) target = index + 1;
if (target !== undefined) {
event.preventDefault();
target = props.loop
? (target + items.length) % items.length
: Math.max(0, Math.min(target, items.length - 1));
const key = items[target].key;
if (event.shiftKey && mode.value === "multiple") {
anchor ??= active.value;
if (anchor !== undefined) selectRange(anchor, key);
} else if (
behavior.value === "replace" &&
!event.ctrlKey &&
!event.metaKey
) {
selection.replace(key);
anchor = key;
}
void focus(key);
return;
}
if (
event.key === "Enter" ||
(event.key === " " && (Date.now() - lastSearch > 1000 || !search))
) {
if (event.repeat) {
event.preventDefault();
return;
}
if (readOnly.value) {
event.preventDefault();
return;
}
pressed.value = active.value;
if (event.key === " ") {
pendingSpace = active.value;
event.preventDefault();
return;
}
if (active.value !== undefined)
registry
.ordered()
.find((member) => member.key() === active.value)
?.activate(event);
event.preventDefault();
return;
}
if (event.ctrlKey || event.metaKey || event.key.length !== 1) return;
const now = Date.now();
search = now - lastSearch > 1000 ? event.key : search + event.key;
lastSearch = now;
const query = [...search].every((char) => char === search[0])
? search[0]
: search;
const collator = new Intl.Collator(config?.locale.value, {
usage: "search",
sensitivity: "base",
});
const searchItems =
query.length > 1 && items[index]
? [items[index], ...items.slice(index + 1), ...items.slice(0, index)]
: [...items.slice(index + 1), ...items.slice(0, index + 1)];
const match = searchItems.find(
(item) => collator.compare(item.text.slice(0, query.length), query) === 0,
);
if (match) {
event.preventDefault();
void focus(match.key);
}
}
function keyup(event: KeyboardEvent) {
if (virtualFocus.value) return;
if (event.key !== " ") return;
const key = pendingSpace;
pendingSpace = undefined;
if (
!event.defaultPrevented &&
key !== undefined &&
contextOwnsEvent(event) &&
focused.value === key
) {
registry
.ordered()
.find((member) => member.key() === key)
?.activate(event);
event.preventDefault();
}
}
function contextOwnsEvent(event: KeyboardEvent) {
return (event.target as Element).closest("[data-hv-listbox]") === root.value;
}
provide(listBoxKey, {
mode: computed(() => mode.value),
readOnly: computed(() => readOnly.value),
keyboard,
focused,
noteFocus: (key) => {
lastFocused.value = key;
focused.value = key;
},
pressed,
active,
selected: (key) => mode.value !== "none" && selection.selected(key),
disabled: keyDisabled,
register: registry.register,
activate,
focus,
virtualized: () => props.virtualized,
virtual: () => virtualFocus.value,
visible: (key) => visibleKeys.value.has(key),
optionId,
restoreFocus,
position: (key) => {
if (!props.virtualized || !data.value) return undefined;
const items = visibleItems.value;
return {
index: items.findIndex((item) => item.id === key) + 1,
size: items.length,
};
},
});
function rootAttrs() {
if (mode.value === "single" && selection.keys.value.length > 1)
throw new TypeError("Single ListBox accepts at most one selected key.");
if (
props.virtualized &&
(!props.items ||
props.orientation !== "vertical" ||
(typeof props.rowHeight === "number" && props.rowHeight <= 0))
)
throw new Error(
"Virtualized ListBox requires items, vertical orientation and a positive rowHeight.",
);
// Force duplicate validation even when a scoped item renderer is absent.
void data.value;
return mergeProps(attrs, {
id: owner?.id ?? attrs.id,
"aria-label": attrs["aria-label"] ?? owner?.ariaLabel(),
"aria-labelledby":
attrs["aria-labelledby"] ??
((attrs["aria-label"] ?? owner?.ariaLabel())
? undefined
: owner?.labelledBy()),
class: listboxVariants({ variant: props.variant }),
role: "listbox",
dir: dir.value,
"data-slot": "list-box",
"data-hv-listbox": "",
// Styling hook: virtualized lists bind their row window to a scrolling
// ancestor and must not be forced into a self-scrolling box.
"data-virtualized": props.virtualized ? "" : undefined,
"data-disabled": disabled.value || undefined,
"aria-disabled": disabled.value || undefined,
"aria-readonly": readOnly.value || undefined,
"aria-orientation": props.orientation,
"aria-multiselectable":
mode.value === "none" ? undefined : mode.value === "multiple",
tabindex:
virtualFocus.value ||
disabled.value ||
(mounted.value &&
registry.available().some((member) => member.key() === active.value))
? -1
: 0,
onKeydown: keydown,
onKeyup: keyup,
onKeyupCapture: () => {
pressed.value = undefined;
},
onFocusout: (event: FocusEvent) => {
if (!root.value?.contains(event.relatedTarget as Node | null)) {
pressed.value = undefined;
pendingSpace = undefined;
}
},
onPointerdownCapture: () => {
keyboard.value = false;
},
onFocus: (event: FocusEvent) => {
if (
!restoringFocus &&
event.target === root.value &&
active.value !== undefined
)
void focus(active.value);
},
// Virtualized scrolling is owned by the resolved scroll parent (native
// listener); the root itself needs no scroll handler.
});
}
defineExpose({
element: root,
focus: (key?: ListBoxKey) =>
key === undefined ? root.value?.focus() : focus(key),
selectAll: () => selection.selectAll(eligible().map((item) => item.key)),
});
</script>
<template>
<component :is="as" ref="root" v-bind="rootAttrs()">
<template v-if="!items">
<!-- Static slots keep every member mounted (so text and selection
survive filtering); the empty channel is additive. -->
<slot v-if="visibleIsEmpty" name="empty" />
<slot :item="undefined!" :index="-1" />
</template>
<template v-else>
<slot v-if="!visibleItems.length" name="empty" />
<div
v-if="virtualized"
v-bind="wrapperProps"
role="presentation"
data-slot="list-box-virtual-content"
>
<div
v-for="entry in windowItems"
:key="entry.data.key"
role="presentation"
:style="{ height: `${entry.data.height}px` }"
>
<div v-if="entry.data.kind === 'pad'" aria-hidden="true" />
<Header v-else-if="entry.data.kind === 'heading'">
{{ entry.data.text }}
</Header>
<slot
v-else-if="entry.data.kind === 'item'"
:item="entry.data.item"
:index="entry.data.index"
/>
<slot v-else name="loader" />
</div>
</div>
<template v-else v-for="(item, index) in items" :key="item.id">
<slot :item="item" :index="index" />
</template>
</template>
</component>
</template>