feat: add Disclosure DisclosureGroup and Accordion

This commit is contained in:
maoyingjie
2026-10-22 18:25:08 +08:00
parent 73bd7da5fa
commit b086d7f30d
63 changed files with 5597 additions and 4 deletions
+163
View File
@@ -0,0 +1,163 @@
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */
/* Base accordion styles */
.hv-accordion {
@apply w-full;
/* Performance optimization - contain layout changes */
contain: layout style;
}
/* Accordion elements */
.hv-accordion__body {
@apply text-sm;
}
.hv-accordion__body-inner {
@apply px-4 pt-0 pb-4 text-muted;
}
.hv-accordion__heading {
@apply flex;
}
.hv-accordion__indicator {
@apply ms-auto size-4 shrink-0 text-muted;
/**
* Transitions
*/
@apply transition duration-250 motion-reduce:transition-none;
/* Expanded state for indicator rotation */
&[data-expanded="true"] {
@apply -rotate-180;
}
}
/* Accordion Item - Separator styles */
.hv-accordion__item {
@apply relative border-none;
}
.hv-accordion__item::after {
content: "";
@apply absolute start-0 bottom-0 h-px w-full rounded-xs bg-separator;
}
.hv-accordion__item:last-child::after {
content: none;
}
/* Hide separator when hideSeparator prop is set */
.hv-accordion__item[data-hide-separator="true"]::after {
display: none;
}
/* ------------------------------------ */
.hv-accordion__trigger {
cursor: var(--cursor-interactive);
/* Base Styles */
@apply flex flex-1 items-center justify-between px-4 py-4 text-start text-sm font-medium no-highlight;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
opacity 150ms var(--ease-out),
box-shadow 150ms var(--ease-out);
@apply motion-reduce:transition-none;
/**
* Hover state
* CRITICAL: inside `@media (hover: hover)` this keys off `:hover` alone. React Aria writes
* `data-hovered` on a render tick, so on pointer leave the attribute outlives the native
* `:hover` by at least a frame; including it here keeps this background painted for that frame,
* after a custom `hover:bg-*` override has already stopped matching, and the default color
* flashes on top. `:hover` is the same signal Tailwind's `hover:` variant compiles to, so the
* default and any override switch in lockstep. `data-hovered` is still on the element for
* consumers who want to key their own styles off it.
*/
@media (hover: hover) {
&:hover:not([aria-expanded="true"]) {
background-color: color-mix(
in oklab,
var(--foreground) 3%,
transparent 90%
);
}
}
/* Focus state */
&:focus-visible:not([data-focused]),
&[data-focus-visible="true"] {
@apply status-focused;
}
/* Disabled State */
&:disabled,
&[aria-disabled="true"] {
@apply status-disabled;
}
}
.hv-accordion__panel {
opacity: 0;
height: var(--disclosure-panel-height);
overflow: clip;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
height 200ms var(--ease-out-quad),
opacity 200ms var(--ease-out);
@apply motion-reduce:transition-none;
&[data-expanded="true"] {
will-change: height, opacity;
opacity: 1;
}
}
/* Surface variant */
.hv-accordion--surface {
@apply bg-surface;
border-radius: min(32px, var(--radius-3xl));
.hv-accordion__trigger {
/* See the base trigger hover state for why `data-hovered` is left out here. */
@media (hover: hover) {
&:hover:not([aria-expanded="true"]) {
@apply bg-default;
}
}
}
.hv-accordion__item::after {
@apply bg-surface-foreground/6;
}
}
.hv-accordion--surface .hv-accordion__item {
/* Surface variant separator styling */
&::after {
@apply start-[3%] w-[94%];
}
/* Special rounding for first and last items in surface variant */
&:first-child [data-slot="accordion-trigger"] {
border-start-start-radius: min(32px, var(--radius-3xl));
border-start-end-radius: min(32px, var(--radius-3xl));
}
&:last-child:not(:has([data-slot="accordion-trigger"][aria-expanded="true"]))
[data-slot="accordion-trigger"] {
border-end-start-radius: min(32px, var(--radius-3xl));
border-end-end-radius: min(32px, var(--radius-3xl));
}
}
@@ -0,0 +1,10 @@
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */
/* Base disclosure-group styles */
.hv-disclosure-group {
@apply w-full;
/* Performance optimization - contain layout changes */
contain: layout style;
}
+93
View File
@@ -0,0 +1,93 @@
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */
/* Base disclosure styles */
.hv-disclosure {
@apply relative;
}
.hv-disclosure__heading {
@apply flex;
}
.hv-disclosure__trigger {
cursor: var(--cursor-interactive);
/*
* Baseline uses inline-block. Button is inline-flex; a later inline-block
* would override it and break icon/text/indicator row layout when asChild
* merges trigger styles onto Button. inline-flex keeps both cases aligned.
*/
@apply inline-flex items-center no-highlight;
/* Focus state */
&:focus-visible:not([data-focused]),
&[data-focus-visible="true"] {
@apply status-focused;
}
/* Disabled state */
&:disabled,
&[aria-disabled="true"] {
@apply status-disabled;
}
}
.hv-disclosure__indicator {
@apply ms-auto size-4 shrink-0 text-inherit;
/**
* Transitions
*/
@apply transition duration-250 motion-reduce:transition-none;
/* Expanded state for indicator rotation */
&[data-expanded="true"] {
@apply -rotate-180;
}
}
/*
* Button's generic svg rule (specificity 0,2,2) sets margin-inline/-size on
* every svg except spinner/link-icon. Beat it and restore end-alignment when
* asChild merges the trigger onto Button.
*/
.hv-button svg.hv-disclosure__indicator[data-slot="disclosure-indicator"] {
margin-block: 0;
margin-inline: 0;
margin-inline-start: auto;
width: 1rem;
height: 1rem;
}
/*
* Height is always var(--disclosure-panel-height). The variable is driven
* by useDisclosurePanelHeight (0px ↔ scrollHeight px → auto) so the CSS
* transition matches React Aria / HeroUI. data-expanded only changes opacity.
*/
.hv-disclosure__content {
opacity: 0;
height: var(--disclosure-panel-height);
overflow: clip;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
height 200ms var(--ease-out-quad),
opacity 200ms var(--ease-out);
@apply motion-reduce:transition-none;
&[data-expanded="true"] {
will-change: height, opacity;
opacity: 1;
}
}
.hv-disclosure__body {
@apply p-2;
}
.hv-disclosure__body-inner {
/* Inner wrapper keeps caller class on the scrolling/inner box. */
}
+6
View File
@@ -114,3 +114,9 @@
@import "./components/progress-circle.css" layer(components);
@import "./components/meter.css" layer(components);
@import "./components/disclosure.css" layer(components);
@import "./components/disclosure-group.css" layer(components);
@import "./components/accordion.css" layer(components);
+51
View File
@@ -840,3 +840,54 @@ export const meterVariants = tv({
});
export type MeterVariants = VariantProps<typeof meterVariants>;
export const disclosureVariants = tv({
defaultVariants: {},
slots: {
base: "hv-disclosure",
body: "hv-disclosure__body",
bodyInner: "hv-disclosure__body-inner",
content: "hv-disclosure__content",
heading: "hv-disclosure__heading",
indicator: "hv-disclosure__indicator",
trigger: "hv-disclosure__trigger",
},
variants: {},
});
export type DisclosureVariants = VariantProps<typeof disclosureVariants>;
export const disclosureGroupVariants = tv({
defaultVariants: {},
slots: {
base: "hv-disclosure-group",
},
variants: {},
});
export type DisclosureGroupVariants = VariantProps<
typeof disclosureGroupVariants
>;
export const accordionVariants = tv({
slots: {
base: "hv-accordion",
body: "hv-accordion__body",
bodyInner: "hv-accordion__body-inner",
heading: "hv-accordion__heading",
indicator: "hv-accordion__indicator",
item: "hv-accordion__item",
panel: "hv-accordion__panel",
trigger: "hv-accordion__trigger",
},
variants: {
variant: {
default: {},
surface: {
base: "hv-accordion--surface",
},
},
},
});
export type AccordionVariants = VariantProps<typeof accordionVariants>;
@@ -0,0 +1,108 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
provide,
useAttrs,
type PropType,
} from "vue";
import { accordionVariants, type AccordionVariants } from "@heroui-vue/styles";
import { useInheritedDisabled } from "../field/disabled";
import {
disclosureGroupContextKey,
useDisclosureGroupState,
type DisclosureKey,
} from "../disclosure-group/context";
import { surfaceContextKey } from "../surface/context";
import { provideAccordion } from "./context";
const DEFAULT_SURFACE_CONTEXT = { variant: computed(() => "default" as const) };
export default defineComponent({
name: "Accordion",
inheritAttrs: false,
props: {
expandedKeys: {
type: Array as PropType<DisclosureKey[] | undefined>,
default: undefined,
},
defaultExpandedKeys: {
type: Array as PropType<DisclosureKey[]>,
default: () => [],
},
allowsMultipleExpanded: { type: Boolean, default: false },
isDisabled: { type: Boolean, default: false },
hideSeparator: { type: Boolean, default: false },
variant: {
type: String as PropType<NonNullable<AccordionVariants["variant"]>>,
default: "default",
},
as: { type: String, default: "div" },
},
emits: ["update:expandedKeys", "expandedChange"],
setup(props, { slots, emit, attrs }) {
const inheritedDisabled = useInheritedDisabled(() => props.isDisabled);
const state = useDisclosureGroupState({
get expandedKeys() {
return props.expandedKeys;
},
get defaultExpandedKeys() {
return props.defaultExpandedKeys;
},
get allowsMultipleExpanded() {
return props.allowsMultipleExpanded;
},
get isDisabled() {
return inheritedDisabled.value;
},
onExpandedChange(keys) {
emit("update:expandedKeys", keys);
emit("expandedChange", keys);
},
});
provide(disclosureGroupContextKey, {
expandedKeys: state.expandedKeys,
allowsMultipleExpanded: state.allowsMultipleExpanded,
isDisabled: computed(() => inheritedDisabled.value),
isExpanded: state.isExpanded,
toggle: state.toggle,
registerItem: state.registerItem,
itemKeys: state.itemKeys,
});
provideAccordion({
hideSeparator: computed(() => props.hideSeparator),
variant: computed(() => props.variant),
});
if (props.variant === "surface") {
provide(surfaceContextKey, DEFAULT_SURFACE_CONTEXT);
}
const slotClasses = computed(() =>
accordionVariants({ variant: props.variant }),
);
return () => {
const raw =
slots.default?.({
expandedKeys: state.expandedKeys.value,
isDisabled: inheritedDisabled.value,
}) ?? [];
return h(
props.as,
{
...attrs,
class: [slotClasses.value.base(), attrs.class],
"data-slot": "accordion",
"data-disabled": inheritedDisabled.value ? "true" : undefined,
"aria-disabled": inheritedDisabled.value ? true : undefined,
},
raw,
);
};
},
});
</script>
@@ -0,0 +1,30 @@
<script setup lang="ts">
import { computed, useAttrs } from "vue";
import { accordionVariants } from "@heroui-vue/styles";
import { injectAccordion } from "./context";
defineOptions({ inheritAttrs: false });
const props = withDefaults(defineProps<{ as?: string }>(), { as: "div" });
const attrs = useAttrs();
const accordion = injectAccordion();
const slotClasses = computed(() =>
accordionVariants({ variant: accordion?.variant.value }),
);
/** Baseline: className merges onto the inner wrapper; other attrs stay on the outer. */
const outerAttrs = computed(() => {
const { class: _c, ...rest } = attrs;
return rest;
});
const innerClass = computed(() => [slotClasses.value.bodyInner(), attrs.class]);
</script>
<template>
<component
:is="props.as"
v-bind="outerAttrs"
:class="slotClasses.body()"
data-slot="accordion-body"
>
<div :class="innerClass"><slot /></div>
</component>
</template>
@@ -0,0 +1,33 @@
<script setup lang="ts">
import { computed, inject, useAttrs } from "vue";
import { accordionVariants } from "@heroui-vue/styles";
import { disclosureItemContextKey } from "../disclosure-group/context";
import { injectAccordion } from "./context";
defineOptions({ inheritAttrs: false });
const props = withDefaults(defineProps<{ as?: string; level?: number }>(), {
as: "h3",
level: 3,
});
const attrs = useAttrs();
const accordion = injectAccordion();
const item = inject(disclosureItemContextKey, undefined);
const slotClasses = computed(() =>
accordionVariants({ variant: accordion?.variant.value }),
);
const tag = computed(() =>
props.as && props.as !== "h3" ? props.as : `h${props.level ?? 3}`,
);
</script>
<template>
<component
:is="tag"
v-bind="attrs"
:class="[slotClasses.heading(), attrs.class]"
data-slot="accordion-heading"
>
<slot v-bind="item ? { isExpanded: item.isExpanded.value } : {}" />
</component>
</template>
@@ -0,0 +1,59 @@
<script lang="ts">
import {
cloneVNode,
computed,
defineComponent,
h,
inject,
isVNode,
useAttrs,
type VNode,
} from "vue";
import { accordionVariants } from "@heroui-vue/styles";
import { disclosureItemContextKey } from "../disclosure-group/context";
import DisclosureChevronIcon from "../disclosure/DisclosureChevronIcon.vue";
import { injectAccordion } from "./context";
function firstVNode(list: unknown[]): VNode | undefined {
for (const node of list) {
if (Array.isArray(node)) {
const found = firstVNode(node);
if (found) return found;
} else if (isVNode(node)) {
return node;
}
}
return undefined;
}
export default defineComponent({
name: "AccordionIndicator",
inheritAttrs: false,
setup(_, { slots, attrs }) {
const item = inject(disclosureItemContextKey, undefined);
const accordion = injectAccordion();
const isExpanded = computed(() => item?.isExpanded.value === true);
const slotClasses = computed(() =>
accordionVariants({ variant: accordion?.variant.value }),
);
return () => {
const children = slots.default?.({ isExpanded: isExpanded.value });
const shared = {
...attrs,
class: [slotClasses.value.indicator(), attrs.class],
"data-expanded": isExpanded.value ? "true" : undefined,
"data-slot": "accordion-indicator",
};
const child = firstVNode(Array.isArray(children) ? children : [children]);
if (child) {
return cloneVNode(child, {
...shared,
class: [shared.class, child.props?.class],
});
}
return h(DisclosureChevronIcon, shared);
};
},
});
</script>
@@ -0,0 +1,74 @@
<script lang="ts">
import { computed, defineComponent, h, useAttrs, type PropType } from "vue";
import { accordionVariants } from "@heroui-vue/styles";
import type { DisclosureKey } from "../disclosure-group/context";
import { useDisclosureItem } from "../disclosure/useDisclosureItem";
import { injectAccordion } from "./context";
export default defineComponent({
name: "AccordionItem",
inheritAttrs: false,
props: {
/** Group key (type-preserving). DOM ids stay unique when keys stringify alike. */
id: {
type: [String, Number] as PropType<DisclosureKey>,
default: undefined,
},
expanded: {
type: Boolean as PropType<boolean | undefined>,
default: undefined,
},
defaultExpanded: { type: Boolean, default: false },
isDisabled: { type: Boolean, default: false },
as: { type: String, default: "div" },
},
emits: ["update:expanded", "expandedChange"],
setup(props, { slots, emit, attrs }) {
const accordion = injectAccordion();
const item = useDisclosureItem({
get id() {
return props.id;
},
get expanded() {
return props.expanded;
},
get defaultExpanded() {
return props.defaultExpanded;
},
get isDisabled() {
return props.isDisabled;
},
onExpanded(next) {
emit("update:expanded", next);
emit("expandedChange", next);
},
});
const slotClasses = computed(() =>
accordionVariants({ variant: accordion?.variant.value }),
);
return () => {
const raw =
slots.default?.({
isExpanded: item.isExpanded.value,
isDisabled: item.isDisabled.value,
}) ?? [];
return h(
props.as,
{
...attrs,
id: item.domId.value,
class: [slotClasses.value.item(), attrs.class],
"data-slot": "accordion-item",
"data-expanded": item.isExpanded.value ? "true" : undefined,
"data-disabled": item.isDisabled.value ? "true" : undefined,
"data-hide-separator":
accordion?.hideSeparator.value === true ? "true" : undefined,
},
raw,
);
};
},
});
</script>
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { computed, inject, ref, useAttrs } from "vue";
import { accordionVariants } from "@heroui-vue/styles";
import { disclosureItemContextKey } from "../disclosure-group/context";
import { useDisclosurePanelHeight } from "../disclosure/useDisclosurePanelHeight";
import { injectAccordion } from "./context";
defineOptions({ inheritAttrs: false });
const props = withDefaults(defineProps<{ as?: string }>(), { as: "div" });
const attrs = useAttrs();
const item = inject(disclosureItemContextKey, undefined);
const accordion = injectAccordion();
const isExpanded = computed(() => item?.isExpanded.value === true);
const isDisabled = computed(() => item?.isDisabled.value === true);
const contentId = computed(() => item?.contentId.value);
const triggerId = computed(() => item?.triggerId.value);
const contentEl = ref<HTMLElement | null>(null);
const { hidden } = useDisclosurePanelHeight(contentEl, isExpanded);
const slotClasses = computed(() =>
accordionVariants({ variant: accordion?.variant.value }),
);
</script>
<template>
<component
:is="props.as"
:id="contentId"
v-bind="attrs"
ref="contentEl"
:class="[slotClasses.panel(), attrs.class]"
:data-expanded="isExpanded ? 'true' : undefined"
:data-disabled="isDisabled ? 'true' : undefined"
:hidden="hidden"
:aria-hidden="!isExpanded"
:aria-labelledby="triggerId"
:role="(attrs.role as string | undefined) ?? 'group'"
data-slot="accordion-panel"
>
<slot v-bind="{ isExpanded, isDisabled }" />
</component>
</template>
@@ -0,0 +1,94 @@
<script lang="ts">
import { computed, defineComponent, h, inject, useAttrs } from "vue";
import { accordionVariants } from "@heroui-vue/styles";
import { useInheritedDisabled } from "../field/disabled";
import { disclosureItemContextKey } from "../disclosure-group/context";
import {
cloneAsChildRoot,
resolveAsChildTarget,
} from "../disclosure/triggerEvents";
import { injectAccordion } from "./context";
export default defineComponent({
name: "AccordionTrigger",
inheritAttrs: false,
props: {
as: { type: String, default: "button" },
asChild: { type: Boolean, default: false },
isDisabled: { type: Boolean, default: false },
},
emits: ["click"],
setup(props, { slots, emit, attrs }) {
const item = inject(disclosureItemContextKey, undefined);
const accordion = injectAccordion();
const localDisabled = useInheritedDisabled(() => props.isDisabled);
const isDisabled = computed(
() => localDisabled.value || item?.isDisabled.value === true,
);
const isExpanded = computed(() => item?.isExpanded.value === true);
const slotClasses = computed(() =>
accordionVariants({ variant: accordion?.variant.value }),
);
return () => {
const children = slots.default?.({
isExpanded: isExpanded.value,
isDisabled: isDisabled.value,
});
const shared: Record<string, unknown> = {
...attrs,
type: props.as === "button" ? "button" : undefined,
"aria-expanded": isExpanded.value,
"aria-controls": item?.contentId.value,
id: (attrs.id as string | undefined) ?? item?.triggerId.value,
disabled: isDisabled.value ? true : undefined,
"aria-disabled": isDisabled.value ? true : undefined,
"data-disabled": isDisabled.value ? "true" : undefined,
"data-slot": "accordion-trigger",
};
if (props.asChild) {
const target = resolveAsChildTarget(children);
if (!target.root) {
if (target.nodes.length > 1) {
console.warn(
"[heroui-vue] AccordionTrigger asChild expects a single effective root; rendering slot unchanged.",
);
}
return target.fallback;
}
return cloneAsChildRoot(target.root, {
isDisabled: () => isDisabled.value,
emitClick: (event) => emit("click", event),
activate: () => item?.toggle(),
class: [
slotClasses.value.trigger(),
attrs.class,
target.root.props?.class,
],
shared,
});
}
return h(
props.as,
{
...shared,
onClick: (event: MouseEvent) => {
if (isDisabled.value) {
event.preventDefault();
event.stopImmediatePropagation();
return;
}
emit("click", event);
if (event.defaultPrevented) return;
item?.toggle();
},
class: [slotClasses.value.trigger(), attrs.class],
},
children,
);
};
},
});
</script>
@@ -0,0 +1,24 @@
import {
computed,
inject,
provide,
type ComputedRef,
type InjectionKey,
} from "vue";
import type { AccordionVariants } from "@heroui-vue/styles";
export interface AccordionContext {
hideSeparator: ComputedRef<boolean>;
variant: ComputedRef<NonNullable<AccordionVariants["variant"]>>;
}
export const accordionContextKey: InjectionKey<AccordionContext> =
Symbol("hv-accordion");
export function provideAccordion(ctx: AccordionContext): void {
provide(accordionContextKey, ctx);
}
export function injectAccordion(): AccordionContext | undefined {
return inject(accordionContextKey, undefined);
}
@@ -0,0 +1,88 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
provide,
useAttrs,
type PropType,
} from "vue";
import { disclosureGroupVariants } from "@heroui-vue/styles";
import { useInheritedDisabled } from "../field/disabled";
import {
disclosureGroupContextKey,
useDisclosureGroupState,
type DisclosureKey,
} from "./context";
export default defineComponent({
name: "DisclosureGroup",
inheritAttrs: false,
props: {
expandedKeys: {
type: Array as PropType<DisclosureKey[] | undefined>,
default: undefined,
},
defaultExpandedKeys: {
type: Array as PropType<DisclosureKey[]>,
default: () => [],
},
allowsMultipleExpanded: { type: Boolean, default: false },
isDisabled: { type: Boolean, default: false },
as: { type: String, default: "div" },
},
emits: ["update:expandedKeys", "expandedChange"],
setup(props, { slots, emit, attrs }) {
const inheritedDisabled = useInheritedDisabled(() => props.isDisabled);
const state = useDisclosureGroupState({
get expandedKeys() {
return props.expandedKeys;
},
get defaultExpandedKeys() {
return props.defaultExpandedKeys;
},
get allowsMultipleExpanded() {
return props.allowsMultipleExpanded;
},
get isDisabled() {
return inheritedDisabled.value;
},
onExpandedChange(keys) {
emit("update:expandedKeys", keys);
emit("expandedChange", keys);
},
});
provide(disclosureGroupContextKey, {
expandedKeys: state.expandedKeys,
allowsMultipleExpanded: state.allowsMultipleExpanded,
isDisabled: computed(() => inheritedDisabled.value),
isExpanded: state.isExpanded,
toggle: state.toggle,
registerItem: state.registerItem,
itemKeys: state.itemKeys,
});
const slotClasses = disclosureGroupVariants({});
return () => {
const raw =
slots.default?.({
expandedKeys: state.expandedKeys.value,
isDisabled: inheritedDisabled.value,
}) ?? [];
return h(
props.as,
{
...attrs,
class: [slotClasses.base(), attrs.class],
"data-slot": "disclosure-group",
"data-disabled": inheritedDisabled.value ? "true" : undefined,
"aria-disabled": inheritedDisabled.value ? true : undefined,
},
raw,
);
};
},
});
</script>
@@ -0,0 +1,164 @@
import {
computed,
inject,
provide,
ref,
watch,
type ComputedRef,
type InjectionKey,
type Ref,
} from "vue";
export type DisclosureKey = string | number;
export interface DisclosureSlots {
[slot: string]: string;
}
export interface DisclosureItemContext {
/** Effective expanded state (group-aware). */
isExpanded: ComputedRef<boolean>;
isDisabled: ComputedRef<boolean>;
toggle: () => void;
/** Stable id used for trigger/panel ARIA association. */
contentId: ComputedRef<string>;
triggerId: ComputedRef<string>;
}
export const disclosureItemContextKey: InjectionKey<DisclosureItemContext> =
Symbol("hv-disclosure-item");
export interface DisclosureGroupContext {
expandedKeys: ComputedRef<DisclosureKey[]>;
allowsMultipleExpanded: ComputedRef<boolean>;
isDisabled: ComputedRef<boolean>;
isExpanded: (key: DisclosureKey) => boolean;
toggle: (key: DisclosureKey) => void;
/** Register a member key for navigation helpers; returns unregister. */
registerItem: (key: DisclosureKey) => () => void;
itemKeys: ComputedRef<DisclosureKey[]>;
}
export const disclosureGroupContextKey: InjectionKey<DisclosureGroupContext> =
Symbol("hv-disclosure-group");
/**
* Key identity uses SameValueZero via Array.includes / index search,
* so numeric 1 and string "1" never collide.
*/
export function keyIndexOf(keys: DisclosureKey[], key: DisclosureKey): number {
for (let i = 0; i < keys.length; i += 1) {
if (Object.is(keys[i], key) || keys[i] === key) return i;
}
return -1;
}
export function keysEqual(a: DisclosureKey[], b: DisclosureKey[]): boolean {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i += 1) {
if (keyIndexOf(b, a[i]!) === -1) return false;
}
return true;
}
export interface UseDisclosureGroupStateOptions {
expandedKeys?: DisclosureKey[] | undefined;
defaultExpandedKeys?: DisclosureKey[] | undefined;
allowsMultipleExpanded?: boolean;
isDisabled?: boolean;
onExpandedChange?: (keys: DisclosureKey[]) => void;
}
export function useDisclosureGroupState(
options: UseDisclosureGroupStateOptions,
emitUpdate?: (keys: DisclosureKey[]) => void,
) {
const internal = ref<DisclosureKey[]>([
...(options.defaultExpandedKeys ?? []),
]);
const itemKeys = ref<DisclosureKey[]>([]);
const isControlled = computed(() => options.expandedKeys !== undefined);
const expandedKeys = computed<DisclosureKey[]>(() =>
isControlled.value ? [...(options.expandedKeys ?? [])] : internal.value,
);
const allowsMultipleExpanded = computed(
() => options.allowsMultipleExpanded === true,
);
const isDisabled = computed(() => options.isDisabled === true);
function commit(next: DisclosureKey[]) {
// Never mutate the caller array.
const copy = [...next];
if (!isControlled.value) {
internal.value = copy;
}
options.onExpandedChange?.(copy);
emitUpdate?.(copy);
}
function isExpanded(key: DisclosureKey): boolean {
return keyIndexOf(expandedKeys.value, key) !== -1;
}
function toggle(key: DisclosureKey) {
if (isDisabled.value) return;
const current = expandedKeys.value;
const open = keyIndexOf(current, key) !== -1;
if (allowsMultipleExpanded.value) {
const next = open
? current.filter((k) => keyIndexOf([key], k) === -1)
: [...current, key];
commit(next);
return;
}
// Single: replace; clicking open item closes it (allowsEmptySelection-style).
commit(open ? [] : [key]);
}
function registerItem(key: DisclosureKey): () => void {
if (keyIndexOf(itemKeys.value, key) !== -1) {
// Keep both instances mounted, but make the collision visible.
console.warn(
`[heroui-vue] duplicate disclosure key ${JSON.stringify(key)}; group expand state will be shared.`,
);
}
itemKeys.value = [...itemKeys.value, key];
return () => {
itemKeys.value = itemKeys.value.filter(
(k) => keyIndexOf([key], k) === -1,
);
};
}
// Keep internal state in sync when controlled prop is removed.
watch(
() => options.expandedKeys,
(value, prev) => {
if (value === undefined && prev !== undefined) {
internal.value = [...(prev ?? [])];
}
},
);
return {
expandedKeys,
allowsMultipleExpanded,
isDisabled,
isExpanded,
toggle,
registerItem,
itemKeys: computed(() => itemKeys.value),
commit,
};
}
export function injectDisclosureGroup(): DisclosureGroupContext | undefined {
return inject(disclosureGroupContextKey, undefined);
}
export function provideDisclosureGroup(ctx: DisclosureGroupContext): void {
provide(disclosureGroupContextKey, ctx);
}
@@ -0,0 +1,100 @@
import { computed, toValue, type MaybeRefOrGetter } from "vue";
import { keyIndexOf, type DisclosureKey } from "../disclosure-group/context";
export interface UseDisclosureGroupNavigationProps {
expandedKeys: MaybeRefOrGetter<DisclosureKey[]>;
itemIds: MaybeRefOrGetter<DisclosureKey[]>;
onExpandedChange: (keys: DisclosureKey[]) => void;
allowsMultipleExpanded?: boolean;
}
export interface UseDisclosureGroupNavigationReturn {
currentIndex: number;
isPrevDisabled: boolean;
isNextDisabled: boolean;
onPrevious: () => void;
onNext: () => void;
}
const EMPTY_ITEM_IDS: DisclosureKey[] = [];
/**
* Vue port of HeroUI useDisclosureGroupNavigation.
* `expandedKeys` / `onExpandedChange` use arrays instead of Set;
* the source collection is never mutated.
*/
export function useDisclosureGroupNavigation({
allowsMultipleExpanded = false,
expandedKeys,
itemIds = EMPTY_ITEM_IDS,
onExpandedChange,
}: UseDisclosureGroupNavigationProps): UseDisclosureGroupNavigationReturn {
const currentIndex = computed(() => {
const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS;
const keys = toValue(expandedKeys) ?? [];
const expandedItems = ids.filter((id) => keyIndexOf(keys, id) !== -1);
const currentItem = expandedItems.length > 0 ? expandedItems[0] : ids[0];
if (currentItem === undefined) return -1;
return keyIndexOf(ids, currentItem);
});
function handlePrevious() {
const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS;
const keys = toValue(expandedKeys) ?? [];
const index = currentIndex.value;
if (index <= 0) return;
const prevItem = ids[index - 1];
if (prevItem === undefined) return;
if (allowsMultipleExpanded) {
if (keyIndexOf(keys, prevItem) === -1) {
onExpandedChange([...keys, prevItem]);
}
} else {
onExpandedChange([prevItem]);
}
}
function handleNext() {
const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS;
const keys = toValue(expandedKeys) ?? [];
const index = currentIndex.value;
if (index >= ids.length - 1) return;
const nextItem = ids[index + 1];
if (nextItem === undefined) return;
if (allowsMultipleExpanded) {
if (keyIndexOf(keys, nextItem) === -1) {
onExpandedChange([...keys, nextItem]);
}
} else {
onExpandedChange([nextItem]);
}
}
const isPrevDisabled = computed(() => currentIndex.value <= 0);
const isNextDisabled = computed(() => {
const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS;
return currentIndex.value >= ids.length - 1;
});
return {
get currentIndex() {
return currentIndex.value;
},
get isPrevDisabled() {
return isPrevDisabled.value;
},
get isNextDisabled() {
return isNextDisabled.value;
},
onPrevious: handlePrevious,
onNext: handleNext,
};
}
@@ -0,0 +1,68 @@
<script lang="ts">
import { defineComponent, h, useAttrs, type PropType } from "vue";
import { disclosureVariants } from "@heroui-vue/styles";
import type { DisclosureKey } from "../disclosure-group/context";
import { useDisclosureItem } from "./useDisclosureItem";
export default defineComponent({
name: "Disclosure",
inheritAttrs: false,
props: {
/** Group key (type-preserving). DOM ids stay unique when keys stringify alike. */
id: {
type: [String, Number] as PropType<DisclosureKey>,
default: undefined,
},
expanded: {
type: Boolean as PropType<boolean | undefined>,
default: undefined,
},
defaultExpanded: { type: Boolean, default: false },
isDisabled: { type: Boolean, default: false },
as: { type: String, default: "div" },
},
emits: ["update:expanded", "expandedChange"],
setup(props, { slots, emit, attrs }) {
const item = useDisclosureItem({
get id() {
return props.id;
},
get expanded() {
return props.expanded;
},
get defaultExpanded() {
return props.defaultExpanded;
},
get isDisabled() {
return props.isDisabled;
},
onExpanded(next) {
emit("update:expanded", next);
emit("expandedChange", next);
},
});
const slotClasses = disclosureVariants({});
return () => {
const raw =
slots.default?.({
isExpanded: item.isExpanded.value,
isDisabled: item.isDisabled.value,
}) ?? [];
return h(
props.as,
{
...attrs,
id: item.domId.value,
class: [slotClasses.base(), attrs.class],
"data-slot": "disclosure",
"data-expanded": item.isExpanded.value ? "true" : undefined,
"data-disabled": item.isDisabled.value ? "true" : undefined,
},
raw,
);
};
},
});
</script>
@@ -0,0 +1,26 @@
<script setup lang="ts">
import { computed, useAttrs } from "vue";
import { disclosureVariants } from "@heroui-vue/styles";
defineOptions({ inheritAttrs: false });
const props = withDefaults(defineProps<{ as?: string }>(), { as: "div" });
const attrs = useAttrs();
const slotClasses = disclosureVariants({});
/** Baseline: className merges onto the inner wrapper; other attrs stay on the outer. */
const outerAttrs = computed(() => {
const { class: _c, ...rest } = attrs;
return rest;
});
const innerClass = computed(() => [slotClasses.bodyInner(), attrs.class]);
</script>
<template>
<component
:is="props.as"
v-bind="outerAttrs"
:class="slotClasses.body()"
data-slot="disclosure-body"
>
<div :class="innerClass"><slot /></div>
</component>
</template>
@@ -0,0 +1,30 @@
<script lang="ts">
/** Baseline IconChevronDown from HeroUI icons.tsx (Apache-2.0). */
export default {
name: "DisclosureChevronIcon",
};
</script>
<script setup lang="ts">
defineOptions({ inheritAttrs: false });
</script>
<template>
<svg
aria-hidden="true"
fill="none"
height="16"
role="presentation"
viewBox="0 0 16 16"
width="16"
xmlns="http://www.w3.org/2000/svg"
v-bind="$attrs"
>
<path
clip-rule="evenodd"
d="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"
fill="currentColor"
fill-rule="evenodd"
/>
</svg>
</template>
@@ -0,0 +1,42 @@
<script setup lang="ts">
import { computed, inject, ref, useAttrs } from "vue";
import { disclosureVariants } from "@heroui-vue/styles";
import { disclosureItemContextKey } from "../disclosure-group/context";
import { useDisclosurePanelHeight } from "./useDisclosurePanelHeight";
defineOptions({ inheritAttrs: false });
const props = withDefaults(defineProps<{ as?: string }>(), { as: "div" });
const attrs = useAttrs();
const item = inject(disclosureItemContextKey, undefined);
const isExpanded = computed(() => item?.isExpanded.value === true);
const isDisabled = computed(() => item?.isDisabled.value === true);
const contentId = computed(() => item?.contentId.value);
const triggerId = computed(() => item?.triggerId.value);
const contentEl = ref<HTMLElement | null>(null);
const { hidden } = useDisclosurePanelHeight(contentEl, isExpanded);
const slotClasses = disclosureVariants({});
const rootClass = computed(() => [slotClasses.content(), attrs.class]);
</script>
<template>
<component
:is="props.as"
:id="contentId"
v-bind="attrs"
ref="contentEl"
:class="rootClass"
:data-expanded="isExpanded ? 'true' : undefined"
:data-disabled="isDisabled ? 'true' : undefined"
:hidden="hidden"
:aria-hidden="!isExpanded"
:aria-labelledby="triggerId"
:role="(attrs.role as string | undefined) ?? 'group'"
data-slot="disclosure-content"
>
<slot v-bind="{ isExpanded, isDisabled }" />
</component>
</template>
@@ -0,0 +1,34 @@
<script setup lang="ts">
import { computed, inject, useAttrs, type PropType } from "vue";
import { disclosureVariants } from "@heroui-vue/styles";
import { disclosureItemContextKey } from "../disclosure-group/context";
defineOptions({ inheritAttrs: false });
const props = withDefaults(
defineProps<{
as?: string;
level?: 1 | 2 | 3 | 4 | 5 | 6;
}>(),
{ as: "h3", level: 3 },
);
const attrs = useAttrs();
const item = inject(disclosureItemContextKey, undefined);
const slotClasses = disclosureVariants({});
const rootClass = computed(() => [slotClasses.heading(), attrs.class]);
const tag = computed(() =>
props.as && props.as !== "h3" ? props.as : `h${props.level}`,
);
</script>
<template>
<component
:is="tag"
v-bind="attrs"
:class="rootClass"
data-slot="disclosure-heading"
>
<slot v-bind="item ? { isExpanded: item.isExpanded.value } : {}" />
</component>
</template>
@@ -0,0 +1,55 @@
<script lang="ts">
import {
cloneVNode,
computed,
defineComponent,
h,
inject,
isVNode,
useAttrs,
type VNode,
} from "vue";
import { disclosureVariants } from "@heroui-vue/styles";
import { disclosureItemContextKey } from "../disclosure-group/context";
import DisclosureChevronIcon from "./DisclosureChevronIcon.vue";
function firstVNode(list: unknown[]): VNode | undefined {
for (const node of list) {
if (Array.isArray(node)) {
const found = firstVNode(node);
if (found) return found;
} else if (isVNode(node)) {
return node;
}
}
return undefined;
}
export default defineComponent({
name: "DisclosureIndicator",
inheritAttrs: false,
setup(_, { slots, attrs }) {
const item = inject(disclosureItemContextKey, undefined);
const isExpanded = computed(() => item?.isExpanded.value === true);
const slotClasses = disclosureVariants({});
return () => {
const children = slots.default?.({ isExpanded: isExpanded.value });
const shared = {
...attrs,
class: [slotClasses.indicator(), attrs.class],
"data-expanded": isExpanded.value ? "true" : undefined,
"data-slot": "disclosure-indicator",
};
const child = firstVNode(Array.isArray(children) ? children : [children]);
if (child) {
return cloneVNode(child, {
...shared,
class: [shared.class, child.props?.class],
});
}
return h(DisclosureChevronIcon, shared);
};
},
});
</script>
@@ -0,0 +1,87 @@
<script lang="ts">
import { computed, defineComponent, h, inject, useAttrs } from "vue";
import { disclosureVariants } from "@heroui-vue/styles";
import { useInheritedDisabled } from "../field/disabled";
import { disclosureItemContextKey } from "../disclosure-group/context";
import { cloneAsChildRoot, resolveAsChildTarget } from "./triggerEvents";
/**
* Trigger button. `asChild` merges disclosure behavior onto the single
* effective root (comments/blank text ignored); otherwise renders `as`.
*/
export default defineComponent({
name: "DisclosureTrigger",
inheritAttrs: false,
props: {
as: { type: String, default: "button" },
asChild: { type: Boolean, default: false },
isDisabled: { type: Boolean, default: false },
},
emits: ["click"],
setup(props, { slots, emit, attrs }) {
const item = inject(disclosureItemContextKey, undefined);
const localDisabled = useInheritedDisabled(() => props.isDisabled);
const isDisabled = computed(
() => localDisabled.value || item?.isDisabled.value === true,
);
const isExpanded = computed(() => item?.isExpanded.value === true);
const slotClasses = disclosureVariants({});
return () => {
const children = slots.default?.({
isExpanded: isExpanded.value,
isDisabled: isDisabled.value,
});
const shared: Record<string, unknown> = {
...attrs,
type: props.as === "button" ? "button" : undefined,
"aria-expanded": isExpanded.value,
"aria-controls": item?.contentId.value,
id: (attrs.id as string | undefined) ?? item?.triggerId.value,
disabled: isDisabled.value ? true : undefined,
"aria-disabled": isDisabled.value ? true : undefined,
"data-disabled": isDisabled.value ? "true" : undefined,
"data-slot": "disclosure-trigger",
};
if (props.asChild) {
const target = resolveAsChildTarget(children);
if (!target.root) {
if (target.nodes.length > 1) {
console.warn(
"[heroui-vue] DisclosureTrigger asChild expects a single effective root; rendering slot unchanged.",
);
}
return target.fallback;
}
return cloneAsChildRoot(target.root, {
isDisabled: () => isDisabled.value,
emitClick: (event) => emit("click", event),
activate: () => item?.toggle(),
class: [slotClasses.trigger(), attrs.class, target.root.props?.class],
shared,
});
}
return h(
props.as,
{
...shared,
onClick: (event: MouseEvent) => {
if (isDisabled.value) {
event.preventDefault();
event.stopImmediatePropagation();
return;
}
emit("click", event);
if (event.defaultPrevented) return;
item?.toggle();
},
class: [slotClasses.trigger(), attrs.class],
},
children,
);
};
},
});
</script>
@@ -0,0 +1,180 @@
import { Comment, Fragment, Text, cloneVNode, isVNode, type VNode } from "vue";
type Handler = (event: MouseEvent) => void;
function isIgnorableVNode(node: VNode): boolean {
if (node.type === Comment) return true;
if (node.type === Text) {
return String(node.children ?? "").trim() === "";
}
return false;
}
/** Flatten arrays/Fragments and drop comments/blank text. */
export function meaningfulVNodes(list: unknown[]): VNode[] {
const out: VNode[] = [];
const walk = (nodes: unknown[]) => {
for (const node of nodes) {
if (node == null || node === false || node === true) continue;
if (Array.isArray(node)) {
walk(node);
continue;
}
if (!isVNode(node)) continue;
if (node.type === Fragment) {
walk((node.children ?? []) as unknown[]);
continue;
}
if (isIgnorableVNode(node)) continue;
out.push(node);
}
};
walk(list);
return out;
}
export interface AsChildTarget {
root?: VNode;
nodes: VNode[];
fallback: unknown;
}
export function resolveAsChildTarget(children: unknown): AsChildTarget {
const list = Array.isArray(children) ? children : [children];
const nodes = meaningfulVNodes(list);
return {
root: nodes.length === 1 ? nodes[0] : undefined,
nodes,
fallback: children,
};
}
/**
* Vue wraps listeners in createInvoker (fn with .value = original handler(s)).
* Unwrap so composed arrays contain the real functions; Vue's array invoker
* then applies native stop / stopImmediatePropagation semantics.
*/
function unwrapInvoker(value: unknown): unknown {
if (typeof value === "function" && value && "value" in value) {
return (value as { value: unknown }).value;
}
return value;
}
function flattenHandlers(value: unknown, out: Handler[] = []): Handler[] {
const raw = unwrapInvoker(value);
if (!raw) return out;
if (Array.isArray(raw)) {
for (const item of raw) flattenHandlers(item, out);
return out;
}
if (typeof raw === "function") out.push(raw as Handler);
return out;
}
export interface TriggerClickOptions {
isDisabled: () => boolean;
/** Child onClick payload (function or array), stripped before clone. */
childOnClick?: unknown;
emitClick: (event: MouseEvent) => void;
activate: () => void;
}
/**
* Ordered asChild click listeners for Vue's array invoker:
* 1. disabled guard (stopImmediatePropagation)
* 2. child listeners (stopPropagation keeps later ones; stopImmediate stops them)
* 3. emit + activate (skipped on stopImmediate; activate skipped on preventDefault)
*/
export function makeTriggerClickHandlers(
options: TriggerClickOptions,
): Handler[] {
return [
function disabledGuard(event: MouseEvent) {
if (options.isDisabled()) {
event.preventDefault();
event.stopImmediatePropagation();
}
},
...flattenHandlers(options.childOnClick),
function emitAndActivate(event: MouseEvent) {
options.emitClick(event);
if (event.defaultPrevented) return;
options.activate();
},
];
}
/**
* Capture-phase listeners: disabled guard first, then Trigger and child captures.
*/
export function makeTriggerCaptureHandlers(
isDisabled: () => boolean,
captureGroups: unknown[],
): Handler[] {
const handlers: Handler[] = [
function disabledGuard(event: MouseEvent) {
if (isDisabled()) {
event.preventDefault();
event.stopImmediatePropagation();
}
},
];
for (const group of captureGroups) {
handlers.push(...flattenHandlers(group));
}
return handlers;
}
export interface AsChildCloneOptions {
isDisabled: () => boolean;
emitClick: (event: MouseEvent) => void;
activate: () => void;
class: unknown;
/** Trigger fallthrough attrs; onClick / onClickCapture are consumed here. */
shared: Record<string, unknown>;
}
/**
* Clone the unique asChild root. Child and Trigger click/capture listeners are
* stripped then re-attached as ordered arrays (one execution path, correct
* stop semantics via Vue's invoker).
*/
export function cloneAsChildRoot(
root: VNode,
options: AsChildCloneOptions,
): VNode {
const childProps = (root.props ?? {}) as Record<string, unknown>;
const childOnClick = childProps.onClick;
const childCapture =
childProps.onClickCapture ??
childProps["onClick-capture"] ??
childProps.onCapture;
const cloned = cloneVNode(root);
const cleanedProps: Record<string, unknown> = { ...(cloned.props ?? {}) };
delete cleanedProps.onClick;
delete cleanedProps.onClickCapture;
delete cleanedProps["onClick-capture"];
cloned.props = cleanedProps;
const triggerCapture = options.shared.onClickCapture;
const sharedRest: Record<string, unknown> = { ...options.shared };
delete sharedRest.onClickCapture;
delete sharedRest.onClick;
return cloneVNode(cloned, {
...sharedRest,
class: options.class,
onClickCapture: makeTriggerCaptureHandlers(options.isDisabled, [
triggerCapture,
childCapture,
]),
onClick: makeTriggerClickHandlers({
isDisabled: options.isDisabled,
childOnClick,
emitClick: options.emitClick,
activate: options.activate,
}),
});
}
@@ -0,0 +1,129 @@
import {
computed,
onUnmounted,
provide,
ref,
useId,
watch,
type ComputedRef,
} from "vue";
import { useInheritedDisabled } from "../field/disabled";
import {
disclosureItemContextKey,
injectDisclosureGroup,
type DisclosureKey,
type DisclosureItemContext,
} from "../disclosure-group/context";
/**
* DOM id encoding: collection keys keep type identity (1 ≠ "1"),
* but DOM ids must stay unique. Explicit string ids are kept as-is
* for DX; numbers and auto keys use the instance's SSR-stable useId.
*/
export function encodeDomId(
key: DisclosureKey | undefined,
fallback: string,
): string {
if (key === undefined) return fallback;
if (typeof key === "number") return fallback;
return String(key);
}
export interface UseDisclosureItemOptions {
id?: DisclosureKey | undefined;
expanded?: boolean | undefined;
defaultExpanded?: boolean;
isDisabled?: boolean;
onExpanded: (next: boolean) => void;
}
export interface DisclosureItemModel {
itemKey: ComputedRef<DisclosureKey>;
domId: ComputedRef<string>;
triggerId: ComputedRef<string>;
contentId: ComputedRef<string>;
isExpanded: ComputedRef<boolean>;
isDisabled: ComputedRef<boolean>;
toggle: () => void;
}
/**
* Shared item state for Disclosure and AccordionItem.
* Group members always participate in the group (auto key when `id` is omitted).
* `onExpanded` receives the requested next flag — not a read-back of controlled props.
*/
export function useDisclosureItem(
options: UseDisclosureItemOptions,
): DisclosureItemModel {
const group = injectDisclosureGroup();
const autoKeyId = useId();
/** Collection key: explicit id (type-preserving) or stable per-instance key. */
const itemKey = computed<DisclosureKey>(() =>
options.id !== undefined ? options.id : autoKeyId,
);
const domId = computed(() => encodeDomId(options.id, autoKeyId));
const triggerId = computed(() => `${domId.value}-trigger`);
const contentId = computed(() => `${domId.value}-content`);
const localExpanded = ref(
options.expanded ?? options.defaultExpanded ?? false,
);
watch(
() => options.expanded,
(value) => {
if (value !== undefined) localExpanded.value = value;
},
);
const isControlled = computed(() => options.expanded !== undefined);
const isExpanded = computed(() => {
if (group) return group.isExpanded(itemKey.value);
return isControlled.value ? options.expanded === true : localExpanded.value;
});
const isDisabled = useInheritedDisabled(
() => options.isDisabled === true || (group?.isDisabled.value ?? false),
);
function toggle() {
if (isDisabled.value) return;
// Compute next from the request; controlled props may not have reflowed yet.
const next = !isExpanded.value;
if (group) {
group.toggle(itemKey.value);
} else if (!isControlled.value) {
localExpanded.value = next;
}
options.onExpanded(next);
}
let unregister: (() => void) | undefined;
if (group) {
unregister = group.registerItem(itemKey.value);
onUnmounted(() => {
unregister?.();
unregister = undefined;
});
}
provide(disclosureItemContextKey, {
isExpanded,
isDisabled,
toggle,
contentId,
triggerId,
});
return {
itemKey,
domId,
triggerId,
contentId,
isExpanded,
isDisabled,
toggle,
};
}
@@ -0,0 +1,118 @@
import {
onMounted,
onUnmounted,
ref,
toValue,
watch,
type MaybeRefOrGetter,
type Ref,
} from "vue";
export interface DisclosurePanelHeightApi {
/** Bound to the panel `hidden` attribute (until-found after close animation). */
hidden: Ref<"until-found" | undefined>;
}
/**
* Port of React Aria useDisclosure panel height protocol.
* CSS always uses `height: var(--disclosure-panel-height)`; this module
* animates that variable (0px ↔ scrollHeight px → auto) so open/close
* matches the fixed HeroUI baseline transition.
*
* Each apply() bumps a generation; stale animation callbacks from a prior
* close/open cycle must not hide a panel that has since been opened.
*/
export function useDisclosurePanelHeight(
panelEl: Ref<HTMLElement | null>,
isExpanded: MaybeRefOrGetter<boolean>,
): DisclosurePanelHeightApi {
const hidden = ref<"until-found" | undefined>(
toValue(isExpanded) ? undefined : "until-found",
);
let generation = 0;
let disposed = false;
let isExpandedRef: boolean | null = null;
function apply(expanded: boolean, isInitial: boolean) {
const gen = ++generation;
if (typeof window === "undefined") return;
const panel = panelEl.value;
if (!panel) return;
const canAnimate = typeof panel.getAnimations === "function";
const commitHidden = (value: "until-found" | undefined) => {
if (disposed || gen !== generation) return;
if (value === undefined) {
panel.removeAttribute("hidden");
hidden.value = undefined;
} else {
panel.setAttribute("hidden", value);
hidden.value = value;
}
};
const commitHeight = (value: string) => {
if (disposed || gen !== generation) return;
panel.style.setProperty("--disclosure-panel-height", value);
};
if (isInitial || !canAnimate) {
if (expanded) {
commitHidden(undefined);
commitHeight("auto");
} else {
commitHidden("until-found");
commitHeight("0px");
}
return;
}
if (expanded) {
commitHidden(undefined);
commitHeight(`${panel.scrollHeight}px`);
void Promise.all(panel.getAnimations().map((a) => a.finished))
.then(() => {
if (disposed || gen !== generation) return;
if (toValue(isExpanded) !== true) return;
commitHeight("auto");
})
.catch(() => {
/* cancelled transition — newer generation owns the panel */
});
} else {
commitHeight(`${panel.scrollHeight}px`);
void getComputedStyle(panel).height;
commitHeight("0px");
void Promise.all(panel.getAnimations().map((a) => a.finished))
.then(() => {
if (disposed || gen !== generation) return;
if (toValue(isExpanded) !== false) return;
commitHidden("until-found");
})
.catch(() => {
if (disposed || gen !== generation) return;
if (toValue(isExpanded) !== false) return;
commitHidden("until-found");
});
}
}
function onExpandedChange() {
const expanded = Boolean(toValue(isExpanded));
apply(expanded, isExpandedRef == null);
isExpandedRef = expanded;
}
onMounted(() => {
const expanded = Boolean(toValue(isExpanded));
apply(expanded, true);
isExpandedRef = expanded;
watch(() => Boolean(toValue(isExpanded)), onExpandedChange);
});
onUnmounted(() => {
disposed = true;
generation += 1;
});
return { hidden };
}
+50
View File
@@ -333,3 +333,53 @@ export {
type ProgressCircleVariants,
type MeterVariants,
} from "@heroui-vue/styles";
export { default as Disclosure } from "./components/disclosure/Disclosure.vue";
export { default as DisclosureHeading } from "./components/disclosure/DisclosureHeading.vue";
export { default as DisclosureTrigger } from "./components/disclosure/DisclosureTrigger.vue";
export { default as DisclosureContent } from "./components/disclosure/DisclosureContent.vue";
export { default as DisclosureBody } from "./components/disclosure/DisclosureBody.vue";
export { default as DisclosureIndicator } from "./components/disclosure/DisclosureIndicator.vue";
export type {
DisclosureProps,
DisclosureHeadingProps,
DisclosureTriggerProps,
DisclosureContentProps,
DisclosureBodyProps,
DisclosureIndicatorProps,
} from "./types";
export { default as DisclosureGroup } from "./components/disclosure-group/DisclosureGroup.vue";
export type { DisclosureGroupProps } from "./types";
export { useDisclosureGroupNavigation } from "./components/disclosure-group/useDisclosureGroupNavigation";
export type {
UseDisclosureGroupNavigationProps,
UseDisclosureGroupNavigationReturn,
} from "./components/disclosure-group/useDisclosureGroupNavigation";
export type { DisclosureKey } from "./components/disclosure-group/context";
export { default as Accordion } from "./components/accordion/Accordion.vue";
export { default as AccordionItem } from "./components/accordion/AccordionItem.vue";
export { default as AccordionHeading } from "./components/accordion/AccordionHeading.vue";
export { default as AccordionTrigger } from "./components/accordion/AccordionTrigger.vue";
export { default as AccordionPanel } from "./components/accordion/AccordionPanel.vue";
export { default as AccordionBody } from "./components/accordion/AccordionBody.vue";
export { default as AccordionIndicator } from "./components/accordion/AccordionIndicator.vue";
export type {
AccordionProps,
AccordionItemProps,
AccordionHeadingProps,
AccordionTriggerProps,
AccordionPanelProps,
AccordionBodyProps,
AccordionIndicatorProps,
} from "./types";
export {
disclosureVariants,
disclosureGroupVariants,
accordionVariants,
type DisclosureVariants,
type DisclosureGroupVariants,
type AccordionVariants,
} from "@heroui-vue/styles";
+47
View File
@@ -230,3 +230,50 @@ export type MeterProps = InstanceType<typeof Meter>["$props"];
export type MeterOutputProps = InstanceType<typeof MeterOutput>["$props"];
export type MeterTrackProps = InstanceType<typeof MeterTrack>["$props"];
export type MeterFillProps = InstanceType<typeof MeterFill>["$props"];
import type Disclosure from "./components/disclosure/Disclosure.vue";
import type DisclosureHeading from "./components/disclosure/DisclosureHeading.vue";
import type DisclosureTrigger from "./components/disclosure/DisclosureTrigger.vue";
import type DisclosureContent from "./components/disclosure/DisclosureContent.vue";
import type DisclosureBody from "./components/disclosure/DisclosureBody.vue";
import type DisclosureIndicator from "./components/disclosure/DisclosureIndicator.vue";
export type DisclosureProps = InstanceType<typeof Disclosure>["$props"];
export type DisclosureHeadingProps = InstanceType<
typeof DisclosureHeading
>["$props"];
export type DisclosureTriggerProps = InstanceType<
typeof DisclosureTrigger
>["$props"];
export type DisclosureContentProps = InstanceType<
typeof DisclosureContent
>["$props"];
export type DisclosureBodyProps = InstanceType<typeof DisclosureBody>["$props"];
export type DisclosureIndicatorProps = InstanceType<
typeof DisclosureIndicator
>["$props"];
import type DisclosureGroup from "./components/disclosure-group/DisclosureGroup.vue";
export type DisclosureGroupProps = InstanceType<
typeof DisclosureGroup
>["$props"];
import type Accordion from "./components/accordion/Accordion.vue";
import type AccordionItem from "./components/accordion/AccordionItem.vue";
import type AccordionHeading from "./components/accordion/AccordionHeading.vue";
import type AccordionTrigger from "./components/accordion/AccordionTrigger.vue";
import type AccordionPanel from "./components/accordion/AccordionPanel.vue";
import type AccordionBody from "./components/accordion/AccordionBody.vue";
import type AccordionIndicator from "./components/accordion/AccordionIndicator.vue";
export type AccordionProps = InstanceType<typeof Accordion>["$props"];
export type AccordionItemProps = InstanceType<typeof AccordionItem>["$props"];
export type AccordionHeadingProps = InstanceType<
typeof AccordionHeading
>["$props"];
export type AccordionTriggerProps = InstanceType<
typeof AccordionTrigger
>["$props"];
export type AccordionPanelProps = InstanceType<typeof AccordionPanel>["$props"];
export type AccordionBodyProps = InstanceType<typeof AccordionBody>["$props"];
export type AccordionIndicatorProps = InstanceType<
typeof AccordionIndicator
>["$props"];