feat: migrate Tag, TagGroup and ErrorMessage with collection and focus contracts

Port the fixed HeroUI baseline tag/tag-group/error-message components onto the
existing collection selection/registry protocols instead of a second state model.

- TagGroup owns selection, disabled scope, removal requests and name/description
  wiring; TagGroupList renders the role=grid node and Tag renders role=row.
- Removal has one path: a press inside the remove subtree is a removal request,
  so custom remove buttons work without a second event source; focus follows the
  next neighbour only after the item is actually gone.
- ErrorMessage keeps the baseline slot marker and reuses the field part ids
  without gaining validation or aria-invalid semantics.
- Ship the 12 tag-group and 2 error-message previews, both doc pages, navigation,
  a 35-case behavioural suite and independent tarball consumption checks.
This commit is contained in:
maoyingjie
2026-10-25 10:45:43 +08:00
parent 3532cc6aad
commit af6bfda3ee
40 changed files with 3790 additions and 4 deletions
@@ -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>
+254
View File
@@ -0,0 +1,254 @@
<script lang="ts">
import {
Fragment,
cloneVNode,
computed,
defineComponent,
h,
isVNode,
mergeProps,
onBeforeUnmount,
provide,
ref,
watchEffect,
type PropType,
type SlotsType,
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.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,
});
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;
};
owner.addEventListener("pointerup", release, true);
owner.addEventListener("pointercancel", release, true);
cleanup(() => {
owner.removeEventListener("pointerup", release, true);
owner.removeEventListener("pointercancel", release, true);
});
});
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;
}
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: () => {
focused.value = false;
focusVisible.value = false;
pressed.value = false;
if (group.focused.value === props.id)
group.focused.value = undefined;
},
onPointerenter: () => {
hovered.value = true;
},
onPointerleave: () => {
hovered.value = false;
pressed.value = false;
},
onPointerdown: (event: PointerEvent) => {
if (
!event.defaultPrevented &&
!disabled.value &&
event.button === 0
)
pressed.value = true;
group.pressed.value = props.id;
},
onPointerup: () => {
pressed.value = false;
if (group.pressed.value === props.id)
group.pressed.value = undefined;
},
}),
{ default: () => removable },
);
};
},
});
</script>
@@ -0,0 +1,476 @@
<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) ||
!!registry
.ordered()
.find((member) => member.key() === key)
?.disabled();
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)) 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;
lastIndex = order.value.indexOf(key);
emit("remove", [key]);
}
// 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) => {
const key = lastFocused.value;
if (key === undefined || !mounted || disposing) return;
if (next.includes(key)) return;
const remaining = eligible();
if (!remaining.length) {
restoreFocus();
return;
}
const index = Math.min(Math.max(lastIndex, 0), remaining.length - 1);
void focus(remaining[index].key());
});
let pendingSpace: TagKey | undefined;
function onKeydown(event: KeyboardEvent) {
if (
event.defaultPrevented ||
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) {
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,
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 = order.value.indexOf(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],
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,83 @@
<script setup lang="ts" generic="T extends TagGroupDataItem = TagGroupDataItem">
import { computed, 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);
const describedBy = computed(() => group.describedBy());
const labelledBy = computed(() =>
group.ariaLabel() ? undefined : group.labelledBy(),
);
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],
"data-slot": "tag-group-list",
"data-disabled": group.disabled.value || undefined,
"aria-label": group.ariaLabel(),
"aria-labelledby": labelledBy.value,
"aria-describedby": describedBy.value,
"aria-disabled": group.disabled.value || undefined,
"aria-multiselectable": group.mode.value === "multiple" ? true : undefined,
// Baseline announces collection additions/removals on the list itself.
"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>
<slot v-else name="empty" />
</template>
<slot v-else :item="undefined!" :index="-1" />
</Primitive>
</template>
@@ -0,0 +1,38 @@
<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"
data-slot="tag-remove-button"
>
<slot />
</CloseButton>
</template>
@@ -0,0 +1,85 @@
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";
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 {
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 {
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;
}