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.
826 lines
27 KiB
Vue
826 lines
27 KiB
Vue
<script lang="ts">
|
|
import {
|
|
cloneVNode,
|
|
computed,
|
|
defineComponent,
|
|
getCurrentInstance,
|
|
h,
|
|
isVNode,
|
|
mergeProps,
|
|
nextTick,
|
|
onBeforeUpdate,
|
|
onMounted,
|
|
provide,
|
|
ref,
|
|
shallowRef,
|
|
useId,
|
|
watch,
|
|
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";
|
|
import { assertKey, copyKeys, type CollectionKey } from "../collection/keys";
|
|
import {
|
|
collectionOwnerKey,
|
|
type CollectionRecord,
|
|
type OwnedCollection,
|
|
} from "../collection/owner";
|
|
import { planCollectionItems } from "./metadata";
|
|
import { SHAPE_ARRAY_CHILDREN, SHAPE_TEXT_CHILDREN } from "./dom";
|
|
import {
|
|
comboBoxKey,
|
|
type ComboBoxItem,
|
|
type ComboBoxMenuTrigger,
|
|
type ComboBoxValue,
|
|
} from "./context";
|
|
|
|
export default defineComponent({
|
|
name: "ComboBox",
|
|
inheritAttrs: false,
|
|
slots: Object as SlotsType<{
|
|
default?: (state: {
|
|
isOpen: boolean;
|
|
inputValue: string;
|
|
selectedKey: CollectionKey | null;
|
|
selectedKeys: CollectionKey[];
|
|
selectedItem: ComboBoxItem | null;
|
|
}) => VNodeChild;
|
|
}>,
|
|
props: {
|
|
modelValue: {
|
|
type: [String, Number, Array, null] as PropType<ComboBoxValue>,
|
|
default: undefined,
|
|
},
|
|
value: {
|
|
type: [String, Number, Array, null] as PropType<ComboBoxValue>,
|
|
default: undefined,
|
|
},
|
|
defaultValue: {
|
|
type: [String, Number, Array, null] as PropType<ComboBoxValue>,
|
|
default: undefined,
|
|
},
|
|
selectedKey: {
|
|
type: [String, Number, null] as PropType<CollectionKey | null>,
|
|
default: undefined,
|
|
},
|
|
defaultSelectedKey: {
|
|
type: [String, Number, null] as PropType<CollectionKey | null>,
|
|
default: undefined,
|
|
},
|
|
selectionMode: {
|
|
type: String as PropType<"single" | "multiple">,
|
|
default: "single",
|
|
},
|
|
inputValue: { type: String, default: undefined },
|
|
defaultInputValue: { type: String, default: "" },
|
|
items: Array as PropType<readonly ComboBoxItem[]>,
|
|
disabledKeys: Array as PropType<readonly CollectionKey[]>,
|
|
open: { type: Boolean, default: undefined },
|
|
isOpen: { type: Boolean, default: undefined },
|
|
defaultOpen: Boolean,
|
|
defaultFilter: Function as PropType<
|
|
(text: string, inputValue: string) => boolean
|
|
>,
|
|
isDisabled: Boolean,
|
|
disabled: Boolean,
|
|
isReadOnly: Boolean,
|
|
isRequired: Boolean,
|
|
isInvalid: Boolean,
|
|
allowsCustomValue: Boolean,
|
|
allowsEmptyCollection: Boolean,
|
|
menuTrigger: {
|
|
type: String as PropType<ComboBoxMenuTrigger>,
|
|
default: "focus",
|
|
},
|
|
shouldFocusWrap: Boolean,
|
|
fullWidth: Boolean,
|
|
variant: {
|
|
type: String as PropType<"primary" | "secondary">,
|
|
default: "primary",
|
|
},
|
|
name: String,
|
|
form: String,
|
|
formValue: {
|
|
type: String as PropType<"key" | "text">,
|
|
default: "key",
|
|
},
|
|
autoComplete: String,
|
|
autoFocus: Boolean,
|
|
validationBehavior: String as PropType<ValidationBehavior>,
|
|
validate: Function as PropType<(value: ComboBoxValue) => ValidateResult>,
|
|
placeholder: { type: String, default: "Select an item" },
|
|
as: { type: String, default: "div" },
|
|
asChild: { type: Boolean, default: false },
|
|
},
|
|
emits: {
|
|
"update:modelValue": (_value: ComboBoxValue) => true,
|
|
change: (_value: ComboBoxValue) => true,
|
|
"update:selectedKey": (_value: CollectionKey | null) => true,
|
|
selectionChange: (_value: CollectionKey | null) => true,
|
|
"update:inputValue": (_value: string) => true,
|
|
inputChange: (_value: string) => true,
|
|
"update:open": (_value: boolean) => true,
|
|
openChange: (_value: boolean) => 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 readValue = (): ComboBoxValue | undefined => {
|
|
if (present(["modelValue", "model-value"]))
|
|
return props.modelValue ?? null;
|
|
if (present(["value"])) return props.value ?? null;
|
|
if (present(["selectedKey", "selected-key"]))
|
|
return props.selectedKey ?? null;
|
|
return undefined;
|
|
};
|
|
const model = useChoiceValue<ComboBoxValue | undefined>(
|
|
readValue,
|
|
() => props.defaultValue ?? props.defaultSelectedKey ?? null,
|
|
["modelValue", "model-value", "value", "selectedKey", "selected-key"],
|
|
(value) => {
|
|
const next = value ?? null;
|
|
emit("update:modelValue", next);
|
|
emit("change", next);
|
|
const single =
|
|
props.selectionMode === "multiple"
|
|
? ((Array.isArray(next) ? next[0] : next) ?? null)
|
|
: Array.isArray(next)
|
|
? (next[0] ?? null)
|
|
: next;
|
|
emit("update:selectedKey", single);
|
|
emit("selectionChange", single);
|
|
},
|
|
);
|
|
const value = computed<ComboBoxValue>(() => {
|
|
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;
|
|
if (
|
|
props.selectionMode === "multiple" &&
|
|
raw !== null &&
|
|
!Array.isArray(raw)
|
|
)
|
|
throw new TypeError("Multiple ComboBox expects a key array.");
|
|
const next = copyKeys(
|
|
raw === null ? [] : Array.isArray(raw) ? raw : [raw],
|
|
);
|
|
if (props.selectionMode === "single" && next.length > 1)
|
|
throw new TypeError("Single ComboBox expects one key or null.");
|
|
return Object.freeze(next);
|
|
});
|
|
const inputModel = useChoiceValue<string | undefined>(
|
|
() => props.inputValue,
|
|
() => props.defaultInputValue,
|
|
["inputValue", "input-value"],
|
|
(next) => {
|
|
emit("update:inputValue", next ?? "");
|
|
emit("inputChange", next ?? "");
|
|
},
|
|
);
|
|
const inputValue = computed(() => inputModel.value.value ?? "");
|
|
|
|
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[]>([]);
|
|
watchEffect(() => {
|
|
if (!collection.value) return;
|
|
const next = collection.value.items();
|
|
if (JSON.stringify(next) !== JSON.stringify(discovered.value))
|
|
discovered.value = next;
|
|
});
|
|
const planned = shallowRef<CollectionRecord[]>([]);
|
|
const complete = ref(false);
|
|
const records = computed<CollectionRecord[]>(() => {
|
|
const explicit = props.items?.map((item) => {
|
|
assertKey(item.id);
|
|
return {
|
|
key: item.id,
|
|
text: item.textValue,
|
|
disabled: !!item.isDisabled,
|
|
} satisfies CollectionRecord;
|
|
});
|
|
// Caller data wins; otherwise the complete slot plan is authoritative for
|
|
// a closed ComboBox, and mounted rows fill in when the plan is opaque.
|
|
const base =
|
|
explicit ??
|
|
(complete.value
|
|
? planned.value
|
|
: discovered.value.length
|
|
? discovered.value
|
|
: planned.value);
|
|
return base.map((record) => ({
|
|
...record,
|
|
disabled: record.disabled || !!props.disabledKeys?.includes(record.key),
|
|
}));
|
|
});
|
|
|
|
const filter = (record: CollectionRecord) =>
|
|
props.defaultFilter
|
|
? props.defaultFilter(record.text, filterText.value)
|
|
: contains(record.text, filterText.value);
|
|
|
|
const instanceId = useId();
|
|
const inputId = `hv-combo-box-${instanceId}-input`;
|
|
const listId = `hv-combo-box-${instanceId}-listbox`;
|
|
const valueId = `hv-combo-box-${instanceId}-value`;
|
|
|
|
const field = useChoiceField<ComboBoxValue>(props, attrs, {
|
|
kind: "group",
|
|
value,
|
|
validate: (current) => props.validate?.(current),
|
|
satisfied: () =>
|
|
props.allowsCustomValue
|
|
? inputValue.value.trim().length > 0
|
|
: keys.value.length > 0,
|
|
requiredMessage: "请选择一个选项。",
|
|
});
|
|
// A combobox input is a text control: Label must render `<label for>` and
|
|
// point at the composed input, not at an unrelated generated id.
|
|
provide(fieldContextKey, {
|
|
...field.field,
|
|
kind: "text",
|
|
controlId: computed(() => inputId),
|
|
} as FieldContext);
|
|
provide(disabledContextKey, field.field.disabled);
|
|
|
|
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>();
|
|
let anchor: (() => HTMLElement | undefined) | undefined;
|
|
const registerAnchor = (element: () => HTMLElement | undefined) => {
|
|
anchor = element;
|
|
};
|
|
|
|
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 || field.field.readOnly.value) return;
|
|
const candidate = (key: CollectionKey) =>
|
|
records.value.find((record) => record.key === key);
|
|
if (
|
|
next.some(
|
|
(key) => candidate(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;
|
|
// 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),
|
|
);
|
|
if (props.selectionMode === "single") {
|
|
const record = next.length ? candidate(next[0]) : undefined;
|
|
if (record && !props.allowsCustomValue) inputModel.request(record.text);
|
|
setOpen(false);
|
|
}
|
|
}
|
|
|
|
function setOpen(next: boolean) {
|
|
if (next === open.value) return;
|
|
if (
|
|
next &&
|
|
(field.field.disabled.value || field.field.readOnly.value) === true
|
|
)
|
|
return;
|
|
if (
|
|
next &&
|
|
props.items &&
|
|
!props.items.length &&
|
|
!props.allowsEmptyCollection
|
|
)
|
|
return;
|
|
openModel.request(next);
|
|
if (next) {
|
|
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);
|
|
});
|
|
} else {
|
|
activeKey.value = undefined;
|
|
}
|
|
}
|
|
|
|
async function setActive(key: CollectionKey | undefined) {
|
|
cursor.value = key;
|
|
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[
|
|
props.shouldFocusWrap
|
|
? (index + delta + items.length) % items.length
|
|
: Math.min(Math.max(index + delta, 0), items.length - 1)
|
|
];
|
|
if (next) void setActive(next.key);
|
|
}
|
|
|
|
function confirmActive() {
|
|
const key = activeKey.value;
|
|
const record =
|
|
key === undefined
|
|
? undefined
|
|
: records.value.find(
|
|
(item) => item.key === key && filter(item) && !item.disabled,
|
|
);
|
|
if (key === undefined || !record) {
|
|
const typed = inputValue.value.trim();
|
|
// A custom value is the typed text itself, not a collection key.
|
|
if (
|
|
props.allowsCustomValue &&
|
|
props.selectionMode === "single" &&
|
|
typed
|
|
)
|
|
request([typed]);
|
|
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]);
|
|
}
|
|
|
|
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. 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" || inputControlled.value) return;
|
|
if (keepDraft) {
|
|
keepDraft = false;
|
|
return;
|
|
}
|
|
syncAcceptedText();
|
|
},
|
|
{ immediate: true },
|
|
);
|
|
|
|
/**
|
|
* 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;
|
|
return selectedRecord.value?.text ?? "";
|
|
});
|
|
|
|
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(
|
|
(record) => filter(record) && !record.disabled,
|
|
);
|
|
if (first) void setActive(first.key);
|
|
}
|
|
if (
|
|
props.selectionMode === "single" &&
|
|
!props.allowsCustomValue &&
|
|
keys.value.length
|
|
) {
|
|
const selected = records.value.find((record) =>
|
|
keys.value.includes(record.key),
|
|
);
|
|
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 ||
|
|
composing.value ||
|
|
event.isComposing ||
|
|
event.keyCode === 229
|
|
)
|
|
return;
|
|
if (field.field.disabled.value || field.field.readOnly.value) return;
|
|
keyboardIntent.value = true;
|
|
const meta = event.metaKey || event.ctrlKey || event.altKey;
|
|
if (meta) return;
|
|
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
event.preventDefault();
|
|
if (!open.value) {
|
|
setOpen(true);
|
|
return;
|
|
}
|
|
moveActive(event.key === "ArrowDown" ? 1 : -1);
|
|
return;
|
|
}
|
|
if (event.key === "Home" || event.key === "End") {
|
|
if (!open.value) return;
|
|
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) return;
|
|
confirmActive();
|
|
return;
|
|
}
|
|
if (event.key === "Escape") {
|
|
if (!open.value) return;
|
|
event.preventDefault();
|
|
setOpen(false);
|
|
return;
|
|
}
|
|
if (event.key === "Tab") {
|
|
setOpen(false);
|
|
}
|
|
}
|
|
|
|
function focusInput() {
|
|
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();
|
|
}
|
|
|
|
const formValueText = computed<string | undefined>(() => {
|
|
if (!props.name) return undefined;
|
|
if (props.formValue === "text" || props.allowsCustomValue) {
|
|
const texts = keys.value
|
|
.map((key) => records.value.find((item) => item.key === key)?.text)
|
|
.filter((text): text is string => !!text);
|
|
return texts.length ? texts.join(",") : inputValue.value || undefined;
|
|
}
|
|
return keys.value.length ? keys.value.map(String).join(",") : undefined;
|
|
});
|
|
|
|
const invalid = computed(() => field.field.invalid.value);
|
|
const slotsBase = computed(() =>
|
|
comboBoxVariants({ fullWidth: props.fullWidth }),
|
|
);
|
|
|
|
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 : inputId),
|
|
ariaLabel: () =>
|
|
typeof attrs["aria-label"] === "string"
|
|
? attrs["aria-label"]
|
|
: undefined,
|
|
request,
|
|
action: (key) => {
|
|
if (props.selectionMode === "single") setOpen(false);
|
|
void key;
|
|
},
|
|
leave: () => setOpen(false),
|
|
connect: (next) => {
|
|
if (collection.value && collection.value !== next)
|
|
throw new Error("ComboBox supports one ListBox.");
|
|
collection.value = next;
|
|
return () => {
|
|
if (collection.value === next) collection.value = undefined;
|
|
};
|
|
},
|
|
filter,
|
|
virtualFocus: () => true,
|
|
activeKey,
|
|
keyboardIntent,
|
|
isOpen: () => open.value,
|
|
});
|
|
|
|
const inputProps = () => ({
|
|
id: inputId,
|
|
role: "combobox",
|
|
autocomplete: props.autoComplete ?? "off",
|
|
spellcheck: false,
|
|
"aria-expanded": open.value,
|
|
"aria-controls": open.value ? listId : undefined,
|
|
"aria-activedescendant": activeId.value,
|
|
"aria-autocomplete": "list" as const,
|
|
"aria-haspopup": "listbox" as const,
|
|
"aria-label": attrs["aria-label"] as string | undefined,
|
|
"aria-labelledby":
|
|
attrs["aria-labelledby"] ??
|
|
(attrs["aria-label"] ? undefined : field.labelledBy()),
|
|
"aria-describedby": describedBy(),
|
|
"aria-invalid": invalid.value || undefined,
|
|
readonly: field.field.readOnly.value || undefined,
|
|
disabled: field.field.disabled.value || undefined,
|
|
required:
|
|
(field.behavior.value === "native" && field.field.required.value) ||
|
|
undefined,
|
|
form: props.form,
|
|
onKeydown: keydown,
|
|
onFocus: focusInput,
|
|
onCompositionstart: () => {
|
|
composing.value = true;
|
|
},
|
|
onCompositionend: () => {
|
|
composing.value = false;
|
|
applyInput(inputValue.value);
|
|
},
|
|
});
|
|
|
|
provide(comboBoxKey, {
|
|
field,
|
|
slots: slotsBase,
|
|
open,
|
|
setOpen,
|
|
inputValue,
|
|
displayInputValue,
|
|
setInputValue,
|
|
inputId,
|
|
listId,
|
|
valueId,
|
|
placeholder: () => props.placeholder,
|
|
activeKey,
|
|
activeId,
|
|
collection,
|
|
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),
|
|
allowsCustomValue: () => props.allowsCustomValue,
|
|
menuTrigger: () => props.menuTrigger,
|
|
inputElement,
|
|
registerAnchor,
|
|
triggerElement,
|
|
inputProps,
|
|
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,
|
|
() => {
|
|
model.reset();
|
|
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);
|
|
},
|
|
);
|
|
watchEffect(() => {
|
|
// `required` plus the custom message live on the visible input, which is
|
|
// the control the browser blocks on.
|
|
const element = inputElement.value;
|
|
if (!element) return;
|
|
element.required =
|
|
field.behavior.value === "native" && field.field.required.value;
|
|
field.validity(element);
|
|
});
|
|
watchEffect(() => {
|
|
if (!open.value || props.allowsEmptyCollection) return;
|
|
if (!records.value.length) return;
|
|
const eligibleRecords = records.value.filter(
|
|
(record) => filter(record) && !record.disabled,
|
|
);
|
|
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,
|
|
open: () => setOpen(true),
|
|
close: () => setOpen(false),
|
|
focus: () => inputElement.value?.focus(),
|
|
});
|
|
|
|
return () => {
|
|
const rendered = slots.default?.({
|
|
isOpen: open.value,
|
|
inputValue: inputValue.value,
|
|
selectedKey: Array.isArray(value.value)
|
|
? null
|
|
: (value.value as CollectionKey | null),
|
|
selectedKeys: [...keys.value],
|
|
selectedItem:
|
|
(!Array.isArray(value.value) && value.value != null
|
|
? (props.items?.find((entry) => entry.id === value.value) ?? null)
|
|
: null) ?? null,
|
|
});
|
|
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 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);
|
|
};
|
|
},
|
|
});
|
|
</script>
|