feat: add Disclosure DisclosureGroup and Accordion
This commit is contained in:
@@ -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 };
|
||||
}
|
||||
Reference in New Issue
Block a user