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,11 +1,15 @@
<script lang="ts">
import {
cloneVNode,
computed,
defineComponent,
getCurrentInstance,
h,
isVNode,
mergeProps,
nextTick,
onBeforeUpdate,
onMounted,
provide,
ref,
shallowRef,
@@ -14,15 +18,19 @@ import {
watchEffect,
type PropType,
type SlotsType,
type VNode,
type VNodeChild,
} from "vue";
import { comboBoxVariants } from "@heroui-vue/styles";
import Popover from "../popover/Popover";
import {
selectionInputs,
useChoiceField,
useChoiceForm,
useChoiceValue,
} from "../choice/shared";
import { useConfig } from "../../providers/context";
import { createBaseContains } from "../collection/match";
import { disabledContextKey } from "../field/disabled";
import { fieldContextKey, type FieldContext } from "../field/context";
import type { ValidateResult, ValidationBehavior } from "../field/context";
@@ -33,6 +41,7 @@ import {
type OwnedCollection,
} from "../collection/owner";
import { planCollectionItems } from "./metadata";
import { SHAPE_ARRAY_CHILDREN, SHAPE_TEXT_CHILDREN } from "./dom";
import {
comboBoxKey,
type ComboBoxItem,
@@ -40,10 +49,6 @@ import {
type ComboBoxValue,
} from "./context";
const contains = (text: string, inputValue: string) =>
!inputValue ||
text.toLocaleLowerCase().includes(inputValue.toLocaleLowerCase());
export default defineComponent({
name: "ComboBox",
inheritAttrs: false,
@@ -133,6 +138,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 readValue = (): ComboBoxValue | undefined => {
@@ -240,8 +246,8 @@ export default defineComponent({
const filter = (record: CollectionRecord) =>
props.defaultFilter
? props.defaultFilter(record.text, inputValue.value)
: contains(record.text, inputValue.value);
? props.defaultFilter(record.text, filterText.value)
: contains(record.text, filterText.value);
const instanceId = useId();
const inputId = `hv-combo-box-${instanceId}-input`;
@@ -269,6 +275,10 @@ export default defineComponent({
const keyboardIntent = ref(true);
const activeKey = ref<CollectionKey>();
/** Open composition session: filtering waits for `compositionend`. */
const composing = ref(false);
/** Text the collection is actually filtered by. */
const filterText = ref("");
const cursor = ref<CollectionKey>();
const inputElement = ref<HTMLInputElement>();
const triggerElement = ref<HTMLElement>();
@@ -298,13 +308,8 @@ export default defineComponent({
)
return;
if (!next.length && !keys.value.length) return;
if (
!next.length &&
!props.allowsCustomValue &&
!props.allowsEmptyCollection &&
(props.isRequired || field.field.required.value)
)
return;
// Validation blocks an invalid submit; it must not stop the user from
// editing a required field back to empty.
field.edit();
model.request(
props.selectionMode === "multiple" ? [...next] : (next[0] ?? null),
@@ -401,40 +406,52 @@ export default defineComponent({
request([key]);
}
const composing = ref(false);
const selectedRecord = computed(() =>
props.selectionMode === "single"
? records.value.find((record) => keys.value.includes(record.key))
: undefined,
);
const selectionIdentity = computed(() =>
keys.value
.map((key) => `${typeof key}\u0001${String(key)}`)
.join("\u0000"),
);
const inputControlled = ref(present(["inputValue", "input-value"]));
onBeforeUpdate(() => {
inputControlled.value = present(["inputValue", "input-value"]);
});
/** Set while a typed draft is allowed to outlive the cleared selection. */
let keepDraft = false;
watch(
// A selection change (initial, external or accepted) owns the single-select
// text; typing inside an allows-custom-value combo must not be overwritten.
() => `${keys.value.map(String).join("\u0000")}|${records.value.length}`,
// text. The identity keeps `0` and `"0"` apart, and the label is watched
// directly so an edited textValue re-syncs without a count change.
[selectionIdentity, () => selectedRecord.value?.text],
() => {
if (props.selectionMode !== "single") return;
const selected = records.value.find((record) =>
keys.value.includes(record.key),
);
if (!selected) return;
if (inputValue.value !== selected.text)
inputModel.request(selected.text);
if (props.selectionMode !== "single" || inputControlled.value) return;
if (keepDraft) {
keepDraft = false;
return;
}
syncAcceptedText();
},
{ immediate: true },
);
/**
* The visible text falls back to the accepted item's label so an initial or
* external selection is readable on the very first render (including SSR),
* before the selection-sync watcher has run.
* Visible text. A controlled `inputValue` wins even when empty; otherwise an
* explicit draft wins, and with no draft the accepted item's label is read at
* render time so the first SSR paint already shows the selection.
*/
const displayInputValue = computed(() => {
if (inputControlled.value) return inputValue.value;
if (inputValue.value) return inputValue.value;
if (props.selectionMode !== "single") return "";
const selected = records.value.find((record) =>
keys.value.includes(record.key),
);
return selected?.text ?? "";
return selectedRecord.value?.text ?? "";
});
function setInputValue(next: string) {
inputModel.request(next);
if (props.menuTrigger === "input" && !open.value && next) setOpen(true);
function applyInput(next: string) {
filterText.value = next;
// Keep the active row on the first match of the new filter.
if (next) {
const first = records.value.find(
@@ -450,12 +467,32 @@ export default defineComponent({
const selected = records.value.find((record) =>
keys.value.includes(record.key),
);
if (selected && next !== selected.text) request([]);
if (selected && next !== selected.text) {
// Dropping the no-longer-matching selection must not erase the draft.
keepDraft = true;
request([]);
void nextTick(() => {
keepDraft = false;
});
}
}
}
function setInputValue(next: string) {
inputModel.request(next);
if (props.menuTrigger === "input" && !open.value && next) setOpen(true);
// Mid-composition text must stay visible without filtering the collection.
if (composing.value) return;
applyInput(next);
}
function keydown(event: KeyboardEvent) {
if (event.defaultPrevented || event.isComposing || event.keyCode === 229)
if (
event.defaultPrevented ||
composing.value ||
event.isComposing ||
event.keyCode === 229
)
return;
if (field.field.disabled.value || field.field.readOnly.value) return;
keyboardIntent.value = true;
@@ -501,6 +538,11 @@ export default defineComponent({
if (props.menuTrigger === "focus") setOpen(true);
}
onMounted(() => {
if (!props.autoFocus || field.field.disabled.value) return;
inputElement.value?.focus({ preventScroll: true });
});
function describedBy() {
return field.describedBy();
}
@@ -576,6 +618,7 @@ export default defineComponent({
required:
(field.behavior.value === "native" && field.field.required.value) ||
undefined,
form: props.form,
onKeydown: keydown,
onFocus: focusInput,
onCompositionstart: () => {
@@ -583,6 +626,7 @@ export default defineComponent({
},
onCompositionend: () => {
composing.value = false;
applyInput(inputValue.value);
},
});
@@ -621,8 +665,17 @@ export default defineComponent({
formValueText,
invalid,
disabled: field.field.disabled,
variant: () => props.variant,
});
function syncAcceptedText() {
if (props.selectionMode !== "single" || inputControlled.value) return;
const next =
selectedRecord.value?.text ??
(props.allowsCustomValue ? (inputModel.value.value ?? "") : "");
if (inputModel.value.value !== next) inputModel.request(next);
}
useChoiceForm(
inputElement,
() => {
@@ -630,6 +683,8 @@ export default defineComponent({
inputModel.reset();
field.reset();
setOpen(false);
// Restore the accepted item's label, not the empty raw input default.
void nextTick(syncAcceptedText);
},
() => {
field.validity(inputElement.value);
@@ -653,6 +708,74 @@ export default defineComponent({
if (!eligibleRecords.length) setOpen(false);
});
/** Keys still backed by an enabled record: removed items are 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)}`);
}),
);
const submitText = computed<string | undefined>(() => {
if (!props.name) return undefined;
if (props.allowsCustomValue) return inputValue.value;
if (props.formValue !== "text") return undefined;
return successfulKeys.value
.map((key) => records.value.find((item) => item.key === key)?.text)
.filter((text): text is string => Boolean(text))
.join(",");
});
/**
* The picker root element owns the popover, so the component has a single
* root node and `as-child` can hand it to the caller's element.
*/
function renderRoot(nodes: VNodeChild[], formLayer: VNode | null) {
const rootProps = mergeProps(attrs, {
class: slotsBase.value.base(),
style: attrs.style,
"data-slot": "combo-box",
"data-invalid": invalid.value || undefined,
"data-disabled": field.field.disabled.value || undefined,
});
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 single root element becomes 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;
}
expose({
element: () => anchor?.(),
input: inputElement,
@@ -680,35 +803,16 @@ export default defineComponent({
planned.value = plan.records;
complete.value = plan.complete;
const nodes = field.prepare(children, true);
return h(
Popover,
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
{
default: () =>
h(
props.as,
mergeProps(attrs, {
class: slotsBase.value.base(),
style: attrs.style,
"data-slot": "combo-box",
"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": "combo-box-form-value",
})
: null,
],
),
},
);
const formLayer = selectionInputs({
name: props.name,
form: props.form,
multiple: props.selectionMode === "multiple",
disabled: field.field.disabled.value,
keys: successfulKeys.value,
text: submitText.value,
slot: "combo-box-form-value",
});
return renderRoot(nodes, formLayer);
};
},
});