feat(autocomplete): migrate Autocomplete with popover-owned filtering
Port the fixed-baseline Autocomplete onto the B02a collection protocol. The trigger is the single Tab entry; opening moves focus to the search box inside the popover, which owns filtering, aria-activedescendant and keyboard navigation while the list only tracks an active row. - Seven parts: root (field, value/open models, form value, owner wiring), trigger (anchor + activation), value (scoped slot with selectedItems and selectedText instead of copied item subtrees), indicator, clear button, popover (measured trigger width), filter (owns the search text and composes the inner SearchFieldInput into the combobox control). - Filter exposes input-value/update:inputValue/inputChange, matching ComboBox. - Confirming the active row in multiple mode now toggles it instead of replacing the accepted set (ComboBox shared the same bug). - ComboBox shows the accepted label on the first render via a display value that falls back to the selected record, so preselected fields are readable before the selection watcher runs (including SSR). - Popovers measure the anchor with a ResizeObserver because Reka does not publish the anchor size; the caller's root class is merged again so the trigger fills the field width. - 24 baseline previews, Chinese doc page, navigation, 17 behaviour tests, 5 demo/document contracts and an independent tarball consumption script for both pickers. Not included: the full bundler/NodeNext type matrix (B02d).
This commit is contained in:
@@ -0,0 +1,287 @@
|
||||
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
|
||||
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
|
||||
/* Autocomplete styles */
|
||||
.hv-autocomplete {
|
||||
@apply flex flex-col gap-1;
|
||||
}
|
||||
|
||||
.hv-autocomplete__trigger {
|
||||
@apply relative isolate inline-flex min-h-9 rounded-field border bg-field px-3 py-2 text-sm text-field-foreground shadow-field outline-none select-none no-highlight;
|
||||
|
||||
/**
|
||||
* Transitions
|
||||
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
|
||||
*/
|
||||
transition:
|
||||
background-color 150ms var(--ease-smooth),
|
||||
border-color 150ms var(--ease-smooth),
|
||||
box-shadow 150ms var(--ease-out);
|
||||
@apply motion-reduce:transition-none;
|
||||
|
||||
/* Cursor */
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
border-width: var(--border-width-field);
|
||||
border-color: var(--field-border);
|
||||
|
||||
/* Add inline-end padding when indicator is present */
|
||||
&:has(.hv-autocomplete__indicator) {
|
||||
@apply pe-7;
|
||||
}
|
||||
|
||||
/* Hover state - exclude when clear button is hovered to prevent double hover effect */
|
||||
@media (hover: hover) {
|
||||
&:hover:not(:has(.hv-autocomplete__clear-button:hover)),
|
||||
&[data-hovered="true"]:not(:has(.hv-autocomplete__clear-button:hover)) {
|
||||
@apply bg-field-hover;
|
||||
border-color: var(--field-border-hover);
|
||||
}
|
||||
}
|
||||
|
||||
/* Focus visible state */
|
||||
&:focus-visible:not([data-focused]),
|
||||
&[data-focus-visible="true"] {
|
||||
@apply status-focused;
|
||||
border-color: var(--field-border-focus);
|
||||
background-color: var(--field-focus);
|
||||
}
|
||||
|
||||
/* Focus state */
|
||||
&:focus,
|
||||
&[data-focus="true"] {
|
||||
}
|
||||
|
||||
/* Invalid state */
|
||||
.hv-autocomplete[data-invalid="true"] &,
|
||||
.hv-autocomplete[aria-invalid="true"] & {
|
||||
@apply status-invalid-field;
|
||||
background-color: var(--field-focus);
|
||||
}
|
||||
|
||||
/* Disabled state */
|
||||
&:disabled,
|
||||
&[data-disabled="true"],
|
||||
&[aria-disabled="true"] {
|
||||
@apply status-disabled;
|
||||
}
|
||||
}
|
||||
|
||||
/* Variant property definitions */
|
||||
.hv-autocomplete--primary {
|
||||
/* Default styles */
|
||||
}
|
||||
|
||||
.hv-autocomplete--secondary .hv-autocomplete__trigger {
|
||||
@apply shadow-none;
|
||||
background-color: var(--hv-autocomplete-trigger-bg);
|
||||
|
||||
--hv-autocomplete-trigger-bg: var(--default);
|
||||
--hv-autocomplete-trigger-bg-hover: var(--default-hover);
|
||||
--hv-autocomplete-trigger-bg-focus: var(--default);
|
||||
|
||||
/* Exclude when clear button is hovered to prevent double hover effect */
|
||||
@media (hover: hover) {
|
||||
&:hover:not(:has(.hv-autocomplete__clear-button:hover)),
|
||||
&[data-hovered="true"]:not(:has(.hv-autocomplete__clear-button:hover)) {
|
||||
background-color: var(--hv-autocomplete-trigger-bg-hover);
|
||||
}
|
||||
}
|
||||
|
||||
&:focus-visible:not([data-focused]),
|
||||
&[data-focus-visible="true"] {
|
||||
background-color: var(--hv-autocomplete-trigger-bg-focus);
|
||||
}
|
||||
|
||||
&:focus,
|
||||
&[data-focus="true"] {
|
||||
}
|
||||
|
||||
.hv-autocomplete[data-invalid="true"] &,
|
||||
.hv-autocomplete[aria-invalid="true"] & {
|
||||
background-color: var(--hv-autocomplete-trigger-bg-focus);
|
||||
}
|
||||
}
|
||||
|
||||
.hv-autocomplete__value {
|
||||
@apply flex-1 text-start text-base wrap-break-word text-current sm:text-sm;
|
||||
|
||||
&[data-placeholder="true"] {
|
||||
@apply text-field-placeholder;
|
||||
}
|
||||
|
||||
/* Removes the list-box-item indicator element from the hv-autocomplete value*/
|
||||
[data-slot="list-box-item-indicator"] {
|
||||
@apply hidden;
|
||||
}
|
||||
}
|
||||
|
||||
.hv-autocomplete__indicator {
|
||||
@apply absolute inset-y-0 end-2 my-auto flex shrink-0 items-center justify-center text-field-placeholder transition duration-150;
|
||||
|
||||
/* Cursor */
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
&[data-open="true"] {
|
||||
@apply rotate-180;
|
||||
}
|
||||
|
||||
&[data-slot="hv-autocomplete-default-indicator"] {
|
||||
@apply size-4;
|
||||
}
|
||||
}
|
||||
|
||||
/* Similar to popover content styles */
|
||||
.hv-autocomplete__popover {
|
||||
@apply flex w-(--trigger-width) max-w-(--trigger-width) origin-(--trigger-anchor-point) scroll-py-1 flex-col overflow-hidden overscroll-contain bg-overlay p-0 pt-2 text-sm outline-none;
|
||||
border-radius: min(32px, var(--radius-3xl));
|
||||
box-shadow: var(--overlay-shadow);
|
||||
|
||||
&:focus,
|
||||
&:focus-visible:not([data-focused]),
|
||||
&[data-focus-visible="true"] {
|
||||
@apply outline-none;
|
||||
}
|
||||
|
||||
/* Entering animations */
|
||||
&[data-entering="true"] {
|
||||
@apply animate-in duration-250 ease-out-fluid fade-in-0 zoom-in-95;
|
||||
|
||||
/* Placement-specific translations */
|
||||
&[data-placement="top"] {
|
||||
@apply slide-in-from-bottom-1;
|
||||
}
|
||||
|
||||
&[data-placement="bottom"] {
|
||||
@apply slide-in-from-top-1;
|
||||
}
|
||||
|
||||
&[data-placement="left"] {
|
||||
@apply slide-in-from-right-1;
|
||||
}
|
||||
|
||||
&[data-placement="right"] {
|
||||
@apply slide-in-from-left-1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Exiting animations */
|
||||
&[data-exiting="true"] {
|
||||
@apply animate-out duration-100 ease-out-quad zoom-out-95 fade-out;
|
||||
/* Stays non-interactive while closing, even if the exit animation is interrupted. */
|
||||
@apply pointer-events-none;
|
||||
}
|
||||
|
||||
&[data-exiting="true"],
|
||||
&[data-entering="true"] {
|
||||
@apply transition-[opacity,transform] will-change-[opacity,transform];
|
||||
}
|
||||
|
||||
/* Arrow styling */
|
||||
& [data-slot="popover-overlay-arrow"] {
|
||||
fill: var(--overlay);
|
||||
}
|
||||
|
||||
/* Arrow rotation based on placement */
|
||||
&[data-placement="bottom"] [data-slot="popover-overlay-arrow"] {
|
||||
rotate: 180deg;
|
||||
}
|
||||
|
||||
&[data-placement="left"] [data-slot="popover-overlay-arrow"] {
|
||||
rotate: -90deg;
|
||||
}
|
||||
|
||||
&[data-placement="right"] [data-slot="popover-overlay-arrow"] {
|
||||
rotate: 90deg;
|
||||
}
|
||||
|
||||
/* Listbox styles.
|
||||
* `min-h-0` + the popover's flex column let the list shrink below 320px when the
|
||||
* popover itself is constrained (e.g. inside a Modal, or a short viewport). Without
|
||||
* it the list keeps its full 320px and its overflow is clipped by the popover, making
|
||||
* the last options unreachable. */
|
||||
[data-slot="list-box"] {
|
||||
@apply max-h-[320px] min-h-0 scrollbar overflow-y-auto p-1.5 outline-none;
|
||||
}
|
||||
|
||||
[data-slot="list-box-item"] {
|
||||
@apply px-2.5;
|
||||
}
|
||||
|
||||
/* Virtualized rows: react-aria's Virtualizer wraps each row in an absolutely-positioned
|
||||
* [role="presentation"] element whose width equals the scroll container's clientWidth
|
||||
* (which includes the list-box horizontal padding) while sitting inside the padded content
|
||||
* box. Without this, rows overflow the right padding and the hover background reaches the
|
||||
* popover edge. Subtract the horizontal padding (2 × p-1.5 = 12px) to keep rows aligned. */
|
||||
[role="presentation"] > [data-slot="list-box-item"] {
|
||||
width: calc(100% - var(--spacing) * 3);
|
||||
}
|
||||
|
||||
/* As the popover closes fast in single-select mode, the default item indicator transition is not even visible - so we disable it only for single-select */
|
||||
[data-slot="list-box"]:not([aria-multiselectable="true"])
|
||||
[data-slot="list-box-item-indicator"],
|
||||
[data-slot="list-box"]:not([aria-multiselectable="true"])
|
||||
[data-slot="list-box-item-indicator"]
|
||||
[data-slot="list-box-item-indicator--checkmark"] {
|
||||
@apply transition-none;
|
||||
}
|
||||
|
||||
/* Search Field styles */
|
||||
[data-slot="search-field"] {
|
||||
@apply shrink-0 px-3 py-1 outline-none;
|
||||
}
|
||||
|
||||
/* Empty State */
|
||||
[data-slot="empty-state"] {
|
||||
@apply text-center text-sm text-overlay-foreground/60;
|
||||
}
|
||||
}
|
||||
|
||||
/* Full width modifier */
|
||||
.hv-autocomplete--full-width {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
.hv-autocomplete__trigger--full-width {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
/* Clear Button styles */
|
||||
.hv-autocomplete__clear-button {
|
||||
@apply relative isolate inline-flex h-6 w-6 shrink-0 origin-center items-center justify-center rounded-xl p-1 text-muted select-none no-highlight;
|
||||
@apply me-0 size-5 shrink-0 self-center bg-transparent;
|
||||
|
||||
/* Cursor */
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
@apply transform-gpu;
|
||||
|
||||
/* Transition only when visible - disappears immediately when cleared */
|
||||
&:not([data-empty="true"]) {
|
||||
transition: opacity 150ms var(--ease-smooth);
|
||||
@apply motion-reduce:transition-none;
|
||||
}
|
||||
|
||||
&[data-empty="true"] {
|
||||
@apply pointer-events-none opacity-0;
|
||||
}
|
||||
|
||||
[data-slot="hv-autocomplete-clear-button-icon"] {
|
||||
@apply size-3.5;
|
||||
}
|
||||
|
||||
&:active,
|
||||
&[data-pressed="true"] {
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
&:hover,
|
||||
&[data-hovered="true"] {
|
||||
@apply bg-default-hover;
|
||||
}
|
||||
}
|
||||
|
||||
&:active,
|
||||
&[data-pressed="true"] {
|
||||
transform: scale(0.93);
|
||||
}
|
||||
}
|
||||
@@ -156,6 +156,7 @@
|
||||
@import "./components/dropdown.css" layer(components);
|
||||
@import "./components/tag-group.css" layer(components);
|
||||
@import "./components/combo-box.css" layer(components);
|
||||
@import "./components/autocomplete.css" layer(components);
|
||||
@import "./components/tag.css" layer(components);
|
||||
|
||||
@import "./components/select.css" layer(components);
|
||||
|
||||
@@ -1700,3 +1700,38 @@ export const comboBoxVariants = tv({
|
||||
});
|
||||
|
||||
export type ComboBoxVariants = VariantProps<typeof comboBoxVariants>;
|
||||
|
||||
export const autocompleteVariants = tv({
|
||||
defaultVariants: {
|
||||
fullWidth: false,
|
||||
variant: "primary",
|
||||
},
|
||||
slots: {
|
||||
base: "hv-autocomplete",
|
||||
clearButton: "hv-autocomplete__clear-button",
|
||||
filter: "hv-autocomplete__filter",
|
||||
indicator: "hv-autocomplete__indicator",
|
||||
popover: "hv-autocomplete__popover",
|
||||
trigger: "hv-autocomplete__trigger",
|
||||
value: "hv-autocomplete__value",
|
||||
},
|
||||
variants: {
|
||||
fullWidth: {
|
||||
false: {},
|
||||
true: {
|
||||
base: "hv-autocomplete--full-width",
|
||||
trigger: "hv-autocomplete__trigger--full-width",
|
||||
},
|
||||
},
|
||||
variant: {
|
||||
primary: {
|
||||
base: "hv-autocomplete--primary",
|
||||
},
|
||||
secondary: {
|
||||
base: "hv-autocomplete--secondary",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export type AutocompleteVariants = VariantProps<typeof autocompleteVariants>;
|
||||
|
||||
@@ -0,0 +1,569 @@
|
||||
<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 { autocompleteVariants } from "@heroui-vue/styles";
|
||||
import Popover from "../popover/Popover";
|
||||
import {
|
||||
useChoiceField,
|
||||
useChoiceForm,
|
||||
useChoiceValue,
|
||||
validationInput,
|
||||
} from "../choice/shared";
|
||||
import { disabledContextKey } from "../field/disabled";
|
||||
import {
|
||||
fieldContextKey,
|
||||
type ValidateResult,
|
||||
type ValidationBehavior,
|
||||
} from "../field/context";
|
||||
import { copyKeys, type CollectionKey } from "../collection/keys";
|
||||
import {
|
||||
collectionOwnerKey,
|
||||
type CollectionRecord,
|
||||
type OwnedCollection,
|
||||
} from "../collection/owner";
|
||||
import { planCollectionItems } from "../combo-box/metadata";
|
||||
import {
|
||||
autocompleteKey,
|
||||
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,
|
||||
slots: Object as SlotsType<{
|
||||
default?: (state: {
|
||||
isOpen: boolean;
|
||||
selectedKeys: CollectionKey[];
|
||||
}) => VNodeChild;
|
||||
}>,
|
||||
props: {
|
||||
modelValue: {
|
||||
type: [String, Number, Array, null] as PropType<AutocompleteValueType>,
|
||||
default: undefined,
|
||||
},
|
||||
value: {
|
||||
type: [String, Number, Array, null] as PropType<AutocompleteValueType>,
|
||||
default: undefined,
|
||||
},
|
||||
defaultValue: {
|
||||
type: [String, Number, Array, null] as PropType<AutocompleteValueType>,
|
||||
default: undefined,
|
||||
},
|
||||
selectionMode: {
|
||||
type: String as PropType<"single" | "multiple">,
|
||||
default: "single",
|
||||
},
|
||||
disabledKeys: Array as PropType<readonly CollectionKey[]>,
|
||||
open: { type: Boolean, default: undefined },
|
||||
isOpen: { type: Boolean, default: undefined },
|
||||
defaultOpen: Boolean,
|
||||
isDisabled: Boolean,
|
||||
disabled: Boolean,
|
||||
isRequired: Boolean,
|
||||
isInvalid: Boolean,
|
||||
allowsEmptyCollection: Boolean,
|
||||
placeholder: { type: String, default: "Select an item" },
|
||||
name: String,
|
||||
form: String,
|
||||
fullWidth: Boolean,
|
||||
variant: {
|
||||
type: String as PropType<"primary" | "secondary">,
|
||||
default: "primary",
|
||||
},
|
||||
validationBehavior: String as PropType<ValidationBehavior>,
|
||||
validate: Function as PropType<
|
||||
(value: AutocompleteValueType) => ValidateResult
|
||||
>,
|
||||
as: { type: String, default: "div" },
|
||||
asChild: { type: Boolean, default: false },
|
||||
},
|
||||
emits: {
|
||||
"update:modelValue": (_value: AutocompleteValueType) => true,
|
||||
change: (_value: AutocompleteValueType) => true,
|
||||
"update:open": (_value: boolean) => true,
|
||||
openChange: (_value: boolean) => true,
|
||||
clear: () => true,
|
||||
},
|
||||
setup(props, { attrs, slots, emit, expose }) {
|
||||
const instance = getCurrentInstance()!;
|
||||
const present = (keys: string[]) =>
|
||||
keys.some((key) => Object.hasOwn(instance.vnode.props ?? {}, key));
|
||||
const model = useChoiceValue<AutocompleteValueType | undefined>(
|
||||
() =>
|
||||
present(["modelValue", "model-value"])
|
||||
? (props.modelValue ?? null)
|
||||
: present(["value"])
|
||||
? (props.value ?? null)
|
||||
: undefined,
|
||||
() => props.defaultValue ?? null,
|
||||
["modelValue", "model-value", "value"],
|
||||
(value) => {
|
||||
const next = value ?? null;
|
||||
emit("update:modelValue", next);
|
||||
emit("change", next);
|
||||
},
|
||||
);
|
||||
const value = computed<AutocompleteValueType>(() => {
|
||||
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;
|
||||
const next = copyKeys(
|
||||
raw === null ? [] : Array.isArray(raw) ? raw : [raw],
|
||||
);
|
||||
if (props.selectionMode === "single" && next.length > 1)
|
||||
throw new TypeError("Single Autocomplete expects one key or null.");
|
||||
return Object.freeze(next);
|
||||
});
|
||||
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[]>([]);
|
||||
const planned = shallowRef<CollectionRecord[]>([]);
|
||||
const complete = ref(false);
|
||||
watchEffect(() => {
|
||||
if (!collection.value) return;
|
||||
const next = collection.value.items();
|
||||
if (JSON.stringify(next) !== JSON.stringify(discovered.value))
|
||||
discovered.value = next;
|
||||
});
|
||||
const records = computed<CollectionRecord[]>(() => {
|
||||
const base = complete.value
|
||||
? planned.value
|
||||
: discovered.value.length
|
||||
? discovered.value
|
||||
: planned.value;
|
||||
const disabledKeys = props.disabledKeys ?? [];
|
||||
return base.map((record) => ({
|
||||
...record,
|
||||
disabled: record.disabled || disabledKeys.includes(record.key),
|
||||
}));
|
||||
});
|
||||
|
||||
const uid = useId();
|
||||
const triggerId = `hv-autocomplete-${uid}-trigger`;
|
||||
const listId = `hv-autocomplete-${uid}-listbox`;
|
||||
const valueId = `hv-autocomplete-${uid}-value`;
|
||||
|
||||
const filterText = ref("");
|
||||
const filterPredicate = ref<(text: string, input: string) => boolean>();
|
||||
const filter = (record: CollectionRecord) =>
|
||||
(filterPredicate.value ?? contains)(record.text, filterText.value);
|
||||
|
||||
const field = useChoiceField<AutocompleteValueType>(props, attrs, {
|
||||
kind: "group",
|
||||
value,
|
||||
validate: (current) => props.validate?.(current),
|
||||
satisfied: () => keys.value.length > 0,
|
||||
requiredMessage: "请选择一个选项。",
|
||||
});
|
||||
provide(fieldContextKey, field.field);
|
||||
provide(disabledContextKey, field.field.disabled);
|
||||
|
||||
const keyboardIntent = ref(true);
|
||||
const activeKey = ref<CollectionKey>();
|
||||
const filterInput = ref<HTMLInputElement>();
|
||||
const triggerElement = ref<HTMLElement>();
|
||||
const proxy = ref<HTMLInputElement>();
|
||||
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) return;
|
||||
if (
|
||||
next.some(
|
||||
(key) =>
|
||||
records.value.find((record) => record.key === 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;
|
||||
field.edit();
|
||||
model.request(
|
||||
props.selectionMode === "multiple" ? [...next] : (next[0] ?? null),
|
||||
);
|
||||
if (props.selectionMode === "single") {
|
||||
setOpen(false);
|
||||
void nextTick(() =>
|
||||
triggerElement.value?.focus({ preventScroll: true }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function setOpen(next: boolean) {
|
||||
if (next === open.value) return;
|
||||
if (next && field.field.disabled.value) return;
|
||||
if (next && props.disabled) return;
|
||||
if (
|
||||
next &&
|
||||
!props.allowsEmptyCollection &&
|
||||
complete.value &&
|
||||
!records.value.some((record) => !record.disabled)
|
||||
)
|
||||
return;
|
||||
openModel.request(next);
|
||||
if (next) {
|
||||
filterText.value = "";
|
||||
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);
|
||||
filterInput.value?.focus({ preventScroll: true });
|
||||
});
|
||||
} else {
|
||||
activeKey.value = undefined;
|
||||
void nextTick(() => {
|
||||
if (
|
||||
filterInput.value?.ownerDocument.activeElement ===
|
||||
filterInput.value ||
|
||||
!filterInput.value
|
||||
)
|
||||
triggerElement.value?.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function setActive(key: CollectionKey | undefined) {
|
||||
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[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;
|
||||
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]);
|
||||
}
|
||||
function clear() {
|
||||
if (field.field.disabled.value) return;
|
||||
if (!keys.value.length) return;
|
||||
request([]);
|
||||
emit("clear");
|
||||
}
|
||||
function focusTrigger() {
|
||||
triggerElement.value?.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
const slotsBase = computed(() =>
|
||||
autocompleteVariants({
|
||||
fullWidth: props.fullWidth,
|
||||
variant: props.variant,
|
||||
}),
|
||||
);
|
||||
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;
|
||||
});
|
||||
|
||||
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 : triggerId),
|
||||
ariaLabel: () =>
|
||||
typeof attrs["aria-label"] === "string"
|
||||
? attrs["aria-label"]
|
||||
: undefined,
|
||||
request,
|
||||
action: (key) => {
|
||||
void key;
|
||||
if (props.selectionMode === "single") setOpen(false);
|
||||
},
|
||||
leave: () => setOpen(false),
|
||||
connect: (next) => {
|
||||
if (collection.value && collection.value !== next)
|
||||
throw new Error("Autocomplete supports one ListBox.");
|
||||
collection.value = next;
|
||||
return () => {
|
||||
if (collection.value === next) collection.value = undefined;
|
||||
};
|
||||
},
|
||||
filter,
|
||||
virtualFocus: () => true,
|
||||
activeKey,
|
||||
keyboardIntent,
|
||||
isOpen: () => open.value,
|
||||
});
|
||||
|
||||
const core = (): Record<string, unknown> => ({
|
||||
role: "combobox",
|
||||
"aria-expanded": true,
|
||||
"aria-controls": listId,
|
||||
"aria-activedescendant": activeId.value,
|
||||
"aria-autocomplete": "list" as const,
|
||||
"aria-haspopup": "listbox" as const,
|
||||
"aria-label":
|
||||
typeof attrs["aria-label"] === "string"
|
||||
? attrs["aria-label"]
|
||||
: undefined,
|
||||
"aria-labelledby":
|
||||
attrs["aria-labelledby"] ??
|
||||
(attrs["aria-label"] ? undefined : field.labelledBy()),
|
||||
"aria-describedby": field.describedBy(),
|
||||
onKeydown: (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.isComposing ||
|
||||
event.keyCode === 229
|
||||
)
|
||||
return;
|
||||
if (field.field.disabled.value) return;
|
||||
keyboardIntent.value = true;
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
moveActive(event.key === "ArrowDown" ? 1 : -1);
|
||||
return;
|
||||
}
|
||||
if (event.key === "Home" || event.key === "End") {
|
||||
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) confirmActive();
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
if (event.key === "Tab") setOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
provide(autocompleteKey, {
|
||||
field,
|
||||
slots: slotsBase,
|
||||
open,
|
||||
setOpen,
|
||||
keys,
|
||||
records,
|
||||
selectedItems: computed(() =>
|
||||
keys.value.map((key) => ({
|
||||
key,
|
||||
textValue:
|
||||
records.value.find((record) => record.key === key)?.text ??
|
||||
String(key),
|
||||
})),
|
||||
),
|
||||
selectionMode: computed(() => props.selectionMode),
|
||||
disabled: field.field.disabled,
|
||||
invalid,
|
||||
listId,
|
||||
triggerId,
|
||||
valueId,
|
||||
placeholder: () => props.placeholder,
|
||||
activeKey,
|
||||
activeId,
|
||||
collection,
|
||||
filterText,
|
||||
filterPredicate,
|
||||
filterInput,
|
||||
triggerElement,
|
||||
ariaLabel: () =>
|
||||
typeof attrs["aria-label"] === "string"
|
||||
? attrs["aria-label"]
|
||||
: undefined,
|
||||
core,
|
||||
focusTrigger,
|
||||
request,
|
||||
moveActive,
|
||||
setActive,
|
||||
confirmActive,
|
||||
clear,
|
||||
formValueText,
|
||||
});
|
||||
|
||||
useChoiceForm(
|
||||
proxy,
|
||||
() => {
|
||||
model.reset();
|
||||
field.reset();
|
||||
setOpen(false);
|
||||
},
|
||||
() => field.validity(proxy.value),
|
||||
);
|
||||
watchEffect(() => field.validity(proxy.value));
|
||||
watch(
|
||||
// Filtering changes the visible set: re-anchor the active row so Enter
|
||||
// always confirms something the user can actually see.
|
||||
() => `${filterText.value}|${records.value.length}|${open.value}`,
|
||||
() => {
|
||||
if (!open.value) return;
|
||||
const visible = records.value.filter(
|
||||
(record) => filter(record) && !record.disabled,
|
||||
);
|
||||
if (!visible.some((record) => record.key === activeKey.value))
|
||||
void setActive(visible[0]?.key);
|
||||
},
|
||||
);
|
||||
watch(
|
||||
() => `${keys.value.map(String).join("\u0000")}|${records.value.length}`,
|
||||
() => {
|
||||
if (
|
||||
!props.allowsEmptyCollection &&
|
||||
open.value &&
|
||||
records.value.length
|
||||
) {
|
||||
const visible = records.value.filter(
|
||||
(record) => filter(record) && !record.disabled,
|
||||
);
|
||||
if (!visible.length) setOpen(false);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
expose({
|
||||
element: triggerElement,
|
||||
open: () => setOpen(true),
|
||||
close: () => setOpen(false),
|
||||
focus: focusTrigger,
|
||||
clear,
|
||||
});
|
||||
|
||||
return () => {
|
||||
const rendered = slots.default?.({
|
||||
isOpen: open.value,
|
||||
selectedKeys: [...keys.value],
|
||||
});
|
||||
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 restAttrs: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(attrs)) {
|
||||
if (NAMING_ATTRS.includes(key) || key === "class" || key === "style")
|
||||
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,
|
||||
),
|
||||
],
|
||||
),
|
||||
},
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,64 @@
|
||||
<script lang="ts">
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import { useAutocomplete } from "./context";
|
||||
const CLOSE_PATH =
|
||||
"M3.47 3.47a.75.75 0 0 1 1.06 0L8 6.94l3.47-3.47a.75.75 0 1 1 1.06 1.06L9.06 8l3.47 3.47a.75.75 0 1 1-1.06 1.06L8 9.06l-3.47 3.47a.75.75 0 0 1-1.06-1.06L6.94 8 3.47 4.53a.75.75 0 0 1 0-1.06Z";
|
||||
|
||||
export default defineComponent({
|
||||
name: "AutocompleteClearButton",
|
||||
inheritAttrs: false,
|
||||
setup(_props, { attrs, slots }) {
|
||||
const ctx = useAutocomplete();
|
||||
const empty = () => ctx.keys.value.length === 0;
|
||||
function click(event: MouseEvent) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (event.defaultPrevented) return;
|
||||
ctx.clear();
|
||||
}
|
||||
return () => {
|
||||
const custom = slots.default?.() ?? [];
|
||||
const icon =
|
||||
custom.length > 0
|
||||
? custom
|
||||
: [
|
||||
h(
|
||||
"svg",
|
||||
{
|
||||
"aria-hidden": "true",
|
||||
"data-slot": "autocomplete-clear-button-icon",
|
||||
fill: "none",
|
||||
height: 16,
|
||||
role: "presentation",
|
||||
viewBox: "0 0 16 16",
|
||||
width: 16,
|
||||
},
|
||||
[
|
||||
h("path", {
|
||||
d: CLOSE_PATH,
|
||||
fill: "currentColor",
|
||||
"fill-rule": "evenodd",
|
||||
"clip-rule": "evenodd",
|
||||
}),
|
||||
],
|
||||
),
|
||||
];
|
||||
const injected: Record<string, unknown> = {
|
||||
type: "button",
|
||||
tabindex: -1,
|
||||
"aria-label":
|
||||
typeof attrs["aria-label"] === "string"
|
||||
? attrs["aria-label"]
|
||||
: "Clear selection",
|
||||
class: ctx.slots.value.clearButton(),
|
||||
"data-slot": "autocomplete-clear-button",
|
||||
"data-empty": empty() || undefined,
|
||||
"aria-hidden": empty() || undefined,
|
||||
disabled: ctx.disabled.value || undefined,
|
||||
onClick: click,
|
||||
};
|
||||
return h("button", mergeProps(attrs, injected), [icon]);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,118 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* Owns the search text used to filter the collection and composes the inner
|
||||
* `SearchField.Input` into the combobox control: value binding, ARIA and the
|
||||
* keyboard contract are injected there, so navigation never moves DOM focus
|
||||
* out of the search box.
|
||||
*/
|
||||
import {
|
||||
cloneVNode,
|
||||
defineComponent,
|
||||
h,
|
||||
isVNode,
|
||||
mergeProps,
|
||||
ref,
|
||||
watchEffect,
|
||||
type PropType,
|
||||
type VNode,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { useChoiceValue } from "../choice/shared";
|
||||
import { useAutocomplete } from "./context";
|
||||
import { elementFromRef } from "../combo-box/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: "AutocompleteFilter",
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
filter: Function as PropType<(text: string, input: string) => boolean>,
|
||||
inputValue: { type: String, default: undefined },
|
||||
defaultInputValue: { type: String, default: "" },
|
||||
},
|
||||
emits: {
|
||||
"update:inputValue": (_value: string) => true,
|
||||
inputChange: (_value: string) => true,
|
||||
},
|
||||
setup(props, { attrs, slots, emit }) {
|
||||
const ctx = useAutocomplete();
|
||||
const model = useChoiceValue<string | undefined>(
|
||||
() => props.inputValue,
|
||||
() => props.defaultInputValue,
|
||||
["inputValue", "input-value"],
|
||||
(next) => {
|
||||
emit("update:inputValue", next ?? "");
|
||||
emit("inputChange", next ?? "");
|
||||
},
|
||||
);
|
||||
const text = () => model.value.value ?? "";
|
||||
const root = ref<HTMLElement>();
|
||||
|
||||
watchEffect(() => {
|
||||
ctx.filterText.value = text();
|
||||
ctx.filterPredicate.value = props.filter;
|
||||
});
|
||||
|
||||
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, {
|
||||
...ctx.core(),
|
||||
modelValue: text(),
|
||||
"onUpdate:modelValue": (next: string) => model.request(next),
|
||||
ref: (instance: unknown) => {
|
||||
ctx.filterInput.value = elementFromRef(instance) as
|
||||
HTMLInputElement | undefined;
|
||||
},
|
||||
});
|
||||
const children = child.children;
|
||||
if (Array.isArray(children)) {
|
||||
const clone = cloneVNode(child);
|
||||
clone.children = compose(children as VNodeChild[]) as never;
|
||||
return clone;
|
||||
}
|
||||
if (children && typeof children === "object") {
|
||||
const withDefault = children as {
|
||||
default?: () => VNodeChild;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
if (typeof withDefault.default === "function") {
|
||||
const clone = cloneVNode(child);
|
||||
clone.children = {
|
||||
...withDefault,
|
||||
default: () =>
|
||||
compose(([withDefault.default!()] as VNodeChild[]).flat()),
|
||||
} as never;
|
||||
return clone;
|
||||
}
|
||||
}
|
||||
return child;
|
||||
});
|
||||
}
|
||||
|
||||
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.filter(),
|
||||
"data-slot": "autocomplete-filter",
|
||||
}),
|
||||
compose(children),
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,53 @@
|
||||
<script lang="ts">
|
||||
/** Decorative chevron: the trigger itself owns activation. */
|
||||
import { defineComponent, h, 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";
|
||||
|
||||
export default defineComponent({
|
||||
name: "AutocompleteIndicator",
|
||||
inheritAttrs: false,
|
||||
setup(_props, { attrs, slots }) {
|
||||
const ctx = useAutocomplete();
|
||||
return () => {
|
||||
const custom = slots.default?.() ?? [];
|
||||
const icon =
|
||||
custom.length > 0
|
||||
? custom
|
||||
: [
|
||||
h(
|
||||
"svg",
|
||||
{
|
||||
"aria-hidden": "true",
|
||||
"data-slot": "autocomplete-default-indicator",
|
||||
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",
|
||||
}),
|
||||
],
|
||||
),
|
||||
];
|
||||
return h(
|
||||
"span",
|
||||
mergeProps(attrs, {
|
||||
"aria-hidden": "true",
|
||||
class: ctx.slots.value.indicator(),
|
||||
"data-slot": "autocomplete-indicator",
|
||||
"data-open": ctx.open.value || undefined,
|
||||
}),
|
||||
icon,
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,50 @@
|
||||
<script lang="ts">
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import PopoverContent from "../popover/PopoverContent.vue";
|
||||
import { useAutocomplete } from "./context";
|
||||
import { useTriggerWidth } from "../combo-box/useTriggerWidth";
|
||||
import type { OverlayPlacement } from "../overlay/placement";
|
||||
|
||||
export default defineComponent({
|
||||
name: "AutocompletePopover",
|
||||
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 = useAutocomplete();
|
||||
const width = useTriggerWidth(() => ctx.triggerElement.value);
|
||||
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": "autocomplete-popover",
|
||||
style: {
|
||||
"--trigger-width": width.value
|
||||
? `${width.value}px`
|
||||
: "var(--reka-popover-trigger-width)",
|
||||
"--trigger-anchor-point": "var(--reka-popper-transform-origin)",
|
||||
},
|
||||
// The filter input owns focus; the content itself never takes it.
|
||||
onOpenAutoFocus: (event: Event) => {
|
||||
event.preventDefault();
|
||||
ctx.filterInput.value?.focus({ preventScroll: true });
|
||||
},
|
||||
}),
|
||||
{ default: () => slots.default?.() },
|
||||
);
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,86 @@
|
||||
<script lang="ts">
|
||||
/** Clickable value surface: opens the popover and is the single Tab entry. */
|
||||
import { defineComponent, h, mergeProps, ref, watch } from "vue";
|
||||
import { injectPopoverRootContext } from "reka-ui";
|
||||
import { useAutocomplete } from "./context";
|
||||
import { elementFromRef } from "../combo-box/dom";
|
||||
|
||||
export default defineComponent({
|
||||
name: "AutocompleteTrigger",
|
||||
inheritAttrs: false,
|
||||
props: { isDisabled: { type: Boolean, default: false } },
|
||||
setup(props, { attrs, slots }) {
|
||||
const ctx = useAutocomplete();
|
||||
const element = ref<HTMLElement>();
|
||||
const popover = injectPopoverRootContext();
|
||||
const disabled = () => props.isDisabled || ctx.disabled.value;
|
||||
|
||||
watch(
|
||||
element,
|
||||
() => {
|
||||
const node = elementFromRef(element.value);
|
||||
ctx.triggerElement.value = node;
|
||||
if (popover)
|
||||
(
|
||||
popover.triggerElement as unknown as { value: HTMLElement | null }
|
||||
).value = node ?? null;
|
||||
},
|
||||
{ immediate: true, flush: "post" },
|
||||
);
|
||||
|
||||
function toggle(event: MouseEvent) {
|
||||
if (event.defaultPrevented || disabled()) return;
|
||||
const target = event.target as Element | null;
|
||||
if (target?.closest?.('[data-slot="autocomplete-clear-button"]')) return;
|
||||
ctx.setOpen(!ctx.open.value);
|
||||
}
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.isComposing ||
|
||||
event.keyCode === 229 ||
|
||||
disabled()
|
||||
)
|
||||
return;
|
||||
if (
|
||||
event.key === "Enter" ||
|
||||
event.key === " " ||
|
||||
event.key === "ArrowDown"
|
||||
) {
|
||||
event.preventDefault();
|
||||
if (!ctx.open.value) ctx.setOpen(true);
|
||||
}
|
||||
if (event.key === "Escape" && ctx.open.value) ctx.setOpen(false);
|
||||
if (event.key === "Delete" || event.key === "Backspace") ctx.clear();
|
||||
}
|
||||
|
||||
return () => {
|
||||
const injected: Record<string, unknown> = {
|
||||
ref: element,
|
||||
id: ctx.triggerId,
|
||||
role: "button",
|
||||
tabindex: disabled() ? -1 : 0,
|
||||
class: ctx.slots.value.trigger(),
|
||||
"data-slot": "autocomplete-trigger",
|
||||
"aria-haspopup": "listbox",
|
||||
"aria-expanded": ctx.open.value,
|
||||
"aria-label": attrs["aria-label"] ?? ctx.ariaLabel(),
|
||||
"aria-labelledby":
|
||||
attrs["aria-labelledby"] ??
|
||||
((attrs["aria-label"] ?? ctx.ariaLabel())
|
||||
? undefined
|
||||
: ctx.field.labelledBy()),
|
||||
onClick: toggle,
|
||||
onKeydown: keydown,
|
||||
};
|
||||
if (ctx.open.value) injected["aria-controls"] = ctx.listId;
|
||||
if (ctx.open.value) injected["data-open"] = true;
|
||||
if (disabled()) {
|
||||
injected["data-disabled"] = true;
|
||||
injected["aria-disabled"] = true;
|
||||
}
|
||||
return h("div", mergeProps(attrs, injected), slots.default?.());
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,37 @@
|
||||
<script lang="ts">
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import { useAutocomplete } from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
name: "AutocompleteValue",
|
||||
inheritAttrs: false,
|
||||
setup(_props, { attrs, slots }) {
|
||||
const ctx = useAutocomplete();
|
||||
return () => {
|
||||
const selectedItems = ctx.selectedItems.value;
|
||||
const isPlaceholder = selectedItems.length === 0;
|
||||
const selectedText = selectedItems
|
||||
.map((item) => item.textValue)
|
||||
.join(", ");
|
||||
const defaultChildren = isPlaceholder ? ctx.placeholder() : selectedText;
|
||||
const content =
|
||||
slots.default?.({
|
||||
isPlaceholder,
|
||||
defaultChildren,
|
||||
selectedText,
|
||||
selectedItems,
|
||||
}) ?? defaultChildren;
|
||||
return h(
|
||||
"span",
|
||||
mergeProps(attrs, {
|
||||
id: ctx.valueId,
|
||||
class: ctx.slots.value.value(),
|
||||
"data-slot": "autocomplete-value",
|
||||
"data-placeholder": isPlaceholder || undefined,
|
||||
}),
|
||||
content,
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,76 @@
|
||||
import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue";
|
||||
import type { autocompleteVariants } 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 AutocompleteValue = CollectionKey | CollectionKey[] | null;
|
||||
export interface AutocompleteSelectedItem {
|
||||
key: CollectionKey;
|
||||
textValue: string;
|
||||
}
|
||||
export interface AutocompleteOptions {
|
||||
modelValue?: AutocompleteValue;
|
||||
value?: AutocompleteValue;
|
||||
defaultValue?: AutocompleteValue;
|
||||
selectionMode?: "single" | "multiple";
|
||||
disabledKeys?: readonly CollectionKey[];
|
||||
open?: boolean;
|
||||
isOpen?: boolean;
|
||||
defaultOpen?: boolean;
|
||||
isDisabled?: boolean;
|
||||
disabled?: boolean;
|
||||
isRequired?: boolean;
|
||||
isInvalid?: boolean;
|
||||
allowsEmptyCollection?: boolean;
|
||||
placeholder?: string;
|
||||
name?: string;
|
||||
form?: string;
|
||||
fullWidth?: boolean;
|
||||
variant?: "primary" | "secondary";
|
||||
validationBehavior?: "native" | "aria";
|
||||
validate?: (value: AutocompleteValue) => unknown;
|
||||
as?: string;
|
||||
asChild?: boolean;
|
||||
}
|
||||
export interface AutocompleteContext {
|
||||
field: ReturnType<typeof useChoiceField<AutocompleteValue>>;
|
||||
slots: ComputedRef<ReturnType<typeof autocompleteVariants>>;
|
||||
open: ComputedRef<boolean>;
|
||||
setOpen: (open: boolean) => void;
|
||||
keys: ComputedRef<readonly CollectionKey[]>;
|
||||
records: ComputedRef<CollectionRecord[]>;
|
||||
selectedItems: ComputedRef<AutocompleteSelectedItem[]>;
|
||||
selectionMode: ComputedRef<"single" | "multiple">;
|
||||
disabled: ComputedRef<boolean>;
|
||||
invalid: ComputedRef<boolean>;
|
||||
listId: string;
|
||||
triggerId: string;
|
||||
valueId: string;
|
||||
placeholder: () => string;
|
||||
activeKey: Ref<CollectionKey | undefined>;
|
||||
activeId: ComputedRef<string | undefined>;
|
||||
collection: Ref<OwnedCollection | undefined>;
|
||||
/** Filter text owned by AutocompleteFilter and read by the collection filter. */
|
||||
filterText: Ref<string>;
|
||||
filterPredicate: Ref<((text: string, input: string) => boolean) | undefined>;
|
||||
filterInput: Ref<HTMLInputElement | undefined>;
|
||||
triggerElement: Ref<HTMLElement | undefined>;
|
||||
ariaLabel: () => string | undefined;
|
||||
core: () => Record<string, unknown>;
|
||||
focusTrigger: () => void;
|
||||
request: (keys: CollectionKey[]) => void;
|
||||
moveActive: (delta: 1 | -1) => void;
|
||||
setActive: (key: CollectionKey | undefined) => Promise<void>;
|
||||
confirmActive: () => void;
|
||||
clear: () => void;
|
||||
formValueText: ComputedRef<string | undefined>;
|
||||
}
|
||||
export const autocompleteKey: InjectionKey<AutocompleteContext> =
|
||||
Symbol("hv-autocomplete");
|
||||
|
||||
export function useAutocomplete(): AutocompleteContext {
|
||||
const context = inject(autocompleteKey, undefined);
|
||||
if (!context) throw new Error("Autocomplete parts require Autocomplete.");
|
||||
return context;
|
||||
}
|
||||
@@ -32,7 +32,7 @@ import {
|
||||
type CollectionRecord,
|
||||
type OwnedCollection,
|
||||
} from "../collection/owner";
|
||||
import { planComboBoxItems } from "./metadata";
|
||||
import { planCollectionItems } from "./metadata";
|
||||
import {
|
||||
comboBoxKey,
|
||||
type ComboBoxItem,
|
||||
@@ -271,6 +271,7 @@ export default defineComponent({
|
||||
const activeKey = ref<CollectionKey>();
|
||||
const cursor = ref<CollectionKey>();
|
||||
const inputElement = ref<HTMLInputElement>();
|
||||
const triggerElement = ref<HTMLElement>();
|
||||
let anchor: (() => HTMLElement | undefined) | undefined;
|
||||
const registerAnchor = (element: () => HTMLElement | undefined) => {
|
||||
anchor = element;
|
||||
@@ -377,6 +378,14 @@ export default defineComponent({
|
||||
(item) => item.key === key && filter(item) && !item.disabled,
|
||||
);
|
||||
if (!record) 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]);
|
||||
}
|
||||
|
||||
@@ -397,6 +406,20 @@ export default defineComponent({
|
||||
{ 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.
|
||||
*/
|
||||
const displayInputValue = computed(() => {
|
||||
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 ?? "";
|
||||
});
|
||||
|
||||
function setInputValue(next: string) {
|
||||
inputModel.request(next);
|
||||
if (props.menuTrigger === "input" && !open.value && next) setOpen(true);
|
||||
@@ -557,6 +580,7 @@ export default defineComponent({
|
||||
open,
|
||||
setOpen,
|
||||
inputValue,
|
||||
displayInputValue,
|
||||
setInputValue,
|
||||
inputId,
|
||||
listId,
|
||||
@@ -580,6 +604,7 @@ export default defineComponent({
|
||||
menuTrigger: () => props.menuTrigger,
|
||||
inputElement,
|
||||
registerAnchor,
|
||||
triggerElement,
|
||||
inputProps,
|
||||
formValueText,
|
||||
invalid,
|
||||
@@ -638,7 +663,7 @@ export default defineComponent({
|
||||
: rendered == null
|
||||
? []
|
||||
: [rendered];
|
||||
const plan = planComboBoxItems(children);
|
||||
const plan = planCollectionItems(children);
|
||||
if (JSON.stringify(plan.records) !== JSON.stringify(planned.value))
|
||||
planned.value = plan.records;
|
||||
complete.value = plan.complete;
|
||||
|
||||
@@ -37,6 +37,13 @@ export default defineComponent({
|
||||
const root = ref<HTMLElement>();
|
||||
|
||||
ctx.registerAnchor(() => elementFromRef(root.value));
|
||||
watch(
|
||||
root,
|
||||
() => {
|
||||
ctx.triggerElement.value = elementFromRef(root.value);
|
||||
},
|
||||
{ immediate: true, flush: "post" },
|
||||
);
|
||||
watch(
|
||||
root,
|
||||
() => {
|
||||
@@ -55,7 +62,7 @@ export default defineComponent({
|
||||
if (!isVNode(node) || componentName(node) !== "Input") return node;
|
||||
return cloneVNode(node, {
|
||||
...ctx.inputProps(),
|
||||
modelValue: ctx.inputValue.value,
|
||||
modelValue: ctx.displayInputValue.value,
|
||||
"onUpdate:modelValue": (next: string) => ctx.setInputValue(next),
|
||||
ref: (instance: unknown) => {
|
||||
ctx.inputElement.value = elementFromRef(instance) as
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import PopoverContent from "../popover/PopoverContent.vue";
|
||||
import { useComboBox } from "./context";
|
||||
import { useTriggerWidth } from "./useTriggerWidth";
|
||||
import type { OverlayPlacement } from "../overlay/placement";
|
||||
|
||||
export default defineComponent({
|
||||
@@ -16,6 +17,7 @@ export default defineComponent({
|
||||
},
|
||||
setup(props, { attrs, slots }) {
|
||||
const ctx = useComboBox();
|
||||
const width = useTriggerWidth(() => ctx.triggerElement.value);
|
||||
return () =>
|
||||
h(
|
||||
PopoverContent,
|
||||
@@ -30,7 +32,9 @@ export default defineComponent({
|
||||
role: "presentation",
|
||||
"data-slot": "combo-box-popover",
|
||||
style: {
|
||||
"--trigger-width": "var(--reka-popover-trigger-width)",
|
||||
"--trigger-width": width.value
|
||||
? `${width.value}px`
|
||||
: "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.
|
||||
|
||||
@@ -56,6 +56,8 @@ export interface ComboBoxContext {
|
||||
open: ComputedRef<boolean>;
|
||||
setOpen: (open: boolean) => void;
|
||||
inputValue: ComputedRef<string>;
|
||||
/** Text shown in the input: the accepted item's label before any typing. */
|
||||
displayInputValue: ComputedRef<string>;
|
||||
setInputValue: (value: string) => void;
|
||||
inputId: string;
|
||||
listId: string;
|
||||
@@ -72,6 +74,7 @@ export interface ComboBoxContext {
|
||||
menuTrigger: () => ComboBoxMenuTrigger;
|
||||
inputElement: Ref<HTMLInputElement | undefined>;
|
||||
registerAnchor: (element: () => HTMLElement | undefined) => void;
|
||||
triggerElement: Ref<HTMLElement | undefined>;
|
||||
/** ARIA plus input handlers injected onto the composed `Input`. */
|
||||
inputProps: () => Record<string, unknown>;
|
||||
formValueText: ComputedRef<string | undefined>;
|
||||
|
||||
@@ -36,14 +36,20 @@ function text(nodes: VNodeChild[]): string {
|
||||
.trim();
|
||||
}
|
||||
|
||||
const CONTAINERS = ["ComboBoxPopover", "SelectPopover", "ListBoxSection"];
|
||||
const CONTAINERS = [
|
||||
"ComboBoxPopover",
|
||||
"AutocompletePopover",
|
||||
"AutocompleteFilter",
|
||||
"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.
|
||||
* Collect collection metadata from a picker's slot tree. Filtering, the initial
|
||||
* value label and form text need the full data set before the popover (and
|
||||
* therefore the ListBox) has ever mounted.
|
||||
*/
|
||||
export function planComboBoxItems(nodes: VNodeChild[]) {
|
||||
export function planCollectionItems(nodes: VNodeChild[]) {
|
||||
const records: CollectionRecord[] = [];
|
||||
let found = false;
|
||||
let opaque = false;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { onBeforeUnmount, ref, watchEffect } from "vue";
|
||||
|
||||
/**
|
||||
* Track the anchor's border-box width so a popover can match it. Reka does not
|
||||
* expose the anchor size without its own trigger component, so the width is
|
||||
* measured here (the baseline component measures its trigger the same way).
|
||||
*/
|
||||
export function useTriggerWidth(get: () => HTMLElement | undefined) {
|
||||
const width = ref<number>();
|
||||
let observer: ResizeObserver | undefined;
|
||||
watchEffect(() => {
|
||||
const element = get();
|
||||
observer?.disconnect();
|
||||
observer = undefined;
|
||||
if (!element) return;
|
||||
const measure = () => {
|
||||
width.value = element.offsetWidth || undefined;
|
||||
};
|
||||
measure();
|
||||
if (typeof ResizeObserver === "function") {
|
||||
observer = new ResizeObserver(measure);
|
||||
observer.observe(element);
|
||||
}
|
||||
});
|
||||
onBeforeUnmount(() => observer?.disconnect());
|
||||
return width;
|
||||
}
|
||||
@@ -979,3 +979,30 @@ export type {
|
||||
} from "./components/combo-box/context";
|
||||
|
||||
export { comboBoxVariants, type ComboBoxVariants } from "@heroui-vue/styles";
|
||||
|
||||
export { default as Autocomplete } from "./components/autocomplete/Autocomplete.vue";
|
||||
export { default as AutocompleteTrigger } from "./components/autocomplete/AutocompleteTrigger.vue";
|
||||
export { default as AutocompleteValue } from "./components/autocomplete/AutocompleteValue.vue";
|
||||
export { default as AutocompleteIndicator } from "./components/autocomplete/AutocompleteIndicator.vue";
|
||||
export { default as AutocompleteClearButton } from "./components/autocomplete/AutocompleteClearButton.vue";
|
||||
export { default as AutocompletePopover } from "./components/autocomplete/AutocompletePopover.vue";
|
||||
export { default as AutocompleteFilter } from "./components/autocomplete/AutocompleteFilter.vue";
|
||||
export type {
|
||||
AutocompleteProps,
|
||||
AutocompleteTriggerProps,
|
||||
AutocompleteValueProps,
|
||||
AutocompleteIndicatorProps,
|
||||
AutocompleteClearButtonProps,
|
||||
AutocompletePopoverProps,
|
||||
AutocompleteFilterProps,
|
||||
} from "./types";
|
||||
export type {
|
||||
AutocompleteSelectedItem,
|
||||
AutocompleteOptions,
|
||||
} from "./components/autocomplete/context";
|
||||
export type { AutocompleteValue as AutocompleteValueModel } from "./components/autocomplete/context";
|
||||
|
||||
export {
|
||||
autocompleteVariants,
|
||||
type AutocompleteVariants,
|
||||
} from "@heroui-vue/styles";
|
||||
|
||||
@@ -765,3 +765,36 @@ import type ComboBoxPopover from "./components/combo-box/ComboBoxPopover.vue";
|
||||
export type ComboBoxPopoverProps = InstanceType<
|
||||
typeof ComboBoxPopover
|
||||
>["$props"];
|
||||
|
||||
import type Autocomplete from "./components/autocomplete/Autocomplete.vue";
|
||||
export type AutocompleteProps = InstanceType<typeof Autocomplete>["$props"];
|
||||
|
||||
import type AutocompleteTrigger from "./components/autocomplete/AutocompleteTrigger.vue";
|
||||
export type AutocompleteTriggerProps = InstanceType<
|
||||
typeof AutocompleteTrigger
|
||||
>["$props"];
|
||||
|
||||
import type AutocompleteValue from "./components/autocomplete/AutocompleteValue.vue";
|
||||
export type AutocompleteValueProps = InstanceType<
|
||||
typeof AutocompleteValue
|
||||
>["$props"];
|
||||
|
||||
import type AutocompleteIndicator from "./components/autocomplete/AutocompleteIndicator.vue";
|
||||
export type AutocompleteIndicatorProps = InstanceType<
|
||||
typeof AutocompleteIndicator
|
||||
>["$props"];
|
||||
|
||||
import type AutocompleteClearButton from "./components/autocomplete/AutocompleteClearButton.vue";
|
||||
export type AutocompleteClearButtonProps = InstanceType<
|
||||
typeof AutocompleteClearButton
|
||||
>["$props"];
|
||||
|
||||
import type AutocompletePopover from "./components/autocomplete/AutocompletePopover.vue";
|
||||
export type AutocompletePopoverProps = InstanceType<
|
||||
typeof AutocompletePopover
|
||||
>["$props"];
|
||||
|
||||
import type AutocompleteFilter from "./components/autocomplete/AutocompleteFilter.vue";
|
||||
export type AutocompleteFilterProps = InstanceType<
|
||||
typeof AutocompleteFilter
|
||||
>["$props"];
|
||||
|
||||
Reference in New Issue
Block a user