fix(pickers): rework B02 against the public review

Restore native clearing, unify the form/field protocol with the other choice
families (per-key entries, disabled and removed keys omitted, shared form
owner), synchronise ComboBox text by key identity, keep filtering out of open
composition sessions, and stop stealing focus when a controlled close is
rejected. Also merge caller refs/ARIA/disabled, implement asChild, autoFocus
and ComboBox variant, use a locale-aware base matcher, and put the indicator
class and slot on the icon element the ported CSS selects.
This commit is contained in:
maoyingjie
2026-10-25 20:40:24 +08:00
parent 3e9be13b19
commit e34b9debdf
24 changed files with 1808 additions and 236 deletions
@@ -1,9 +1,11 @@
<script lang="ts">
import {
cloneVNode,
computed,
defineComponent,
getCurrentInstance,
h,
isVNode,
mergeProps,
nextTick,
provide,
@@ -19,6 +21,7 @@ import {
import { autocompleteVariants } from "@heroui-vue/styles";
import Popover from "../popover/Popover";
import {
selectionInputs,
useChoiceField,
useChoiceForm,
useChoiceValue,
@@ -37,16 +40,16 @@ import {
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"];
const contains = (text: string, inputValue: string) =>
!inputValue ||
text.toLocaleLowerCase().includes(inputValue.toLocaleLowerCase());
export default defineComponent({
name: "Autocomplete",
inheritAttrs: false,
@@ -73,6 +76,7 @@ export default defineComponent({
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 },
@@ -106,6 +110,7 @@ export default defineComponent({
},
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>(
@@ -160,11 +165,22 @@ export default defineComponent({
discovered.value = next;
});
const records = computed<CollectionRecord[]>(() => {
const base = complete.value
? planned.value
: discovered.value.length
? discovered.value
: planned.value;
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,
@@ -178,6 +194,8 @@ export default defineComponent({
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);
@@ -222,12 +240,8 @@ export default defineComponent({
model.request(
props.selectionMode === "multiple" ? [...next] : (next[0] ?? null),
);
if (props.selectionMode === "single") {
setOpen(false);
void nextTick(() =>
triggerElement.value?.focus({ preventScroll: true }),
);
}
// Focus restoration belongs to the close that the parent actually accepts.
if (props.selectionMode === "single") setOpen(false);
}
function setOpen(next: boolean) {
@@ -254,8 +268,10 @@ export default defineComponent({
filterInput.value?.focus({ preventScroll: true });
});
} else {
activeKey.value = undefined;
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 ||
@@ -319,10 +335,22 @@ export default defineComponent({
}),
);
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;
/** 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,
@@ -376,6 +404,7 @@ export default defineComponent({
onKeydown: (event: KeyboardEvent) => {
if (
event.defaultPrevented ||
composing.value ||
event.isComposing ||
event.keyCode === 229
)
@@ -451,7 +480,7 @@ export default defineComponent({
setActive,
confirmActive,
clear,
formValueText,
composing,
});
useChoiceForm(
@@ -522,47 +551,60 @@ export default defineComponent({
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,
),
],
),
},
);
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;
};
},
});