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,121 @@
/* Adapted from HeroUI ce90ea3. Apache-2.0; see third-party/HEROUI-LICENSE. */
/* ==========================================================================
Base list-box item styles
========================================================================== */
.hv-list-box-item {
@apply relative flex min-h-9 w-full items-center justify-start gap-3 rounded-2xl px-2 py-1.5 outline-none no-highlight;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
transform 250ms var(--ease-out-quart),
box-shadow 150ms var(--ease-out);
@apply motion-reduce:transition-none;
/* Cursor */
cursor: var(--cursor-interactive);
[data-slot="label"] {
@apply pointer-events-none w-fit select-none;
}
[data-slot="description"] {
@apply pointer-events-none text-wrap select-none;
}
/* Add inline-end padding when indicator is present */
&:has(.hv-list-box-item__indicator) {
@apply pe-7;
}
/* Focus visible state (keyboard focus only).
React Aria always sets data-focused when it owns the item, so the native
fallback is scoped to consumers rendering this class outside React Aria. */
&:focus-visible:not([data-focused]),
&[data-focus-visible="true"] {
@apply status-focused;
}
/* Focus state */
&:focus,
&[data-focus="true"] {
}
/* Pressed state */
&:active,
&[data-pressed="true"] {
transform: scale(0.98);
}
/* Hover state */
@media (hover: hover) {
&:hover,
&[data-hovered="true"] {
@apply bg-default;
}
}
/* Selected state */
&[aria-selected="true"],
&[data-selected="true"] {
}
/* Disabled state */
&[data-disabled="true"] {
@apply status-disabled;
}
}
/* ==========================================================================
List-box item indicator
========================================================================== */
.hv-list-box-item__indicator {
@apply absolute end-2 top-1/2 flex size-4 shrink-0 -translate-y-1/2 items-center justify-center text-default-foreground;
/**
* Transitions
*/
@apply transition duration-250 motion-reduce:transition-none;
/* Checkmark SVG indicator */
[data-slot="list-box-item-indicator--checkmark"] {
@apply size-2.5;
/**
* Transitions
*/
@apply transition-all duration-300 motion-reduce:transition-none;
}
.hv-list-box-item[aria-selected="true"]
[data-slot="list-box-item-indicator--checkmark"],
.hv-list-box-item[data-selected="true"]
[data-slot="list-box-item-indicator--checkmark"] {
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition: stroke-dashoffset 250ms linear;
@apply motion-reduce:transition-none;
}
}
/* Default variant */
.hv-list-box-item--default {
}
/* Danger variant */
.hv-list-box-item--danger {
.hv-list-box-item__indicator {
@apply text-danger;
}
[data-slot="label"] {
@apply text-danger;
}
}
@@ -0,0 +1,8 @@
/* Adapted from HeroUI ce90ea3. Apache-2.0; see third-party/HEROUI-LICENSE. */
/* ==========================================================================
Base list-box section styles
========================================================================== */
.hv-list-box-section {
@apply flex flex-col items-start gap-0;
}
+26
View File
@@ -0,0 +1,26 @@
/* Adapted from HeroUI ce90ea3. Apache-2.0; see third-party/HEROUI-LICENSE. */
/* ==========================================================================
Base list-box styles
========================================================================== */
.hv-list-box {
@apply relative w-full overflow-clip p-1;
/**
* Spacing between direct children.
*
* NOTE: We intentionally avoid `display: flex` + `gap` here because
* react-aria's Virtualizer renders a `position: relative` content
* div with an explicit large height (e.g. 50000px) as the only child
* of the ListBox. Flex shrinking would collapse that height and break
* scrollbar sizing during virtualized scroll.
*/
& > * + * {
@apply mt-1;
}
/* This makes the horizontal separator take up 94% of the width and be centered */
[data-slot="separator"][data-orientation="horizontal"] {
@apply ms-[3%] w-[94%];
}
}
+4
View File
@@ -141,3 +141,7 @@
@import "./components/number-field.css";
@import "./components/slider.css" layer(components);
@import "./components/list-box.css" layer(components);
@import "./components/list-box-item.css" layer(components);
@import "./components/list-box-section.css" layer(components);
+25
View File
@@ -1273,3 +1273,28 @@ export const sliderVariants = tv({
},
});
export type SliderVariants = VariantProps<typeof sliderVariants>;
// Adapted from HeroUI ce90ea3, Apache-2.0.
export const listboxVariants = tv({
base: "hv-list-box",
defaultVariants: { variant: "default" },
variants: {
variant: { default: "hv-list-box--default", danger: "hv-list-box--danger" },
},
});
export type ListBoxVariants = VariantProps<typeof listboxVariants>;
export const listboxItemVariants = tv({
slots: { item: "hv-list-box-item", indicator: "hv-list-box-item__indicator" },
defaultVariants: { variant: "default" },
variants: {
variant: {
default: { item: "hv-list-box-item--default" },
danger: { item: "hv-list-box-item--danger" },
},
},
});
export type ListBoxItemVariants = VariantProps<typeof listboxItemVariants>;
export const listboxSectionVariants = tv({ base: "hv-list-box-section" });
export type ListBoxSectionVariants = VariantProps<
typeof listboxSectionVariants
>;
@@ -10,10 +10,12 @@ export interface CollectionMember {
/** One registry per collection provider. No document queries or global IDs.
* Read order at interaction time: Vue can reorder nodes without changing refs. */
export function useCollectionRegistry() {
const members = shallowRef<readonly CollectionMember[]>([]);
export function useCollectionRegistry<
T extends CollectionMember = CollectionMember,
>() {
const members = shallowRef<readonly T[]>([]);
function ordered(): CollectionMember[] {
function ordered(): T[] {
const seen = new Set<CollectionKey>();
for (const member of members.value) {
const key = member.key();
@@ -32,7 +34,7 @@ export function useCollectionRegistry() {
});
}
function register(member: CollectionMember): () => void {
function register(member: T): () => void {
assertKey(member.key());
if (ordered().some((item) => item.key() === member.key())) {
throw new Error(`Duplicate collection key: ${member.key()}`);
@@ -52,7 +54,7 @@ export function useCollectionRegistry() {
key: CollectionKey | undefined,
intent: "first" | "last" | "next" | "previous",
loop = false,
): CollectionMember | undefined {
): T | undefined {
const items = available();
if (intent === "first") return items[0];
if (intent === "last") return items.at(-1);
@@ -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>
@@ -0,0 +1,212 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
mergeProps,
onBeforeUnmount,
provide,
ref,
type PropType,
type SlotsType,
type VNodeChild,
watchEffect,
} from "vue";
import { listboxItemVariants } from "@heroui-vue/styles";
import { useChoiceField } from "../choice/shared";
import {
listBoxItemKey,
useListBox,
type ListBoxKey,
type ListBoxItemState,
} from "./context";
import { mergeIds } from "../field/context";
export default defineComponent({
name: "ListBoxItem",
inheritAttrs: false,
slots: Object as SlotsType<{
default: (state: ListBoxItemState) => VNodeChild[];
}>,
props: {
/** Collection identity, distinct from the generated DOM id. */
id: { type: [String, Number] as PropType<ListBoxKey>, required: true },
textValue: String,
isDisabled: Boolean,
variant: {
type: String as PropType<"default" | "danger">,
default: "default",
},
as: { type: String, default: "div" },
},
emits: {
select: (
_event: CustomEvent<{
key: ListBoxKey;
originalEvent: MouseEvent | KeyboardEvent;
}>,
) => true,
},
setup(props, { attrs, slots, emit, expose }) {
const context = useListBox();
const element = ref<HTMLElement>();
const hovered = ref(false),
pressed = ref(false);
const disabled = computed(
() => props.isDisabled || context.disabled(props.id),
);
// Isolate option labels/descriptions from a surrounding Select/Form field.
const text = useChoiceField(
{
get isDisabled() {
return disabled.value;
},
},
{},
{
kind: "group",
value: computed(() => props.id),
satisfied: () => true,
requiredMessage: "",
},
);
const state = () => ({
isSelected: context.selected(props.id),
isDisabled: disabled.value,
isFocused: context.focused.value === props.id,
isFocusVisible:
context.focused.value === props.id &&
(context.keyboard.value || !!element.value?.matches(":focus-visible")),
isPressed:
(pressed.value || context.pressed.value === props.id) &&
!disabled.value,
isHovered: hovered.value && !disabled.value,
});
provide(listBoxItemKey, state);
const remove = context.register({
key: () => props.id,
element: () => element.value,
textValue: () =>
props.textValue ??
element.value
?.querySelector('[data-slot="label"]')
?.textContent?.trim() ??
element.value?.textContent?.trim() ??
"",
disabled: () => disabled.value,
activate: click,
});
onBeforeUnmount(() => {
const hadFocus =
element.value?.ownerDocument.activeElement === element.value;
remove();
if (hadFocus) {
if (context.virtualized()) context.restoreFocus();
else {
context.focused.value = undefined;
const key = context.active.value;
if (key !== undefined) void context.focus(key);
else context.restoreFocus();
}
}
});
watchEffect((cleanup) => {
if (!pressed.value || !element.value) return;
const document = element.value.ownerDocument;
const release = () => {
pressed.value = false;
};
document.addEventListener("pointerup", release, true);
document.addEventListener("pointercancel", release, true);
cleanup(() => {
document.removeEventListener("pointerup", release, true);
document.removeEventListener("pointercancel", release, true);
});
});
watchEffect(() => {
if (
disabled.value &&
element.value?.ownerDocument.activeElement === element.value
) {
const key = context.active.value;
if (key !== undefined && key !== props.id) void context.focus(key);
else context.restoreFocus();
}
});
function click(event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || disabled.value || context.readOnly.value)
return;
const select = new CustomEvent("select", {
cancelable: true,
detail: { key: props.id, originalEvent: event },
});
emit("select", select);
if (select.defaultPrevented) return;
context.activate(props.id, event);
void context.focus(props.id);
}
expose({ element, focus: () => context.focus(props.id) });
return () => {
const current = state();
const position = context.position(props.id);
const children = text.prepare(slots.default?.(current) ?? [], true);
return h(
props.as,
mergeProps(attrs, {
ref: element,
id: text.field.controlId.value,
role: "option",
class: listboxItemVariants({
variant: props.variant,
}).item(),
tabindex:
!disabled.value && context.active.value === props.id ? 0 : -1,
"aria-selected":
context.mode.value === "none" ? undefined : current.isSelected,
"aria-disabled": disabled.value || undefined,
"aria-posinset": attrs["aria-posinset"] ?? position?.index,
"aria-setsize": attrs["aria-setsize"] ?? position?.size,
"aria-labelledby":
attrs["aria-labelledby"] ??
(attrs["aria-label"] ? undefined : text.labelledBy()),
"aria-describedby": mergeIds(
attrs["aria-describedby"] as string | undefined,
text.describedBy(),
),
"data-slot": "list-box-item",
"data-disabled": disabled.value || undefined,
"data-selected": current.isSelected || undefined,
"data-focused": current.isFocused || undefined,
"data-focus-visible": current.isFocusVisible || undefined,
"data-hovered": current.isHovered || undefined,
"data-pressed": current.isPressed || undefined,
onClick: click,
onFocus: () => {
if (!disabled.value) context.noteFocus(props.id);
},
onBlur: () => {
if (context.focused.value === props.id)
context.focused.value = undefined;
pressed.value = false;
},
onPointerenter: () => {
hovered.value = true;
},
onPointerleave: () => {
hovered.value = false;
},
onPointerdown: (event: PointerEvent) => {
if (
!event.defaultPrevented &&
!disabled.value &&
event.button === 0
)
pressed.value = true;
},
}),
children,
);
};
},
});
</script>
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { inject } from "vue";
import { listboxItemVariants } from "@heroui-vue/styles";
import { listBoxItemKey, type ListBoxItemState } from "./context";
defineOptions({ inheritAttrs: false });
defineProps<{ as?: string }>();
defineSlots<{ default?: (state: ListBoxItemState) => unknown }>();
const state = inject(listBoxItemKey);
if (!state) throw new Error("ListBoxItemIndicator requires ListBoxItem.");
</script>
<template>
<component
:is="as ?? 'span'"
v-bind="$attrs"
:class="[listboxItemVariants().indicator(), $attrs.class]"
aria-hidden="true"
data-slot="list-box-item-indicator"
:data-visible="state().isSelected || undefined"
>
<slot v-bind="state()">
<!-- HeroUI ce90ea3 licensed checkmark; see third-party/HEROUI-LICENSE. -->
<svg
aria-hidden="true"
role="presentation"
fill="none"
stroke="currentColor"
stroke-dasharray="22"
:stroke-dashoffset="state().isSelected ? 44 : 66"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 17 18"
data-slot="list-box-item-indicator--checkmark"
>
<polyline points="1 9 7 14 15 4" />
</svg>
</slot>
</component>
</template>
@@ -0,0 +1,61 @@
<script lang="ts">
import {
cloneVNode,
defineComponent,
Fragment,
h,
isVNode,
mergeProps,
useId,
type VNodeChild,
} from "vue";
import { listboxSectionVariants } from "@heroui-vue/styles";
export default defineComponent({
name: "ListBoxSection",
inheritAttrs: false,
props: { as: { type: String, default: "div" } },
setup(props, { attrs, slots }) {
const id = useId();
return () => {
const headers: string[] = [];
function prepare(nodes: VNodeChild[], path = ""): VNodeChild[] {
return nodes.map((node, index) => {
if (!isVNode(node)) return node;
const type = node.type as { name?: string; __name?: string };
const at = `${path}-${index}`;
if ((type.name ?? type.__name) === "HeaderRoot") {
const headerId = String(node.props?.id ?? `${id}-heading${at}`);
headers.push(headerId);
return cloneVNode(node, { id: headerId });
}
if (
(typeof node.type === "string" || node.type === Fragment) &&
Array.isArray(node.children)
) {
const clone = cloneVNode(node);
clone.children = prepare(
node.children as VNodeChild[],
at,
) as typeof clone.children;
return clone;
}
return node;
});
}
const children = prepare(slots.default?.() ?? []);
return h(
props.as,
mergeProps(attrs, {
role: "group",
class: listboxSectionVariants(),
"data-slot": "list-box-section",
"aria-labelledby":
attrs["aria-labelledby"] ??
(attrs["aria-label"] ? undefined : headers.join(" ") || undefined),
}),
children,
);
};
},
});
</script>
@@ -0,0 +1,69 @@
import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue";
import type { CollectionKey } from "../collection/keys";
import type { CollectionMember } from "../collection/registry";
import type { CollectionSelectionMode } from "../collection/selection";
export type ListBoxKey = CollectionKey;
export interface ListBoxDataItem {
id: ListBoxKey;
textValue?: string;
isDisabled?: boolean;
}
/** Shared schema: generic SFC parameter extraction can erase its prop types. */
export interface ListBoxOptions<T extends ListBoxDataItem = ListBoxDataItem> {
modelValue?: readonly ListBoxKey[];
selectedKeys?: readonly ListBoxKey[];
defaultValue?: readonly ListBoxKey[];
defaultSelectedKeys?: readonly ListBoxKey[];
selectionMode?: CollectionSelectionMode;
selectionBehavior?: "toggle" | "replace";
disabledKeys?: readonly ListBoxKey[];
isDisabled?: boolean;
isReadOnly?: boolean;
disallowEmptySelection?: boolean;
orientation?: "vertical" | "horizontal";
dir?: "ltr" | "rtl";
loop?: boolean;
variant?: "default" | "danger";
as?: string;
items?: readonly T[];
virtualized?: boolean;
rowHeight?: number;
overscan?: number;
}
export interface ListBoxItemState {
isSelected: boolean;
isDisabled: boolean;
isFocused: boolean;
isFocusVisible: boolean;
isPressed: boolean;
isHovered: boolean;
}
export interface ListBoxMember extends CollectionMember {
activate: (event: MouseEvent | KeyboardEvent) => void;
}
export interface ListBoxContext {
mode: ComputedRef<CollectionSelectionMode>;
readOnly: ComputedRef<boolean>;
keyboard: Ref<boolean>;
focused: Ref<ListBoxKey | undefined>;
noteFocus: (key: ListBoxKey) => void;
pressed: Ref<ListBoxKey | undefined>;
active: ComputedRef<ListBoxKey | undefined>;
selected: (key: ListBoxKey) => boolean;
disabled: (key: ListBoxKey) => boolean;
register: (member: ListBoxMember) => () => void;
activate: (key: ListBoxKey, event: MouseEvent | KeyboardEvent) => void;
focus: (key: ListBoxKey) => Promise<void>;
virtualized: () => boolean;
restoreFocus: () => void;
position: (key: ListBoxKey) => { index: number; size: number } | undefined;
}
export const listBoxKey: InjectionKey<ListBoxContext> = Symbol("hv-list-box");
export const listBoxItemKey: InjectionKey<() => ListBoxItemState> =
Symbol("hv-list-box-item");
export function useListBox() {
const context = inject(listBoxKey);
if (!context) throw new Error("ListBoxItem requires ListBox.");
return context;
}
+28
View File
@@ -630,3 +630,31 @@ export type {
SliderOutputProps,
SliderMarksProps,
} from "./types";
export {
default as ListBox,
default as ListBoxRoot,
} from "./components/list-box/ListBox.vue";
export { default as ListBoxItem } from "./components/list-box/ListBoxItem.vue";
export { default as ListBoxItemIndicator } from "./components/list-box/ListBoxItemIndicator.vue";
export { default as ListBoxSection } from "./components/list-box/ListBoxSection.vue";
export type {
ListBoxKey,
ListBoxDataItem,
ListBoxItemState,
} from "./components/list-box/context";
export type {
ListBoxProps,
ListBoxRootProps,
ListBoxItemProps,
ListBoxItemIndicatorProps,
ListBoxSectionProps,
} from "./types";
export {
listboxVariants,
listboxItemVariants,
listboxSectionVariants,
type ListBoxVariants,
type ListBoxItemVariants,
type ListBoxSectionVariants,
} from "@heroui-vue/styles";
+29
View File
@@ -16,6 +16,35 @@ import type AvatarGroupCount from "./components/avatar/AvatarGroupCount.vue";
import type Skeleton from "./components/skeleton/Skeleton.vue";
export type ButtonProps = InstanceType<typeof Button>["$props"];
export type ListBoxProps<
T extends import("./components/list-box/context").ListBoxDataItem =
import("./components/list-box/context").ListBoxDataItem,
> = import("./components/list-box/context").ListBoxOptions<T> &
import("vue").HTMLAttributes & {
"onUpdate:modelValue"?: (
keys: import("./components/list-box/context").ListBoxKey[],
) => void;
onSelectionChange?: (
keys: import("./components/list-box/context").ListBoxKey[],
) => void;
onAction?: (
key: import("./components/list-box/context").ListBoxKey,
) => void;
};
export type ListBoxRootProps<
T extends import("./components/list-box/context").ListBoxDataItem =
import("./components/list-box/context").ListBoxDataItem,
> = ListBoxProps<T>;
export type ListBoxItemProps = InstanceType<
typeof import("./components/list-box/ListBoxItem.vue").default
>["$props"];
export type ListBoxItemIndicatorProps = InstanceType<
typeof import("./components/list-box/ListBoxItemIndicator.vue").default
>["$props"];
export type ListBoxSectionProps = InstanceType<
typeof import("./components/list-box/ListBoxSection.vue").default
>["$props"];
export type CardProps = InstanceType<typeof Card>["$props"];
export type InputProps = InstanceType<typeof Input>["$props"];
export type SwitchProps = InstanceType<typeof Switch>["$props"];
+9 -1
View File
@@ -10,6 +10,7 @@ withDefaults(
multiple?: boolean;
disabled?: boolean;
name?: string;
cancelNavigation?: boolean;
}>(),
{ modelValue: undefined, defaultValue: undefined },
);
@@ -26,7 +27,14 @@ const emit = defineEmits<{ "update:modelValue": [value: unknown] }>();
:name="name"
@update:model-value="emit('update:modelValue', $event)"
>
<ListboxContent aria-label="Audit choices">
<ListboxContent
aria-label="Audit choices"
@keydown="
(event: KeyboardEvent) => {
if (cancelNavigation) event.preventDefault();
}
"
>
<ListboxItem :value="0">Numeric zero</ListboxItem>
<ListboxItem value="0">String zero</ListboxItem>
<ListboxItem value="disabled" disabled>Disabled</ListboxItem>