feat(autocomplete): migrate Autocomplete with popover-owned filtering

Port the fixed-baseline Autocomplete onto the B02a collection protocol. The
trigger is the single Tab entry; opening moves focus to the search box inside the
popover, which owns filtering, aria-activedescendant and keyboard navigation
while the list only tracks an active row.

- Seven parts: root (field, value/open models, form value, owner wiring),
  trigger (anchor + activation), value (scoped slot with selectedItems and
  selectedText instead of copied item subtrees), indicator, clear button,
  popover (measured trigger width), filter (owns the search text and composes the
  inner SearchFieldInput into the combobox control).
- Filter exposes input-value/update:inputValue/inputChange, matching ComboBox.
- Confirming the active row in multiple mode now toggles it instead of replacing
  the accepted set (ComboBox shared the same bug).
- ComboBox shows the accepted label on the first render via a display value that
  falls back to the selected record, so preselected fields are readable before
  the selection watcher runs (including SSR).
- Popovers measure the anchor with a ResizeObserver because Reka does not publish
  the anchor size; the caller's root class is merged again so the trigger fills
  the field width.
- 24 baseline previews, Chinese doc page, navigation, 17 behaviour tests, 5
  demo/document contracts and an independent tarball consumption script for both
  pickers.

Not included: the full bundler/NodeNext type matrix (B02d).
This commit is contained in:
maoyingjie
2026-10-25 17:20:17 +08:00
parent 46e4df7e85
commit 5e688680e9
53 changed files with 5730 additions and 11 deletions
@@ -0,0 +1,569 @@
<script lang="ts">
import {
computed,
defineComponent,
getCurrentInstance,
h,
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 {
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 {
autocompleteKey,
type AutocompleteValue as AutocompleteValueType,
} from "./context";
const NAMING_ATTRS = ["aria-label", "aria-labelledby", "aria-describedby"];
const contains = (text: string, inputValue: string) =>
!inputValue ||
text.toLocaleLowerCase().includes(inputValue.toLocaleLowerCase());
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",
},
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 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 base = 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("");
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),
);
if (props.selectionMode === "single") {
setOpen(false);
void nextTick(() =>
triggerElement.value?.focus({ preventScroll: true }),
);
}
}
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 {
activeKey.value = undefined;
void nextTick(() => {
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);
const formValueText = computed<string | undefined>(() => {
if (!props.name) return undefined;
return keys.value.length ? keys.value.map(String).join(",") : undefined;
});
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 ||
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),
})),
),
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,
formValueText,
});
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;
}
return h(
Popover,
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
{
default: () =>
h(
props.as,
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,
}),
[
...nodes,
props.name
? h("input", {
type: "hidden",
name: props.name,
form: props.form,
value: formValueText.value ?? "",
"data-slot": "autocomplete-form-value",
})
: null,
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,
),
],
),
},
);
};
},
});
</script>