merge: integrate public collection picker migration

# Conflicts:
#	AGENTS.md
#	docs/compatibility.md
#	docs/upstream.md
#	docs/verification.md
#	package.json
#	packages/styles/src/index.ts
#	packages/vue/src/index.ts
#	packages/vue/src/types.ts
#	tests/package/README.md
This commit is contained in:
maoyingjie
2026-10-25 20:55:18 +08:00
201 changed files with 25848 additions and 48 deletions
@@ -0,0 +1,611 @@
<script lang="ts">
import {
cloneVNode,
computed,
defineComponent,
getCurrentInstance,
h,
isVNode,
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 {
selectionInputs,
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 { createBaseContains } from "../collection/match";
import { SHAPE_ARRAY_CHILDREN, SHAPE_TEXT_CHILDREN } from "../combo-box/dom";
import { useConfig } from "../../providers/context";
import {
autocompleteKey,
type AutocompleteItem,
type AutocompleteValue as AutocompleteValueType,
} from "./context";
const NAMING_ATTRS = ["aria-label", "aria-labelledby", "aria-describedby"];
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",
},
items: Array as PropType<readonly AutocompleteItem[]>,
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 contains = createBaseContains(useConfig()?.locale.value);
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 explicit = props.items?.map((item) => {
if (item.id === undefined || item.id === null)
throw new TypeError("Autocomplete items need an id.");
return {
key: item.id,
text: item.textValue,
disabled: !!item.isDisabled,
} satisfies CollectionRecord;
});
const base =
explicit ??
(complete.value
? planned.value
: discovered.value.length
? discovered.value
: planned.value);
const disabledKeys = props.disabledKeys ?? [];
return base.map((record) => ({
...record,
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("");
/** Open composition session in the popover search box. */
const composing = ref(false);
const filterPredicate = ref<(text: string, input: string) => boolean>();
const filter = (record: CollectionRecord) =>
(filterPredicate.value ?? contains)(record.text, filterText.value);
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),
);
// Focus restoration belongs to the close that the parent actually accepts.
if (props.selectionMode === "single") setOpen(false);
}
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 {
void nextTick(() => {
// A rejected close keeps the row, the focus and the ARIA state intact.
if (open.value) return;
activeKey.value = undefined;
if (
filterInput.value?.ownerDocument.activeElement ===
filterInput.value ||
!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);
/** Keys still backed by an enabled record: a removed item is not submitted. */
// Keys the collection has ever offered. A key that disappeared from the
// collection was removed and must not submit; a key that was never listed
// (closed-state or caller-owned value) is trusted.
const seenKeys = ref(new Set<string>());
watchEffect(() => {
for (const record of records.value)
seenKeys.value.add(`${typeof record.key}\u0001${String(record.key)}`);
});
const successfulKeys = computed(() =>
keys.value.filter((key) => {
const record = records.value.find((item) => item.key === key);
if (record) return !record.disabled;
return !seenKeys.value.has(`${typeof key}\u0001${String(key)}`);
}),
);
provide(collectionOwnerKey, {
keys,
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 ||
composing.value ||
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,
composing,
});
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;
}
const rootProps = mergeProps(restAttrs, {
class: [slotsBase.value.base(), attrs.class],
style: attrs.style,
"data-slot": "autocomplete",
"data-invalid": invalid.value || undefined,
"data-disabled": field.field.disabled.value || undefined,
});
const formLayer = [
selectionInputs({
name: props.name,
form: props.form,
multiple: props.selectionMode === "multiple",
disabled: field.field.disabled.value,
keys: successfulKeys.value,
slot: "autocomplete-form-value",
}),
validationInput(
proxy,
props,
field.field.disabled.value,
field.behavior.value,
(event) =>
field.invalidEvent(event, () => triggerElement.value?.focus()),
props.isRequired && field.behavior.value === "native",
keys.value.length > 0,
),
];
const popover = (inner: VNodeChild[]) =>
h(
Popover,
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
{ default: () => [...inner, ...formLayer] },
);
if (!props.asChild) return h(props.as, rootProps, [popover(nodes)]);
const [host, ...rest] = nodes;
if (!isVNode(host) || typeof host.type !== "string")
return h(props.as, rootProps, [popover(nodes)]);
// `as-child`: the caller's element is the picker root and keeps its own
// attributes, events, children and ref.
const inner = host.children;
const hostChildren = Array.isArray(inner)
? (inner as VNodeChild[])
: inner == null
? []
: [inner as VNodeChild];
const clone = cloneVNode(host, mergeProps(host.props ?? {}, rootProps));
// `children` is replaced, so the shape flag must stop claiming text.
clone.children = [
popover([...hostChildren, ...rest]),
] as typeof clone.children;
clone.shapeFlag =
(clone.shapeFlag & ~SHAPE_TEXT_CHILDREN) | SHAPE_ARRAY_CHILDREN;
return clone;
};
},
});
</script>
@@ -0,0 +1,71 @@
<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;
const callerDisabled = () =>
attrs.disabled !== undefined && attrs.disabled !== false
? true
: undefined;
function click(event: MouseEvent) {
// Caller cancellation is checked before we cancel the default ourselves,
// otherwise a native click would always look pre-cancelled.
if (event.defaultPrevented) return;
event.preventDefault();
event.stopPropagation();
if (callerDisabled() || ctx.disabled.value) 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 || callerDisabled() || undefined,
onClick: click,
};
return h("button", mergeProps(attrs, injected), [icon]);
};
},
});
</script>
@@ -0,0 +1,145 @@
<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>();
/** While a composition session is open the collection keeps its rows. */
const composing = ref(false);
watchEffect(() => {
ctx.filterPredicate.value = props.filter;
ctx.composing.value = composing.value;
// Mid-composition text stays visible without filtering the collection.
if (!composing.value) ctx.filterText.value = text();
});
function commitComposition() {
composing.value = false;
ctx.composing.value = false;
ctx.filterText.value = text();
}
function compose(nodes: VNodeChild[]): VNodeChild[] {
return nodes.map((child) => {
if (!isVNode(child)) return child;
const name = componentName(child);
if (name === "ListBox") return child;
if (name === "SearchFieldInput") {
const own = (child.props ?? {}) as Record<string, unknown>;
const injected: Record<string, unknown> = {
...ctx.core(),
modelValue: text(),
"onUpdate:modelValue": (next: string) => model.request(next),
onCompositionstart: () => {
composing.value = true;
},
onCompositionend: () => commitComposition(),
// Let Vue preserve the caller's normalized template ref.
ref: (instance: unknown) => {
ctx.filterInput.value = elementFromRef(instance) as
HTMLInputElement | undefined;
},
};
// The search input's own accessible name and description win over the
// picker root's: the trigger name is not a name for this control.
for (const key of [
"aria-label",
"aria-labelledby",
"aria-describedby",
]) {
if (own[key] !== undefined) delete injected[key];
}
return cloneVNode(child, injected, true);
}
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,65 @@
<script lang="ts">
/** Decorative chevron: the trigger itself owns activation. */
import { cloneVNode, defineComponent, h, isVNode, mergeProps } from "vue";
import { useAutocomplete } from "./context";
const CHEVRON_PATH =
"M2.97 5.47a.75.75 0 0 1 1.06 0L8 9.44l3.97-3.97a.75.75 0 1 1 1.06 1.06l-4.5 4.5a.75.75 0 0 1-1.06 0l-4.5-4.5a.75.75 0 0 1 0-1.06";
export default defineComponent({
name: "AutocompleteIndicator",
inheritAttrs: false,
setup(_props, { attrs, slots }) {
const ctx = useAutocomplete();
return () => {
const custom = slots.default?.() ?? [];
const indicatorClass = ctx.slots.value.indicator();
const openAttr = ctx.open.value || undefined;
// The baseline puts the indicator class, `data-slot` and `data-open` on the
// same element (the icon), which is what the ported CSS selects.
const icon =
custom.length > 0
? custom.map((node) =>
isVNode(node)
? cloneVNode(node, {
class: [indicatorClass, node.props?.class],
"data-slot": "autocomplete-indicator",
"data-open": openAttr,
})
: node,
)
: [
h(
"svg",
{
"aria-hidden": "true",
class: indicatorClass,
"data-open": openAttr,
"data-slot": "autocomplete-default-indicator",
fill: "none",
height: 16,
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",
"data-slot": "autocomplete-indicator-wrapper",
}),
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,96 @@
<script lang="ts">
/** Clickable value surface: opens the popover and is the single Tab entry. */
import { defineComponent, h, mergeProps, ref, watch } from "vue";
import { PopoverAnchor, 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 ||
(attrs.disabled !== undefined && attrs.disabled !== false);
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(
PopoverAnchor,
{ asChild: true },
{
default: () =>
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,96 @@
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;
}
/** Scoped-slot state of `AutocompleteValue`. */
export interface AutocompleteValueState {
/** No accepted selection: render the placeholder. */
isPlaceholder: boolean;
/** Default text: joined `textValue`s, or the placeholder. */
defaultChildren: string;
/** Accepted `textValue`s joined by ", ". */
selectedText: string;
selectedItems: AutocompleteSelectedItem[];
}
/** Scoped-slot state of the `Autocomplete` root. */
export interface AutocompleteState {
isOpen: boolean;
selectedKeys: CollectionKey[];
}
export interface AutocompleteItem {
id: CollectionKey;
textValue: string;
isDisabled?: boolean;
}
export interface AutocompleteContext {
field: ReturnType<typeof useChoiceField<AutocompleteValue>>;
slots: ComputedRef<ReturnType<typeof autocompleteVariants>>;
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;
composing: Ref<boolean>;
}
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,6 +32,7 @@ import {
type ValidateResult,
type ValidationBehavior,
} from "../field/context";
import type { CollectionKey } from "../collection/keys";
import { useInheritedDisabled } from "../field/disabled";
export interface ChoiceFieldProps {
@@ -304,6 +305,51 @@ export function useChoiceForm(
onBeforeUnmount(() => owner?.removeEventListener("reset", onReset));
}
/**
* The native submission layer for key-based pickers: same-name hidden inputs so
* a multiple selection arrives as separate entries, nothing at all when the
* field is disabled or a key is no longer part of the collection, and a single
* text entry when the picker submits text instead of keys.
*/
export function selectionInputs(options: {
name?: string;
form?: string;
multiple: boolean;
disabled: boolean;
keys: readonly CollectionKey[];
/** Text submission wins over keys when defined. */
text?: string;
slot: string;
}): VNode | null {
const { name, form, slot } = options;
if (!name || options.disabled) return null;
if (options.text !== undefined) {
if (!options.text) return null;
return h("input", {
type: "hidden",
name,
form,
value: options.text,
class: "hv-choice-input",
"data-slot": slot,
});
}
if (!options.keys.length) return null;
return h(
"span",
{ class: "hv-choice-input", "data-slot": `${slot}-entries` },
options.keys.map((key) =>
h("input", {
type: "hidden",
name,
form,
value: String(key),
"data-slot": slot,
}),
),
);
}
export function validationInput(
input: Ref<HTMLInputElement | undefined>,
props: ChoiceFieldProps,
@@ -0,0 +1,21 @@
/** Locale-aware base-sensitivity substring matching; no hand-written accent folding. */
export function createBaseContains(locale?: string) {
const collator = new Intl.Collator(locale, {
usage: "search",
sensitivity: "base",
});
return (text: string, query: string) => {
if (!query) return true;
const characters = Array.from(text.normalize("NFC"));
const needle = query.normalize("NFC");
// Collation expansions (ß/ss, ligatures) need not have equal code-point lengths.
for (let start = 0; start < characters.length; start++) {
let candidate = "";
for (let end = start; end < characters.length; end++) {
candidate += characters[end];
if (collator.compare(candidate, needle) === 0) return true;
}
}
return false;
};
}
@@ -1,16 +1,43 @@
import type { ComputedRef, InjectionKey } from "vue";
import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { CollectionKey } from "./keys";
export interface CollectionRecord {
key: CollectionKey;
text: string;
disabled: boolean;
}
/** Filtering and virtual focus are optional: absent means the previous behaviour. */
export interface CollectionView {
/**
* Filter over the full data set. Filtered-out records stay mounted and keep
* their text/selection, but leave display and keyboard navigation.
*/
filter?: (record: CollectionRecord) => boolean;
/** Keep DOM focus outside the collection and track `activeKey` instead. */
virtualFocus?: () => boolean;
/** Active key for virtual focus; the owning composite drives it. */
activeKey?: Ref<CollectionKey | undefined>;
/**
* Keyboard modality shared with the composite that holds DOM focus. The
* collection clears it on pointer presses; the composite sets it on keys, so
* there is one source instead of a second copy.
*/
keyboardIntent?: Ref<boolean>;
/** The composite's disclosure state; closed collections cancel pending reveals. */
isOpen?: () => boolean;
}
export interface OwnedCollection {
items: () => CollectionRecord[];
focus: (edge: "first" | "last" | "selected") => Promise<void>;
/** Mounted DOM id of an option, for `aria-activedescendant`. */
optionId?: (key: CollectionKey) => string | undefined;
/**
* Make `key` the revealed row: scroll a virtualized window first, then wait
* for the row to mount. Never moves DOM focus.
*/
reveal?: (key: CollectionKey) => Promise<void>;
}
/** A field composite may own a ListBox, without adding another value store. */
export interface CollectionOwner {
export interface CollectionOwner extends CollectionView {
keys: ComputedRef<readonly CollectionKey[]>;
mode: ComputedRef<"single" | "multiple">;
disabled: ComputedRef<boolean>;
@@ -0,0 +1,819 @@
<script lang="ts">
import {
cloneVNode,
computed,
defineComponent,
getCurrentInstance,
h,
isVNode,
mergeProps,
nextTick,
onBeforeUpdate,
onMounted,
provide,
ref,
shallowRef,
useId,
watch,
watchEffect,
type PropType,
type SlotsType,
type VNode,
type VNodeChild,
} from "vue";
import { comboBoxVariants } from "@heroui-vue/styles";
import Popover from "../popover/Popover";
import {
selectionInputs,
useChoiceField,
useChoiceForm,
useChoiceValue,
} from "../choice/shared";
import { useConfig } from "../../providers/context";
import { createBaseContains } from "../collection/match";
import { disabledContextKey } from "../field/disabled";
import { fieldContextKey, type FieldContext } from "../field/context";
import type { ValidateResult, ValidationBehavior } from "../field/context";
import { assertKey, copyKeys, type CollectionKey } from "../collection/keys";
import {
collectionOwnerKey,
type CollectionRecord,
type OwnedCollection,
} from "../collection/owner";
import { planCollectionItems } from "./metadata";
import { SHAPE_ARRAY_CHILDREN, SHAPE_TEXT_CHILDREN } from "./dom";
import {
comboBoxKey,
type ComboBoxItem,
type ComboBoxMenuTrigger,
type ComboBoxValue,
} from "./context";
export default defineComponent({
name: "ComboBox",
inheritAttrs: false,
slots: Object as SlotsType<{
default?: (state: {
isOpen: boolean;
inputValue: string;
selectedKey: CollectionKey | null;
selectedKeys: CollectionKey[];
}) => VNodeChild;
}>,
props: {
modelValue: {
type: [String, Number, Array, null] as PropType<ComboBoxValue>,
default: undefined,
},
value: {
type: [String, Number, Array, null] as PropType<ComboBoxValue>,
default: undefined,
},
defaultValue: {
type: [String, Number, Array, null] as PropType<ComboBoxValue>,
default: undefined,
},
selectedKey: {
type: [String, Number, null] as PropType<CollectionKey | null>,
default: undefined,
},
defaultSelectedKey: {
type: [String, Number, null] as PropType<CollectionKey | null>,
default: undefined,
},
selectionMode: {
type: String as PropType<"single" | "multiple">,
default: "single",
},
inputValue: { type: String, default: undefined },
defaultInputValue: { type: String, default: "" },
items: Array as PropType<readonly ComboBoxItem[]>,
disabledKeys: Array as PropType<readonly CollectionKey[]>,
open: { type: Boolean, default: undefined },
isOpen: { type: Boolean, default: undefined },
defaultOpen: Boolean,
defaultFilter: Function as PropType<
(text: string, inputValue: string) => boolean
>,
isDisabled: Boolean,
disabled: Boolean,
isReadOnly: Boolean,
isRequired: Boolean,
isInvalid: Boolean,
allowsCustomValue: Boolean,
allowsEmptyCollection: Boolean,
menuTrigger: {
type: String as PropType<ComboBoxMenuTrigger>,
default: "focus",
},
shouldFocusWrap: Boolean,
fullWidth: Boolean,
variant: {
type: String as PropType<"primary" | "secondary">,
default: "primary",
},
name: String,
form: String,
formValue: {
type: String as PropType<"key" | "text">,
default: "key",
},
autoComplete: String,
autoFocus: Boolean,
validationBehavior: String as PropType<ValidationBehavior>,
validate: Function as PropType<(value: ComboBoxValue) => ValidateResult>,
placeholder: { type: String, default: "Select an item" },
as: { type: String, default: "div" },
asChild: { type: Boolean, default: false },
},
emits: {
"update:modelValue": (_value: ComboBoxValue) => true,
change: (_value: ComboBoxValue) => true,
"update:selectedKey": (_value: CollectionKey | null) => true,
selectionChange: (_value: CollectionKey | null) => true,
"update:inputValue": (_value: string) => true,
inputChange: (_value: string) => true,
"update:open": (_value: boolean) => true,
openChange: (_value: boolean) => true,
},
setup(props, { attrs, slots, emit, expose }) {
const instance = getCurrentInstance()!;
const contains = createBaseContains(useConfig()?.locale.value);
const present = (keys: string[]) =>
keys.some((key) => Object.hasOwn(instance.vnode.props ?? {}, key));
const readValue = (): ComboBoxValue | undefined => {
if (present(["modelValue", "model-value"]))
return props.modelValue ?? null;
if (present(["value"])) return props.value ?? null;
if (present(["selectedKey", "selected-key"]))
return props.selectedKey ?? null;
return undefined;
};
const model = useChoiceValue<ComboBoxValue | undefined>(
readValue,
() => props.defaultValue ?? props.defaultSelectedKey ?? null,
["modelValue", "model-value", "value", "selectedKey", "selected-key"],
(value) => {
const next = value ?? null;
emit("update:modelValue", next);
emit("change", next);
const single =
props.selectionMode === "multiple"
? ((Array.isArray(next) ? next[0] : next) ?? null)
: Array.isArray(next)
? (next[0] ?? null)
: next;
emit("update:selectedKey", single);
emit("selectionChange", single);
},
);
const value = computed<ComboBoxValue>(() => {
const raw = model.value.value ?? null;
if (props.selectionMode === "multiple")
return raw === null ? [] : Array.isArray(raw) ? raw : [raw];
return Array.isArray(raw) ? (raw[0] ?? null) : raw;
});
const keys = computed<readonly CollectionKey[]>(() => {
const raw = value.value;
if (
props.selectionMode === "multiple" &&
raw !== null &&
!Array.isArray(raw)
)
throw new TypeError("Multiple ComboBox expects a key array.");
const next = copyKeys(
raw === null ? [] : Array.isArray(raw) ? raw : [raw],
);
if (props.selectionMode === "single" && next.length > 1)
throw new TypeError("Single ComboBox expects one key or null.");
return Object.freeze(next);
});
const inputModel = useChoiceValue<string | undefined>(
() => props.inputValue,
() => props.defaultInputValue,
["inputValue", "input-value"],
(next) => {
emit("update:inputValue", next ?? "");
emit("inputChange", next ?? "");
},
);
const inputValue = computed(() => inputModel.value.value ?? "");
const openModel = useChoiceValue<boolean | undefined>(
() => (present(["open"]) ? props.open : props.isOpen),
() => props.defaultOpen,
["open", "isOpen", "is-open"],
(next) => {
emit("update:open", !!next);
emit("openChange", !!next);
},
);
const open = computed(() => !!openModel.value.value);
const collection = shallowRef<OwnedCollection>();
const discovered = shallowRef<CollectionRecord[]>([]);
watchEffect(() => {
if (!collection.value) return;
const next = collection.value.items();
if (JSON.stringify(next) !== JSON.stringify(discovered.value))
discovered.value = next;
});
const planned = shallowRef<CollectionRecord[]>([]);
const complete = ref(false);
const records = computed<CollectionRecord[]>(() => {
const explicit = props.items?.map((item) => {
assertKey(item.id);
return {
key: item.id,
text: item.textValue,
disabled: !!item.isDisabled,
} satisfies CollectionRecord;
});
// Caller data wins; otherwise the complete slot plan is authoritative for
// a closed ComboBox, and mounted rows fill in when the plan is opaque.
const base =
explicit ??
(complete.value
? planned.value
: discovered.value.length
? discovered.value
: planned.value);
return base.map((record) => ({
...record,
disabled: record.disabled || !!props.disabledKeys?.includes(record.key),
}));
});
const filter = (record: CollectionRecord) =>
props.defaultFilter
? props.defaultFilter(record.text, filterText.value)
: contains(record.text, filterText.value);
const instanceId = useId();
const inputId = `hv-combo-box-${instanceId}-input`;
const listId = `hv-combo-box-${instanceId}-listbox`;
const valueId = `hv-combo-box-${instanceId}-value`;
const field = useChoiceField<ComboBoxValue>(props, attrs, {
kind: "group",
value,
validate: (current) => props.validate?.(current),
satisfied: () =>
props.allowsCustomValue
? inputValue.value.trim().length > 0
: keys.value.length > 0,
requiredMessage: "请选择一个选项。",
});
// A combobox input is a text control: Label must render `<label for>` and
// point at the composed input, not at an unrelated generated id.
provide(fieldContextKey, {
...field.field,
kind: "text",
controlId: computed(() => inputId),
} as FieldContext);
provide(disabledContextKey, field.field.disabled);
const keyboardIntent = ref(true);
const activeKey = ref<CollectionKey>();
/** Open composition session: filtering waits for `compositionend`. */
const composing = ref(false);
/** Text the collection is actually filtered by. */
const filterText = ref("");
const cursor = ref<CollectionKey>();
const inputElement = ref<HTMLInputElement>();
const triggerElement = ref<HTMLElement>();
let anchor: (() => HTMLElement | undefined) | undefined;
const registerAnchor = (element: () => HTMLElement | undefined) => {
anchor = element;
};
const activeId = computed<string | undefined>(() => {
if (!open.value || activeKey.value === undefined) return undefined;
return collection.value?.optionId?.(activeKey.value);
});
function request(next: CollectionKey[]) {
if (field.field.disabled.value || field.field.readOnly.value) return;
const candidate = (key: CollectionKey) =>
records.value.find((record) => record.key === key);
if (
next.some(
(key) => candidate(key)?.disabled && !keys.value.includes(key),
)
)
return;
if (
next.length === keys.value.length &&
next.every((key) => keys.value.includes(key))
)
return;
if (!next.length && !keys.value.length) return;
// Validation blocks an invalid submit; it must not stop the user from
// editing a required field back to empty.
field.edit();
model.request(
props.selectionMode === "multiple" ? [...next] : (next[0] ?? null),
);
if (props.selectionMode === "single") {
const record = next.length ? candidate(next[0]) : undefined;
if (record && !props.allowsCustomValue) inputModel.request(record.text);
setOpen(false);
}
}
function setOpen(next: boolean) {
if (next === open.value) return;
if (
next &&
(field.field.disabled.value || field.field.readOnly.value) === true
)
return;
if (
next &&
props.items &&
!props.items.length &&
!props.allowsEmptyCollection
)
return;
openModel.request(next);
if (next) {
void nextTick(() => {
const record =
records.value.find(
(item) =>
keys.value.includes(item.key) && filter(item) && !item.disabled,
) ?? records.value.find((item) => filter(item) && !item.disabled);
void setActive(record?.key);
});
} else {
activeKey.value = undefined;
}
}
async function setActive(key: CollectionKey | undefined) {
cursor.value = key;
activeKey.value = key;
if (key !== undefined) await collection.value?.reveal?.(key);
}
function moveActive(delta: 1 | -1) {
const items = records.value.filter(
(record) => filter(record) && !record.disabled,
);
if (!items.length) {
void setActive(undefined);
return;
}
const index = items.findIndex((item) => item.key === activeKey.value);
const next =
index < 0
? items[delta > 0 ? 0 : items.length - 1]
: items[
props.shouldFocusWrap
? (index + delta + items.length) % items.length
: Math.min(Math.max(index + delta, 0), items.length - 1)
];
if (next) void setActive(next.key);
}
function confirmActive() {
const key = activeKey.value;
const record =
key === undefined
? undefined
: records.value.find(
(item) => item.key === key && filter(item) && !item.disabled,
);
if (key === undefined || !record) {
const typed = inputValue.value.trim();
// A custom value is the typed text itself, not a collection key.
if (
props.allowsCustomValue &&
props.selectionMode === "single" &&
typed
)
request([typed]);
return;
}
if (props.selectionMode === "multiple") {
// Confirming the active row toggles it inside the accepted set.
const next = keys.value.includes(key)
? keys.value.filter((item) => item !== key)
: [...keys.value, key];
request(next);
return;
}
request([key]);
}
const selectedRecord = computed(() =>
props.selectionMode === "single"
? records.value.find((record) => keys.value.includes(record.key))
: undefined,
);
const selectionIdentity = computed(() =>
keys.value
.map((key) => `${typeof key}\u0001${String(key)}`)
.join("\u0000"),
);
const inputControlled = ref(present(["inputValue", "input-value"]));
onBeforeUpdate(() => {
inputControlled.value = present(["inputValue", "input-value"]);
});
/** Set while a typed draft is allowed to outlive the cleared selection. */
let keepDraft = false;
watch(
// A selection change (initial, external or accepted) owns the single-select
// text. The identity keeps `0` and `"0"` apart, and the label is watched
// directly so an edited textValue re-syncs without a count change.
[selectionIdentity, () => selectedRecord.value?.text],
() => {
if (props.selectionMode !== "single" || inputControlled.value) return;
if (keepDraft) {
keepDraft = false;
return;
}
syncAcceptedText();
},
{ immediate: true },
);
/**
* Visible text. A controlled `inputValue` wins even when empty; otherwise an
* explicit draft wins, and with no draft the accepted item's label is read at
* render time so the first SSR paint already shows the selection.
*/
const displayInputValue = computed(() => {
if (inputControlled.value) return inputValue.value;
if (inputValue.value) return inputValue.value;
return selectedRecord.value?.text ?? "";
});
function applyInput(next: string) {
filterText.value = next;
// Keep the active row on the first match of the new filter.
if (next) {
const first = records.value.find(
(record) => filter(record) && !record.disabled,
);
if (first) void setActive(first.key);
}
if (
props.selectionMode === "single" &&
!props.allowsCustomValue &&
keys.value.length
) {
const selected = records.value.find((record) =>
keys.value.includes(record.key),
);
if (selected && next !== selected.text) {
// Dropping the no-longer-matching selection must not erase the draft.
keepDraft = true;
request([]);
void nextTick(() => {
keepDraft = false;
});
}
}
}
function setInputValue(next: string) {
inputModel.request(next);
if (props.menuTrigger === "input" && !open.value && next) setOpen(true);
// Mid-composition text must stay visible without filtering the collection.
if (composing.value) return;
applyInput(next);
}
function keydown(event: KeyboardEvent) {
if (
event.defaultPrevented ||
composing.value ||
event.isComposing ||
event.keyCode === 229
)
return;
if (field.field.disabled.value || field.field.readOnly.value) return;
keyboardIntent.value = true;
const meta = event.metaKey || event.ctrlKey || event.altKey;
if (meta) return;
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!open.value) {
setOpen(true);
return;
}
moveActive(event.key === "ArrowDown" ? 1 : -1);
return;
}
if (event.key === "Home" || event.key === "End") {
if (!open.value) return;
event.preventDefault();
const items = records.value.filter(
(record) => filter(record) && !record.disabled,
);
const target = event.key === "Home" ? items[0] : items.at(-1);
if (target) void setActive(target.key);
return;
}
if (event.key === "Enter") {
event.preventDefault();
if (event.repeat) return;
confirmActive();
return;
}
if (event.key === "Escape") {
if (!open.value) return;
event.preventDefault();
setOpen(false);
return;
}
if (event.key === "Tab") {
setOpen(false);
}
}
function focusInput() {
if (props.menuTrigger === "focus") setOpen(true);
}
onMounted(() => {
if (!props.autoFocus || field.field.disabled.value) return;
inputElement.value?.focus({ preventScroll: true });
});
function describedBy() {
return field.describedBy();
}
const formValueText = computed<string | undefined>(() => {
if (!props.name) return undefined;
if (props.formValue === "text" || props.allowsCustomValue) {
const texts = keys.value
.map((key) => records.value.find((item) => item.key === key)?.text)
.filter((text): text is string => !!text);
return texts.length ? texts.join(",") : inputValue.value || undefined;
}
return keys.value.length ? keys.value.map(String).join(",") : undefined;
});
const invalid = computed(() => field.field.invalid.value);
const slotsBase = computed(() =>
comboBoxVariants({ fullWidth: props.fullWidth }),
);
provide(collectionOwnerKey, {
keys,
mode: computed(() => props.selectionMode),
disabled: field.field.disabled,
readOnly: field.field.readOnly,
disabledKeys: computed(() => props.disabledKeys ?? []),
id: listId,
labelledBy: () =>
field.labelledBy() ?? (attrs["aria-label"] ? undefined : inputId),
ariaLabel: () =>
typeof attrs["aria-label"] === "string"
? attrs["aria-label"]
: undefined,
request,
action: (key) => {
if (props.selectionMode === "single") setOpen(false);
void key;
},
leave: () => setOpen(false),
connect: (next) => {
if (collection.value && collection.value !== next)
throw new Error("ComboBox supports one ListBox.");
collection.value = next;
return () => {
if (collection.value === next) collection.value = undefined;
};
},
filter,
virtualFocus: () => true,
activeKey,
keyboardIntent,
isOpen: () => open.value,
});
const inputProps = () => ({
id: inputId,
role: "combobox",
autocomplete: props.autoComplete ?? "off",
spellcheck: false,
"aria-expanded": open.value,
"aria-controls": open.value ? listId : undefined,
"aria-activedescendant": activeId.value,
"aria-autocomplete": "list" as const,
"aria-haspopup": "listbox" as const,
"aria-label": attrs["aria-label"] as string | undefined,
"aria-labelledby":
attrs["aria-labelledby"] ??
(attrs["aria-label"] ? undefined : field.labelledBy()),
"aria-describedby": describedBy(),
"aria-invalid": invalid.value || undefined,
readonly: field.field.readOnly.value || undefined,
disabled: field.field.disabled.value || undefined,
required:
(field.behavior.value === "native" && field.field.required.value) ||
undefined,
form: props.form,
onKeydown: keydown,
onFocus: focusInput,
onCompositionstart: () => {
composing.value = true;
},
onCompositionend: () => {
composing.value = false;
applyInput(inputValue.value);
},
});
provide(comboBoxKey, {
field,
slots: slotsBase,
open,
setOpen,
inputValue,
displayInputValue,
setInputValue,
inputId,
listId,
valueId,
placeholder: () => props.placeholder,
activeKey,
activeId,
collection,
keys,
records,
selectedItems: computed(() =>
keys.value.map((key) => ({
key,
textValue:
records.value.find((record) => record.key === key)?.text ??
String(key),
})),
),
selectionMode: computed(() => props.selectionMode),
allowsCustomValue: () => props.allowsCustomValue,
menuTrigger: () => props.menuTrigger,
inputElement,
registerAnchor,
triggerElement,
inputProps,
formValueText,
invalid,
disabled: field.field.disabled,
variant: () => props.variant,
});
function syncAcceptedText() {
if (props.selectionMode !== "single" || inputControlled.value) return;
const next =
selectedRecord.value?.text ??
(props.allowsCustomValue ? (inputModel.value.value ?? "") : "");
if (inputModel.value.value !== next) inputModel.request(next);
}
useChoiceForm(
inputElement,
() => {
model.reset();
inputModel.reset();
field.reset();
setOpen(false);
// Restore the accepted item's label, not the empty raw input default.
void nextTick(syncAcceptedText);
},
() => {
field.validity(inputElement.value);
},
);
watchEffect(() => {
// `required` plus the custom message live on the visible input, which is
// the control the browser blocks on.
const element = inputElement.value;
if (!element) return;
element.required =
field.behavior.value === "native" && field.field.required.value;
field.validity(element);
});
watchEffect(() => {
if (!open.value || props.allowsEmptyCollection) return;
if (!records.value.length) return;
const eligibleRecords = records.value.filter(
(record) => filter(record) && !record.disabled,
);
if (!eligibleRecords.length) setOpen(false);
});
/** Keys still backed by an enabled record: removed items are not submitted. */
// Keys the collection has ever offered. A key that disappeared from the
// collection was removed and must not submit; a key that was never listed
// (closed-state or caller-owned value) is trusted.
const seenKeys = ref(new Set<string>());
watchEffect(() => {
for (const record of records.value)
seenKeys.value.add(`${typeof record.key}\u0001${String(record.key)}`);
});
const successfulKeys = computed(() =>
keys.value.filter((key) => {
const record = records.value.find((item) => item.key === key);
if (record) return !record.disabled;
return !seenKeys.value.has(`${typeof key}\u0001${String(key)}`);
}),
);
const submitText = computed<string | undefined>(() => {
if (!props.name) return undefined;
if (props.allowsCustomValue) return inputValue.value;
if (props.formValue !== "text") return undefined;
return successfulKeys.value
.map((key) => records.value.find((item) => item.key === key)?.text)
.filter((text): text is string => Boolean(text))
.join(",");
});
/**
* The picker root element owns the popover, so the component has a single
* root node and `as-child` can hand it to the caller's element.
*/
function renderRoot(nodes: VNodeChild[], formLayer: VNode | null) {
const rootProps = mergeProps(attrs, {
class: slotsBase.value.base(),
style: attrs.style,
"data-slot": "combo-box",
"data-invalid": invalid.value || undefined,
"data-disabled": field.field.disabled.value || undefined,
});
const popover = (inner: VNodeChild[]) =>
h(
Popover,
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
{ default: () => [...inner, formLayer] },
);
if (!props.asChild) return h(props.as, rootProps, [popover(nodes)]);
const [host, ...rest] = nodes;
if (!isVNode(host) || typeof host.type !== "string")
return h(props.as, rootProps, [popover(nodes)]);
// `as-child`: the caller's single root element becomes the picker root and
// keeps its own attributes, events, children and ref.
const inner = host.children;
const hostChildren = Array.isArray(inner)
? (inner as VNodeChild[])
: inner == null
? []
: [inner as VNodeChild];
const clone = cloneVNode(host, mergeProps(host.props ?? {}, rootProps));
// `children` is replaced, so the shape flag must stop claiming text.
clone.children = [
popover([...hostChildren, ...rest]),
] as typeof clone.children;
clone.shapeFlag =
(clone.shapeFlag & ~SHAPE_TEXT_CHILDREN) | SHAPE_ARRAY_CHILDREN;
return clone;
}
expose({
element: () => anchor?.(),
input: inputElement,
open: () => setOpen(true),
close: () => setOpen(false),
focus: () => inputElement.value?.focus(),
});
return () => {
const rendered = slots.default?.({
isOpen: open.value,
inputValue: inputValue.value,
selectedKey: Array.isArray(value.value)
? null
: (value.value as CollectionKey | null),
selectedKeys: [...keys.value],
});
const children = Array.isArray(rendered)
? rendered
: rendered == null
? []
: [rendered];
const plan = planCollectionItems(children);
if (JSON.stringify(plan.records) !== JSON.stringify(planned.value))
planned.value = plan.records;
complete.value = plan.complete;
const nodes = field.prepare(children, true);
const formLayer = selectionInputs({
name: props.name,
form: props.form,
multiple: props.selectionMode === "multiple",
disabled: field.field.disabled.value,
keys: successfulKeys.value,
text: submitText.value,
slot: "combo-box-form-value",
});
return renderRoot(nodes, formLayer);
};
},
});
</script>
@@ -0,0 +1,106 @@
<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 { PopoverAnchor, 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,
() => {
ctx.triggerElement.value = elementFromRef(root.value);
},
{ immediate: true, flush: "post" },
);
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;
const own = (node.props ?? {}) as Record<string, unknown>;
const injected: Record<string, unknown> = {
...ctx.inputProps(),
modelValue: ctx.displayInputValue.value,
"onUpdate:modelValue": (next: string) => ctx.setInputValue(next),
// The root variant is inherited; an explicit Input variant still wins.
variant: own.variant ?? ctx.variant(),
// Vue merges normalized refs, including string/useTemplateRef/ref_for.
ref: (instance: unknown) => {
ctx.inputElement.value = elementFromRef(instance) as
HTMLInputElement | undefined;
},
};
for (const key of Object.keys(injected))
if (injected[key] === undefined) delete injected[key];
return cloneVNode(node, injected, true);
}
return () => {
const rendered = slots.default?.() ?? [];
const children = (
Array.isArray(rendered) ? rendered : [rendered]
) as VNodeChild[];
return h(
PopoverAnchor,
{ asChild: true },
{
default: () =>
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,47 @@
<script lang="ts">
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({
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();
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": "combo-box-popover",
style: {
"--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.
onOpenAutoFocus: (event: Event) => event.preventDefault(),
}),
{ default: () => slots.default?.() },
);
},
});
</script>
@@ -0,0 +1,77 @@
<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();
// `disabled` may arrive as an attribute (`<ComboBoxTrigger disabled />`).
const callerDisabled = () =>
attrs.disabled !== undefined && attrs.disabled !== false
? true
: undefined;
const disabled = () =>
props.isDisabled || ctx.disabled.value || callerDisabled() === true;
function toggle(event: MouseEvent) {
if (event.defaultPrevented || disabled()) return;
ctx.setOpen(!ctx.open.value);
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-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,104 @@
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;
}
/** Scoped-slot state of the `ComboBox` root. */
export interface ComboBoxState {
isOpen: boolean;
inputValue: string;
selectedKey: CollectionKey | null;
selectedKeys: CollectionKey[];
}
/** Scoped-slot state of `ComboBoxValue`. */
export interface ComboBoxValueState {
isPlaceholder: boolean;
selectedItems: ComboBoxSelectedItem[];
}
export interface ComboBoxSelectedItem {
key: CollectionKey;
textValue: string;
}
/** 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>;
/** Text shown in the input: the accepted item's label before any typing. */
displayInputValue: 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;
triggerElement: Ref<HTMLElement | undefined>;
/** ARIA plus input handlers injected onto the composed `Input`. */
inputProps: () => Record<string, unknown>;
formValueText: ComputedRef<string | undefined>;
variant: () => "primary" | "secondary";
invalid: ComputedRef<boolean>;
disabled: ComputedRef<boolean>;
}
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,14 @@
/** 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;
}
/**
* Vue vnode shape bits (not exported by the package). `cloneVNode` copies
* `shapeFlag`, so replacing an element's children needs these to stay coherent.
*/
export const SHAPE_TEXT_CHILDREN = 8;
export const SHAPE_ARRAY_CHILDREN = 16;
@@ -0,0 +1,134 @@
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",
"AutocompletePopover",
"AutocompleteFilter",
"SelectPopover",
"ListBoxSection",
];
/**
* 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 planCollectionItems(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 };
}
@@ -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;
}
@@ -0,0 +1,47 @@
<script lang="ts">
import { defineComponent, h, type PropType } from "vue";
import MenuItem from "../menu-item/MenuItem.vue";
import type { MenuItemVariants } from "@heroui-vue/styles";
import type { MenuKey } from "../menu/context";
export default defineComponent({
name: "DropdownItem",
inheritAttrs: false,
props: {
id: { type: [String, Number] as PropType<MenuKey>, default: undefined },
textValue: { type: String, default: undefined },
isDisabled: { type: Boolean, default: false },
disabled: { type: Boolean, default: undefined },
variant: {
type: String as PropType<MenuItemVariants["variant"]>,
default: "default",
},
closeOnSelect: { type: Boolean, default: undefined },
hasSubmenu: { type: Boolean, default: undefined },
href: { type: String, default: undefined },
target: { type: String, default: undefined },
rel: { type: String, default: undefined },
download: {
type: [String, Boolean] as PropType<string | boolean>,
default: undefined,
},
hrefLang: { type: String, default: undefined },
referrerPolicy: { type: String, default: undefined },
},
emits: {
select: (_key: MenuKey) => true,
},
setup(props, { attrs, slots, emit }) {
return () =>
h(
MenuItem as never,
{
...props,
...attrs,
onSelect: (key: MenuKey) => emit("select", key),
},
slots,
);
},
});
</script>
@@ -0,0 +1,12 @@
<script lang="ts">
import { defineComponent, h } from "vue";
import MenuItemIndicator from "../menu-item/MenuItemIndicator.vue";
export default defineComponent({
name: "DropdownItemIndicator",
inheritAttrs: false,
setup(_, { attrs, slots }) {
return () => h(MenuItemIndicator as never, attrs, slots);
},
});
</script>
@@ -0,0 +1,55 @@
<script lang="ts">
import { defineComponent, h, type PropType } from "vue";
import Menu from "../menu/Menu.vue";
import type { MenuKey, MenuSelectionMode } from "../menu/context";
export default defineComponent({
name: "DropdownMenu",
inheritAttrs: false,
props: {
selectionMode: {
type: String as PropType<MenuSelectionMode>,
default: "none",
},
selectedKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: undefined,
},
defaultSelectedKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: () => [],
},
disabledKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: () => [],
},
disallowEmptySelection: { type: Boolean, default: false },
shouldCloseOnSelect: {
type: [Boolean, Function] as PropType<
boolean | ((key: MenuKey) => boolean)
>,
default: undefined,
},
},
emits: {
"update:selectedKeys": (_keys: MenuKey[]) => true,
selectionChange: (_keys: MenuKey[]) => true,
action: (_key: MenuKey) => true,
},
setup(props, { attrs, slots, emit }) {
return () =>
h(
Menu as never,
{
...props,
...attrs,
"onUpdate:selectedKeys": (keys: MenuKey[]) =>
emit("update:selectedKeys", keys),
onSelectionChange: (keys: MenuKey[]) => emit("selectionChange", keys),
onAction: (key: MenuKey) => emit("action", key),
},
slots,
);
},
});
</script>
@@ -0,0 +1,261 @@
<script lang="ts">
import {
Fragment,
computed,
defineComponent,
h,
inject,
provide,
ref,
useAttrs,
watchEffect,
type PropType,
type Ref,
} from "vue";
import {
DropdownMenuContent as RekaDropdownMenuContent,
DropdownMenuPortal as RekaDropdownMenuPortal,
injectDropdownMenuRootContext,
} from "reka-ui";
import { dropdownVariants } from "@heroui-vue/styles";
import {
dropdownContextKey,
menuCloseKey,
menuContentAttrsKey,
submenuContentKey,
} from "../menu/context";
import { useOverlayAnimation } from "../overlay/animation";
import { resolvePlacement, type OverlayPlacement } from "../overlay/placement";
import { useConfig } from "../../providers/context";
import { surfaceContextKey } from "../surface/context";
import { menuSurfaceFromVNode } from "./dom";
/**
* Dropdown popover / menu content shell. Provides close for Menu items.
* Inside a submenu, renders a style shell (Reka SubContent already positions).
*/
export default defineComponent({
name: "DropdownPopover",
inheritAttrs: false,
props: {
/** Placement relative to the trigger (official prop name). */
placement: {
type: String as PropType<OverlayPlacement>,
default: "bottom",
},
/** Distance from the trigger (official `offset`). */
offset: { type: Number, default: 0 },
/** Cross-axis distance (official `crossOffset`). */
crossOffset: { type: Number, default: 0 },
/** Flip on collision (official `shouldFlip`). */
shouldFlip: { type: Boolean, default: true },
/** Viewport padding kept free (official `containerPadding`). */
containerPadding: { type: Number, default: 12 },
/** Ignore Escape while true (official `isKeyboardDismissDisabled`). */
isKeyboardDismissDisabled: { type: Boolean, default: false },
/** Return false to keep the menu open for an outside interaction. */
shouldCloseOnInteractOutside: {
type: Function as PropType<(event: Event) => boolean>,
default: undefined,
},
/** Portal target; defaults to `document.body`. */
to: {
type: [String, Object] as PropType<string | HTMLElement>,
default: undefined,
},
// Low-level positioning overrides, kept for direct control.
side: { type: String as PropType<string>, default: undefined },
align: { type: String as PropType<string>, default: undefined },
sideOffset: { type: Number, default: undefined },
alignOffset: { type: Number, default: undefined },
avoidCollisions: { type: Boolean, default: undefined },
collisionPadding: {
type: [Number, Object] as PropType<number | Record<string, number>>,
default: undefined,
},
loop: { type: Boolean, default: undefined },
},
setup(props, { slots }) {
const attrs = useAttrs();
const dropdownCtx = inject(dropdownContextKey, null);
const inSubmenu = inject(submenuContentKey, false);
const rootCtx = injectDropdownMenuRootContext(null);
const config = useConfig();
provide(menuCloseKey, () => {
rootCtx?.onOpenChange(false);
});
// Surface resets to the overlay default, like the fixed upstream popover,
// so nested fields do not inherit a surrounding surface variant.
provide(surfaceContextKey, { variant: computed(() => "default" as const) });
// Label/description attributes belong on the real `role="menu"` element.
const contentAttrs = inSubmenu
? (inject(menuContentAttrsKey, null) ?? null)
: {
label: ref<string | undefined>(),
labelledBy: ref<string | undefined>(),
describedBy: ref<string | undefined>(),
loop: ref<boolean | undefined>(),
autoFocus: ref<boolean | undefined>(),
escapeKeyBehavior: ref<"clearSelection" | "none">("none"),
clearSelection: () => {},
};
if (!inSubmenu && contentAttrs) provide(menuContentAttrsKey, contentAttrs);
const contentElement = ref<HTMLElement | null>(null);
const isOpen = computed(() => rootCtx?.open.value ?? false);
const { entering, exiting, onAnimationEnd } = useOverlayAnimation(
isOpen as Ref<boolean>,
contentElement,
true,
);
const position = computed(() =>
resolvePlacement(props.placement, config?.dir.value ?? "ltr"),
);
const resolvedSide = computed(() => props.side ?? position.value.side);
const resolvedAlign = computed(() => props.align ?? position.value.align);
type Handler<Ev> =
((event: Ev) => void) | ((event: Ev) => void)[] | undefined;
/** Caller handlers first, then the internal one: Vue array semantics. */
function chain<Ev extends Event>(
name: string,
own: (event: Ev) => void,
): Array<(event: Ev) => void> {
const user = (attrs as Record<string, Handler<Ev>>)[name];
const list = Array.isArray(user) ? user : user ? [user] : [];
return [...list, own];
}
function escape(event: KeyboardEvent) {
if (event.defaultPrevented) return;
if (props.isKeyboardDismissDisabled) event.preventDefault();
}
/**
* `escapeKeyBehavior="clearSelection"` clears the selection and keeps the
* overlay open; the dismissable layer respects `defaultPrevented`.
*/
function onSurfaceKeydown(event: KeyboardEvent) {
if (event.defaultPrevented) return;
if (event.key !== "Escape") return;
if (contentAttrs?.escapeKeyBehavior.value !== "clearSelection") return;
event.preventDefault();
contentAttrs.clearSelection();
}
function interactOutside(event: {
defaultPrevented?: boolean;
preventDefault?: () => void;
}) {
if (
props.shouldCloseOnInteractOutside?.(event as unknown as Event) ===
false
)
event.preventDefault?.();
}
watchEffect(() => {
if (inSubmenu || !contentAttrs) return;
contentAttrs.label.value = attrs["aria-label"] as string | undefined;
contentAttrs.labelledBy.value = attrs["aria-labelledby"] as
string | undefined;
contentAttrs.describedBy.value = attrs["aria-describedby"] as
string | undefined;
});
function labelProps(): Record<string, unknown> {
const out: Record<string, unknown> = {};
const label = (contentAttrs?.label.value ??
(attrs["aria-label"] as string | undefined)) as string | undefined;
const labelledBy = (contentAttrs?.labelledBy.value ??
(attrs["aria-labelledby"] as string | undefined)) as string | undefined;
const describedBy = (contentAttrs?.describedBy.value ??
(attrs["aria-describedby"] as string | undefined)) as
string | undefined;
if (label) {
out["aria-label"] = label;
// aria-labelledby would win over aria-label; drop the trigger default.
out["aria-labelledby"] = labelledBy;
} else if (labelledBy) {
out["aria-labelledby"] = labelledBy;
}
if (describedBy) out["aria-describedby"] = describedBy;
return out;
}
return () => {
const scope = {
isEntering: entering.value,
isExiting: exiting.value,
placement: props.placement,
};
if (inSubmenu) {
// Reka SubContent already positions and dismisses this level;
// the submenu trigger forwards attrs onto that element.
return h(Fragment, null, slots.default?.(scope) as never);
}
return h(
RekaDropdownMenuPortal as never,
{ to: props.to },
{
default: () =>
h(
RekaDropdownMenuContent as never,
{
...attrs,
...labelProps(),
class: dropdownCtx?.slots.value.popover({
class: attrs.class as never,
}),
"data-slot": "dropdown-popover",
"data-entering": entering.value || undefined,
"data-exiting": exiting.value || undefined,
side: resolvedSide.value,
align: resolvedAlign.value,
sideOffset: props.sideOffset ?? props.offset,
alignOffset: props.alignOffset ?? props.crossOffset,
avoidCollisions: props.avoidCollisions ?? props.shouldFlip,
collisionPadding:
props.collisionPadding ?? props.containerPadding,
// Boolean on purpose: undefined -> true updates are dropped by
// the base prop chain.
loop: props.loop ?? contentAttrs?.loop.value ?? false,
onAnimationend: chain<AnimationEvent>(
"onAnimationend",
onAnimationEnd,
),
onOpenAutoFocus: chain<Event>("onOpenAutoFocus", (event) => {
if (event.defaultPrevented) return;
if (contentAttrs?.autoFocus.value === false)
event.preventDefault();
}),
onEscapeKeyDown: chain<KeyboardEvent>(
"onEscapeKeyDown",
escape,
),
onInteractOutside: chain<Event>(
"onInteractOutside",
interactOutside as (event: Event) => void,
),
onKeydown: chain<KeyboardEvent>("onKeydown", onSurfaceKeydown),
onVnodeMounted: (vnode) => {
contentElement.value = menuSurfaceFromVNode(vnode);
},
onVnodeUpdated: (vnode) => {
const element = menuSurfaceFromVNode(vnode);
if (element) contentElement.value = element;
},
onVnodeUnmounted: () => {
contentElement.value = null;
},
},
{ default: () => slots.default?.(scope) },
),
},
);
};
},
});
</script>
@@ -0,0 +1,87 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
provide,
ref,
useAttrs,
type PropType,
} from "vue";
import { DropdownMenuRoot as RekaDropdownMenuRoot } from "reka-ui";
import { dropdownVariants } from "@heroui-vue/styles";
import { dropdownContextKey } from "../menu/context";
export const LONG_PRESS_DURATION = 500;
export default defineComponent({
name: "DropdownRoot",
inheritAttrs: false,
props: {
open: { type: Boolean, default: undefined },
defaultOpen: { type: Boolean, default: undefined },
dir: { type: String as PropType<"ltr" | "rtl">, default: undefined },
modal: { type: Boolean, default: true },
/**
* Trigger mode. `longPress` opens on press-and-hold and suppresses the
* following click, matching the upstream Dropdown `trigger` contract.
*/
trigger: {
type: String as PropType<"press" | "longPress">,
default: "press",
},
/** Long-press duration in ms (longPress trigger). */
longPressDuration: { type: Number, default: LONG_PRESS_DURATION },
},
emits: ["update:open"],
setup(props, { slots, emit }) {
const attrs = useAttrs();
const slotsComputed = computed(() => dropdownVariants());
const uncontrolledOpen = ref(props.defaultOpen ?? false);
const isOpen = computed(() =>
props.open !== undefined ? props.open : uncontrolledOpen.value,
);
// The trigger suppresses the base trigger's own toggle while it decides.
const suppressOpenRequests = ref(false);
function setOpen(value: boolean) {
if (suppressOpenRequests.value) return;
if (props.open === undefined) uncontrolledOpen.value = value;
emit("update:open", value);
}
provide(dropdownContextKey, {
slots: slotsComputed,
triggerMode: computed(() => props.trigger),
longPressDuration: computed(() => props.longPressDuration),
open: isOpen,
setOpen,
suppressOpenRequests,
});
return () =>
h(
"div",
{
...attrs,
class: [slotsComputed.value.root(), attrs.class],
"data-slot": "dropdown-root",
"data-trigger": props.trigger,
},
[
h(
RekaDropdownMenuRoot as never,
{
open: isOpen.value,
defaultOpen: props.defaultOpen,
dir: props.dir,
modal: props.modal,
"onUpdate:open": (value: boolean) => setOpen(value),
},
{ default: () => slots.default?.() },
),
],
);
},
});
</script>
@@ -0,0 +1,47 @@
<script lang="ts">
import { defineComponent, h, type PropType } from "vue";
import MenuSection from "../menu-section/MenuSection.vue";
import type { MenuKey, MenuSelectionMode } from "../menu/context";
export default defineComponent({
name: "DropdownSection",
inheritAttrs: false,
props: {
selectionMode: {
type: String as PropType<MenuSelectionMode>,
default: undefined,
},
selectedKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: undefined,
},
defaultSelectedKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: () => [],
},
disabledKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: () => [],
},
disallowEmptySelection: { type: Boolean, default: false },
},
emits: {
"update:selectedKeys": (_keys: MenuKey[]) => true,
selectionChange: (_keys: MenuKey[]) => true,
},
setup(props, { attrs, slots, emit }) {
return () =>
h(
MenuSection as never,
{
...props,
...attrs,
onUpdateSelectedKeys: (keys: MenuKey[]) =>
emit("update:selectedKeys", keys),
onSelectionChange: (keys: MenuKey[]) => emit("selectionChange", keys),
},
slots,
);
},
});
</script>
@@ -0,0 +1,12 @@
<script lang="ts">
import { defineComponent, h } from "vue";
import MenuItemSubmenuIndicator from "../menu-item/MenuItemSubmenuIndicator.vue";
export default defineComponent({
name: "DropdownSubmenuIndicator",
inheritAttrs: false,
setup(_, { attrs, slots }) {
return () => h(MenuItemSubmenuIndicator as never, attrs, slots);
},
});
</script>
@@ -0,0 +1,397 @@
<script lang="ts">
import {
Fragment,
cloneVNode,
defineComponent,
h,
inject,
isVNode,
nextTick,
onMounted,
provide,
ref,
useAttrs,
useId,
watch,
type PropType,
type Ref,
type VNodeChild,
} from "vue";
import {
DropdownMenuPortal as RekaDropdownMenuPortal,
DropdownMenuSub as RekaDropdownMenuSub,
DropdownMenuSubContent as RekaDropdownMenuSubContent,
DropdownMenuSubTrigger as RekaDropdownMenuSubTrigger,
} from "reka-ui";
import { dropdownVariants } from "@heroui-vue/styles";
import {
dropdownContextKey,
menuContentAttrsKey,
submenuContentKey,
submenuOpenKey,
} from "../menu/context";
import { useOverlayAnimation } from "../overlay/animation";
import { resolvePlacement, type OverlayPlacement } from "../overlay/placement";
import { useConfig } from "../../providers/context";
import { elementFromValue, menuSurfaceFromVNode } from "./dom";
import DropdownPopover from "./DropdownPopover.vue";
/** Panel props that are translated instead of spread onto the element. */
const CONTROL_PROPS = new Set([
"placement",
"offset",
"crossOffset",
"shouldFlip",
"containerPadding",
"side",
"align",
"sideOffset",
"alignOffset",
"avoidCollisions",
"collisionPadding",
"loop",
"to",
"isKeyboardDismissDisabled",
"shouldCloseOnInteractOutside",
"class",
"onKeydown",
"onInteractOutside",
]);
type Handler =
((event: Event) => void) | ((event: Event) => void)[] | undefined;
function flatten(nodes: VNodeChild[], out: VNodeChild[] = []): VNodeChild[] {
for (const n of nodes) {
if (Array.isArray(n)) flatten(n, out);
else out.push(n);
}
return out;
}
function asArray(handler: Handler): Array<(event: Event) => void> {
if (!handler) return [];
return Array.isArray(handler) ? handler : [handler];
}
/** Attributes a nested `<DropdownPopover>` may pass to the submenu surface. */
function inheritedProps(props: Record<string, unknown> | null) {
const out: Record<string, unknown> = {};
if (!props) return out;
for (const [key, value] of Object.entries(props)) {
if (key === "ref" || key === "key") continue;
if (
key === "class" ||
key === "style" ||
key === "id" ||
key === "role" ||
key.startsWith("data-") ||
key.startsWith("aria-") ||
/^on[A-Z]/.test(key) ||
CONTROL_PROPS.has(key)
)
out[key] = value;
}
return out;
}
/**
* Submenu trigger: first child is the trigger item (asChild, single menuitem
* DOM), remaining children render inside Reka SubContent. Each level keeps its
* own open state, and Escape closes only the level that owns focus before the
* dismiss handler can reach the root menu.
*/
export default defineComponent({
name: "DropdownSubmenuTrigger",
inheritAttrs: false,
setup(_, { slots }) {
const attrs = useAttrs();
const dropdownCtx = inject(dropdownContextKey, null);
const config = useConfig();
provide(submenuContentKey, true);
const subOpen = ref(false);
const triggerRef = ref<unknown>(null);
const contentElement = ref<HTMLElement | null>(null);
const fallbackId = useId();
const contentAttrs = {
label: ref<string | undefined>(),
labelledBy: ref<string | undefined>(),
describedBy: ref<string | undefined>(),
loop: ref<boolean | undefined>(),
autoFocus: ref<boolean | undefined>(),
escapeKeyBehavior: ref<"clearSelection" | "none">("none"),
clearSelection: () => {},
};
provide(menuContentAttrsKey, contentAttrs);
provide(submenuOpenKey, subOpen);
const { entering, exiting, onAnimationEnd } = useOverlayAnimation(
subOpen as Ref<boolean>,
contentElement,
true,
);
// Panel configuration for the current render; event handlers read it later.
const panelConfig: {
dismissDisabled: boolean;
shouldCloseOutside?: (event: Event) => boolean;
} = { dismissDisabled: false };
// Accessible-name decision for the current render; the repair pass reads it.
const panelAria: { label?: string; labelledBy?: string } = {};
/**
* Reka labels the submenu surface with the id it generates for its own
* trigger, but our trigger item keeps an instance id, so that reference
* dangles. Priority: explicit aria-label (wins over any id reference) >
* caller/Menu `aria-labelledby` > this instance's trigger element.
*/
function repairLabel() {
const content = contentElement.value;
if (!content) return;
if (panelAria.label) {
content.removeAttribute("aria-labelledby");
return;
}
if (panelAria.labelledBy) {
content.setAttribute("aria-labelledby", panelAria.labelledBy);
return;
}
const trigger = elementFromValue(triggerRef.value);
if (!trigger) return;
if (!trigger.id) trigger.id = fallbackId;
content.setAttribute("aria-labelledby", trigger.id);
}
watch(
contentElement,
(element) => {
if (element) void nextTick(repairLabel);
},
{ flush: "post" },
);
onMounted(repairLabel as () => void);
function handleEscape(event: KeyboardEvent) {
if (event.defaultPrevented) return;
if (event.key !== "Escape") return;
if (panelConfig.dismissDisabled) {
// Keep this level, the parent menu and any modal open.
event.preventDefault();
event.stopPropagation();
return;
}
if (contentAttrs.escapeKeyBehavior.value === "clearSelection") {
event.preventDefault();
contentAttrs.clearSelection();
return;
}
if (!subOpen.value) return;
const target = event.target as HTMLElement | null;
// Only the menu level that owns the focused element closes.
if (!target?.closest?.("[role='menu']")) return;
// Stop the window Escape listeners used by Reka's dismissable layer so
// the parent menu stays open, then close this level ourselves. Focus is
// restored to the submenu trigger, matching one-layer-at-a-time close.
event.preventDefault();
event.stopPropagation();
subOpen.value = false;
elementFromValue(triggerRef.value)?.focus();
}
function handleInteractOutside(event: {
defaultPrevented?: boolean;
preventDefault?: () => void;
}) {
if (event.defaultPrevented) return;
if (panelConfig.shouldCloseOutside?.(event as unknown as Event) === false)
event.preventDefault?.();
}
return () => {
const children = flatten(slots.default?.() ?? []);
const triggerVNode = children[0] ?? null;
const contentVNodes = children.slice(1);
const popoverVNode = contentVNodes.find(
(node) => isVNode(node) && node.type === DropdownPopover,
);
const popoverProps = inheritedProps(
isVNode(popoverVNode)
? (popoverVNode.props as Record<string, unknown> | null)
: null,
);
const domProps: Record<string, unknown> = {};
for (const [key, value] of Object.entries(popoverProps)) {
if (!CONTROL_PROPS.has(key)) domProps[key] = value;
}
const placement = (popoverProps.placement as OverlayPlacement) ?? "end";
const position = resolvePlacement(placement, config?.dir.value ?? "ltr");
panelConfig.dismissDisabled =
(popoverProps.isKeyboardDismissDisabled as boolean | undefined) ??
false;
panelConfig.shouldCloseOutside =
popoverProps.shouldCloseOnInteractOutside as
((event: Event) => boolean) | undefined;
// Reka fixes the submenu side/align to the parent convention, so only
// the offsets/collision props can be forwarded.
const panelProps: Record<string, unknown> = {
sideOffset:
(popoverProps.sideOffset as number | undefined) ??
(popoverProps.offset as number | undefined),
alignOffset:
(popoverProps.alignOffset as number | undefined) ??
(popoverProps.crossOffset as number | undefined),
avoidCollisions:
(popoverProps.avoidCollisions as boolean | undefined) ??
(popoverProps.shouldFlip as boolean | undefined),
collisionPadding:
(popoverProps.collisionPadding as number | undefined) ??
(popoverProps.containerPadding as number | undefined),
// Always a boolean: an undefined -> true transition is dropped by the
// base prop chain, so the menu-level policy would never apply.
loop:
(popoverProps.loop as boolean | undefined) ??
contentAttrs.loop.value ??
false,
};
const side = (popoverProps.side as string | undefined) ?? position.side;
const align =
(popoverProps.align as string | undefined) ?? position.align;
const keydownChain = [
...asArray(popoverProps.onKeydown as Handler),
...asArray(attrs.onKeydown as Handler),
handleEscape,
];
const interactChain = [
...asArray(popoverProps.onInteractOutside as Handler),
handleInteractOutside as (event: Event) => void,
];
const focusChain = [
...asArray(popoverProps.onOpenAutoFocus as Handler),
(event: Event) => {
if (event.defaultPrevented) return;
if (contentAttrs.autoFocus.value === false) event.preventDefault();
},
];
const animationChain = [
...asArray(popoverProps.onAnimationend as Handler),
onAnimationEnd as (event: Event) => void,
];
// Explicit caller values win over the Menu content channel; a label
// always beats an id reference so it cannot be shadowed silently.
const callerLabel = popoverProps["aria-label"] as string | undefined;
const callerLabelledBy = popoverProps["aria-labelledby"] as
string | undefined;
const callerDescribedBy = popoverProps["aria-describedby"] as
string | undefined;
const effectiveLabel = callerLabel ?? contentAttrs.label.value;
const effectiveLabelledBy =
callerLabelledBy ?? contentAttrs.labelledBy.value;
const describedBy = callerDescribedBy ?? contentAttrs.describedBy.value;
panelAria.label = effectiveLabel;
panelAria.labelledBy = effectiveLabelledBy;
const ariaProps: Record<string, unknown> = {};
if (effectiveLabel) {
ariaProps["aria-label"] = effectiveLabel;
// An id reference would win over the explicit label; drop it.
ariaProps["aria-labelledby"] = undefined;
} else if (effectiveLabelledBy) {
ariaProps["aria-labelledby"] = effectiveLabelledBy;
}
if (describedBy) ariaProps["aria-describedby"] = describedBy;
return h(
RekaDropdownMenuSub as never,
{
open: subOpen.value,
"onUpdate:open": (value: boolean) => {
subOpen.value = value;
},
},
{
default: () => [
// asChild: the Item itself is the single menuitem; no nested menuitem.
h(
RekaDropdownMenuSubTrigger as never,
{
asChild: true,
"data-slot": "dropdown-submenu-trigger",
},
{
default: () =>
triggerVNode
? cloneVNode(triggerVNode as never, {
...attrs,
ref: triggerRef as never,
// The item is a submenu trigger regardless of whether
// the caller renders an indicator.
hasSubmenu: true,
// Escape with focus on the trigger (pointer-opened
// submenu) must also close only this level.
onKeydown: handleEscape,
})
: null,
},
),
h(
RekaDropdownMenuPortal as never,
{ to: popoverProps.to as string | HTMLElement | undefined },
{
default: () =>
h(
RekaDropdownMenuSubContent as never,
{
...domProps,
...panelProps,
side,
align,
...ariaProps,
class: [
dropdownCtx?.slots.value.popover(),
popoverProps.class,
],
"data-slot": "dropdown-popover",
"data-submenu-content": "true",
"data-entering": entering.value || undefined,
"data-exiting": exiting.value || undefined,
onKeydown: keydownChain,
onInteractOutside: interactChain,
onAnimationend: animationChain,
onOpenAutoFocus: focusChain,
onVnodeMounted: (vnode) => {
contentElement.value = menuSurfaceFromVNode(vnode);
void nextTick(repairLabel);
},
onVnodeUpdated: (vnode) => {
const element = menuSurfaceFromVNode(vnode);
if (!element) return;
contentElement.value = element;
void nextTick(repairLabel);
},
onVnodeUnmounted: () => {
contentElement.value = null;
},
},
{
default: () =>
h(
Fragment,
null,
// Nested DropdownPopover is a style shell inside SubContent.
contentVNodes as never,
),
},
),
},
),
],
},
);
};
},
});
</script>
@@ -0,0 +1,196 @@
<script lang="ts">
import {
defineComponent,
h,
inject,
nextTick,
onBeforeUnmount,
onMounted,
ref,
useAttrs,
} from "vue";
import { DropdownMenuTrigger as RekaDropdownMenuTrigger } from "reka-ui";
import { dropdownContextKey } from "../menu/context";
import { elementFromValue } from "./dom";
const LONG_PRESS_MOVE_PX = 10;
const SELECTION_KEYS = new Set(["Enter", " ", "Spacebar"]);
type Handler =
| ((event: KeyboardEvent) => void)
| ((event: KeyboardEvent) => void)
| undefined;
/**
* Trigger. In `longPress` mode this component owns the press lifecycle and
* cancels Reka's own click/keydown activation through its documented
* `event.defaultPrevented` guard, so the real trigger element decides when the
* menu opens instead of a late bubble interception.
*/
export default defineComponent({
name: "DropdownTrigger",
inheritAttrs: false,
props: {
as: { type: String, default: undefined },
asChild: { type: Boolean, default: undefined },
},
setup(props, { slots }) {
const attrs = useAttrs();
const dropdownCtx = inject(dropdownContextKey, null);
const triggerRef = ref<unknown>(null);
const isLongPress = () =>
(dropdownCtx?.triggerMode.value ?? "press") === "longPress";
let timer: ReturnType<typeof setTimeout> | null = null;
let startX = 0;
let startY = 0;
function clearPress() {
if (timer) {
clearTimeout(timer);
timer = null;
}
}
function onPointerdown(event: PointerEvent) {
if (event.isPrimary === false) return;
if (event.pointerType === "mouse" && event.button !== 0) return;
clearPress();
startX = event.clientX;
startY = event.clientY;
timer = setTimeout(() => {
timer = null;
dropdownCtx?.setOpen(true);
}, dropdownCtx?.longPressDuration.value ?? 500);
}
function onPointermove(event: PointerEvent) {
if (!timer) return;
if (
Math.hypot(event.clientX - startX, event.clientY - startY) <=
LONG_PRESS_MOVE_PX
)
return;
clearPress();
}
function onActivation(event: MouseEvent | KeyboardEvent) {
if (!isLongPress()) return;
// Short press never opens; after a long press the closing click/keyup
// must not toggle the menu back. Cancelling here also stops Reka's own
// trigger handler for this event.
event.preventDefault();
}
/**
* Long-press keyboard activation. The base trigger toggles on keydown, so
* for Enter/Space the caller's own keydown handlers run first (on the
* capture phase of the trigger region, with native Vue array semantics),
* then this component either cancels or opens exactly once while the base
* trigger's toggle is suspended — a cancelled keydown never opens the menu.
*/
function suspendBaseToggle() {
const ctx = dropdownCtx;
if (!ctx) return;
ctx.suppressOpenRequests.value = true;
setTimeout(() => {
ctx.suppressOpenRequests.value = false;
}, 0);
}
function decideKeydown(event: KeyboardEvent) {
if (!isLongPress()) return;
if (!SELECTION_KEYS.has(event.key)) return;
if (event.defaultPrevented) return;
event.preventDefault();
const ctx = dropdownCtx;
// Open first, then suspend: the base trigger toggles later in the same
// event and must not undo this decision.
ctx?.setOpen(!(ctx.open.value ?? false));
suspendBaseToggle();
}
function keydownChain() {
if (!isLongPress()) return undefined;
const user = (attrs as { onKeydown?: Handler }).onKeydown;
const userHandlers = Array.isArray(user) ? user : user ? [user] : [];
return [...userHandlers, decideKeydown];
}
/**
* Upstream's `Dropdown.Trigger` is a real `<button>`, so a custom trigger
* (e.g. an Avatar) stays keyboard operable. With `asChild` the element is
* whatever the caller supplied, so restore button semantics when it is not
* natively focusable.
*/
function ensureFocusable() {
const el = elementFromValue(triggerRef.value);
if (!el) return;
const tag = el.tagName;
const role = el.getAttribute("role");
if (
tag === "BUTTON" ||
(tag === "A" && el.hasAttribute("href")) ||
el.hasAttribute("tabindex") ||
role === "button" ||
role === "link" ||
role === "menuitem"
)
return;
if (!role) el.setAttribute("role", "button");
el.setAttribute("tabindex", "0");
}
onMounted(() => void nextTick(ensureFocusable));
onBeforeUnmount(clearPress);
const guardHandlers = {
onPointerdownCapture: onPointerdown,
onPointermoveCapture: onPointermove,
onPointerupCapture: clearPress,
onPointercancelCapture: clearPress,
onPointerleaveCapture: clearPress,
onClickCapture: onActivation,
onKeydownCapture: keydownChain(),
onContextmenuCapture: clearPress,
};
return () => {
const longPress = isLongPress();
const triggerAttrs: Record<string, unknown> = { ...attrs };
if (longPress) delete triggerAttrs.onKeydown;
const trigger = h(
RekaDropdownMenuTrigger as never,
{
...triggerAttrs,
ref: triggerRef,
as: props.as,
asChild: props.asChild ?? true,
class: dropdownCtx?.slots.value.trigger({
class: attrs.class as never,
}),
"data-slot": "dropdown-trigger",
},
{
default: () =>
slots.default?.({
isOpen: dropdownCtx?.open.value ?? false,
}),
},
);
if (!longPress) return trigger;
return h(
"span",
{
...guardHandlers,
style: "display: contents",
"data-slot": "dropdown-trigger-region",
},
[trigger],
);
};
},
});
</script>
@@ -0,0 +1,36 @@
import type { VNode } from "vue";
/** Resolve a component/ref handle to its DOM element. */
export function elementFromValue(value: unknown): HTMLElement | null {
if (value instanceof Element) return value as HTMLElement;
const el = (value as { $el?: unknown } | null)?.$el;
return el instanceof Element ? (el as HTMLElement) : null;
}
/**
* Resolve the element a vnode mounted to. Reka's content components expose the
* positioned element through `$el`; fragments (text nodes) resolve to null.
*/
export function elementFromVNode(
vnode: VNode | null | undefined,
): HTMLElement | null {
if (!vnode) return null;
const el = vnode.el;
if (el instanceof Element) return el as HTMLElement;
const proxyEl = (vnode.component?.proxy as { $el?: unknown } | null)?.$el;
return proxyEl instanceof Element ? (proxyEl as HTMLElement) : null;
}
/**
* Reka renders a positioning wrapper around the menu surface; the popover
* styles and animations live on the inner `[data-reka-menu-content]` node.
*/
export function menuSurfaceFromVNode(
vnode: VNode | null | undefined,
): HTMLElement | null {
const el = elementFromVNode(vnode);
if (!el) return null;
if (el.matches("[data-reka-menu-content]")) return el;
const inner = el.querySelector("[data-reka-menu-content]");
return inner instanceof Element ? (inner as HTMLElement) : el;
}
@@ -0,0 +1,24 @@
<script setup lang="ts">
import { useAttrs } from "vue";
import { errorMessageVariants } from "@heroui-vue/styles";
import { useFieldPart } from "../field/useFieldPart";
defineOptions({ name: "ErrorMessage", inheritAttrs: false });
// The `slot` attribute mirrors the fixed baseline's RAC Text slot. In Vue it is
// a plain DOM attribute (a CSS hook), not a slot assignment.
const attrs = useAttrs();
const { id } = useFieldPart("error", attrs);
</script>
<template>
<p
v-bind="attrs"
:id="id"
:class="errorMessageVariants()"
slot="errorMessage"
data-slot="error-message"
>
<slot />
</p>
</template>
@@ -1,6 +1,15 @@
<script lang="ts">
import { defineComponent, h, useAttrs } from "vue";
import {
defineComponent,
h,
inject,
onUnmounted,
useAttrs,
useId,
watch,
} from "vue";
import { headerVariants } from "@heroui-vue/styles";
import { menuSectionLabelKey } from "../menu/context";
/**
* Collection / group section heading (RAC Header).
@@ -19,12 +28,33 @@ export default defineComponent({
},
setup(props, { slots }) {
const attrs = useAttrs();
// Inside a MenuSection the header names the group (upstream wires this
// through the collection); elsewhere it stays a plain heading element.
const section = inject(menuSectionLabelKey, null);
const autoId = useId();
let unregister: (() => void) | undefined;
const resolveId = () =>
(attrs.id as string | undefined) || (section ? autoId : undefined);
watch(
resolveId,
(id, prev) => {
if (!section || !id || id === prev) return;
unregister?.();
unregister = section.registerLabel(id);
},
{ immediate: true },
);
onUnmounted(() => {
unregister?.();
unregister = undefined;
});
function render() {
return h(
props.as,
{
...attrs,
id: resolveId(),
class: [headerVariants(), attrs.class],
"data-slot": "header",
},
+178 -36
View File
@@ -11,6 +11,7 @@ import {
provide,
ref,
useAttrs,
watchEffect,
} from "vue";
import { useVirtualList } from "@vueuse/core";
import { listboxVariants } from "@heroui-vue/styles";
@@ -84,6 +85,10 @@ const disabled = useInheritedDisabled(
);
provide(disabledContextKey, disabled);
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
// Optional owner-driven view: filtering and virtual focus stay off unless the
// composite asks for them, so standalone ListBox and Select are unchanged.
const virtualFocus = computed(() => !!owner?.virtualFocus?.());
const ownerFilter = computed(() => owner?.filter);
const registry = useCollectionRegistry<ListBoxMember>();
const mounted = ref(false);
let disconnectOwner: (() => void) | undefined;
@@ -92,6 +97,8 @@ onMounted(() => {
if (owner)
disconnectOwner = owner.connect({
items: known,
optionId,
reveal,
focus: async (edge) => {
const available = eligible();
const key =
@@ -144,7 +151,36 @@ const known = () => {
}))
);
};
const eligible = () => known().filter((item) => !item.disabled);
/** Full data set with the owner filter applied: display and navigation only. */
const visibleKnown = () => {
const filter = ownerFilter.value;
const items = known();
return filter ? items.filter((item) => filter(item)) : items;
};
const visibleKeys = computed(
() => new Set(visibleKnown().map((item) => item.key)),
);
const eligible = () => visibleKnown().filter((item) => !item.disabled);
/** Empty channel needs a settled collection: static children register on mount. */
const visibleIsEmpty = computed(
() => visibleKeys.value.size === 0 && (!!props.items || mounted.value),
);
// A removed, disabled or filtered-out row cannot stay active. The collection
// clears the shared active key (it never invents a value) and leaves the next
// candidate to the composite; a closed collection has no active row at all.
watchEffect(() => {
if (!virtualFocus.value || !mounted.value) return;
const activeRef = owner?.activeKey;
if (!activeRef || activeRef.value === undefined) return;
const key = activeRef.value;
void visibleKeys.value;
if (
owner?.isOpen?.() === false ||
!eligible().some((item) => item.key === key)
)
activeRef.value = undefined;
});
const blockedKeys = computed(() =>
known()
.filter((item) => item.disabled)
@@ -170,8 +206,10 @@ const selection = useCollectionSelection({
const focused = ref<ListBoxKey>();
const lastFocused = ref<ListBoxKey>();
const pressed = ref<ListBoxKey>();
const keyboard = ref(true);
// Pointer presses clear keyboard intent; the composite sets it again on keys.
const keyboard = owner?.keyboardIntent ?? ref(true);
const active = computed(() => {
if (virtualFocus.value && owner?.activeKey) return owner.activeKey.value;
if (!mounted.value) return undefined;
const items = eligible();
return (
@@ -181,7 +219,18 @@ const active = computed(() => {
items[0]?.key
);
});
const source = computed(() => (props.items ? [...props.items] : []));
/**
* Items as the caller passed them, restricted to the visible subset. The full
* data set stays available through `known()` for text and accepted values.
*/
const visibleItems = computed(() => {
const items = props.items ? [...props.items] : [];
const filter = ownerFilter.value;
if (!items.length || !filter) return items;
const visible = visibleKeys.value;
return items.filter((item) => visible.has(item.id));
});
const source = computed(() => visibleItems.value);
// VueUse owns measurement, scroll range and cleanup; one logical collection
// remains available for select-all/typeahead even while most rows are unmounted.
const {
@@ -207,6 +256,85 @@ onBeforeUnmount(() => {
disposing = true;
focusRequest++;
});
/** Mounted DOM id of an option; undefined while a virtualized row is unmounted. */
function optionId(key: ListBoxKey): string | undefined {
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
return element?.id || undefined;
}
const nextFrame = (): Promise<void> =>
typeof requestAnimationFrame === "function"
? new Promise((resolve) => requestAnimationFrame(() => resolve()))
: nextTick();
/** A virtualized row mounts after the window moves; wait for real DOM, bounded. */
async function waitForMountedRow(key: ListBoxKey, valid: () => boolean) {
for (let attempt = 0; attempt < 3; attempt++) {
if (!valid()) return;
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
if (element?.isConnected) return;
await nextFrame();
}
}
/**
* Bring a row into view without taking DOM focus. Virtualized lists move the
* window by index; ordinary lists scroll the mounted row (the row itself may
* sit inside any scroll container supplied by the caller).
*/
async function revealRow(key: ListBoxKey, valid: () => boolean) {
// Every side effect is guarded: filtering, closing, unmounting or a newer
// request invalidates the work that is still awaiting.
if (!valid()) return;
if (props.virtualized) {
const index = source.value.findIndex((item) => item.id === key);
if (index < 0 || !valid()) return;
const rowTop = index * props.rowHeight;
const element = root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
) {
if (!valid()) return;
scrollTo(index);
}
await waitForMountedRow(key, valid);
return;
}
await nextTick();
if (!valid()) return;
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
if (!valid() || !element?.isConnected) return;
element.scrollIntoView?.({ block: "nearest" });
}
let revealRequest = 0;
/**
* A request stays valid only while it is the newest one, the row is still
* visible/enabled, the collection is open and the component is alive.
*/
function revealToken(key: ListBoxKey) {
const request = ++revealRequest;
return () =>
!disposing &&
request === revealRequest &&
!disabled.value &&
owner?.isOpen?.() !== false &&
eligible().some((item) => item.key === key);
}
/** Reveal a row without taking DOM focus (virtual focus / activedescendant). */
async function reveal(key: ListBoxKey) {
const valid = revealToken(key);
if (!valid()) return;
lastFocused.value = key;
await revealRow(key, valid);
}
async function focus(key: ListBoxKey) {
if (
disposing ||
@@ -216,18 +344,18 @@ async function focus(key: ListBoxKey) {
return;
const request = ++focusRequest;
lastFocused.value = key;
if (props.virtualized) {
const index = source.value.findIndex((item) => item.id === key);
const rowTop = index * props.rowHeight;
const element = root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
)
scrollTo(index);
if (virtualFocus.value) {
const valid = revealToken(key);
if (!valid()) return;
if (owner?.activeKey && owner.activeKey.value !== key)
owner.activeKey.value = key;
await revealRow(key, valid);
return;
}
await nextTick();
await revealRow(
key,
() => !disposing && !disabled.value && request === focusRequest,
);
if (disposing || request !== focusRequest || disabled.value) return;
const element = registry
.available()
@@ -274,6 +402,7 @@ let search = "",
let pendingSpace: ListBoxKey | undefined;
function keydown(event: KeyboardEvent) {
if (
virtualFocus.value ||
event.defaultPrevented ||
event.isComposing ||
event.keyCode === 229 ||
@@ -406,6 +535,7 @@ function keydown(event: KeyboardEvent) {
}
}
function keyup(event: KeyboardEvent) {
if (virtualFocus.value) return;
if (event.key !== " ") return;
const key = pendingSpace;
pendingSpace = undefined;
@@ -442,14 +572,18 @@ provide(listBoxKey, {
activate,
focus,
virtualized: () => props.virtualized,
virtual: () => virtualFocus.value,
visible: (key) => visibleKeys.value.has(key),
optionId,
restoreFocus,
position: (key) =>
props.virtualized && data.value
? {
index: data.value.findIndex((item) => item.key === key) + 1,
size: data.value.length,
}
: undefined,
position: (key) => {
if (!props.virtualized || !data.value) return undefined;
const items = visibleItems.value;
return {
index: items.findIndex((item) => item.id === key) + 1,
size: items.length,
};
},
});
function rootAttrs() {
if (mode.value === "single" && selection.keys.value.length > 1)
@@ -483,6 +617,7 @@ function rootAttrs() {
"aria-multiselectable":
mode.value === "none" ? undefined : mode.value === "multiple",
tabindex:
virtualFocus.value ||
disabled.value ||
(mounted.value &&
registry.available().some((member) => member.key() === active.value))
@@ -523,25 +658,32 @@ defineExpose({
<template>
<component :is="as" ref="root" v-bind="rootAttrs()">
<slot v-if="!items" :item="undefined!" :index="-1" />
<slot v-else-if="!items.length" name="empty" />
<div
v-else-if="virtualized"
v-bind="wrapperProps"
role="presentation"
data-slot="list-box-virtual-content"
>
<template v-if="!items">
<!-- Static slots keep every member mounted (so text and selection
survive filtering); the empty channel is additive. -->
<slot v-if="visibleIsEmpty" name="empty" />
<slot :item="undefined!" :index="-1" />
</template>
<template v-else>
<slot v-if="!visibleItems.length" name="empty" />
<div
v-for="entry in windowItems"
:key="entry.data.id"
v-if="virtualized"
v-bind="wrapperProps"
role="presentation"
:style="{ height: `${rowHeight}px` }"
data-slot="list-box-virtual-content"
>
<slot :item="entry.data" :index="entry.index" />
<div
v-for="entry in windowItems"
:key="entry.data.id"
role="presentation"
:style="{ height: `${rowHeight}px` }"
>
<slot :item="entry.data" :index="entry.index" />
</div>
</div>
</div>
<template v-else v-for="(item, index) in items" :key="item.id">
<slot :item="item" :index="index" />
<template v-else v-for="(item, index) in items" :key="item.id">
<slot :item="item" :index="index" />
</template>
</template>
</component>
</template>
@@ -73,10 +73,16 @@ export default defineComponent({
const state = () => ({
isSelected: context.selected(props.id),
isDisabled: disabled.value,
isFocused: context.focused.value === props.id,
isFocusVisible:
context.focused.value === props.id &&
(context.keyboard.value || !!element.value?.matches(":focus-visible")),
// Under virtual focus the DOM focus stays in the composite's input, so the
// active key is what marks the row as focused.
isFocused: context.virtual()
? context.active.value === props.id
: context.focused.value === props.id,
isFocusVisible: context.virtual()
? context.keyboard.value && context.active.value === props.id
: context.focused.value === props.id &&
(context.keyboard.value ||
!!element.value?.matches(":focus-visible")),
isPressed:
(pressed.value || context.pressed.value === props.id) &&
!disabled.value,
@@ -133,9 +139,38 @@ export default defineComponent({
else context.restoreFocus();
}
});
/**
* Nested controls own their own press, focus and click. `[contenteditable]`
* matches the attribute alone so "", "true" and "plaintext-only" all count;
* explicit "false" opts out.
*/
const NESTED_INTERACTIVE =
'button, a[href], input, select, textarea, summary, [role="button"], ' +
'[role="link"], [role="menuitem"], [role="checkbox"], [role="radio"], ' +
'[role="switch"], [role="tab"], [role="option"], ' +
'[contenteditable]:not([contenteditable="false"])';
function nestedInteractive(target: EventTarget | null) {
const hit = (target as Element | null)?.closest?.(NESTED_INTERACTIVE);
return hit && hit !== element.value ? hit : undefined;
}
/**
* Native presses move focus to the pressed element (or body for a
* non-focusable row). Under virtual focus the composite's input must keep
* focus, so the default focus transfer is cancelled here — but only for a
* plain row press: nested controls keep their own focus behaviour and a
* caller that already cancelled is respected.
*/
function keepInputFocus(event: MouseEvent | PointerEvent) {
if (!context.virtual() || event.defaultPrevented) return;
if (event instanceof MouseEvent && event.button !== 0) return;
if (nestedInteractive(event.target)) return;
event.preventDefault();
}
function click(event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || disabled.value || context.readOnly.value)
return;
// A click that bubbled out of a nested control belongs to that control.
if (nestedInteractive(event.target)) return;
const select = new CustomEvent("select", {
cancelable: true,
detail: { key: props.id, originalEvent: event },
@@ -149,6 +184,11 @@ export default defineComponent({
return () => {
const current = state();
const position = context.position(props.id);
const visible = context.visible(props.id);
// Never emit an undefined-valued key over the caller's attribute:
// mergeProps removes the earlier key when a later value is undefined.
const hideFiltered =
!visible && (attrs as Record<string, unknown>).hidden === undefined;
const children = text.prepare(slots.default?.(current) ?? [], true);
return h(
props.as,
@@ -160,7 +200,11 @@ export default defineComponent({
variant: props.variant,
}).item(),
tabindex:
!disabled.value && context.active.value === props.id ? 0 : -1,
!disabled.value &&
!context.virtual() &&
context.active.value === props.id
? 0
: -1,
"aria-selected":
context.mode.value === "none" ? undefined : current.isSelected,
"aria-disabled": disabled.value || undefined,
@@ -174,6 +218,11 @@ export default defineComponent({
text.describedBy(),
),
"data-slot": "list-box-item",
// Filtered rows stay mounted and are hidden, not removed, so their
// text and accepted selection survive. `hidden` is only added when the
// caller did not set it; the stylesheet also hides data-filtered.
...(hideFiltered ? { hidden: true } : {}),
"data-filtered": visible ? undefined : true,
"data-disabled": disabled.value || undefined,
"data-selected": current.isSelected || undefined,
"data-focused": current.isFocused || undefined,
@@ -196,13 +245,23 @@ export default defineComponent({
hovered.value = false;
},
onPointerdown: (event: PointerEvent) => {
// The caller's cancellation must be read before our focus guard
// calls preventDefault, otherwise every row would look cancelled.
const cancelled = event.defaultPrevented;
keepInputFocus(event);
if (
!event.defaultPrevented &&
!cancelled &&
!disabled.value &&
event.button === 0
event.button === 0 &&
!nestedInteractive(event.target)
)
pressed.value = true;
},
onMousedown: (event: MouseEvent) => {
// Chromium transfers focus on mousedown even when pointerdown was
// cancelled, so the same rule is applied to both events.
keepInputFocus(event);
},
}),
children,
);
@@ -56,6 +56,11 @@ export interface ListBoxContext {
activate: (key: ListBoxKey, event: MouseEvent | KeyboardEvent) => void;
focus: (key: ListBoxKey) => Promise<void>;
virtualized: () => boolean;
/** Keep DOM focus outside the collection; only the active key moves. */
virtual: () => boolean;
/** Whether the owner filter currently shows this record. */
visible: (key: ListBoxKey) => boolean;
optionId: (key: ListBoxKey) => string | undefined;
restoreFocus: () => void;
position: (key: ListBoxKey) => { index: number; size: number } | undefined;
}
@@ -0,0 +1,283 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
inject,
onMounted,
onUnmounted,
provide,
ref,
useAttrs,
useId,
type PropType,
} from "vue";
import { DropdownMenuItem as RekaMenuItem } from "reka-ui";
import { menuItemVariants, type MenuItemVariants } from "@heroui-vue/styles";
import {
menuContextKey,
menuItemContextKey,
menuSectionContextKey,
type MenuKey,
} from "../menu/context";
type NativeClickHandler =
((e: MouseEvent) => void) | ((e: MouseEvent) => void)[] | undefined;
type NativeHandler<Ev> = ((e: Ev) => void) | ((e: Ev) => void)[] | undefined;
const LINK_ATTRS = [
"href",
"target",
"rel",
"download",
"hrefLang",
"referrerPolicy",
] as const;
export default defineComponent({
name: "MenuItem",
inheritAttrs: false,
props: {
/** Business key used by selection and actions. Never becomes a DOM id. */
id: { type: [String, Number] as PropType<MenuKey>, default: undefined },
textValue: { type: String, default: undefined },
isDisabled: { type: Boolean, default: false },
disabled: { type: Boolean, default: undefined },
variant: {
type: String as PropType<MenuItemVariants["variant"]>,
default: "default",
},
/** Explicit close policy for this item (official `shouldCloseOnSelect`). */
closeOnSelect: { type: Boolean, default: undefined },
/**
* Render this item as a submenu trigger. `DropdownSubmenuTrigger` sets it
* so the item no longer depends on a rendered indicator to know it has a
* submenu (upstream derives it from the collection structure).
*/
hasSubmenu: { type: Boolean, default: undefined },
/** Render a link menu item instead of a button-like item. */
href: { type: String, default: undefined },
target: { type: String, default: undefined },
rel: { type: String, default: undefined },
download: {
type: [String, Boolean] as PropType<string | boolean>,
default: undefined,
},
hrefLang: { type: String, default: undefined },
referrerPolicy: { type: String, default: undefined },
},
emits: {
select: (_key: MenuKey) => true,
},
setup(props, { slots, emit }) {
const attrs = useAttrs();
const menuCtx = inject(menuContextKey, null);
const sectionCtx = inject(menuSectionContextKey, null);
const owner = sectionCtx?.selection ?? menuCtx?.selection;
const indicatorSubmenu = ref(false);
const isFocused = ref(false);
const isHovered = ref(false);
const isPressed = ref(false);
const domId = useId();
const key = computed<MenuKey>(
() => props.id ?? (attrs.id as MenuKey | undefined) ?? "",
);
const hasSubmenu = computed(
() => props.hasSubmenu ?? indicatorSubmenu.value,
);
const isDisabled = computed(
() =>
props.isDisabled ||
props.disabled === true ||
(owner?.isItemDisabled(key.value) ?? false),
);
const isSelected = computed(
() => owner?.isItemSelected(key.value) ?? false,
);
const selectionMode = computed(() => owner?.selectionMode.value ?? "none");
const slotsComputed = computed(() =>
menuItemVariants({ variant: props.variant as never }),
);
const role = computed(() => {
if (selectionMode.value === "multiple") return "menuitemcheckbox";
if (selectionMode.value === "single") return "menuitemradio";
return "menuitem";
});
const linkProps = computed(() => {
if (!props.href) return null;
const out: Record<string, unknown> = { as: "a", href: props.href };
for (const name of LINK_ATTRS) {
if (name === "href") continue;
if (props[name] !== undefined) out[name] = props[name];
}
return out;
});
provide(menuItemContextKey, {
slots: slotsComputed,
isDisabled,
isSelected,
isFocused,
isPressed,
hasSubmenu,
setHasSubmenu(value: boolean) {
indicatorSubmenu.value = value;
},
});
let unregister: (() => void) | undefined;
onMounted(() => {
unregister = menuCtx?.registerItem();
});
onUnmounted(() => {
unregister?.();
unregister = undefined;
});
function shouldClose() {
// Priority: item policy -> menu policy -> per-mode default.
if (props.closeOnSelect !== undefined) return props.closeOnSelect;
const menuPolicy = menuCtx?.shouldCloseOnSelect.value;
if (typeof menuPolicy === "function") return menuPolicy(key.value);
if (typeof menuPolicy === "boolean") return menuPolicy;
// Default: action and radio items close, checkboxes stay open.
return selectionMode.value !== "multiple";
}
function activate() {
if (isDisabled.value) return;
emit("select", key.value);
if (hasSubmenu.value) return;
const mode = selectionMode.value;
if (mode !== "none") {
owner?.proposeSelection(key.value);
if (shouldClose()) menuCtx?.closeLevel();
return;
}
menuCtx?.emitAction(key.value);
if (shouldClose()) menuCtx?.closeLevel();
}
/** Keep the caller's own handler(s) in front of the internal tracker. */
function withOwn<Ev extends Event>(
name: string,
own: (event: Ev) => void,
): NativeHandler<Ev> {
const user = (attrs as Record<string, NativeHandler<Ev>>)[name];
if (!user) return own;
return Array.isArray(user) ? [...user, own] : [user, own];
}
return () => {
// Hand the user handlers and our activation to Vue as one DOM `onClick`
// array so browser/Vue listener semantics stay intact: capture order,
// preventDefault and stopImmediatePropagation all behave natively, and a
// cancelled event never reaches the activation entry. Reka's own
// `handleSelect` is prepended by its prop merge and is neutralised in
// `onSelect`, so it cannot emit an action or close the menu.
const userOnClick = (attrs as { onClick?: NativeClickHandler }).onClick;
const rest: Record<string, unknown> = {
...(attrs as Record<string, unknown>),
};
for (const name of [
"onClick",
"onFocus",
"onBlur",
"onPointerDown",
"onPointerUp",
"onPointerCancel",
"onPointerEnter",
"onPointerLeave",
]) {
delete rest[name];
}
const clickChain: Array<(e: MouseEvent) => void> = (
Array.isArray(userOnClick)
? [...userOnClick]
: userOnClick
? [userOnClick]
: []
) as Array<(e: MouseEvent) => void>;
clickChain.push((event: MouseEvent) => {
if (event.defaultPrevented) return;
if (isDisabled.value) {
// A disabled link must not navigate either.
event.preventDefault();
return;
}
activate();
});
const roleAttr = (attrs.role as string | undefined) ?? role.value;
return h(
RekaMenuItem as never,
{
...rest,
...linkProps.value,
id: domId,
class: slotsComputed.value.item({ class: attrs.class as never }),
role: roleAttr,
"aria-checked":
selectionMode.value === "none"
? undefined
: isSelected.value
? "true"
: "false",
"aria-disabled": isDisabled.value || undefined,
"data-slot": "menu-item",
"data-selected": isSelected.value || undefined,
// RAC's render-state hooks that the ported CSS and the official
// custom-styles demo rely on.
"data-focused": isFocused.value || undefined,
"data-hovered": isHovered.value || undefined,
"data-pressed": isPressed.value || undefined,
"data-has-submenu": hasSubmenu.value || undefined,
"data-selection-mode": selectionMode.value,
"data-key": String(key.value),
disabled: isDisabled.value,
textValue: props.textValue,
onClick: clickChain,
onFocus: withOwn<FocusEvent>("onFocus", () => {
isFocused.value = true;
}),
onBlur: withOwn<FocusEvent>("onBlur", () => {
isFocused.value = false;
isPressed.value = false;
}),
onPointerDown: withOwn<PointerEvent>("onPointerDown", () => {
isPressed.value = true;
}),
onPointerUp: withOwn<PointerEvent>("onPointerUp", () => {
isPressed.value = false;
}),
onPointerCancel: withOwn<PointerEvent>("onPointerCancel", () => {
isPressed.value = false;
}),
onPointerEnter: withOwn<PointerEvent>("onPointerEnter", () => {
isHovered.value = true;
}),
onPointerLeave: withOwn<PointerEvent>("onPointerLeave", () => {
isHovered.value = false;
isPressed.value = false;
}),
onSelect: (itemSelectEvent?: { preventDefault?: () => void }) => {
itemSelectEvent?.preventDefault?.();
},
},
{
default: () =>
slots.default?.({
isSelected: isSelected.value,
isFocused: isFocused.value,
isDisabled: isDisabled.value,
isPressed: isPressed.value,
}),
},
);
};
},
});
</script>
@@ -0,0 +1,90 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs, type PropType } from "vue";
import { menuItemContextKey } from "../menu/context";
function CheckmarkIcon(selected: boolean) {
return h(
"svg",
{
"aria-hidden": "true",
"data-slot": "menu-item-indicator--checkmark",
fill: "none",
role: "presentation",
stroke: "currentColor",
"stroke-dasharray": 22,
"stroke-dashoffset": selected ? 44 : 66,
"stroke-linecap": "round",
"stroke-linejoin": "round",
"stroke-width": 2,
viewBox: "0 0 17 18",
},
[h("polyline", { points: "1 9 7 14 15 4" })],
);
}
function DotIcon() {
return h(
"svg",
{
"aria-hidden": "true",
"data-slot": "menu-item-indicator--dot",
fill: "currentColor",
"fill-rule": "evenodd",
role: "presentation",
viewBox: "0 0 16 16",
xmlns: "http://www.w3.org/2000/svg",
},
[
h("path", {
"clip-rule": "evenodd",
d: "M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14",
"fill-rule": "evenodd",
}),
],
);
}
export default defineComponent({
name: "MenuItemIndicator",
inheritAttrs: false,
props: {
as: { type: String, default: "span" },
type: {
type: String as PropType<"checkmark" | "dot">,
default: "checkmark",
},
},
setup(props, { slots }) {
const attrs = useAttrs();
const item = inject(menuItemContextKey, null);
return () => {
const state = {
isSelected: item?.isSelected.value ?? false,
// Menu items have no indeterminate state; kept for the upstream
// render-prop contract.
isIndeterminate: false,
isFocused: item?.isFocused.value ?? false,
isDisabled: item?.isDisabled.value ?? false,
isPressed: item?.isPressed.value ?? false,
};
const content = slots.default
? slots.default(state)
: props.type === "dot"
? DotIcon()
: CheckmarkIcon(state.isSelected);
return h(
props.as,
{
...attrs,
"aria-hidden": "true",
class: item?.slots.value.indicator({ class: attrs.class as never }),
"data-slot": "menu-item-indicator",
"data-type": props.type,
"data-visible": state.isSelected || undefined,
},
content,
);
};
},
});
</script>
@@ -0,0 +1,65 @@
<script lang="ts">
import {
defineComponent,
h,
inject,
onMounted,
onUnmounted,
useAttrs,
} from "vue";
import { menuItemContextKey } from "../menu/context";
/** Ported from HeroUI `IconChevronRight` (icons.tsx) so the default
* submenu affordance keeps the baseline artwork without adding an icon
* dependency to the component package. */
function ChevronIcon() {
return h(
"svg",
{
"aria-hidden": "true",
fill: "none",
height: "16",
role: "presentation",
viewBox: "0 0 16 16",
width: "16",
xmlns: "http://www.w3.org/2000/svg",
},
[
h("path", {
"clip-rule": "evenodd",
d: "M5.47 2.97a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1 0 1.06l-4.5 4.5a.75.75 0 1 1-1.06-1.06L9.44 8 5.47 4.03a.75.75 0 0 1 0-1.06Z",
fill: "currentColor",
"fill-rule": "evenodd",
}),
],
);
}
export default defineComponent({
name: "MenuItemSubmenuIndicator",
inheritAttrs: false,
props: { as: { type: String, default: "span" } },
setup(props, { slots }) {
const attrs = useAttrs();
const item = inject(menuItemContextKey, null);
item?.setHasSubmenu(true);
onMounted(() => item?.setHasSubmenu(true));
onUnmounted(() => item?.setHasSubmenu(false));
return () => {
if (!item?.hasSubmenu.value) return null;
return h(
props.as,
{
...attrs,
"aria-hidden": "true",
class: item.slots.value.submenuIndicator({
class: attrs.class as never,
}),
"data-slot": "submenu-indicator",
},
slots.default ? slots.default() : ChevronIcon(),
);
};
},
});
</script>
@@ -0,0 +1,153 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
inject,
provide,
ref,
useAttrs,
watch,
type PropType,
} from "vue";
import { DropdownMenuGroup as RekaMenuGroup } from "reka-ui";
import { menuSectionVariants } from "@heroui-vue/styles";
import {
menuContextKey,
menuSectionContextKey,
menuSectionLabelKey,
type MenuKey,
type MenuSelectionMode,
} from "../menu/context";
import { useMenuSelection } from "../menu/useMenuSelection";
export default defineComponent({
name: "MenuSection",
inheritAttrs: false,
props: {
/** Section-level selection mode. Omit to inherit the menu's selection. */
selectionMode: {
type: String as PropType<MenuSelectionMode>,
default: undefined,
},
selectedKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: undefined,
},
defaultSelectedKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: () => [],
},
disabledKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: () => [],
},
/** Clear the last selection when the user deselects it. */
disallowEmptySelection: { type: Boolean, default: false },
},
emits: {
"update:selectedKeys": (_keys: MenuKey[]) => true,
selectionChange: (_keys: MenuKey[]) => true,
},
setup(props, { slots, emit }) {
const attrs = useAttrs();
const menuCtx = inject(menuContextKey, null);
const ownsSelection = computed(
() =>
props.selectionMode !== undefined || props.selectedKeys !== undefined,
);
const internal = ref<MenuKey[]>([...(props.defaultSelectedKeys ?? [])]);
const isControlled = computed(() => props.selectedKeys !== undefined);
const acceptedKeys = computed(() =>
isControlled.value ? (props.selectedKeys ?? []) : internal.value,
);
const effectiveMode = computed<MenuSelectionMode>(
() => props.selectionMode ?? menuCtx?.selectionMode.value ?? "none",
);
const sectionSelection = useMenuSelection({
selectionMode: effectiveMode,
selectedKeys: acceptedKeys,
disabledKeys: computed(() => props.disabledKeys ?? []),
disallowEmptySelection: computed(() => props.disallowEmptySelection),
onSelectionChange(next) {
if (!isControlled.value) internal.value = next;
emit("update:selectedKeys", next);
emit("selectionChange", next);
},
});
watch(
() => props.selectedKeys,
(next) => {
if (next) internal.value = [...next];
},
);
// A nested Header registers here so the group keeps an accessible name.
const labelIds = ref<string[]>([]);
provide(menuSectionLabelKey, {
labelledBy: computed(() =>
labelIds.value.length ? labelIds.value.join(" ") : undefined,
),
registerLabel(id: string) {
if (!labelIds.value.includes(id))
labelIds.value = [...labelIds.value, id];
return () => {
labelIds.value = labelIds.value.filter((item) => item !== id);
};
},
});
provide(menuSectionContextKey, {
selection: {
get selectionMode() {
return ownsSelection.value
? sectionSelection.selectionMode
: (menuCtx?.selection.selectionMode ??
sectionSelection.selectionMode);
},
get selectedKeys() {
return ownsSelection.value
? sectionSelection.selectedKeys
: (menuCtx?.selection.selectedKeys ??
sectionSelection.selectedKeys);
},
proposeSelection: (key: MenuKey) =>
(ownsSelection.value
? sectionSelection
: (menuCtx?.selection ?? sectionSelection)
).proposeSelection(key),
isItemSelected: (key: MenuKey) =>
(ownsSelection.value
? sectionSelection
: (menuCtx?.selection ?? sectionSelection)
).isItemSelected(key),
// Disabled keys are additive: the section list never overrides the
// menu list, whichever side owns the selection.
isItemDisabled: (key: MenuKey) =>
(props.disabledKeys ?? []).some((item) => item === key) ||
(menuCtx?.selection.isItemDisabled(key) ?? false),
},
});
return () => {
const labelledBy =
(attrs["aria-labelledby"] as string | undefined) ??
(labelIds.value.length ? labelIds.value.join(" ") : undefined);
return h(
RekaMenuGroup as never,
{
...attrs,
class: menuSectionVariants({ class: attrs.class as never }),
"aria-labelledby": labelledBy,
"data-slot": "menu-section",
role: (attrs.role as string | undefined) ?? "group",
},
slots,
);
};
},
});
</script>
+256
View File
@@ -0,0 +1,256 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
inject,
provide,
ref,
useAttrs,
watch,
watchEffect,
type PropType,
} from "vue";
import {
DropdownMenuContent as RekaDropdownMenuContent,
DropdownMenuPortal as RekaDropdownMenuPortal,
DropdownMenuRoot as RekaDropdownMenuRoot,
injectDropdownMenuRootContext,
} from "reka-ui";
import { dropdownVariants, menuVariants } from "@heroui-vue/styles";
import {
dropdownContextKey,
menuCloseKey,
menuContentAttrsKey,
menuContextKey,
menuSectionContextKey,
submenuOpenKey,
type MenuKey,
type MenuSelectionMode,
} from "./context";
import { useMenuSelection } from "./useMenuSelection";
/**
* Menu list: selection/action context + menu styles.
* Standalone use renders the same list without a modal overlay; inside
* DropdownPopover the surrounding Reka content is reused.
*/
export default defineComponent({
name: "Menu",
inheritAttrs: false,
props: {
selectionMode: {
type: String as PropType<MenuSelectionMode>,
default: "none",
},
selectedKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: undefined,
},
defaultSelectedKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: () => [],
},
disabledKeys: {
type: Array as PropType<ReadonlyArray<MenuKey>>,
default: () => [],
},
/** Clear the last selection when the user deselects it. */
disallowEmptySelection: { type: Boolean, default: false },
/** Wrap keyboard focus at the ends (official `shouldFocusWrap`). */
shouldFocusWrap: { type: Boolean, default: undefined },
/** Focus the menu when it opens (official `autoFocus`). */
autoFocus: { type: Boolean, default: true },
/** Escape clears the selection instead of closing (official name). */
escapeKeyBehavior: {
type: String as PropType<"clearSelection" | "none">,
default: "none",
},
/** Menu-level close policy for activation (official prop name). */
shouldCloseOnSelect: {
type: [Boolean, Function] as PropType<
boolean | ((key: MenuKey) => boolean)
>,
default: undefined,
},
},
emits: {
"update:selectedKeys": (_keys: MenuKey[]) => true,
selectionChange: (_keys: MenuKey[]) => true,
action: (_key: MenuKey) => true,
/** Fired when this menu level closes (official `onClose`). */
close: () => true,
},
setup(props, { slots, emit }) {
const attrs = useAttrs();
const dropdownCtx = inject(dropdownContextKey, null);
const outerClose = inject(menuCloseKey, null);
// Outside a Dropdown surface the Menu owns its content, so it provides the
// channel itself and keeps the name/description on the real menu node.
const liveContentAttrs = inject(menuContentAttrsKey, null) ?? {
label: ref<string | undefined>(),
labelledBy: ref<string | undefined>(),
describedBy: ref<string | undefined>(),
loop: ref<boolean | undefined>(),
autoFocus: ref<boolean | undefined>(),
escapeKeyBehavior: ref<"clearSelection" | "none">("none"),
clearSelection: () => {},
};
provide(menuContentAttrsKey, liveContentAttrs);
const contentAttrs = liveContentAttrs;
const outerMenuRoot = injectDropdownMenuRootContext(null);
// Standalone Menu (no DropdownRoot/Popover) still supports items.
const needsOwnRoot = computed(() => !outerMenuRoot);
const internal = ref<MenuKey[]>([...(props.defaultSelectedKeys ?? [])]);
const isControlled = computed(() => props.selectedKeys !== undefined);
const acceptedKeys = computed(() =>
isControlled.value ? (props.selectedKeys ?? []) : internal.value,
);
const selection = useMenuSelection({
selectionMode: computed(() => props.selectionMode),
selectedKeys: acceptedKeys,
disabledKeys: computed(() => props.disabledKeys ?? []),
disallowEmptySelection: computed(() => props.disallowEmptySelection),
onSelectionChange(next) {
if (!isControlled.value) internal.value = next;
emit("update:selectedKeys", next);
emit("selectionChange", next);
},
});
watch(
() => props.selectedKeys,
(next) => {
if (next) internal.value = [...next];
},
);
function clearSelection() {
if (props.disallowEmptySelection) return;
if (acceptedKeys.value.length === 0) return;
if (!isControlled.value) internal.value = [];
emit("update:selectedKeys", []);
emit("selectionChange", []);
}
// Label/description/focus attributes for the surrounding surface.
watchEffect(() => {
if (!contentAttrs) return;
contentAttrs.loop.value = props.shouldFocusWrap;
contentAttrs.autoFocus.value = props.autoFocus;
contentAttrs.escapeKeyBehavior.value = props.escapeKeyBehavior;
});
if (contentAttrs) contentAttrs.clearSelection = clearSelection;
// `close` fires when this menu level leaves the open state, whatever the
// cause (item activation, Escape, outside interaction).
const submenuOpen = inject(submenuOpenKey, null);
const levelOpen = submenuOpen ?? dropdownCtx?.open ?? null;
if (levelOpen)
watch(levelOpen, (value, previous) => {
if (previous && !value) emit("close");
});
const itemCount = ref(0);
provide(menuContextKey, {
closeLevel: () => {
if (outerClose) outerClose();
else outerMenuRoot?.onOpenChange(false);
},
emitAction: (key: MenuKey) => emit("action", key),
selection,
selectionMode: computed(() => props.selectionMode),
// Unset stays undefined: the item resolves the per-mode default so an
// explicit policy is never pre-empted by a guessed boolean.
shouldCloseOnSelect: computed(() => props.shouldCloseOnSelect),
itemCount,
registerItem: () => {
itemCount.value += 1;
return () => {
itemCount.value = Math.max(0, itemCount.value - 1);
};
},
});
// A Menu opened inside a MenuSection owns its own scope; without this a
// nested list would keep the outer section's selection owner.
provide(menuSectionContextKey, null);
// The accessible name belongs on the real `role="menu"` node, which lives
// on the surrounding content element rather than on this list.
watchEffect(() => {
if (!contentAttrs) return;
contentAttrs.label.value = attrs["aria-label"] as string | undefined;
contentAttrs.labelledBy.value = attrs["aria-labelledby"] as
string | undefined;
contentAttrs.describedBy.value = attrs["aria-describedby"] as
string | undefined;
});
function listProps() {
const userRole = attrs.role as string | undefined;
const rest: Record<string, unknown> = { ...attrs };
for (const key of [
"role",
"aria-label",
"aria-labelledby",
"aria-describedby",
])
delete rest[key];
return {
...rest,
...(userRole ? { role: userRole } : {}),
class: menuVariants({
class: [dropdownCtx?.slots.value.menu(), attrs.class],
}),
"data-selection-mode": props.selectionMode,
"data-slot": dropdownCtx ? "dropdown-menu" : "menu",
};
}
const listNode = () =>
h("div", listProps(), [
slots.default?.(),
itemCount.value === 0 ? slots.empty?.() : undefined,
]);
return () => {
if (!needsOwnRoot.value) return listNode();
// Standalone Menu: keep the base menu semantics and keyboard model, but
// without modal behaviour (no scroll lock, no outside pointer blocking)
// and without stealing focus.
return h(
RekaDropdownMenuRoot as never,
{ open: true, modal: false },
{
default: () =>
h(
RekaDropdownMenuPortal as never,
{ disabled: true },
{
default: () =>
h(
RekaDropdownMenuContent as never,
{
class: dropdownVariants().popover(),
"data-slot": "dropdown-popover",
sideOffset: 0,
avoidCollisions: false,
"aria-label": contentAttrs.label.value,
"aria-labelledby": contentAttrs.labelledBy.value,
"aria-describedby": contentAttrs.describedBy.value,
"data-static": "true",
// A static in-flow list never steals focus from the page.
onOpenAutoFocus: (event: Event) => event.preventDefault(),
},
{ default: listNode },
),
},
),
},
);
};
},
});
</script>
+119
View File
@@ -0,0 +1,119 @@
import type { ComputedRef, InjectionKey, Ref } from "vue";
export type MenuKey = string | number;
export type MenuSelectionMode = "none" | "single" | "multiple";
export interface MenuSelectionOwner {
selectionMode: ComputedRef<MenuSelectionMode>;
selectedKeys: ComputedRef<ReadonlyArray<MenuKey>>;
/** Submit a selection proposal. Parent decides accepted value. */
proposeSelection: (key: MenuKey) => void;
isItemSelected: (key: MenuKey) => boolean;
isItemDisabled: (key: MenuKey) => boolean;
}
export interface MenuContextValue {
/** Close the nearest menu level (not parent menus). */
closeLevel: () => void;
/** Fire the menu-level action callback. */
emitAction: (key: MenuKey) => void;
/** Selection owner (menu-level); section may override. */
selection: MenuSelectionOwner;
/** Root selection mode for data-selection-mode styling. */
selectionMode: ComputedRef<MenuSelectionMode>;
/**
* Menu-level close policy for activation (official `shouldCloseOnSelect`).
* Undefined means "no explicit policy"; the item then applies the per-mode
* default.
*/
shouldCloseOnSelect: ComputedRef<
boolean | ((key: MenuKey) => boolean) | undefined
>;
/** Number of mounted items, used for the empty-state slot. */
itemCount: Ref<number>;
registerItem: () => () => void;
}
export const menuContextKey: InjectionKey<MenuContextValue> = Symbol("hv-menu");
export interface MenuSectionContextValue {
selection: MenuSelectionOwner;
}
/** `null` resets the owner so a nested Menu does not inherit a section. */
export const menuSectionContextKey: InjectionKey<MenuSectionContextValue | null> =
Symbol("hv-menu-section");
/** MenuSection exposes this so a nested Header can name the group. */
export interface MenuSectionLabelValue {
labelledBy: ComputedRef<string | undefined>;
registerLabel: (id: string) => () => void;
}
export const menuSectionLabelKey: InjectionKey<MenuSectionLabelValue> = Symbol(
"hv-menu-section-label",
);
/** Label/description attributes that belong on the real `role="menu"` node. */
export interface MenuContentAttrsValue {
label: Ref<string | undefined>;
labelledBy: Ref<string | undefined>;
describedBy: Ref<string | undefined>;
/** Focus wrap while navigating with the keyboard (official `shouldFocusWrap`). */
loop: Ref<boolean | undefined>;
/** Focus the menu when it opens (official `autoFocus`). */
autoFocus: Ref<boolean | undefined>;
/** Escape behaviour of the owning menu (official `escapeKeyBehavior`). */
escapeKeyBehavior: Ref<"clearSelection" | "none">;
/** Clear the selection for the owning menu (no-op when disallowed). */
clearSelection: () => void;
}
export const menuContentAttrsKey: InjectionKey<MenuContentAttrsValue> = Symbol(
"hv-menu-content-attrs",
);
export interface MenuItemContextValue {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
slots: ComputedRef<any>;
isDisabled: ComputedRef<boolean>;
isSelected: ComputedRef<boolean>;
isFocused: Ref<boolean>;
isPressed: Ref<boolean>;
hasSubmenu: ComputedRef<boolean>;
setHasSubmenu: (value: boolean) => void;
}
export const menuItemContextKey: InjectionKey<MenuItemContextValue> =
Symbol("hv-menu-item");
/** Provided by DropdownPopover / submenu content to close this menu level. */
export const menuCloseKey: InjectionKey<() => void> = Symbol("hv-menu-close");
/** Open state of the enclosing submenu level, when any. */
export const submenuOpenKey: InjectionKey<Ref<boolean>> = Symbol(
"hv-dropdown-submenu-open",
);
/** True when a DropdownPopover nests inside DropdownSubmenuTrigger. */
export const submenuContentKey: InjectionKey<boolean> = Symbol(
"hv-dropdown-submenu-content",
);
export interface DropdownTriggerModeValue {
triggerMode: ComputedRef<"press" | "longPress">;
longPressDuration: ComputedRef<number>;
open: ComputedRef<boolean>;
setOpen: (value: boolean) => void;
/** While true, open requests coming from the base trigger are ignored. */
suppressOpenRequests: Ref<boolean>;
}
export interface DropdownContextValue extends DropdownTriggerModeValue {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
slots: ComputedRef<any>;
}
export const dropdownContextKey: InjectionKey<DropdownContextValue> =
Symbol("hv-dropdown");
@@ -0,0 +1,55 @@
import { computed, type ComputedRef, type Ref } from "vue";
import type {
MenuKey,
MenuSelectionMode,
MenuSelectionOwner,
} from "../menu/context";
export interface UseMenuSelectionOptions {
selectionMode: Ref<MenuSelectionMode> | ComputedRef<MenuSelectionMode>;
selectedKeys:
Ref<ReadonlyArray<MenuKey>> | ComputedRef<ReadonlyArray<MenuKey>>;
disabledKeys?:
Ref<ReadonlyArray<MenuKey>> | ComputedRef<ReadonlyArray<MenuKey>>;
/** Keep the last selected key when the user tries to clear it. */
disallowEmptySelection?: Ref<boolean> | ComputedRef<boolean>;
/** Accepted-value update. Return the accepted keys (may reject the proposal). */
onSelectionChange: (keys: MenuKey[]) => void;
}
/**
* Menu/section selection owner. Proposals are one-shot toggles; the parent
* emits the next keys and keeps ownership of the accepted value.
*/
export function useMenuSelection(
options: UseMenuSelectionOptions,
): MenuSelectionOwner {
const isItemSelected = (key: MenuKey) =>
options.selectedKeys.value.some((k) => k === key);
const isItemDisabled = (key: MenuKey) =>
options.disabledKeys?.value.some((k) => k === key) ?? false;
const proposeSelection = (key: MenuKey) => {
const mode = options.selectionMode.value;
if (mode === "none") return;
const current = options.selectedKeys.value;
const has = isItemSelected(key);
if (mode === "single") {
if (has && options.disallowEmptySelection?.value) return;
options.onSelectionChange(has ? [] : [key]);
return;
}
const next = has ? current.filter((k) => k !== key) : [...current, key];
if (has && next.length === 0 && options.disallowEmptySelection?.value)
return;
options.onSelectionChange(next);
};
return {
selectionMode: computed(() => options.selectionMode.value),
selectedKeys: computed(() => options.selectedKeys.value),
proposeSelection,
isItemSelected,
isItemDisabled,
};
}
+308
View File
@@ -0,0 +1,308 @@
<script lang="ts">
import {
Fragment,
cloneVNode,
computed,
defineComponent,
h,
isVNode,
mergeProps,
onBeforeUnmount,
provide,
ref,
watchEffect,
watch,
type PropType,
type Component,
type Slots,
type SlotsType,
type VNodeArrayChildren,
type VNode,
type VNodeChild,
} from "vue";
import { Primitive } from "reka-ui";
import {
useTagGroup,
tagKey,
type TagKey,
type TagRenderState,
} from "./context";
import TagRemoveButton from "./TagRemoveButton.vue";
import { elementFromRef } from "./dom";
function isRemoveButton(node: VNode): boolean {
const type = node.type as { name?: string; __name?: string };
return (type?.name ?? type?.__name) === "TagRemoveButton";
}
/** RAC `pickChildren`: the custom remove button is re-rendered last. */
function pickRemoveButton(nodes: VNodeChild[]): [VNodeChild[], VNode[]] {
const rest: VNodeChild[] = [];
const removed: VNode[] = [];
const walk = (children: VNodeChild[]) => {
for (const node of children) {
if (!isVNode(node)) {
rest.push(node);
continue;
}
if (isRemoveButton(node)) {
removed.push(node);
continue;
}
if (node.type === Fragment && Array.isArray(node.children)) {
walk(node.children as VNodeChild[]);
continue;
}
rest.push(node);
}
};
walk(nodes);
return [rest, removed];
}
/** Baseline derives `textValue` from the first string child. */
function firstText(nodes: VNodeChild[], depth = 0): string | undefined {
for (const node of nodes) {
if (typeof node === "string" && node.trim()) return node.trim();
if (typeof node === "number") return String(node);
if (!isVNode(node) || depth > 3) continue;
const children = node.children;
if (typeof children === "string" && children.trim()) return children.trim();
if (typeof children === "number") return String(children);
if (Array.isArray(children)) {
const found = firstText(children as VNodeChild[], depth + 1);
if (found) return found;
}
}
return undefined;
}
export default defineComponent({
name: "Tag",
inheritAttrs: false,
slots: Object as SlotsType<{
default: (state: TagRenderState) => VNodeChild[];
}>,
props: {
/** Collection identity, distinct from the generated DOM id. */
id: { type: [String, Number] as PropType<TagKey>, required: true },
textValue: { type: String, default: undefined },
isDisabled: { type: Boolean, default: false },
as: { type: String, default: "div" },
asChild: { type: Boolean, default: false },
},
setup(props, { attrs, slots, expose }) {
const group = useTagGroup();
const root = ref<unknown>();
const element = () => elementFromRef(root.value);
const hovered = ref(false);
const pressed = ref(false);
const focused = ref(false);
const focusVisible = ref(false);
// Rendered text is read through a plain variable so nothing writes reactive
// state during render.
let latestText = "";
const disabled = computed(
() => props.isDisabled || group.isDisabledKey(props.id),
);
const textValue = () => props.textValue ?? latestText;
const state = (): TagRenderState => ({
isSelected: group.mode.value !== "none" && group.selected(props.id),
isDisabled: disabled.value,
isHovered: hovered.value && !disabled.value,
isPressed:
(pressed.value || group.pressed.value === props.id) && !disabled.value,
isFocused: group.focused.value === props.id,
isFocusVisible:
group.focused.value === props.id &&
(group.keyboard.value || !!element()?.matches(":focus-visible")),
allowsRemoving: group.allowsRemoving(),
});
provide(tagKey, {
tagSlots: group.tagSlots,
textValue,
disabled,
});
const unregister = group.register({
key: () => props.id,
element,
textValue,
disabled: () => disabled.value,
noteBlur: () => {
pressed.value = false;
},
});
onBeforeUnmount(unregister);
// A press released outside the row must not leave the visual state stuck.
watchEffect((cleanup) => {
const node = element();
if (!pressed.value || !node) return;
const owner = node.ownerDocument;
const release = () => {
pressed.value = false;
if (group.pressed.value === props.id) group.pressed.value = undefined;
};
owner.addEventListener("pointerup", release, true);
owner.addEventListener("pointercancel", release, true);
cleanup(() => {
owner.removeEventListener("pointerup", release, true);
owner.removeEventListener("pointercancel", release, true);
});
});
watch(disabled, (value) => {
if (value) {
pressed.value = false;
hovered.value = false;
if (group.pressed.value === props.id) group.pressed.value = undefined;
}
});
expose({ element, focus: () => group.focus(props.id) });
function click(event: MouseEvent) {
if (event.defaultPrevented || disabled.value) return;
const target = event.target as Element | null;
const owner = element();
const removeButton = target?.closest?.('[data-slot="tag-remove-button"]');
if (removeButton && owner?.contains(removeButton)) {
group.requestRemoval(props.id);
return;
}
const interactive = target?.closest?.(
'button, a, input, select, textarea, [role="button"], [role="checkbox"], [role="switch"]',
);
if (interactive && interactive !== owner) return;
group.activate(props.id, event);
void group.focus(props.id);
}
return () => {
const current = state();
const rendered = slots.default?.(current) ?? [];
const raw = (
Array.isArray(rendered) ? rendered : [rendered]
) as VNodeChild[];
const [content, custom] = pickRemoveButton(raw);
const label = props.textValue ?? firstText(content) ?? "";
latestText = label;
const removable = current.allowsRemoving
? [
...content,
...(custom.length
? custom.map((node: VNode) =>
cloneVNode(node, {
textValue: node.props?.textValue ?? label,
}),
)
: [h(TagRemoveButton, { textValue: label })]),
]
: content;
const restAttrs: Record<string, unknown> = {};
for (const [key, value] of Object.entries(attrs)) {
if (key === "class" || key === "style") continue;
restAttrs[key] = value;
}
const cell = (children: VNodeChild[]) =>
h(
"span",
{ role: "gridcell", style: { display: "contents" } },
children,
);
let rowChildren: VNodeChild[] = [cell(removable)];
if (props.asChild) {
// Keep the caller's actual row root, then insert its semantic cell.
const child =
content.length === 1 && isVNode(content[0]) ? content[0] : undefined;
if (!child)
throw new Error("Tag asChild requires one element or component.");
const buttons = current.allowsRemoving
? removable.slice(content.length)
: [];
if (typeof child.type === "string") {
const children = Array.isArray(child.children)
? (child.children as VNodeChild[])
: [child.children as VNodeChild];
rowChildren = [
h(child.type, child.props, [cell([...children, ...buttons])]),
];
} else {
const childSlots = child.children as Slots | null;
rowChildren = [
h(child.type as Component, child.props, {
...childSlots,
default: (...args: unknown[]) => [
cell([...(childSlots?.default?.(...args) ?? []), ...buttons]),
],
}),
];
}
// Preserve the caller's normalized ref owner when rebuilding children.
const row = rowChildren[0];
if (isVNode(row)) row.ref = child.ref;
}
return h(
Primitive,
mergeProps({ as: props.as, asChild: props.asChild }, restAttrs, {
ref: root,
style: attrs.style,
role: "row",
class: [group.tagSlots.value.base(), attrs.class],
"data-slot": "tag",
"data-allows-removing": current.allowsRemoving || undefined,
"data-disabled": disabled.value || undefined,
"data-selected":
(group.mode.value !== "none" && current.isSelected) || undefined,
"data-focused": current.isFocused || undefined,
"data-focus-visible": current.isFocusVisible || undefined,
"data-hovered": current.isHovered || undefined,
"data-pressed": current.isPressed || undefined,
"aria-selected":
group.mode.value === "none" ? undefined : current.isSelected,
"aria-disabled": disabled.value || undefined,
tabindex: !disabled.value && group.active.value === props.id ? 0 : -1,
onClick: click,
onFocus: () => {
focused.value = true;
focusVisible.value = !!element()?.matches(":focus-visible");
if (!disabled.value) group.noteFocus(props.id);
},
onBlur: (event: FocusEvent) => {
if (element()?.contains(event.relatedTarget as Node | null)) return;
focused.value = false;
focusVisible.value = false;
pressed.value = false;
if (group.focused.value === props.id)
group.focused.value = undefined;
if (group.pressed.value === props.id)
group.pressed.value = undefined;
},
onPointerenter: () => {
hovered.value = true;
},
onPointerleave: () => {
hovered.value = false;
pressed.value = false;
},
onPointerdown: (event: PointerEvent) => {
if (event.defaultPrevented || disabled.value || event.button !== 0)
return;
group.keyboard.value = false;
pressed.value = true;
group.pressed.value = props.id;
},
onPointerup: () => {
pressed.value = false;
if (group.pressed.value === props.id)
group.pressed.value = undefined;
},
}),
{ default: () => rowChildren as VNodeArrayChildren },
);
};
},
});
</script>
@@ -0,0 +1,541 @@
<script lang="ts">
import {
Fragment,
cloneVNode,
computed,
defineComponent,
getCurrentInstance,
h,
isVNode,
createVNode,
mergeProps,
nextTick,
onBeforeUnmount,
onBeforeUpdate,
onMounted,
provide,
ref,
shallowRef,
useId,
watch,
type VNodeChild,
} from "vue";
import { Primitive } from "reka-ui";
import { tagGroupVariants, tagVariants } from "@heroui-vue/styles";
import { useConfig } from "../../providers/context";
import { useInheritedDisabled, disabledContextKey } from "../field/disabled";
import { fieldContextKey, mergeIds, type FieldContext } from "../field/context";
import { useCollectionSelection } from "../collection/selection";
import { useCollectionRegistry } from "../collection/registry";
import {
tagGroupKey,
type TagGroupOptions,
type TagKey,
type TagMember,
} from "./context";
const NAMING_ATTRS = ["aria-label", "aria-labelledby", "aria-describedby"];
export default defineComponent({
name: "TagGroup",
inheritAttrs: false,
props: {
modelValue: { type: Array as () => readonly TagKey[], default: undefined },
selectedKeys: {
type: Array as () => readonly TagKey[],
default: undefined,
},
defaultValue: {
type: Array as () => readonly TagKey[],
default: undefined,
},
defaultSelectedKeys: {
type: Array as () => readonly TagKey[],
default: undefined,
},
selectionMode: {
type: String as () => NonNullable<TagGroupOptions["selectionMode"]>,
default: "none",
},
disabledKeys: {
type: Array as () => readonly TagKey[],
default: () => [],
},
isDisabled: { type: Boolean, default: false },
disallowEmptySelection: { type: Boolean, default: false },
size: {
type: String as () => NonNullable<TagGroupOptions["size"]>,
default: "md",
},
variant: {
type: String as () => NonNullable<TagGroupOptions["variant"]>,
default: "default",
},
dir: { type: String as () => "ltr" | "rtl", default: undefined },
as: { type: String, default: "div" },
asChild: { type: Boolean, default: false },
},
emits: {
"update:modelValue": (_keys: TagKey[]) => true,
selectionChange: (_keys: TagKey[]) => true,
remove: (_keys: TagKey[]) => true,
},
setup(props, { attrs, slots, emit, expose }) {
const instance = getCurrentInstance()!;
const present = (key: string) =>
Object.hasOwn(instance.vnode.props ?? {}, key);
const hasModel = ref(present("modelValue") || present("model-value"));
const controlled = ref(
hasModel.value || present("selectedKeys") || present("selected-keys"),
);
const removing = ref(present("onRemove"));
onBeforeUpdate(() => {
hasModel.value = present("modelValue") || present("model-value");
controlled.value =
hasModel.value || present("selectedKeys") || present("selected-keys");
removing.value = present("onRemove");
});
const config = useConfig();
const disabled = useInheritedDisabled(() => props.isDisabled);
provide(disabledContextKey, disabled);
const groupSlots = computed(() => tagGroupVariants());
const tagSlots = computed(() =>
tagVariants({ size: props.size, variant: props.variant }),
);
const dir = computed<"ltr" | "rtl">(
() =>
props.dir ??
(typeof attrs.dir === "string"
? (attrs.dir as "ltr" | "rtl")
: undefined) ??
config?.dir.value ??
"ltr",
);
const registry = useCollectionRegistry<TagMember>();
const blockedKeys = computed(() =>
registry
.ordered()
.filter((member) => member.disabled())
.map((member) => member.key()),
);
const isDisabledKey = (key: TagKey) =>
disabled.value || props.disabledKeys.includes(key);
const selection = useCollectionSelection({
mode: () => props.selectionMode,
controlled: () => controlled.value,
value: () => (hasModel.value ? props.modelValue : props.selectedKeys),
defaultValue: props.defaultValue ?? props.defaultSelectedKeys,
disabled: () => disabled.value,
readOnly: () => false,
disabledKeys: () => [...props.disabledKeys, ...blockedKeys.value],
disallowEmptySelection: () => props.disallowEmptySelection,
onChange: (keys) => {
emit("update:modelValue", [...keys]);
emit("selectionChange", [...keys]);
},
});
const labels = ref<string[]>([]);
const descriptions = ref<string[]>([]);
const errors = ref<string[]>([]);
const fieldId = `hv-tag-group-${useId()}`;
const controlId = computed(() =>
typeof attrs.id === "string" && attrs.id ? attrs.id : fieldId,
);
const field: FieldContext = {
kind: "group",
controlId,
disabled,
readOnly: computed(() => false),
required: computed(() => false),
invalid: computed(() => false),
errors: computed(() => []),
labelIds: labels,
descriptionIds: descriptions,
errorIds: errors,
};
provide(fieldContextKey, field);
// Description / ErrorMessage / Label ids are planned here so the grid can
// reference them on the first render pass, before those parts register.
const planned = shallowRef({
labels: [] as string[],
descriptions: [] as string[],
errors: [] as string[],
});
function prepare(nodes: VNodeChild[], position = ""): VNodeChild[] {
const found = {
labels: [] as string[],
descriptions: [] as string[],
errors: [] as string[],
};
const walk = (children: VNodeChild[], path: string): VNodeChild[] =>
children.map((node, index) => {
if (!isVNode(node)) return node;
const at = `${path}-${index}`;
const type = node.type as
{ name?: string; __name?: string } | undefined;
const name = type?.name ?? type?.__name;
const part =
name === "Label"
? "labels"
: name === "Description"
? "descriptions"
: name === "ErrorMessage"
? "errors"
: undefined;
if (part) {
const partId = String(node.props?.id ?? `${fieldId}-${part}-${at}`);
found[part].push(partId);
return cloneVNode(node, { id: partId });
}
if (node.type === Fragment && Array.isArray(node.children)) {
// Rebuilt children must be fully diffed: a cloned fragment keeps the
// original patch flag, which can mark them stable and skip patching.
return createVNode(
Fragment,
{ key: node.key ?? undefined },
walk(node.children as VNodeChild[], at) as VNodeChild[],
);
}
return node;
});
const result = walk(nodes, position);
if (JSON.stringify(found) !== JSON.stringify(planned.value))
planned.value = found;
return result;
}
const ariaLabel = () =>
typeof attrs["aria-label"] === "string"
? (attrs["aria-label"] as string)
: undefined;
const ariaLabelledBy = () =>
typeof attrs["aria-labelledby"] === "string"
? (attrs["aria-labelledby"] as string)
: undefined;
const ariaDescribedBy = () =>
typeof attrs["aria-describedby"] === "string"
? (attrs["aria-describedby"] as string)
: undefined;
const focused = ref<TagKey>();
const lastFocused = ref<TagKey>();
const pressed = ref<TagKey>();
const keyboard = ref(true);
const listElement = shallowRef<() => HTMLElement | undefined>();
// A plain flag: the first render must not depend on a post-mount update.
let mounted = false;
onMounted(() => {
mounted = true;
});
const eligible = () => registry.available();
const active = computed<TagKey | undefined>(() => {
const items = eligible();
return (
items.find((member) => member.key() === lastFocused.value)?.key() ??
items
.find(
(member) =>
props.selectionMode !== "none" &&
selection.selected(member.key()),
)
?.key() ??
items[0]?.key()
);
});
let focusRequest = 0;
let disposing = false;
onBeforeUnmount(() => {
disposing = true;
focusRequest++;
});
async function focus(key: TagKey) {
if (disposing || disabled.value) return;
if (!eligible().some((member) => member.key() === key)) return;
const request = ++focusRequest;
lastFocused.value = key;
await nextTick();
if (disposing || request !== focusRequest) return;
const element = registry
.available()
.find((member) => member.key() === key)
?.element();
element?.focus({ preventScroll: true });
element?.scrollIntoView?.({ block: "nearest" });
}
function restoreFocus() {
lastFocused.value = undefined;
focused.value = undefined;
listElement.value?.()?.focus({ preventScroll: true });
}
function activate(key: TagKey, event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || disabled.value) return;
const member = registry.ordered().find((entry) => entry.key() === key);
if (!member || member.disabled()) return;
if (props.selectionMode !== "none") selection.toggle(key);
void focus(key);
}
const allowsRemoving = () => removing.value && !disabled.value;
function requestRemoval(key: TagKey) {
if (
disabled.value ||
!removing.value ||
isDisabledKey(key) ||
registry
.ordered()
.find((member) => member.key() === key)
?.disabled()
)
return;
// Remember where the removal started: pressing the remove button moves
// DOM focus to that button, so the row itself was never focused.
lastFocused.value = key;
const list = listElement.value?.();
const current = list?.ownerDocument.activeElement ?? null;
if (
list &&
(list.contains(current) || current === list.ownerDocument.body)
) {
focused.value = key;
removalFocus = key;
}
lastIndex = registry
.ordered()
.findIndex((member) => member.key() === key);
pendingRemovals.set(key, textValue(key));
emit("remove", [key]);
}
let removalFocus: TagKey | undefined;
const announcement = ref("");
const pendingRemovals = new Map<TagKey, string>();
// Focus follows the removal only after the item is actually gone: a parent
// that rejects the proposal keeps both the item and the focus.
const order = computed(() =>
registry.ordered().map((member) => member.key()),
);
let lastIndex = -1;
watch(order, (next) => {
for (const [removedKey, label] of pendingRemovals) {
if (next.includes(removedKey)) continue;
pendingRemovals.delete(removedKey);
announcement.value = config?.locale.value.startsWith("zh")
? `已移除 ${label}`
: `Removed ${label}`;
}
const key = lastFocused.value;
if (key === undefined || !mounted || disposing) return;
if (next.includes(key)) return;
// Remembering the Tab entry does not grant ownership of external focus.
const list = listElement.value?.();
const current = list?.ownerDocument.activeElement ?? null;
const restoringRemoval =
removalFocus === key &&
list &&
(current === list.ownerDocument.body || list.contains(current));
removalFocus = undefined;
if (focused.value !== key && !restoringRemoval) {
lastFocused.value = undefined;
return;
}
const remaining = eligible();
if (!remaining.length) {
restoreFocus();
return;
}
const enabledKeys = new Set(remaining.map((member) => member.key()));
const index = Math.max(lastIndex, 0);
const neighbour =
next.slice(index).find((key) => enabledKeys.has(key)) ??
next
.slice(0, index)
.reverse()
.find((key) => enabledKeys.has(key));
if (neighbour !== undefined) void focus(neighbour);
});
let pendingSpace: TagKey | undefined;
function ownsKey(event: KeyboardEvent) {
const target = event.target as Element | null;
const list = listElement.value?.();
if (!target || !list || target.closest('[role="grid"]') !== list)
return false;
const interactive = target.closest(
'button, a, input, select, textarea, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="textbox"], [role="checkbox"], [role="switch"]',
);
return !interactive || interactive === list;
}
function onKeydown(event: KeyboardEvent) {
if (
event.defaultPrevented ||
!ownsKey(event) ||
event.isComposing ||
event.keyCode === 229 ||
disabled.value
)
return;
keyboard.value = true;
const items = eligible();
const index = items.findIndex((member) => member.key() === active.value);
if (items.length) {
const backward = dir.value === "rtl" ? "ArrowRight" : "ArrowLeft";
const forward = dir.value === "rtl" ? "ArrowLeft" : "ArrowRight";
let target: number | undefined;
if (event.key === "Home") target = 0;
else if (event.key === "End") target = items.length - 1;
else if (event.key === backward || event.key === "ArrowUp")
target = index - 1;
else if (event.key === forward || event.key === "ArrowDown")
target = index + 1;
if (target !== undefined) {
event.preventDefault();
const bounded = Math.max(0, Math.min(target, items.length - 1));
void focus(items[bounded].key());
return;
}
}
if (event.key === "Backspace" || event.key === "Delete") {
if (!removing.value || active.value === undefined) return;
event.preventDefault();
if (event.repeat) return;
requestRemoval(active.value);
return;
}
if (event.key === "Enter" || event.key === " ") {
if (event.repeat) {
event.preventDefault();
return;
}
if (active.value === undefined) return;
if (event.key === " ") {
event.preventDefault();
pressed.value = active.value;
pendingSpace = active.value;
return;
}
activate(active.value, event);
event.preventDefault();
}
}
function onKeyup(event: KeyboardEvent) {
if (event.key !== " ") return;
const key = pendingSpace;
pendingSpace = undefined;
pressed.value = undefined;
if (
key !== undefined &&
!event.defaultPrevented &&
ownsKey(event) &&
focused.value === key
) {
activate(key, event);
event.preventDefault();
}
}
const labelledBy = () =>
mergeIds(ariaLabelledBy(), planned.value.labels, labels.value);
const describedBy = () =>
mergeIds(
ariaDescribedBy(),
planned.value.descriptions,
descriptions.value,
planned.value.errors,
errors.value,
);
const textValue = (key: TagKey) =>
registry
.ordered()
.find((member) => member.key() === key)
?.textValue() ?? "";
provide(tagGroupKey, {
slots: groupSlots,
announcement,
tagSlots,
mode: computed(() => props.selectionMode),
disabled,
selected: (key) => selection.selected(key),
isDisabledKey,
allowsRemoving,
requestRemoval,
register: registry.register,
hasEnabled: () => eligible().length > 0,
registerList: (element) => {
listElement.value = element;
},
active,
focused,
pressed,
keyboard,
activate,
focus,
noteFocus: (key) => {
lastFocused.value = key;
focused.value = key;
lastIndex = registry
.ordered()
.findIndex((member) => member.key() === key);
},
textValue,
ariaLabel,
labelledBy,
describedBy,
onKeydown,
onKeyup,
});
watch(
disabled,
(value) => {
if (value) {
pressed.value = undefined;
pendingSpace = undefined;
}
},
{ flush: "sync" },
);
expose({
element: () => listElement.value?.(),
focus: (key?: TagKey) =>
key === undefined ? restoreFocus() : focus(key),
});
return () => {
const rest: Record<string, unknown> = {};
for (const [key, value] of Object.entries(attrs)) {
if (NAMING_ATTRS.includes(key) || key === "class" || key === "style")
continue;
rest[key] = value;
}
return h(
Primitive,
mergeProps({ as: props.as, asChild: props.asChild }, rest, {
class: [tagGroupVariants().base(), attrs.class],
style: attrs.style,
dir: dir.value,
"data-slot": "tag-group",
"data-disabled": disabled.value || undefined,
}),
{
default: () => {
const rendered = slots.default?.() ?? [];
return prepare(
(Array.isArray(rendered) ? rendered : [rendered]) as VNodeChild[],
);
},
},
);
};
},
});
</script>
@@ -0,0 +1,106 @@
<script setup lang="ts" generic="T extends TagGroupDataItem = TagGroupDataItem">
import { mergeProps, ref, useAttrs } from "vue";
import { Primitive } from "reka-ui";
import { elementFromRef } from "./dom";
import {
useTagGroup,
type TagGroupDataItem,
type TagGroupListProps,
} from "./context";
defineOptions({ name: "TagGroupList", inheritAttrs: false });
const props = withDefaults(defineProps<TagGroupListProps<T>>(), {
as: "div",
asChild: false,
});
defineSlots<{
default?: (props: { item: T; index: number }) => unknown;
empty?: () => unknown;
}>();
const attrs = useAttrs();
const group = useTagGroup();
const root = ref<unknown>();
const element = () => elementFromRef(root.value);
group.registerList(element);
function rootAttrs() {
const rest: Record<string, unknown> = {};
for (const [key, value] of Object.entries(attrs)) {
if (
key === "class" ||
key === "style" ||
key === "aria-label" ||
key === "aria-labelledby" ||
key === "aria-describedby"
)
continue;
rest[key] = value;
}
return mergeProps(rest, {
ref: root,
role: "grid",
class: [group.slots.value.list(), attrs.class],
style: attrs.style,
"data-slot": "tag-group-list",
"data-disabled": group.disabled.value || undefined,
"aria-label": attrs["aria-label"] ?? group.ariaLabel(),
"aria-labelledby":
attrs["aria-labelledby"] ??
(attrs["aria-label"] || group.ariaLabel()
? undefined
: group.labelledBy()),
"aria-describedby":
[attrs["aria-describedby"], group.describedBy()]
.filter(Boolean)
.join(" ") || undefined,
"aria-disabled": group.disabled.value || undefined,
"aria-multiselectable": group.mode.value === "multiple" ? true : undefined,
// Preserve baseline metadata; confirmed removals use the status below.
"aria-atomic": "false",
"aria-relevant": "additions text",
tabindex: group.hasEnabled() ? -1 : 0,
onKeydown: group.onKeydown,
onKeyup: group.onKeyup,
onFocusout: (event: FocusEvent) => {
if (!element()?.contains(event.relatedTarget as Node | null)) {
group.focused.value = undefined;
}
},
});
}
</script>
<template>
<Primitive v-bind="rootAttrs()" :as="props.as" :as-child="props.asChild">
<template v-if="props.items">
<template v-if="props.items.length">
<template v-for="(item, index) in props.items" :key="item.id">
<slot :item="item" :index="index" />
</template>
</template>
<div v-else role="row">
<span role="gridcell"><slot name="empty" /></span>
</div>
</template>
<slot v-else :item="undefined!" :index="-1" />
</Primitive>
<span
role="status"
aria-live="polite"
aria-atomic="true"
style="
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border: 0;
"
>
{{ group.announcement.value }}
</span>
</template>
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { computed, inject, useAttrs } from "vue";
import CloseButton from "../close-button/CloseButton.vue";
import { tagKey } from "./context";
defineOptions({ name: "TagRemoveButton", inheritAttrs: false });
const props = withDefaults(
defineProps<{
/** Tag text used for the accessible name; `Tag` supplies it when omitted. */
textValue?: string;
isDisabled?: boolean;
}>(),
{ textValue: undefined, isDisabled: false },
);
const attrs = useAttrs();
const tag = inject(tagKey, undefined);
const label = computed(() => {
const text = props.textValue ?? tag?.textValue() ?? "";
return text ? `Remove tag ${text}` : "Remove tag";
});
// Removal stays owned by the enclosing Tag row: its click handler treats a
// press inside this subtree as a removal request rather than a selection. One
// path also covers custom remove buttons supplied through the tag slot.
</script>
<template>
<CloseButton
v-bind="attrs"
:aria-label="(attrs['aria-label'] as string | undefined) ?? label"
:class="[tag?.tagSlots.value.removeButton(), attrs.class]"
:is-disabled="props.isDisabled || !tag || tag.disabled.value"
:tabindex="(attrs.tabindex as number | string | undefined) ?? -1"
data-slot="tag-remove-button"
>
<slot />
</CloseButton>
</template>
@@ -0,0 +1,88 @@
import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue";
import type { tagGroupVariants, tagVariants } from "@heroui-vue/styles";
import type { CollectionKey } from "../collection/keys";
import type { CollectionMember } from "../collection/registry";
import type { CollectionSelectionMode } from "../collection/selection";
export type TagKey = CollectionKey;
export interface TagGroupDataItem {
id: TagKey;
textValue?: string;
isDisabled?: boolean;
}
/** Public schema shared by the SFC props and the context. */
export interface TagGroupOptions {
modelValue?: readonly TagKey[];
selectedKeys?: readonly TagKey[];
defaultValue?: readonly TagKey[];
defaultSelectedKeys?: readonly TagKey[];
selectionMode?: CollectionSelectionMode;
disabledKeys?: readonly TagKey[];
isDisabled?: boolean;
disallowEmptySelection?: boolean;
size?: "sm" | "md" | "lg";
variant?: "default" | "surface";
dir?: "ltr" | "rtl";
as?: string;
asChild?: boolean;
}
export interface TagRenderState {
isSelected: boolean;
isDisabled: boolean;
isHovered: boolean;
isPressed: boolean;
isFocused: boolean;
isFocusVisible: boolean;
allowsRemoving: boolean;
}
export interface TagMember extends CollectionMember {
noteBlur: () => void;
}
export interface TagGroupListProps<
T extends TagGroupDataItem = TagGroupDataItem,
> {
items?: readonly T[];
as?: string;
asChild?: boolean;
}
export interface TagGroupContext {
announcement: Ref<string>;
slots: ComputedRef<ReturnType<typeof tagGroupVariants>>;
tagSlots: ComputedRef<ReturnType<typeof tagVariants>>;
mode: ComputedRef<CollectionSelectionMode>;
disabled: ComputedRef<boolean>;
selected: (key: TagKey) => boolean;
isDisabledKey: (key: TagKey) => boolean;
allowsRemoving: () => boolean;
requestRemoval: (key: TagKey) => void;
register: (member: TagMember) => () => void;
hasEnabled: () => boolean;
registerList: (element: () => HTMLElement | undefined) => void;
active: ComputedRef<TagKey | undefined>;
focused: Ref<TagKey | undefined>;
pressed: Ref<TagKey | undefined>;
keyboard: Ref<boolean>;
activate: (key: TagKey, event: MouseEvent | KeyboardEvent) => void;
focus: (key: TagKey) => Promise<void>;
noteFocus: (key: TagKey) => void;
textValue: (key: TagKey) => string;
ariaLabel: () => string | undefined;
labelledBy: () => string | undefined;
describedBy: () => string | undefined;
onKeydown: (event: KeyboardEvent) => void;
onKeyup: (event: KeyboardEvent) => void;
}
export interface TagContext {
disabled: ComputedRef<boolean>;
tagSlots: ComputedRef<ReturnType<typeof tagVariants>>;
textValue: () => string;
}
export const tagGroupKey: InjectionKey<TagGroupContext> =
Symbol("hv-tag-group");
export const tagKey: InjectionKey<TagContext> = Symbol("hv-tag");
export function useTagGroup(): TagGroupContext {
const context = inject(tagGroupKey, undefined);
if (!context) throw new Error("Tag requires TagGroup and TagGroupList.");
return context;
}
+9
View File
@@ -0,0 +1,9 @@
/** Reka's Primitive exposes the element through `$el`, not as a DOM node. */
export function elementFromRef(value: unknown): HTMLElement | undefined {
// Server rendering and prerendering have no DOM; the collection then keeps
// registration order because no element is available.
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;
}