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