feat: migrate ListBox with virtual collection and accessible parts

This commit is contained in:
maoyingjie
2026-10-23 15:02:30 +08:00
parent dea5ded716
commit 65db60a7ac
39 changed files with 2694 additions and 12 deletions
@@ -0,0 +1,496 @@
<script setup lang="ts" generic="T extends ListBoxDataItem = ListBoxDataItem">
import {
computed,
getCurrentInstance,
mergeProps,
nextTick,
onBeforeUpdate,
onBeforeUnmount,
onMounted,
provide,
ref,
useAttrs,
} from "vue";
import { useVirtualList } from "@vueuse/core";
import { listboxVariants } from "@heroui-vue/styles";
import { useConfig } from "../../providers/context";
import { useInheritedDisabled, disabledContextKey } from "../field/disabled";
import { useCollectionSelection } from "../collection/selection";
import { useCollectionRegistry } from "../collection/registry";
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,
overscan: 5,
});
const emit = defineEmits<{
"update:modelValue": [keys: ListBoxKey[]];
selectionChange: [keys: ListBoxKey[]];
action: [key: ListBoxKey];
}>();
defineSlots<{
default?: (props: { item: T; index: number }) => unknown;
empty?: () => unknown;
}>();
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);
provide(disabledContextKey, disabled);
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
const registry = useCollectionRegistry<ListBoxMember>();
const mounted = ref(false);
onMounted(() => {
mounted.value = true;
});
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 || !!props.disabledKeys?.includes(item.id),
text: item.textValue ?? "",
};
});
});
const keyDisabled = (key: ListBoxKey) =>
disabled.value ||
!!props.disabledKeys?.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(),
}))
);
};
const eligible = () => known().filter((item) => !item.disabled);
const blockedKeys = computed(() =>
known()
.filter((item) => item.disabled)
.map((item) => item.key),
);
const selection = useCollectionSelection({
mode: () => props.selectionMode,
controlled: () => controlled.value,
value: () => (hasModel.value ? props.modelValue : props.selectedKeys),
defaultValue: props.defaultValue ?? props.defaultSelectedKeys,
disabled: () => disabled.value,
readOnly: () => props.isReadOnly,
disabledKeys: () => blockedKeys.value,
disallowEmptySelection: () => props.disallowEmptySelection,
onChange: (keys) => {
emit("update:modelValue", [...keys]);
emit("selectionChange", [...keys]);
},
});
const focused = ref<ListBoxKey>();
const lastFocused = ref<ListBoxKey>();
const pressed = ref<ListBoxKey>();
const keyboard = ref(true);
const active = computed(() => {
if (!mounted.value) return undefined;
const items = eligible();
return (
items.find((item) => item.key === lastFocused.value)?.key ??
items.find(
(item) => props.selectionMode !== "none" && selection.selected(item.key),
)?.key ??
items[0]?.key
);
});
const source = computed(() => (props.items ? [...props.items] : []));
// 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(source, {
itemHeight: () => props.rowHeight,
overscan: props.overscan,
});
const root = containerProps.ref;
let restoringFocus = false;
function restoreFocus() {
restoringFocus = true;
root.value?.focus({ preventScroll: true });
restoringFocus = false;
}
let focusRequest = 0;
let disposing = false;
onBeforeUnmount(() => {
disposing = true;
focusRequest++;
});
async function focus(key: ListBoxKey) {
if (
disposing ||
disabled.value ||
!eligible().some((item) => item.key === key)
)
return;
const request = ++focusRequest;
lastFocused.value = key;
if (props.virtualized) {
const index = source.value.findIndex((item) => item.id === key);
const rowTop = index * props.rowHeight;
const element = root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
)
scrollTo(index);
}
await nextTick();
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 ||
props.isReadOnly ||
!item ||
item.disabled
)
return;
if (props.selectionMode === "multiple" && event.shiftKey) {
anchor ??= selection.keys.value[0] ?? active.value ?? key;
selectRange(anchor, key);
} else if (
props.selectionBehavior === "replace" &&
!event.ctrlKey &&
!event.metaKey
)
selection.replace(key);
else selection.toggle(key);
if (!event.shiftKey) anchor = 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 (
event.defaultPrevented ||
event.isComposing ||
event.keyCode === 229 ||
disabled.value ||
(event.target as Element).closest("[data-hv-listbox]") !== root.value
)
return;
keyboard.value = true;
const items = eligible();
if (!items.length) return;
if (
(event.ctrlKey || event.metaKey) &&
event.key.toLowerCase() === "a" &&
props.selectionMode === "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 height = props.virtualized
? props.rowHeight
: current?.getBoundingClientRect().height || props.rowHeight;
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 && props.selectionMode === "multiple") {
anchor ??= active.value;
if (anchor !== undefined) selectRange(anchor, key);
} else if (
props.selectionBehavior === "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 (props.isReadOnly) {
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 (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(() => props.selectionMode),
readOnly: computed(() => props.isReadOnly),
keyboard,
focused,
noteFocus: (key) => {
lastFocused.value = key;
focused.value = key;
},
pressed,
active,
selected: (key) => props.selectionMode !== "none" && selection.selected(key),
disabled: keyDisabled,
register: registry.register,
activate,
focus,
virtualized: () => props.virtualized,
restoreFocus,
position: (key) =>
props.virtualized && data.value
? {
index: data.value.findIndex((item) => item.key === key) + 1,
size: data.value.length,
}
: undefined,
});
function rootAttrs() {
if (props.selectionMode === "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" || 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, {
class: listboxVariants({ variant: props.variant }),
role: "listbox",
dir: dir.value,
"data-slot": "list-box",
"data-hv-listbox": "",
"data-disabled": disabled.value || undefined,
"aria-disabled": disabled.value || undefined,
"aria-readonly": props.isReadOnly || undefined,
"aria-orientation": props.orientation,
"aria-multiselectable":
props.selectionMode === "none"
? undefined
: props.selectionMode === "multiple",
tabindex:
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);
},
onScroll: props.virtualized ? containerProps.onScroll : undefined,
});
}
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()">
<slot v-if="!items" :item="undefined!" :index="-1" />
<slot v-else-if="!items.length" name="empty" />
<div
v-else-if="virtualized"
v-bind="wrapperProps"
role="presentation"
data-slot="list-box-virtual-content"
>
<div
v-for="entry in windowItems"
:key="entry.data.id"
role="presentation"
:style="{ height: `${rowHeight}px` }"
>
<slot :item="entry.data" :index="entry.index" />
</div>
</div>
<template v-else v-for="(item, index) in items" :key="item.id">
<slot :item="item" :index="index" />
</template>
</component>
</template>