feat(combo-box): migrate ComboBox with input-owned focus and filtering
Port the fixed-baseline ComboBox onto the B02a collection protocol: the input keeps real DOM focus, the list only tracks an active row, and filtering reuses the owner filter instead of a second collection kernel. - Five parts: root (field text control, value/input/open models, form value, owner wiring), InputGroup (composes the caller's Input into the combobox control and anchors the popover), Trigger, Value, Popover. - Closed-state metadata is planned from the slot tree, so filtering, the initial value label and form-value="text" work before the list has mounted. - Selection text syncs on selection changes only, so allows-custom-value typing is not overwritten; read-only and disabled are injected onto the composed input because it reads the text-field protocol, not the field context. - 24 baseline previews, the Chinese doc page, navigation, 19 behaviour tests and 6 demo/document contracts. Async demo uses a local async source with abort, loading and incremental append (documented adaptations). Not included: independent tarball consumption (B02d).
This commit is contained in:
@@ -0,0 +1,678 @@
|
||||
<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 { comboBoxVariants } from "@heroui-vue/styles";
|
||||
import Popover from "../popover/Popover";
|
||||
import {
|
||||
useChoiceField,
|
||||
useChoiceForm,
|
||||
useChoiceValue,
|
||||
} from "../choice/shared";
|
||||
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 { planComboBoxItems } from "./metadata";
|
||||
import {
|
||||
comboBoxKey,
|
||||
type ComboBoxItem,
|
||||
type ComboBoxMenuTrigger,
|
||||
type ComboBoxValue,
|
||||
} from "./context";
|
||||
|
||||
const contains = (text: string, inputValue: string) =>
|
||||
!inputValue ||
|
||||
text.toLocaleLowerCase().includes(inputValue.toLocaleLowerCase());
|
||||
|
||||
export default defineComponent({
|
||||
name: "ComboBox",
|
||||
inheritAttrs: false,
|
||||
slots: Object as SlotsType<{
|
||||
default?: (state: {
|
||||
isOpen: boolean;
|
||||
inputValue: string;
|
||||
selectedKey: CollectionKey | null;
|
||||
selectedKeys: CollectionKey[];
|
||||
}) => 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 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, inputValue.value)
|
||||
: contains(record.text, inputValue.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>();
|
||||
const cursor = ref<CollectionKey>();
|
||||
const inputElement = ref<HTMLInputElement>();
|
||||
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;
|
||||
if (
|
||||
!next.length &&
|
||||
!props.allowsCustomValue &&
|
||||
!props.allowsEmptyCollection &&
|
||||
(props.isRequired || field.field.required.value)
|
||||
)
|
||||
return;
|
||||
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;
|
||||
if (key === undefined) return;
|
||||
const record = records.value.find(
|
||||
(item) => item.key === key && filter(item) && !item.disabled,
|
||||
);
|
||||
if (!record) return;
|
||||
request([key]);
|
||||
}
|
||||
|
||||
const composing = ref(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}`,
|
||||
() => {
|
||||
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);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
function setInputValue(next: string) {
|
||||
inputModel.request(next);
|
||||
if (props.menuTrigger === "input" && !open.value && next) setOpen(true);
|
||||
// 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) request([]);
|
||||
}
|
||||
}
|
||||
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (event.defaultPrevented || 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);
|
||||
}
|
||||
|
||||
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,
|
||||
onKeydown: keydown,
|
||||
onFocus: focusInput,
|
||||
onCompositionstart: () => {
|
||||
composing.value = true;
|
||||
},
|
||||
onCompositionend: () => {
|
||||
composing.value = false;
|
||||
},
|
||||
});
|
||||
|
||||
provide(comboBoxKey, {
|
||||
field,
|
||||
slots: slotsBase,
|
||||
open,
|
||||
setOpen,
|
||||
inputValue,
|
||||
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),
|
||||
})),
|
||||
),
|
||||
selectionMode: computed(() => props.selectionMode),
|
||||
allowsCustomValue: () => props.allowsCustomValue,
|
||||
menuTrigger: () => props.menuTrigger,
|
||||
inputElement,
|
||||
registerAnchor,
|
||||
inputProps,
|
||||
formValueText,
|
||||
invalid,
|
||||
disabled: field.field.disabled,
|
||||
});
|
||||
|
||||
useChoiceForm(
|
||||
inputElement,
|
||||
() => {
|
||||
model.reset();
|
||||
inputModel.reset();
|
||||
field.reset();
|
||||
setOpen(false);
|
||||
},
|
||||
() => {
|
||||
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);
|
||||
});
|
||||
|
||||
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],
|
||||
});
|
||||
const children = Array.isArray(rendered)
|
||||
? rendered
|
||||
: rendered == null
|
||||
? []
|
||||
: [rendered];
|
||||
const plan = planComboBoxItems(children);
|
||||
if (JSON.stringify(plan.records) !== JSON.stringify(planned.value))
|
||||
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,
|
||||
],
|
||||
),
|
||||
},
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,85 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* Container for the combobox input and its trigger. It also composes the
|
||||
* consumer's `Input` into the combobox control: value binding, ARIA and the
|
||||
* keyboard contract are injected onto that single input, so focus never leaves
|
||||
* it while the list navigates.
|
||||
*/
|
||||
import {
|
||||
cloneVNode,
|
||||
defineComponent,
|
||||
h,
|
||||
isVNode,
|
||||
mergeProps,
|
||||
onMounted,
|
||||
onUpdated,
|
||||
ref,
|
||||
watch,
|
||||
type VNode,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { injectPopoverRootContext } from "reka-ui";
|
||||
import { useComboBox } from "./context";
|
||||
import { elementFromRef } from "./dom";
|
||||
|
||||
function componentName(node: VNode): string | undefined {
|
||||
const type = node.type as Record<string, unknown> | undefined;
|
||||
const name = type?.name ?? type?.__name;
|
||||
return typeof name === "string" ? name : undefined;
|
||||
}
|
||||
|
||||
export default defineComponent({
|
||||
name: "ComboBoxInputGroup",
|
||||
inheritAttrs: false,
|
||||
setup(_props, { attrs, slots }) {
|
||||
const ctx = useComboBox();
|
||||
const popover = injectPopoverRootContext();
|
||||
const root = ref<HTMLElement>();
|
||||
|
||||
ctx.registerAnchor(() => elementFromRef(root.value));
|
||||
watch(
|
||||
root,
|
||||
() => {
|
||||
if (popover) popover.triggerElement.value = elementFromRef(root.value);
|
||||
},
|
||||
{ immediate: true, flush: "post" },
|
||||
);
|
||||
onMounted(() => {
|
||||
if (popover) popover.triggerElement.value = elementFromRef(root.value);
|
||||
});
|
||||
onUpdated(() => {
|
||||
if (popover) popover.triggerElement.value = elementFromRef(root.value);
|
||||
});
|
||||
|
||||
function compose(node: VNodeChild): VNodeChild {
|
||||
if (!isVNode(node) || componentName(node) !== "Input") return node;
|
||||
return cloneVNode(node, {
|
||||
...ctx.inputProps(),
|
||||
modelValue: ctx.inputValue.value,
|
||||
"onUpdate:modelValue": (next: string) => ctx.setInputValue(next),
|
||||
ref: (instance: unknown) => {
|
||||
ctx.inputElement.value = elementFromRef(instance) as
|
||||
HTMLInputElement | undefined;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
const rendered = slots.default?.() ?? [];
|
||||
const children = (
|
||||
Array.isArray(rendered) ? rendered : [rendered]
|
||||
) as VNodeChild[];
|
||||
return h(
|
||||
"div",
|
||||
mergeProps(attrs, {
|
||||
ref: root,
|
||||
class: ctx.slots.value.inputGroup(),
|
||||
"data-slot": "combo-box-input-group",
|
||||
"data-disabled": ctx.disabled.value || undefined,
|
||||
}),
|
||||
children.map(compose),
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,43 @@
|
||||
<script lang="ts">
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import PopoverContent from "../popover/PopoverContent.vue";
|
||||
import { useComboBox } from "./context";
|
||||
import type { OverlayPlacement } from "../overlay/placement";
|
||||
|
||||
export default defineComponent({
|
||||
name: "ComboBoxPopover",
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
placement: { type: String as () => OverlayPlacement, default: "bottom" },
|
||||
offset: { type: Number, default: 8 },
|
||||
to: [String, Object] as unknown as () => string | HTMLElement,
|
||||
shouldFlip: { type: Boolean, default: true },
|
||||
containerPadding: { type: Number, default: 12 },
|
||||
},
|
||||
setup(props, { attrs, slots }) {
|
||||
const ctx = useComboBox();
|
||||
return () =>
|
||||
h(
|
||||
PopoverContent,
|
||||
mergeProps(attrs, {
|
||||
placement: props.placement,
|
||||
offset: props.offset,
|
||||
to: props.to,
|
||||
shouldFlip: props.shouldFlip,
|
||||
containerPadding: props.containerPadding,
|
||||
class: ctx.slots.value.popover(),
|
||||
id: `${ctx.listId}-popover`,
|
||||
role: "presentation",
|
||||
"data-slot": "combo-box-popover",
|
||||
style: {
|
||||
"--trigger-width": "var(--reka-popover-trigger-width)",
|
||||
"--trigger-anchor-point": "var(--reka-popper-transform-origin)",
|
||||
},
|
||||
// Focus stays in the combobox input; the list only tracks an active row.
|
||||
onOpenAutoFocus: (event: Event) => event.preventDefault(),
|
||||
}),
|
||||
{ default: () => slots.default?.() },
|
||||
);
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,70 @@
|
||||
<script lang="ts">
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import { useComboBox } from "./context";
|
||||
// Baseline chevron, adapted from HeroUI ce90ea3 icons.tsx (Apache-2.0).
|
||||
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";
|
||||
|
||||
export default defineComponent({
|
||||
name: "ComboBoxTrigger",
|
||||
inheritAttrs: false,
|
||||
props: { isDisabled: { type: Boolean, default: false } },
|
||||
setup(props, { attrs, slots }) {
|
||||
const ctx = useComboBox();
|
||||
const disabled = () => props.isDisabled || ctx.disabled.value;
|
||||
function toggle(event: MouseEvent) {
|
||||
if (event.defaultPrevented || disabled()) return;
|
||||
ctx.setOpen(!ctx.open.value);
|
||||
ctx.inputElement.value?.focus({ preventScroll: true });
|
||||
}
|
||||
return () => {
|
||||
const open = ctx.open.value;
|
||||
const custom = slots.default?.() ?? [];
|
||||
const icon =
|
||||
custom.length > 0
|
||||
? custom
|
||||
: [
|
||||
h(
|
||||
"svg",
|
||||
{
|
||||
"aria-hidden": "true",
|
||||
"data-slot": "combo-box-trigger-default-icon",
|
||||
fill: "none",
|
||||
height: 16,
|
||||
role: "presentation",
|
||||
viewBox: "0 0 16 16",
|
||||
width: 16,
|
||||
},
|
||||
[
|
||||
h("path", {
|
||||
d: CHEVRON_PATH,
|
||||
fill: "currentColor",
|
||||
"fill-rule": "evenodd",
|
||||
"clip-rule": "evenodd",
|
||||
}),
|
||||
],
|
||||
),
|
||||
];
|
||||
const injected: Record<string, unknown> = {
|
||||
type: "button",
|
||||
class: ctx.slots.value.trigger(),
|
||||
"data-slot": "combo-box-trigger",
|
||||
tabindex: -1,
|
||||
disabled: disabled() || undefined,
|
||||
"aria-label":
|
||||
typeof attrs["aria-label"] === "string"
|
||||
? attrs["aria-label"]
|
||||
: "Show suggestions",
|
||||
"aria-expanded": open,
|
||||
onClick: toggle,
|
||||
};
|
||||
if (open) {
|
||||
injected["data-open"] = true;
|
||||
injected["aria-controls"] = ctx.listId;
|
||||
}
|
||||
if (disabled()) injected["data-disabled"] = true;
|
||||
return h("button", mergeProps(attrs, injected), [icon]);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,35 @@
|
||||
<script lang="ts">
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import { useComboBox } from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
name: "ComboBoxValue",
|
||||
inheritAttrs: false,
|
||||
props: { placeholder: { type: String, default: undefined } },
|
||||
setup(props, { attrs, slots }) {
|
||||
const ctx = useComboBox();
|
||||
return () => {
|
||||
const selected = ctx.selectedItems.value;
|
||||
const isPlaceholder = selected.length === 0;
|
||||
const text = selected
|
||||
.map((item) => item.textValue)
|
||||
.join(", ")
|
||||
.trim();
|
||||
const placeholder = props.placeholder ?? ctx.placeholder();
|
||||
const content =
|
||||
slots.default?.({ isPlaceholder, selectedItems: selected }) ??
|
||||
(isPlaceholder ? placeholder : text);
|
||||
return h(
|
||||
"div",
|
||||
mergeProps(attrs, {
|
||||
class: ctx.slots.value.value(),
|
||||
id: ctx.valueId,
|
||||
"data-slot": "combo-box-value",
|
||||
"data-placeholder": isPlaceholder || undefined,
|
||||
}),
|
||||
content,
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,88 @@
|
||||
import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue";
|
||||
import type { comboBoxVariants } from "@heroui-vue/styles";
|
||||
import type { CollectionKey } from "../collection/keys";
|
||||
import type { CollectionRecord, OwnedCollection } from "../collection/owner";
|
||||
import type { useChoiceField } from "../choice/shared";
|
||||
|
||||
export type ComboBoxValue = CollectionKey | CollectionKey[] | null;
|
||||
export type ComboBoxMenuTrigger = "focus" | "input" | "manual";
|
||||
export interface ComboBoxItem {
|
||||
id: CollectionKey;
|
||||
textValue: string;
|
||||
isDisabled?: boolean;
|
||||
}
|
||||
export interface ComboBoxSelectedItem {
|
||||
key: CollectionKey;
|
||||
textValue: string;
|
||||
}
|
||||
/** Props shared by the SFC and the context; keep one schema. */
|
||||
export interface ComboBoxOptions {
|
||||
modelValue?: ComboBoxValue;
|
||||
value?: ComboBoxValue;
|
||||
defaultValue?: ComboBoxValue;
|
||||
selectedKey?: CollectionKey | null;
|
||||
defaultSelectedKey?: CollectionKey | null;
|
||||
selectionMode?: "single" | "multiple";
|
||||
inputValue?: string;
|
||||
defaultInputValue?: string;
|
||||
items?: readonly ComboBoxItem[];
|
||||
disabledKeys?: readonly CollectionKey[];
|
||||
open?: boolean;
|
||||
isOpen?: boolean;
|
||||
defaultOpen?: boolean;
|
||||
defaultFilter?: (text: string, inputValue: string) => boolean;
|
||||
isDisabled?: boolean;
|
||||
disabled?: boolean;
|
||||
isReadOnly?: boolean;
|
||||
isRequired?: boolean;
|
||||
isInvalid?: boolean;
|
||||
allowsCustomValue?: boolean;
|
||||
allowsEmptyCollection?: boolean;
|
||||
menuTrigger?: ComboBoxMenuTrigger;
|
||||
shouldFocusWrap?: boolean;
|
||||
fullWidth?: boolean;
|
||||
variant?: "primary" | "secondary";
|
||||
name?: string;
|
||||
form?: string;
|
||||
formValue?: "key" | "text";
|
||||
autoComplete?: string;
|
||||
autoFocus?: boolean;
|
||||
validationBehavior?: "native" | "aria";
|
||||
placeholder?: string;
|
||||
}
|
||||
export interface ComboBoxContext {
|
||||
field: ReturnType<typeof useChoiceField<ComboBoxValue>>;
|
||||
slots: ComputedRef<ReturnType<typeof comboBoxVariants>>;
|
||||
open: ComputedRef<boolean>;
|
||||
setOpen: (open: boolean) => void;
|
||||
inputValue: ComputedRef<string>;
|
||||
setInputValue: (value: string) => void;
|
||||
inputId: string;
|
||||
listId: string;
|
||||
valueId: string;
|
||||
placeholder: () => string;
|
||||
activeKey: Ref<CollectionKey | undefined>;
|
||||
activeId: ComputedRef<string | undefined>;
|
||||
collection: Ref<OwnedCollection | undefined>;
|
||||
keys: ComputedRef<readonly CollectionKey[]>;
|
||||
records: ComputedRef<CollectionRecord[]>;
|
||||
selectedItems: ComputedRef<ComboBoxSelectedItem[]>;
|
||||
selectionMode: ComputedRef<"single" | "multiple">;
|
||||
allowsCustomValue: () => boolean;
|
||||
menuTrigger: () => ComboBoxMenuTrigger;
|
||||
inputElement: Ref<HTMLInputElement | undefined>;
|
||||
registerAnchor: (element: () => HTMLElement | undefined) => void;
|
||||
/** ARIA plus input handlers injected onto the composed `Input`. */
|
||||
inputProps: () => Record<string, unknown>;
|
||||
formValueText: ComputedRef<string | undefined>;
|
||||
invalid: ComputedRef<boolean>;
|
||||
disabled: ComputedRef<boolean>;
|
||||
}
|
||||
export const comboBoxKey: InjectionKey<ComboBoxContext> =
|
||||
Symbol("hv-combo-box");
|
||||
|
||||
export function useComboBox(): ComboBoxContext {
|
||||
const context = inject(comboBoxKey, undefined);
|
||||
if (!context) throw new Error("ComboBox parts require ComboBox.");
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/** Resolve a component ref handle (or element) to its DOM node. */
|
||||
export function elementFromRef(value: unknown): HTMLElement | undefined {
|
||||
if (typeof Element === "undefined") return undefined;
|
||||
if (value instanceof Element) return value as HTMLElement;
|
||||
const element = (value as { $el?: unknown } | null)?.$el;
|
||||
return element instanceof Element ? (element as HTMLElement) : undefined;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { Fragment, Text, isVNode, type VNode, type VNodeChild } from "vue";
|
||||
import { assertKey, type CollectionKey } from "../collection/keys";
|
||||
import type { CollectionRecord } from "../collection/owner";
|
||||
|
||||
function name(node: VNode) {
|
||||
const type = node.type as { name?: string; __name?: string } | undefined;
|
||||
return type?.name ?? type?.__name;
|
||||
}
|
||||
function children(node: VNode): VNodeChild[] {
|
||||
if (Array.isArray(node.children)) return node.children as VNodeChild[];
|
||||
if (node.children && typeof node.children === "object") {
|
||||
const result = (
|
||||
node.children as { default?: () => VNodeChild }
|
||||
).default?.();
|
||||
return Array.isArray(result) ? result : result == null ? [] : [result];
|
||||
}
|
||||
return typeof node.children === "string" ? [node.children] : [];
|
||||
}
|
||||
function text(nodes: VNodeChild[]): string {
|
||||
return nodes
|
||||
.map((node) => {
|
||||
if (typeof node === "string" || typeof node === "number")
|
||||
return String(node);
|
||||
if (Array.isArray(node)) return text(node);
|
||||
if (!isVNode(node)) return "";
|
||||
if (node.type === Text) return String(node.children);
|
||||
if (
|
||||
node.type === Fragment ||
|
||||
typeof node.type === "string" ||
|
||||
name(node) === "Label"
|
||||
)
|
||||
return text(children(node));
|
||||
return "";
|
||||
})
|
||||
.join("")
|
||||
.trim();
|
||||
}
|
||||
|
||||
const CONTAINERS = ["ComboBoxPopover", "SelectPopover", "ListBoxSection"];
|
||||
|
||||
/**
|
||||
* Collect the collection metadata of a closed ComboBox from its slot tree.
|
||||
* Filtering, the initial value label and `form-value="text"` need the full data
|
||||
* set before the popover (and therefore the ListBox) has ever mounted.
|
||||
*/
|
||||
export function planComboBoxItems(nodes: VNodeChild[]) {
|
||||
const records: CollectionRecord[] = [];
|
||||
let found = false;
|
||||
let opaque = false;
|
||||
function add(record: CollectionRecord) {
|
||||
assertKey(record.key);
|
||||
if (records.some((item) => item.key === record.key))
|
||||
throw new Error(`Duplicate collection key: ${record.key}`);
|
||||
records.push(record);
|
||||
}
|
||||
function walk(
|
||||
nodes: VNodeChild[],
|
||||
inside = false,
|
||||
blocked: readonly CollectionKey[] = [],
|
||||
) {
|
||||
for (const node of nodes) {
|
||||
if (Array.isArray(node)) {
|
||||
walk(node, inside, blocked);
|
||||
continue;
|
||||
}
|
||||
if (!isVNode(node)) continue;
|
||||
const component = name(node);
|
||||
if (component === "ListBoxItem") {
|
||||
const key = node.props?.id;
|
||||
const disabled = node.props?.isDisabled ?? node.props?.["is-disabled"];
|
||||
add({
|
||||
key,
|
||||
text:
|
||||
node.props?.textValue ??
|
||||
node.props?.["text-value"] ??
|
||||
text(children(node)),
|
||||
disabled:
|
||||
disabled === true || disabled === "" || blocked.includes(key),
|
||||
});
|
||||
} else if (component === "ListBox") {
|
||||
found = true;
|
||||
const disabledKeys =
|
||||
node.props?.disabledKeys ?? node.props?.["disabled-keys"] ?? [];
|
||||
const keys = [...blocked, ...disabledKeys] as CollectionKey[];
|
||||
if (node.props?.items) {
|
||||
const slot = (
|
||||
node.children as { default?: (state: unknown) => VNodeChild[] }
|
||||
)?.default;
|
||||
const items = node.props.items as {
|
||||
id: CollectionKey;
|
||||
textValue?: string;
|
||||
isDisabled?: boolean;
|
||||
}[];
|
||||
items.forEach((item, index) => {
|
||||
const before = records.length;
|
||||
if (slot) {
|
||||
const rendered = slot({ item, index });
|
||||
walk(Array.isArray(rendered) ? rendered : [rendered], true, keys);
|
||||
}
|
||||
if (records.length === before)
|
||||
add({
|
||||
key: item.id,
|
||||
text: item.textValue ?? String(item.id),
|
||||
disabled: !!item.isDisabled || keys.includes(item.id),
|
||||
});
|
||||
else if (item.isDisabled)
|
||||
records.slice(before).forEach((record) => {
|
||||
record.disabled = true;
|
||||
});
|
||||
});
|
||||
} else walk(children(node), true, keys);
|
||||
} else if (
|
||||
node.type === Fragment ||
|
||||
typeof node.type === "string" ||
|
||||
CONTAINERS.includes(component ?? "")
|
||||
)
|
||||
walk(children(node), inside, blocked);
|
||||
else if (
|
||||
inside &&
|
||||
component &&
|
||||
!["Header", "Separator"].includes(component)
|
||||
)
|
||||
opaque = true;
|
||||
}
|
||||
}
|
||||
walk(nodes);
|
||||
return { records, complete: found && !opaque };
|
||||
}
|
||||
Reference in New Issue
Block a user