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;
};
},
});
@@ -10,10 +10,17 @@ export default defineComponent({
setup(_props, { attrs, slots }) {
const ctx = useAutocomplete();
const empty = () => ctx.keys.value.length === 0;
const callerDisabled = () =>
attrs.disabled !== undefined && attrs.disabled !== false
? true
: undefined;
function click(event: MouseEvent) {
// Caller cancellation is checked before we cancel the default ourselves,
// otherwise a native click would always look pre-cancelled.
if (event.defaultPrevented) return;
event.preventDefault();
event.stopPropagation();
if (event.defaultPrevented) return;
if (callerDisabled() || ctx.disabled.value) return;
ctx.clear();
}
return () => {
@@ -54,7 +61,7 @@ export default defineComponent({
"data-slot": "autocomplete-clear-button",
"data-empty": empty() || undefined,
"aria-hidden": empty() || undefined,
disabled: ctx.disabled.value || undefined,
disabled: ctx.disabled.value || callerDisabled() || undefined,
onClick: click,
};
return h("button", mergeProps(attrs, injected), [icon]);
@@ -19,7 +19,7 @@ import {
} from "vue";
import { useChoiceValue } from "../choice/shared";
import { useAutocomplete } from "./context";
import { elementFromRef } from "../combo-box/dom";
import { elementFromRef, mergedRef } from "../combo-box/dom";
function componentName(node: VNode): string | undefined {
const type = node.type as Record<string, unknown> | undefined;
@@ -52,27 +52,54 @@ export default defineComponent({
);
const text = () => model.value.value ?? "";
const root = ref<HTMLElement>();
/** While a composition session is open the collection keeps its rows. */
const composing = ref(false);
watchEffect(() => {
ctx.filterText.value = text();
ctx.filterPredicate.value = props.filter;
ctx.composing.value = composing.value;
// Mid-composition text stays visible without filtering the collection.
if (!composing.value) ctx.filterText.value = text();
});
function commitComposition() {
composing.value = false;
ctx.composing.value = false;
ctx.filterText.value = text();
}
function compose(nodes: VNodeChild[]): VNodeChild[] {
return nodes.map((child) => {
if (!isVNode(child)) return child;
const name = componentName(child);
if (name === "ListBox") return child;
if (name === "SearchFieldInput")
return cloneVNode(child, {
if (name === "SearchFieldInput") {
const own = (child.props ?? {}) as Record<string, unknown>;
const injected: Record<string, unknown> = {
...ctx.core(),
modelValue: text(),
"onUpdate:modelValue": (next: string) => model.request(next),
ref: (instance: unknown) => {
onCompositionstart: () => {
composing.value = true;
},
onCompositionend: () => commitComposition(),
// cloneVNode only honours a ref passed through its extra props.
ref: mergedRef(child.ref, (instance: unknown) => {
ctx.filterInput.value = elementFromRef(instance) as
HTMLInputElement | undefined;
},
});
}),
};
// The search input's own accessible name and description win over the
// picker root's: the trigger name is not a name for this control.
for (const key of [
"aria-label",
"aria-labelledby",
"aria-describedby",
]) {
if (own[key] !== undefined) delete injected[key];
}
return cloneVNode(child, injected);
}
const children = child.children;
if (Array.isArray(children)) {
const clone = cloneVNode(child);
@@ -1,6 +1,6 @@
<script lang="ts">
/** Decorative chevron: the trigger itself owns activation. */
import { defineComponent, h, mergeProps } from "vue";
import { cloneVNode, defineComponent, h, isVNode, mergeProps } from "vue";
import { useAutocomplete } from "./context";
const CHEVRON_PATH =
"M2.97 5.47a.75.75 0 0 1 1.06 0L8 9.44l3.97-3.97a.75.75 0 1 1 1.06 1.06l-4.5 4.5a.75.75 0 0 1-1.06 0l-4.5-4.5a.75.75 0 0 1 0-1.06";
@@ -12,14 +12,28 @@ export default defineComponent({
const ctx = useAutocomplete();
return () => {
const custom = slots.default?.() ?? [];
const indicatorClass = ctx.slots.value.indicator();
const openAttr = ctx.open.value || undefined;
// The baseline puts the indicator class, `data-slot` and `data-open` on the
// same element (the icon), which is what the ported CSS selects.
const icon =
custom.length > 0
? custom
? custom.map((node) =>
isVNode(node)
? cloneVNode(node, {
class: [indicatorClass, node.props?.class],
"data-slot": "autocomplete-indicator",
"data-open": openAttr,
})
: node,
)
: [
h(
"svg",
{
"aria-hidden": "true",
class: indicatorClass,
"data-open": openAttr,
"data-slot": "autocomplete-default-indicator",
fill: "none",
height: 16,
@@ -41,9 +55,7 @@ export default defineComponent({
"span",
mergeProps(attrs, {
"aria-hidden": "true",
class: ctx.slots.value.indicator(),
"data-slot": "autocomplete-indicator",
"data-open": ctx.open.value || undefined,
"data-slot": "autocomplete-indicator-wrapper",
}),
icon,
);
@@ -33,6 +33,26 @@ export interface AutocompleteOptions {
as?: string;
asChild?: boolean;
}
/** Scoped-slot state of `AutocompleteValue`. */
export interface AutocompleteValueState {
/** No accepted selection: render the placeholder. */
isPlaceholder: boolean;
/** Default text: joined `textValue`s, or the placeholder. */
defaultChildren: string;
/** Accepted `textValue`s joined by ", ". */
selectedText: string;
selectedItems: AutocompleteSelectedItem[];
}
/** Scoped-slot state of the `Autocomplete` root. */
export interface AutocompleteState {
isOpen: boolean;
selectedKeys: CollectionKey[];
}
export interface AutocompleteItem {
id: CollectionKey;
textValue: string;
isDisabled?: boolean;
}
export interface AutocompleteContext {
field: ReturnType<typeof useChoiceField<AutocompleteValue>>;
slots: ComputedRef<ReturnType<typeof autocompleteVariants>>;
@@ -64,7 +84,7 @@ export interface AutocompleteContext {
setActive: (key: CollectionKey | undefined) => Promise<void>;
confirmActive: () => void;
clear: () => void;
formValueText: ComputedRef<string | undefined>;
composing: Ref<boolean>;
}
export const autocompleteKey: InjectionKey<AutocompleteContext> =
Symbol("hv-autocomplete");
@@ -32,6 +32,7 @@ import {
type ValidateResult,
type ValidationBehavior,
} from "../field/context";
import type { CollectionKey } from "../collection/keys";
import { useInheritedDisabled } from "../field/disabled";
export interface ChoiceFieldProps {
@@ -301,6 +302,51 @@ export function useChoiceForm(
onBeforeUnmount(() => owner?.removeEventListener("reset", onReset));
}
/**
* The native submission layer for key-based pickers: same-name hidden inputs so
* a multiple selection arrives as separate entries, nothing at all when the
* field is disabled or a key is no longer part of the collection, and a single
* text entry when the picker submits text instead of keys.
*/
export function selectionInputs(options: {
name?: string;
form?: string;
multiple: boolean;
disabled: boolean;
keys: readonly CollectionKey[];
/** Text submission wins over keys when defined. */
text?: string;
slot: string;
}): VNode | null {
const { name, form, slot } = options;
if (!name || options.disabled) return null;
if (options.text !== undefined) {
if (!options.text) return null;
return h("input", {
type: "hidden",
name,
form,
value: options.text,
class: "hv-choice-input",
"data-slot": slot,
});
}
if (!options.keys.length) return null;
return h(
"span",
{ class: "hv-choice-input", "data-slot": `${slot}-entries` },
options.keys.map((key) =>
h("input", {
type: "hidden",
name,
form,
value: String(key),
"data-slot": slot,
}),
),
);
}
export function validationInput(
input: Ref<HTMLInputElement | undefined>,
props: ChoiceFieldProps,
@@ -0,0 +1,15 @@
/**
* Case- and accent-insensitive substring match, the equivalent of ICU
* "base" sensitivity for search: `Café` matches `cafe`, `STRASSE` matches
* `strasse` after compatibility normalisation.
*/
const fold = (value: string) => value.normalize("NFKD").replace(/\p{Mn}/gu, "");
export function createBaseContains(locale?: string) {
return (text: string, query: string) => {
if (!query) return true;
return fold(text)
.toLocaleLowerCase(locale)
.includes(fold(query).toLocaleLowerCase(locale));
};
}
@@ -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);
};
},
});
@@ -20,7 +20,7 @@ import {
} from "vue";
import { injectPopoverRootContext } from "reka-ui";
import { useComboBox } from "./context";
import { elementFromRef } from "./dom";
import { elementFromRef, mergedRef } from "./dom";
function componentName(node: VNode): string | undefined {
const type = node.type as Record<string, unknown> | undefined;
@@ -60,15 +60,23 @@ export default defineComponent({
function compose(node: VNodeChild): VNodeChild {
if (!isVNode(node) || componentName(node) !== "Input") return node;
return cloneVNode(node, {
const own = (node.props ?? {}) as Record<string, unknown>;
const injected: Record<string, unknown> = {
...ctx.inputProps(),
modelValue: ctx.displayInputValue.value,
"onUpdate:modelValue": (next: string) => ctx.setInputValue(next),
ref: (instance: unknown) => {
// The root variant is inherited; an explicit Input variant still wins.
variant: own.variant ?? ctx.variant(),
// cloneVNode only honours a ref passed through its extra props, so the
// caller's template ref and ours are merged here.
ref: mergedRef(node.ref, (instance: unknown) => {
ctx.inputElement.value = elementFromRef(instance) as
HTMLInputElement | undefined;
},
});
}),
};
for (const key of Object.keys(injected))
if (injected[key] === undefined) delete injected[key];
return cloneVNode(node, injected);
}
return () => {
@@ -11,7 +11,13 @@ export default defineComponent({
props: { isDisabled: { type: Boolean, default: false } },
setup(props, { attrs, slots }) {
const ctx = useComboBox();
const disabled = () => props.isDisabled || ctx.disabled.value;
// `disabled` may arrive as an attribute (`<ComboBoxTrigger disabled />`).
const callerDisabled = () =>
attrs.disabled !== undefined && attrs.disabled !== false
? true
: undefined;
const disabled = () =>
props.isDisabled || ctx.disabled.value || callerDisabled() === true;
function toggle(event: MouseEvent) {
if (event.defaultPrevented || disabled()) return;
ctx.setOpen(!ctx.open.value);
@@ -51,6 +57,7 @@ export default defineComponent({
"data-slot": "combo-box-trigger",
tabindex: -1,
disabled: disabled() || undefined,
"aria-disabled": undefined,
"aria-label":
typeof attrs["aria-label"] === "string"
? attrs["aria-label"]
@@ -11,6 +11,18 @@ export interface ComboBoxItem {
textValue: string;
isDisabled?: boolean;
}
/** Scoped-slot state of the `ComboBox` root. */
export interface ComboBoxState {
isOpen: boolean;
inputValue: string;
selectedKey: CollectionKey | null;
selectedKeys: CollectionKey[];
}
/** Scoped-slot state of `ComboBoxValue`. */
export interface ComboBoxValueState {
isPlaceholder: boolean;
selectedItems: ComboBoxSelectedItem[];
}
export interface ComboBoxSelectedItem {
key: CollectionKey;
textValue: string;
@@ -78,6 +90,7 @@ export interface ComboBoxContext {
/** ARIA plus input handlers injected onto the composed `Input`. */
inputProps: () => Record<string, unknown>;
formValueText: ComputedRef<string | undefined>;
variant: () => "primary" | "secondary";
invalid: ComputedRef<boolean>;
disabled: ComputedRef<boolean>;
}
@@ -5,3 +5,35 @@ export function elementFromRef(value: unknown): HTMLElement | undefined {
const element = (value as { $el?: unknown } | null)?.$el;
return element instanceof Element ? (element as HTMLElement) : undefined;
}
/**
* Keep both the caller's template ref and our internal one. Vue replaces a
* cloned vnode's ref, so the merge has to happen here; Vue 3.5 also stores
* component refs inside a `{ i, r }` holder that must be unwrapped.
*/
export function mergedRef(...refs: unknown[]) {
const assign = (ref: unknown, instance: unknown) => {
if (!ref) return;
if (typeof ref === "function") {
ref(instance);
return;
}
if (typeof ref !== "object") return;
if ("value" in (ref as object)) {
(ref as { value: unknown }).value = instance;
return;
}
const inner = (ref as { r?: unknown }).r;
if (inner !== undefined) assign(inner, instance);
};
return (instance: unknown) => {
for (const ref of refs) assign(ref, instance);
};
}
/**
* Vue vnode shape bits (not exported by the package). `cloneVNode` copies
* `shapeFlag`, so replacing an element's children needs these to stay coherent.
*/
export const SHAPE_TEXT_CHILDREN = 8;
export const SHAPE_ARRAY_CHILDREN = 16;