c8d54abefb
HD-10 scope, against heroui ce90ea3 collection sources and their react-aria/react-stately dependencies: - the ComboBox async demo now auto-loads on scroll-to-bottom (IntersectionObserver sentinel + fill chain mirroring the pinned ListBoxLoadMoreItem re-observe semantics), never duplicates requests (loading guards + monotonic sequence token), drops stale responses on query switches, keeps a retry path for failures (injectable mock failure) and documents its differences from the pinned SWAPI source; the Select demo's observer stays untouched (real-network scroll triggering verified in browser) - the Autocomplete virtualization demo and the default filter share one locale-sensitive matcher: createBaseContains (Intl.Collator base sensitivity, cafe matches Cafe with accent folding) is now exported from the package root - Autocomplete trigger semantics verified complete (single tab stop, Enter/Space/Escape/Delete/IME, single and multiple selection) and the scoped slots gained composition data instead of child copying: AutocompleteValue exposes selectedItem and per-entry source item, the ComboBox root exposes selectedItem - DropdownSubmenuTrigger exposes the pinned delay contract (default 200ms): the controlled open gate retimes Reka's fixed 100ms hover, keyboard opens stay immediate and cancel the pending hover, pointer leave cancels; the dead side/align forwarding is gone (Reka fixes the submenu side per direction); Button/Avatar trigger layout compensation kept after browser proof it is what wins the cascade - tests/fixtures/collections-rtl.vue drives the real-browser delay and RTL geometry checks; b02-pickers contract pins the new export and slot typing Full suite 111 files / 1666 tests, typecheck, build:docs and the b02-pickers + api-root-aliases tarball contracts pass.
613 lines
20 KiB
Vue
613 lines
20 KiB
Vue
<script lang="ts">
|
|
import {
|
|
cloneVNode,
|
|
computed,
|
|
defineComponent,
|
|
getCurrentInstance,
|
|
h,
|
|
isVNode,
|
|
mergeProps,
|
|
nextTick,
|
|
provide,
|
|
ref,
|
|
shallowRef,
|
|
useId,
|
|
watch,
|
|
watchEffect,
|
|
type PropType,
|
|
type SlotsType,
|
|
type VNodeChild,
|
|
} from "vue";
|
|
import { autocompleteVariants } from "@heroui-vue/styles";
|
|
import Popover from "../popover/Popover";
|
|
import {
|
|
selectionInputs,
|
|
useChoiceField,
|
|
useChoiceForm,
|
|
useChoiceValue,
|
|
validationInput,
|
|
} from "../choice/shared";
|
|
import { disabledContextKey } from "../field/disabled";
|
|
import {
|
|
fieldContextKey,
|
|
type ValidateResult,
|
|
type ValidationBehavior,
|
|
} from "../field/context";
|
|
import { copyKeys, type CollectionKey } from "../collection/keys";
|
|
import {
|
|
collectionOwnerKey,
|
|
type CollectionRecord,
|
|
type OwnedCollection,
|
|
} from "../collection/owner";
|
|
import { planCollectionItems } from "../combo-box/metadata";
|
|
import { createBaseContains } from "../collection/match";
|
|
import { SHAPE_ARRAY_CHILDREN, SHAPE_TEXT_CHILDREN } from "../combo-box/dom";
|
|
import { useConfig } from "../../providers/context";
|
|
import {
|
|
autocompleteKey,
|
|
type AutocompleteItem,
|
|
type AutocompleteValue as AutocompleteValueType,
|
|
} from "./context";
|
|
|
|
const NAMING_ATTRS = ["aria-label", "aria-labelledby", "aria-describedby"];
|
|
export default defineComponent({
|
|
name: "Autocomplete",
|
|
inheritAttrs: false,
|
|
slots: Object as SlotsType<{
|
|
default?: (state: {
|
|
isOpen: boolean;
|
|
selectedKeys: CollectionKey[];
|
|
}) => VNodeChild;
|
|
}>,
|
|
props: {
|
|
modelValue: {
|
|
type: [String, Number, Array, null] as PropType<AutocompleteValueType>,
|
|
default: undefined,
|
|
},
|
|
value: {
|
|
type: [String, Number, Array, null] as PropType<AutocompleteValueType>,
|
|
default: undefined,
|
|
},
|
|
defaultValue: {
|
|
type: [String, Number, Array, null] as PropType<AutocompleteValueType>,
|
|
default: undefined,
|
|
},
|
|
selectionMode: {
|
|
type: String as PropType<"single" | "multiple">,
|
|
default: "single",
|
|
},
|
|
items: Array as PropType<readonly AutocompleteItem[]>,
|
|
disabledKeys: Array as PropType<readonly CollectionKey[]>,
|
|
open: { type: Boolean, default: undefined },
|
|
isOpen: { type: Boolean, default: undefined },
|
|
defaultOpen: Boolean,
|
|
isDisabled: Boolean,
|
|
disabled: Boolean,
|
|
isRequired: Boolean,
|
|
isInvalid: Boolean,
|
|
allowsEmptyCollection: Boolean,
|
|
placeholder: { type: String, default: "Select an item" },
|
|
name: String,
|
|
form: String,
|
|
fullWidth: Boolean,
|
|
variant: {
|
|
type: String as PropType<"primary" | "secondary">,
|
|
default: "primary",
|
|
},
|
|
validationBehavior: String as PropType<ValidationBehavior>,
|
|
validate: Function as PropType<
|
|
(value: AutocompleteValueType) => ValidateResult
|
|
>,
|
|
as: { type: String, default: "div" },
|
|
asChild: { type: Boolean, default: false },
|
|
},
|
|
emits: {
|
|
"update:modelValue": (_value: AutocompleteValueType) => true,
|
|
change: (_value: AutocompleteValueType) => true,
|
|
"update:open": (_value: boolean) => true,
|
|
openChange: (_value: boolean) => true,
|
|
clear: () => true,
|
|
},
|
|
setup(props, { attrs, slots, emit, expose }) {
|
|
const instance = getCurrentInstance()!;
|
|
const contains = createBaseContains(useConfig()?.locale.value);
|
|
const present = (keys: string[]) =>
|
|
keys.some((key) => Object.hasOwn(instance.vnode.props ?? {}, key));
|
|
const model = useChoiceValue<AutocompleteValueType | undefined>(
|
|
() =>
|
|
present(["modelValue", "model-value"])
|
|
? (props.modelValue ?? null)
|
|
: present(["value"])
|
|
? (props.value ?? null)
|
|
: undefined,
|
|
() => props.defaultValue ?? null,
|
|
["modelValue", "model-value", "value"],
|
|
(value) => {
|
|
const next = value ?? null;
|
|
emit("update:modelValue", next);
|
|
emit("change", next);
|
|
},
|
|
);
|
|
const value = computed<AutocompleteValueType>(() => {
|
|
const raw = model.value.value ?? null;
|
|
if (props.selectionMode === "multiple")
|
|
return raw === null ? [] : Array.isArray(raw) ? raw : [raw];
|
|
return Array.isArray(raw) ? (raw[0] ?? null) : raw;
|
|
});
|
|
const keys = computed<readonly CollectionKey[]>(() => {
|
|
const raw = value.value;
|
|
const next = copyKeys(
|
|
raw === null ? [] : Array.isArray(raw) ? raw : [raw],
|
|
);
|
|
if (props.selectionMode === "single" && next.length > 1)
|
|
throw new TypeError("Single Autocomplete expects one key or null.");
|
|
return Object.freeze(next);
|
|
});
|
|
const openModel = useChoiceValue<boolean | undefined>(
|
|
() => (present(["open"]) ? props.open : props.isOpen),
|
|
() => props.defaultOpen,
|
|
["open", "isOpen", "is-open"],
|
|
(next) => {
|
|
emit("update:open", !!next);
|
|
emit("openChange", !!next);
|
|
},
|
|
);
|
|
const open = computed(() => !!openModel.value.value);
|
|
|
|
const collection = shallowRef<OwnedCollection>();
|
|
const discovered = shallowRef<CollectionRecord[]>([]);
|
|
const planned = shallowRef<CollectionRecord[]>([]);
|
|
const complete = ref(false);
|
|
watchEffect(() => {
|
|
if (!collection.value) return;
|
|
const next = collection.value.items();
|
|
if (JSON.stringify(next) !== JSON.stringify(discovered.value))
|
|
discovered.value = next;
|
|
});
|
|
const records = computed<CollectionRecord[]>(() => {
|
|
const explicit = props.items?.map((item) => {
|
|
if (item.id === undefined || item.id === null)
|
|
throw new TypeError("Autocomplete items need an id.");
|
|
return {
|
|
key: item.id,
|
|
text: item.textValue,
|
|
disabled: !!item.isDisabled,
|
|
} satisfies CollectionRecord;
|
|
});
|
|
const base =
|
|
explicit ??
|
|
(complete.value
|
|
? planned.value
|
|
: discovered.value.length
|
|
? discovered.value
|
|
: planned.value);
|
|
const disabledKeys = props.disabledKeys ?? [];
|
|
return base.map((record) => ({
|
|
...record,
|
|
disabled: record.disabled || disabledKeys.includes(record.key),
|
|
}));
|
|
});
|
|
|
|
const uid = useId();
|
|
const triggerId = `hv-autocomplete-${uid}-trigger`;
|
|
const listId = `hv-autocomplete-${uid}-listbox`;
|
|
const valueId = `hv-autocomplete-${uid}-value`;
|
|
|
|
const filterText = ref("");
|
|
/** Open composition session in the popover search box. */
|
|
const composing = ref(false);
|
|
const filterPredicate = ref<(text: string, input: string) => boolean>();
|
|
const filter = (record: CollectionRecord) =>
|
|
(filterPredicate.value ?? contains)(record.text, filterText.value);
|
|
|
|
const field = useChoiceField<AutocompleteValueType>(props, attrs, {
|
|
kind: "group",
|
|
value,
|
|
validate: (current) => props.validate?.(current),
|
|
satisfied: () => keys.value.length > 0,
|
|
requiredMessage: "请选择一个选项。",
|
|
});
|
|
provide(fieldContextKey, field.field);
|
|
provide(disabledContextKey, field.field.disabled);
|
|
|
|
const keyboardIntent = ref(true);
|
|
const activeKey = ref<CollectionKey>();
|
|
const filterInput = ref<HTMLInputElement>();
|
|
const triggerElement = ref<HTMLElement>();
|
|
const proxy = ref<HTMLInputElement>();
|
|
const activeId = computed<string | undefined>(() => {
|
|
if (!open.value || activeKey.value === undefined) return undefined;
|
|
return collection.value?.optionId?.(activeKey.value);
|
|
});
|
|
|
|
function request(next: CollectionKey[]) {
|
|
if (field.field.disabled.value) return;
|
|
if (
|
|
next.some(
|
|
(key) =>
|
|
records.value.find((record) => record.key === key)?.disabled &&
|
|
!keys.value.includes(key),
|
|
)
|
|
)
|
|
return;
|
|
if (
|
|
next.length === keys.value.length &&
|
|
next.every((key) => keys.value.includes(key))
|
|
)
|
|
return;
|
|
if (!next.length && !keys.value.length) return;
|
|
field.edit();
|
|
model.request(
|
|
props.selectionMode === "multiple" ? [...next] : (next[0] ?? null),
|
|
);
|
|
// Focus restoration belongs to the close that the parent actually accepts.
|
|
if (props.selectionMode === "single") setOpen(false);
|
|
}
|
|
|
|
function setOpen(next: boolean) {
|
|
if (next === open.value) return;
|
|
if (next && field.field.disabled.value) return;
|
|
if (next && props.disabled) return;
|
|
if (
|
|
next &&
|
|
!props.allowsEmptyCollection &&
|
|
complete.value &&
|
|
!records.value.some((record) => !record.disabled)
|
|
)
|
|
return;
|
|
openModel.request(next);
|
|
if (next) {
|
|
filterText.value = "";
|
|
void nextTick(() => {
|
|
const record =
|
|
records.value.find(
|
|
(item) =>
|
|
keys.value.includes(item.key) && filter(item) && !item.disabled,
|
|
) ?? records.value.find((item) => filter(item) && !item.disabled);
|
|
void setActive(record?.key);
|
|
filterInput.value?.focus({ preventScroll: true });
|
|
});
|
|
} else {
|
|
void nextTick(() => {
|
|
// A rejected close keeps the row, the focus and the ARIA state intact.
|
|
if (open.value) return;
|
|
activeKey.value = undefined;
|
|
if (
|
|
filterInput.value?.ownerDocument.activeElement ===
|
|
filterInput.value ||
|
|
!filterInput.value
|
|
)
|
|
triggerElement.value?.focus({ preventScroll: true });
|
|
});
|
|
}
|
|
}
|
|
|
|
async function setActive(key: CollectionKey | undefined) {
|
|
activeKey.value = key;
|
|
if (key !== undefined) await collection.value?.reveal?.(key);
|
|
}
|
|
function moveActive(delta: 1 | -1) {
|
|
const items = records.value.filter(
|
|
(record) => filter(record) && !record.disabled,
|
|
);
|
|
if (!items.length) {
|
|
void setActive(undefined);
|
|
return;
|
|
}
|
|
const index = items.findIndex((item) => item.key === activeKey.value);
|
|
const next =
|
|
index < 0
|
|
? items[delta > 0 ? 0 : items.length - 1]
|
|
: items[Math.min(Math.max(index + delta, 0), items.length - 1)];
|
|
if (next) void setActive(next.key);
|
|
}
|
|
function confirmActive() {
|
|
const key = activeKey.value;
|
|
if (key === undefined) return;
|
|
const record = records.value.find(
|
|
(item) => item.key === key && filter(item) && !item.disabled,
|
|
);
|
|
if (!record) return;
|
|
if (props.selectionMode === "multiple") {
|
|
// Confirming the active row toggles it inside the accepted set.
|
|
const next = keys.value.includes(key)
|
|
? keys.value.filter((item) => item !== key)
|
|
: [...keys.value, key];
|
|
request(next);
|
|
return;
|
|
}
|
|
request([key]);
|
|
}
|
|
function clear() {
|
|
if (field.field.disabled.value) return;
|
|
if (!keys.value.length) return;
|
|
request([]);
|
|
emit("clear");
|
|
}
|
|
function focusTrigger() {
|
|
triggerElement.value?.focus({ preventScroll: true });
|
|
}
|
|
|
|
const slotsBase = computed(() =>
|
|
autocompleteVariants({
|
|
fullWidth: props.fullWidth,
|
|
variant: props.variant,
|
|
}),
|
|
);
|
|
const invalid = computed(() => field.field.invalid.value);
|
|
/** Keys still backed by an enabled record: a removed item is not submitted. */
|
|
// Keys the collection has ever offered. A key that disappeared from the
|
|
// collection was removed and must not submit; a key that was never listed
|
|
// (closed-state or caller-owned value) is trusted.
|
|
const seenKeys = ref(new Set<string>());
|
|
watchEffect(() => {
|
|
for (const record of records.value)
|
|
seenKeys.value.add(`${typeof record.key}\u0001${String(record.key)}`);
|
|
});
|
|
const successfulKeys = computed(() =>
|
|
keys.value.filter((key) => {
|
|
const record = records.value.find((item) => item.key === key);
|
|
if (record) return !record.disabled;
|
|
return !seenKeys.value.has(`${typeof key}\u0001${String(key)}`);
|
|
}),
|
|
);
|
|
|
|
provide(collectionOwnerKey, {
|
|
keys,
|
|
mode: computed(() => props.selectionMode),
|
|
disabled: field.field.disabled,
|
|
readOnly: field.field.readOnly,
|
|
disabledKeys: computed(() => props.disabledKeys ?? []),
|
|
id: listId,
|
|
labelledBy: () =>
|
|
field.labelledBy() ?? (attrs["aria-label"] ? undefined : triggerId),
|
|
ariaLabel: () =>
|
|
typeof attrs["aria-label"] === "string"
|
|
? attrs["aria-label"]
|
|
: undefined,
|
|
request,
|
|
action: (key) => {
|
|
void key;
|
|
if (props.selectionMode === "single") setOpen(false);
|
|
},
|
|
leave: () => setOpen(false),
|
|
connect: (next) => {
|
|
if (collection.value && collection.value !== next)
|
|
throw new Error("Autocomplete supports one ListBox.");
|
|
collection.value = next;
|
|
return () => {
|
|
if (collection.value === next) collection.value = undefined;
|
|
};
|
|
},
|
|
filter,
|
|
virtualFocus: () => true,
|
|
activeKey,
|
|
keyboardIntent,
|
|
isOpen: () => open.value,
|
|
});
|
|
|
|
const core = (): Record<string, unknown> => ({
|
|
role: "combobox",
|
|
"aria-expanded": true,
|
|
"aria-controls": listId,
|
|
"aria-activedescendant": activeId.value,
|
|
"aria-autocomplete": "list" as const,
|
|
"aria-haspopup": "listbox" as const,
|
|
"aria-label":
|
|
typeof attrs["aria-label"] === "string"
|
|
? attrs["aria-label"]
|
|
: undefined,
|
|
"aria-labelledby":
|
|
attrs["aria-labelledby"] ??
|
|
(attrs["aria-label"] ? undefined : field.labelledBy()),
|
|
"aria-describedby": field.describedBy(),
|
|
onKeydown: (event: KeyboardEvent) => {
|
|
if (
|
|
event.defaultPrevented ||
|
|
composing.value ||
|
|
event.isComposing ||
|
|
event.keyCode === 229
|
|
)
|
|
return;
|
|
if (field.field.disabled.value) return;
|
|
keyboardIntent.value = true;
|
|
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
|
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
event.preventDefault();
|
|
moveActive(event.key === "ArrowDown" ? 1 : -1);
|
|
return;
|
|
}
|
|
if (event.key === "Home" || event.key === "End") {
|
|
event.preventDefault();
|
|
const items = records.value.filter(
|
|
(record) => filter(record) && !record.disabled,
|
|
);
|
|
const target = event.key === "Home" ? items[0] : items.at(-1);
|
|
if (target) void setActive(target.key);
|
|
return;
|
|
}
|
|
if (event.key === "Enter") {
|
|
event.preventDefault();
|
|
if (!event.repeat) confirmActive();
|
|
return;
|
|
}
|
|
if (event.key === "Escape") {
|
|
event.preventDefault();
|
|
setOpen(false);
|
|
return;
|
|
}
|
|
if (event.key === "Tab") setOpen(false);
|
|
},
|
|
});
|
|
|
|
provide(autocompleteKey, {
|
|
field,
|
|
slots: slotsBase,
|
|
open,
|
|
setOpen,
|
|
keys,
|
|
records,
|
|
selectedItems: computed(() =>
|
|
keys.value.map((key) => ({
|
|
key,
|
|
textValue:
|
|
records.value.find((record) => record.key === key)?.text ??
|
|
String(key),
|
|
item: props.items?.find((entry) => entry.id === key),
|
|
})),
|
|
),
|
|
selectionMode: computed(() => props.selectionMode),
|
|
disabled: field.field.disabled,
|
|
invalid,
|
|
listId,
|
|
triggerId,
|
|
valueId,
|
|
placeholder: () => props.placeholder,
|
|
activeKey,
|
|
activeId,
|
|
collection,
|
|
filterText,
|
|
filterPredicate,
|
|
filterInput,
|
|
triggerElement,
|
|
ariaLabel: () =>
|
|
typeof attrs["aria-label"] === "string"
|
|
? attrs["aria-label"]
|
|
: undefined,
|
|
core,
|
|
focusTrigger,
|
|
request,
|
|
moveActive,
|
|
setActive,
|
|
confirmActive,
|
|
clear,
|
|
composing,
|
|
});
|
|
|
|
useChoiceForm(
|
|
proxy,
|
|
() => {
|
|
model.reset();
|
|
field.reset();
|
|
setOpen(false);
|
|
},
|
|
() => field.validity(proxy.value),
|
|
);
|
|
watchEffect(() => field.validity(proxy.value));
|
|
watch(
|
|
// Filtering changes the visible set: re-anchor the active row so Enter
|
|
// always confirms something the user can actually see.
|
|
() => `${filterText.value}|${records.value.length}|${open.value}`,
|
|
() => {
|
|
if (!open.value) return;
|
|
const visible = records.value.filter(
|
|
(record) => filter(record) && !record.disabled,
|
|
);
|
|
if (!visible.some((record) => record.key === activeKey.value))
|
|
void setActive(visible[0]?.key);
|
|
},
|
|
);
|
|
watch(
|
|
() => `${keys.value.map(String).join("\u0000")}|${records.value.length}`,
|
|
() => {
|
|
if (
|
|
!props.allowsEmptyCollection &&
|
|
open.value &&
|
|
records.value.length
|
|
) {
|
|
const visible = records.value.filter(
|
|
(record) => filter(record) && !record.disabled,
|
|
);
|
|
if (!visible.length) setOpen(false);
|
|
}
|
|
},
|
|
);
|
|
|
|
expose({
|
|
element: triggerElement,
|
|
open: () => setOpen(true),
|
|
close: () => setOpen(false),
|
|
focus: focusTrigger,
|
|
clear,
|
|
});
|
|
|
|
return () => {
|
|
const rendered = slots.default?.({
|
|
isOpen: open.value,
|
|
selectedKeys: [...keys.value],
|
|
});
|
|
const children = Array.isArray(rendered)
|
|
? rendered
|
|
: rendered == null
|
|
? []
|
|
: [rendered];
|
|
const plan = planCollectionItems(children);
|
|
if (JSON.stringify(plan.records) !== JSON.stringify(planned.value))
|
|
planned.value = plan.records;
|
|
complete.value = plan.complete;
|
|
const nodes = field.prepare(children, true);
|
|
const restAttrs: Record<string, unknown> = {};
|
|
for (const [key, value] of Object.entries(attrs)) {
|
|
if (NAMING_ATTRS.includes(key) || key === "class" || key === "style")
|
|
continue;
|
|
restAttrs[key] = value;
|
|
}
|
|
const rootProps = mergeProps(restAttrs, {
|
|
class: [slotsBase.value.base(), attrs.class],
|
|
style: attrs.style,
|
|
"data-slot": "autocomplete",
|
|
"data-invalid": invalid.value || undefined,
|
|
"data-disabled": field.field.disabled.value || undefined,
|
|
});
|
|
const formLayer = [
|
|
selectionInputs({
|
|
name: props.name,
|
|
form: props.form,
|
|
multiple: props.selectionMode === "multiple",
|
|
disabled: field.field.disabled.value,
|
|
keys: successfulKeys.value,
|
|
slot: "autocomplete-form-value",
|
|
}),
|
|
validationInput(
|
|
proxy,
|
|
props,
|
|
field.field.disabled.value,
|
|
field.behavior.value,
|
|
(event) =>
|
|
field.invalidEvent(event, () => triggerElement.value?.focus()),
|
|
props.isRequired && field.behavior.value === "native",
|
|
keys.value.length > 0,
|
|
),
|
|
];
|
|
const popover = (inner: VNodeChild[]) =>
|
|
h(
|
|
Popover,
|
|
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
|
|
{ default: () => [...inner, ...formLayer] },
|
|
);
|
|
if (!props.asChild) return h(props.as, rootProps, [popover(nodes)]);
|
|
|
|
const [host, ...rest] = nodes;
|
|
if (!isVNode(host) || typeof host.type !== "string")
|
|
return h(props.as, rootProps, [popover(nodes)]);
|
|
// `as-child`: the caller's element is the picker root and keeps its own
|
|
// attributes, events, children and ref.
|
|
const inner = host.children;
|
|
const hostChildren = Array.isArray(inner)
|
|
? (inner as VNodeChild[])
|
|
: inner == null
|
|
? []
|
|
: [inner as VNodeChild];
|
|
const clone = cloneVNode(host, mergeProps(host.props ?? {}, rootProps));
|
|
// `children` is replaced, so the shape flag must stop claiming text.
|
|
clone.children = [
|
|
popover([...hostChildren, ...rest]),
|
|
] as typeof clone.children;
|
|
clone.shapeFlag =
|
|
(clone.shapeFlag & ~SHAPE_TEXT_CHILDREN) | SHAPE_ARRAY_CHILDREN;
|
|
return clone;
|
|
};
|
|
},
|
|
});
|
|
</script>
|