DocumentationCollapse
Collapse
Height collapse with a real exit animation, held open until the keyframes finish.
Shared live previews stay running while you switch code examples and API documentation.
Place content in the default slot.. Native attributes use Vue spelling, and component refs expose element.
Quick start
Copy the component and everything it needs into your Vue 3.5+ project.
npx shadcn-vue@2.8.2 add https://kida-ui.onrender.com/r/vue/collapse.jsonRun this from a project with components.json. The CLI creates all required files and installs the declared runtime dependencies. New to shadcn? Follow theinstallation guide first.
Copy manually7 files
1. Install runtime dependencies
npm install @zag-js/presence@1.43.3 @zag-js/vue@1.43.32. Create the source files
Keep this directory structure so the component's relative imports continue to work.
src/components/ui/kida/collapse.vue
<script setup lang="ts">
import './collapse.css'
import {
type CollapseSizeObserver,
observeCollapseSize,
prefersReducedMotion,
} from './collapse.motion.js'
import * as presence from '@zag-js/presence'
import { normalizeProps, useMachine } from '@zag-js/vue'
import { computed, onUpdated, shallowRef, watch } from 'vue'
import type { CollapseProps } from './collapse.types.js'
defineOptions({ name: 'KidaCollapse', inheritAttrs: false })
const props = defineProps<CollapseProps>()
const emit = defineEmits<{ 'exit-complete': [] }>()
const service = useMachine(presence.machine, {
get present() {
return props.open
},
onExitComplete: () => emit('exit-complete'),
})
const api = computed(() => presence.connect(service, normalizeProps))
const element = shallowRef<HTMLDivElement | null>(null)
const content = shallowRef<HTMLDivElement | null>(null)
let size: CollapseSizeObserver | undefined
defineExpose({ element })
watch(element, (node) => api.value.setNode(node), { flush: 'post' })
watch(
[element, content],
([node, inner], _, onCleanup) => {
if (!node || !inner) return
const observer = observeCollapseSize(node, inner)
size = observer
onCleanup(() => {
observer.disconnect()
size = undefined
})
},
{ flush: 'post' },
)
// Root styles can change without resizing the inner content. Refresh after Vue patches them.
onUpdated(() => size?.measure())
watch(
() => props.open,
(open) => {
if (!open && prefersReducedMotion()) api.value.unmount()
},
{ flush: 'post' },
)
</script>
<template>
<div
v-if="api.present"
v-bind="$attrs"
ref="element"
data-kida-collapse=""
:data-state="props.open ? 'open' : 'closed'"
:data-skip-animation="api.skip ? '' : undefined"
>
<div ref="content"><slot /></div>
</div>
</template>src/components/ui/kida/collapse.types.ts
export interface CollapseProps {
/** Controlled visibility; the node remains mounted until its exit finishes. */
open: boolean;
}
/** Vue component refs expose the root DOM element, null when presence removes it. */
export interface KidaElement {
element: HTMLElement | null;
}src/components/ui/kida/collapse-size.motion.ts
interface Frame {
paddingTop: number
paddingBottom: number
borderTopWidth: number
borderBottomWidth: number
borderBox: boolean
}
export interface CollapseSizeObserver {
/** Remeasure after the adapter updates root styles or content. */
measure(): void
/** Stop observation when presence removes the node or the adapter unmounts. */
disconnect(): void
}
/**
* Measure the natural content height and root frame into the shared Collapse CSS variables.
* The adapter owns presence; this helper owns layout and container-size observation.
*/
export function observeCollapseSize(root: HTMLElement, content: HTMLElement): CollapseSizeObserver {
let frame: Frame | undefined
let active = true
const readFrame = (): Frame => {
// Opening keyframes zero the root's frame. Suppress them across this read so we measure
// authored padding/borders rather than the animated values.
const restore = root.style.animationName
root.style.animationName = 'none'
try {
const style = getComputedStyle(root)
return {
paddingTop: Number.parseFloat(style.paddingTop),
paddingBottom: Number.parseFloat(style.paddingBottom),
borderTopWidth: Number.parseFloat(style.borderTopWidth),
borderBottomWidth: Number.parseFloat(style.borderBottomWidth),
borderBox: style.boxSizing === 'border-box',
}
} finally {
root.style.animationName = restore
}
}
const measure = () => {
if (!active) return
// Keep the frame cached during motion: suppressing a running animation to read it would
// restart the animation. Refresh when settled so authored style changes still take effect.
if (!frame || root.getAnimations().length === 0) frame = readFrame()
// CSS height uses the root's box-sizing. Only border-box includes the root's own frame.
let height = content.getBoundingClientRect().height
if (frame.borderBox) {
height +=
frame.paddingTop + frame.paddingBottom + frame.borderTopWidth + frame.borderBottomWidth
}
root.style.setProperty('--kida-collapse-height', `${height}px`)
root.style.setProperty('--kida-collapse-padding-top', `${frame.paddingTop}px`)
root.style.setProperty('--kida-collapse-padding-bottom', `${frame.paddingBottom}px`)
root.style.setProperty('--kida-collapse-border-top-width', `${frame.borderTopWidth}px`)
root.style.setProperty('--kida-collapse-border-bottom-width', `${frame.borderBottomWidth}px`)
}
measure()
const observer = new ResizeObserver(measure)
observer.observe(content)
return {
measure,
disconnect() {
active = false
observer.disconnect()
},
}
}src/components/ui/kida/collapse.motion.ts
export { type CollapseSizeObserver, observeCollapseSize } from './collapse-size.motion.js'
export { prefersReducedMotion } from './reduced-motion.motion.js'src/components/ui/kida/reduced-motion.motion.ts
const QUERY = '(prefers-reduced-motion: reduce)'
/**
* Whether the user has asked for reduced motion.
*
* SSR-safe: returns `false` when there is no `window`, matching the CSS default
* (the `prefers-reduced-motion` media query in `@kida-ui/styles` is the real guard;
* this is for the JS-driven paths that CSS cannot express).
*/
export function prefersReducedMotion(): boolean {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false
return window.matchMedia(QUERY).matches
}
/**
* Subscribe to changes of the reduced-motion preference.
* Returns an unsubscribe function. No-op (and immediately unsubscribable) on the server.
*/
export function watchReducedMotion(onChange: (reduced: boolean) => void): () => void {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return () => {}
const list = window.matchMedia(QUERY)
const handler = (event: MediaQueryListEvent) => onChange(event.matches)
list.addEventListener('change', handler)
return () => list.removeEventListener('change', handler)
}src/components/ui/kida/collapse.css
@import './tokens.css';
/*
* Collapse — the CSS-driven half of ADR D5.
*
* `@zag-js/presence` reads the computed animation on this element to decide how long to
* keep it mounted, so the exit transition MUST be a CSS animation. If it were a JS
* animation the node would be torn out on the first frame.
*
* Height is animated rather than transform, which is not compositor-friendly — the usual
* and unavoidable trade for collapsing to natural height. Content inside should animate
* with opacity/transform if it needs motion of its own.
*/
[data-kida-collapse] {
overflow: hidden;
}
[data-kida-collapse][data-state="open"] {
animation: kida-collapse-open var(--kida-collapse-duration, var(--kida-duration-md))
var(--kida-collapse-ease, var(--kida-ease-out));
}
/*
* Deliberately not `--kida-ease-in`. Both of that curve's control points sit at y=0, so
* it is pinned near zero for most of its length: measured over the old 150ms close, the
* panel was 4% collapsed at the halfway mark and dropped the last 53% inside ~26ms —
* a frame and a half. It reads as the panel blinking out rather than closing. Reversing
* the open curve is exact on paper and wrong in the eye, because the fast part lands
* where nobody is still looking. Here the shrinking IS the information, so it has to be
* legible, which also means matching the open duration instead of halving it.
*
* `forwards` holds the final frame: presence unmounts on `animationend`, and without a
* fill mode any gap between the two lets the element revert to its natural height for a
* frame — a full-height flash on the way out.
*/
[data-kida-collapse][data-state="closed"] {
animation: kida-collapse-close var(--kida-collapse-duration, var(--kida-duration-md))
var(--kida-collapse-ease, var(--kida-ease-in-out)) forwards;
}
/*
* Mounted already-open: there is no previous state to animate from.
* Declared last so it wins on order — both selectors have the same specificity, which is
* why this needs no `!important`.
*/
[data-kida-collapse][data-skip-animation] {
animation: none;
}
/* Presence checks computed animation styles before deciding whether to hold the node for an
exit. A 1ms reduced-motion animation can finish before that listener is attached, leaving the
closed node mounted forever. With no animation, presence removes it immediately. */
@media (prefers-reduced-motion: reduce) {
[data-kida-collapse] {
animation: none;
}
}
/*
* The root's vertical frame collapses with the content, because `height: 0` does not mean
* "invisible": a root with a 1px border still renders a 2px box, and one with
* `padding: 1rem` a 32px slab. Left in, that residue sits perfectly static at the end of
* the close until presence unmounts — a hairline that hangs for a few frames and then
* pops out.
*
* Both ends of every property are written out on purpose. An omitted end is supposed to
* be filled in from the element's own value, and for `opacity` it is, but Chrome does not
* synthesise one for border widths: a keyframe naming only `border-top-width: 0` leaves
* the border sitting at its authored width for the whole animation. Hence the four
* variables, which the component measures off the root and writes back. They are outputs,
* not knobs — the `0px` fallbacks only stand in for the frame before the first
* measurement lands, and a root with no border or padding animates 0 to 0 for free.
*
* Padding collapses cleanly, sub-pixel and all the way down. A border does not: Chrome
* renders any width between 0 and 1px as a full hairline, so a 1px border reads as 1px
* for the entire close and only disappears on the final frame. That is enough to keep the
* last frame honest, but a bordered root still hits a 2px floor slightly before the
* animation ends and holds it for a few frames. There is no CSS answer to that, so the
* rule is: keep borders on the content, and let this root be the thing that clips it.
*/
@keyframes kida-collapse-open {
from {
height: 0;
padding-top: 0;
padding-bottom: 0;
border-top-width: 0;
border-bottom-width: 0;
}
to {
height: var(--kida-collapse-height);
padding-top: var(--kida-collapse-padding-top, 0px);
padding-bottom: var(--kida-collapse-padding-bottom, 0px);
border-top-width: var(--kida-collapse-border-top-width, 0px);
border-bottom-width: var(--kida-collapse-border-bottom-width, 0px);
}
}
@keyframes kida-collapse-close {
from {
height: var(--kida-collapse-height);
padding-top: var(--kida-collapse-padding-top, 0px);
padding-bottom: var(--kida-collapse-padding-bottom, 0px);
border-top-width: var(--kida-collapse-border-top-width, 0px);
border-bottom-width: var(--kida-collapse-border-bottom-width, 0px);
}
to {
height: 0;
padding-top: 0;
padding-bottom: 0;
border-top-width: 0;
border-bottom-width: 0;
}
}src/components/ui/kida/tokens.css
/*
* Kida UI — motion tokens.
* Plain CSS custom properties (ADR D7). No preprocessor, no Tailwind, no build step.
*/
:root {
/* Durations */
--kida-duration-xs: 100ms;
--kida-duration-sm: 150ms;
--kida-duration-md: 300ms;
--kida-duration-lg: 500ms;
--kida-duration-xl: 800ms;
/* Easings */
--kida-ease-out: cubic-bezier(0.16, 1, 0.3, 1);
--kida-ease-in: cubic-bezier(0.7, 0, 0.84, 0);
--kida-ease-in-out: cubic-bezier(0.65, 0, 0.35, 1);
--kida-ease-spring: linear(0, 0.5, 0.9, 1.02, 1);
/* Travel distances used by the enter/exit keyframes */
--kida-distance-sm: 4px;
--kida-distance-md: 8px;
--kida-distance-lg: 16px;
/* Stagger step between siblings */
--kida-stagger: 60ms;
}
/*
* The shared reduced-motion guard for CSS-driven animation in the library.
* Durations collapse to ~0 by default. Components whose presence lifecycle cannot safely observe
* a 1ms animation, such as Collapse, disable it explicitly and complete presence in their adapter.
*/
@media (prefers-reduced-motion: reduce) {
:root {
--kida-duration-xs: 1ms;
--kida-duration-sm: 1ms;
--kida-duration-md: 1ms;
--kida-duration-lg: 1ms;
--kida-duration-xl: 1ms;
--kida-distance-sm: 0px;
--kida-distance-md: 0px;
--kida-distance-lg: 0px;
--kida-stagger: 0ms;
}
}<script setup lang="ts">
import { ref, useId } from 'vue'
import Collapse from '@/components/ui/kida/collapse.vue'
const open = ref(false)
const panelId = useId()
</script>
<template>
<div>
<button type="button" :aria-expanded="open" :aria-controls="open ? panelId : undefined" @click="open = !open">
{{ open ? 'Hide details' : 'Show details' }}
</button>
<Collapse :id="panelId" :open="open"><div>Anything at all.</div></Collapse>
</div>
</template>The copy-source command includes the required styles.
API
Props
| Prop | Type | Default | Description |
|---|---|---|---|
open |
boolean |
— | Whether the content is shown. |
@exit-complete |
() => void |
— | Fires after the exit animation ends and the node is removed. |
class |
Vue class binding | — | Applied to the collapsing root. |
style |
Vue style binding | — | Applied to the collapsing root. |
Native div attributes, class, style, and events apply to the collapsing root. A component ref
exposes element, which becomes null after the exit animation finishes and the panel unmounts.
CSS custom properties
| Property | Default | Description |
|---|---|---|
--kida-collapse-duration |
--kida-duration-md |
Applies to both directions. |
--kida-collapse-ease |
--kida-ease-out opening, --kida-ease-in-out closing |
Easing for each direction. |
Customization
Set --kida-collapse-duration or --kida-collapse-ease on the Collapse root through a class or
the style prop. Put visual borders, backgrounds, and padding on the inner content so the root can
shrink cleanly to zero.
Accessibility and input behavior
Collapse preserves its children’s semantics and focus behavior while open. When reduced motion is
requested, the transition is skipped while still unmounting the panel and emitting
exit-complete.
Troubleshooting
Put borders and padding on the content inside Collapse, not on its root. The root needs to shrink cleanly to zero while it clips the panel.
The required CSS is included by the copy-source command. After npm publication, package consumers must
import @kida-ui/styles/kida.css once in your application.