<!-- Source: https://motion.svelte.page/examples/use-presence -->

# usePresence

> Custom exit animations from inside the child. PresenceChild holds the component rendered until your safeToRemove() fires.

**Source:** [https://motion.svelte.page/examples/use-presence](https://motion.svelte.page/examples/use-presence)

**Markdown mirror:** [https://motion.svelte.page/examples/use-presence.md](https://motion.svelte.page/examples/use-presence.md)

---

This mirror preserves the prose, implementation notes, and runnable Svelte source behind the live example page.

## FIG-001: custom exit via usePresence.

`<PresenceChild present={…}>` keeps the card rendered after `present` flips false. Inside, `usePresence` hands the card a `safeToRemove` callback — the card runs its own CSS transition and releases the wrapper on `transitionend`.

**Metadata:** tag: `ANIMATE-PRESENCE` | pattern: `PresenceChild + safeToRemove`

### Notes

- `PresenceChild` holds the child rendered while the surrounding `AnimatePresence` is exiting it. The card stays in the DOM with `isPresent === false` until `safeToRemove()` fires.
- Inside the card, `const presence = usePresence()` (called once) registers the card with its wrapper and returns `[isPresent, safeToRemove]` reactively. The effect listens for `transitionend` on the card node and calls `safeToRemove` once the CSS transition completes — fully custom exit under the component's own control.
- Re-entering (clicking Show mid-exit) cancels the hold; the stale `safeToRemove` becomes a no-op so a late `transitionend` can't tear down a now-present card. `onExitComplete` on the parent tallies finished exits.

### Source

#### Default.svelte

Source file: [src/lib/examples/use-presence/demos/Default.svelte](https://github.com/humanspeak/svelte-motion/blob/main/docs/src/lib/examples/use-presence/demos/Default.svelte)

```svelte
<script lang="ts">
    import { AnimatePresence, PresenceChild, motion, styleString } from '@humanspeak/svelte-motion'
    import { onMount } from 'svelte'
    import UsePresenceCard from './UsePresenceCard.svelte'

    // Custom exit driven from the child: `<PresenceChild present={…}>` holds the
    // card rendered after `present` flips to `false`. Inside the card, `usePresence`
    // returns `[false, safeToRemove]` once the hold begins — the card runs its own
    // CSS transition and calls `safeToRemove()` on `transitionend` so the wrapper
    // releases it.
    let visible = $state(true)
    let exitsCompleted = $state(0)

    // Defer the AnimatePresence subtree until after hydration — SSR doesn't have a
    // window to register presence children against.
    let mounted = $state(false)
    onMount(() => (mounted = true))
</script>

<!-- dk-strip: docs-kit positioning shell — stripped from the published code. -->
<div class="dk-demo-shell">
    <div class="strip">
        <div class="strip-head">
            <span class="micro">// use-presence</span>
            <span class="micro state">
                exits: {String(exitsCompleted).padStart(2, '0')}
            </span>
        </div>

        <div class="stage">
            {#if mounted}
                <AnimatePresence onExitComplete={() => exitsCompleted++}>
                    <PresenceChild present={visible}>
                        <UsePresenceCard />
                    </PresenceChild>
                </AnimatePresence>
            {/if}
        </div>

        <div class="strip-foot">
            <motion.button
                type="button"
                onclick={() => (visible = !visible)}
                whileHover={{ scale: 1.04 }}
                whileTap={{ scale: 0.96 }}
                transition={{ type: 'spring', stiffness: 500, damping: 30 }}
                style={styleString(() => ({
                    fontFamily: 'var(--brut-mono, monospace)',
                    fontSize: '0.6875rem',
                    textTransform: 'uppercase',
                    letterSpacing: '0.08em',
                    border: '1px solid var(--brut-accent, #247768)',
                    backgroundColor: 'var(--brut-accent-soft, rgba(36, 119, 104, 0.1))',
                    color: 'var(--brut-accent, #247768)',
                    padding: '0.5rem 0.875rem',
                    cursor: 'pointer'
                }))}
            >
                {visible ? '– hide card' : '+ show card'}
            </motion.button>
            <span class="micro">exit: css transition → safeToRemove()</span>
        </div>
    </div>
</div>

<style>
    .dk-demo-shell {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 1.5rem;
        min-height: 360px;
    }

    .strip {
        width: 100%;
        max-width: 420px;
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
    }

    .micro {
        font-family: var(--brut-mono, monospace);
        font-size: 0.6875rem;
        letter-spacing: 0.08em;
        text-transform: uppercase;
        color: var(--brut-ink-3, #9a9a9a);
    }

    .state {
        color: var(--brut-accent, #247768);
        font-variant-numeric: tabular-nums;
    }

    .strip-head,
    .strip-foot {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
        border-bottom: 1px dashed var(--brut-rule-2, #bbc4c0);
        padding-bottom: 0.5rem;
    }

    .strip-foot {
        border-bottom: none;
        border-top: 1px dashed var(--brut-rule-2, #bbc4c0);
        padding-top: 0.75rem;
        padding-bottom: 0;
    }

    .stage {
        height: 8rem;
        display: flex;
        align-items: center;
        justify-content: center;
    }
</style>
```

#### UsePresenceCard.svelte

Source file: [src/lib/examples/use-presence/demos/UsePresenceCard.svelte](https://github.com/humanspeak/svelte-motion/blob/main/docs/src/lib/examples/use-presence/demos/UsePresenceCard.svelte)

```svelte
<script lang="ts">
    import { usePresence } from '@humanspeak/svelte-motion'

    const presence = usePresence()
    const isPresent = $derived(presence[0])
    let node: HTMLElement | undefined = $state()

    $effect(() => {
        const [present, safeToRemove] = presence
        if (present || !node || !safeToRemove) return
        const el = node
        const onEnd = (e: TransitionEvent) => {
            if (e.target !== el) return
            safeToRemove()
        }
        el.addEventListener('transitionend', onEnd, { once: true })
        return () => el.removeEventListener('transitionend', onEnd)
    })
</script>

<div bind:this={node} class="card" class:exiting={!isPresent} data-is-present={isPresent}>
    <span class="card-label">// usePresence()</span>
    <strong class="card-value">{isPresent ? 'present' : 'exiting'}</strong>
</div>

<style>
    /* The exit is driven by THIS CSS transition — `usePresence` hands back
       `safeToRemove`, which the card calls on `transitionend`. Keep the
       transition intact; it is the API being demonstrated. */
    .card {
        width: 220px;
        display: flex;
        flex-direction: column;
        gap: 0.375rem;
        padding: 1rem 1.125rem;
        border: 1px solid var(--brut-ink, #0a0a0a);
        background: var(--brut-bg-2, #eef4f1);
        box-shadow: 6px 6px 0 var(--brut-rule, #d6dedb);
        opacity: 1;
        transform: translateY(0);
        transition:
            opacity 300ms ease,
            transform 300ms ease;
    }

    .card.exiting {
        opacity: 0;
        transform: translateY(-12px);
    }

    .card-label {
        font-family: var(--brut-mono, monospace);
        font-size: 0.625rem;
        letter-spacing: 0.08em;
        text-transform: uppercase;
        color: var(--brut-ink-3, #9a9a9a);
    }

    .card-value {
        font-family: var(--brut-mono, monospace);
        font-size: 0.875rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.04em;
        color: var(--brut-accent, #247768);
    }
</style>
```

## FIG-002: wait for every exit.

Independent motion descendants share one owned wrapper. The fast exit finishes first; removal waits for the slow exit too.

**Metadata:** tag: `OWNED-GROUP` | pattern: `owned group + automatic completion`

### Source

#### OwnedGroup.svelte

Source file: [src/lib/examples/use-presence/demos/OwnedGroup.svelte](https://github.com/humanspeak/svelte-motion/blob/main/docs/src/lib/examples/use-presence/demos/OwnedGroup.svelte)

```svelte
<script lang="ts">
    import {
        AnimatePresence,
        motion,
        useMotionValue,
        useReducedMotion
    } from '@humanspeak/svelte-motion'
    import { onMount } from 'svelte'

    const reduced = useReducedMotion()
    let mounted = $state(false)
    onMount(() => (mounted = true))
    let present = $state(true)
    let generation = $state(0)
    let exitCycle = 0
    let exitLabel = $state('exit-0')
    let groupNode = $state<HTMLDivElement>()
    let completions = $state(0)
    let fast = $state('ready')
    let slow = $state('ready')
    const fastX = useMotionValue(0)
    const slowX = useMotionValue(0)
    const fastProgress = $derived(fast === 'finished' ? 100 : present ? 0 : progress(fastX.current))
    const slowProgress = $derived(slow === 'finished' ? 100 : present ? 0 : progress(slowX.current))

    function show() {
        present = true
        fast = slow = 'ready'
    }

    function hide() {
        exitLabel = `exit-${++exitCycle}`
        fast = slow = 'exiting'
        present = false
    }

    function reset() {
        show()
        generation += 1
        fastX.jump(0)
        slowX.jump(0)
        completions = 0
    }

    function progress(x: number) {
        return Math.round(Math.max(0, Math.min(100, x)))
    }
</script>

<div class="group-demo">
    <p>
        Click <strong>Hide group</strong>. Fast finishes first; the wrapper stays mounted while Slow
        finishes. Both are removed together. Show during exit to cancel, or Reset to start over.
    </p>
    <div class="controls">
        <button type="button" data-testid="group-hide" onclick={hide} disabled={!present}
            >Hide group</button
        >
        <button type="button" data-testid="group-show" onclick={show} disabled={present}
            >Show group</button
        >
        <button type="button" data-testid="group-reset" onclick={reset}>Reset</button>
    </div>
    <dl class="metrics" aria-live="polite">
        <div>
            <dt>Fast · {reduced.current ? 'instant' : '0.6 s'}</dt>
            <dd data-testid="group-fast-state">{fast}</dd>
        </div>
        <div>
            <dt>Slow · {reduced.current ? 'instant' : '2.4 s'}</dt>
            <dd data-testid="group-slow-state">{slow}</dd>
        </div>
        <div>
            <dt>Wrapper</dt>
            <dd data-testid="group-mounted">{groupNode ? 'mounted' : 'removed'}</dd>
        </div>
        <div>
            <dt>Completed groups</dt>
            <dd data-testid="group-completions">{completions}</dd>
        </div>
    </dl>
    <div class="stage">
        {#if mounted}
            {#key generation}
                <AnimatePresence
                    {present}
                    onExitComplete={() => {
                        if (!present) {
                            completions += 1
                            fast = slow = 'finished'
                        }
                    }}
                >
                    {#snippet child()}
                        <div bind:this={groupNode} class="cards" data-testid="owned-group-wrapper">
                            <motion.div
                                data-testid="group-fast-card"
                                initial={false}
                                animate="visible"
                                exit={exitLabel}
                                variants={{
                                    visible: { opacity: 1, x: 0 },
                                    [exitLabel]: { opacity: 0.15, x: reduced.current ? 0 : 100 }
                                }}
                                transition={{
                                    duration: reduced.current ? 0 : 0.6,
                                    ease: 'linear'
                                }}
                                onAnimationComplete={(definition) => {
                                    if (!present && (definition as unknown) === exitLabel) {
                                        fast = 'finished'
                                    }
                                }}
                                style={{
                                    x: fastX,
                                    padding: '18px',
                                    borderRadius: '8px',
                                    background: 'var(--brut-accent, #247768)',
                                    color: 'white'
                                }}>Fast exit</motion.div
                            >
                            <motion.div
                                data-testid="group-slow-card"
                                initial={false}
                                animate="visible"
                                exit={exitLabel}
                                variants={{
                                    visible: { opacity: 1, x: 0 },
                                    [exitLabel]: { opacity: 0.15, x: reduced.current ? 0 : 100 }
                                }}
                                transition={{
                                    duration: reduced.current ? 0 : 2.4,
                                    ease: 'linear'
                                }}
                                onAnimationComplete={(definition) => {
                                    if (!present && (definition as unknown) === exitLabel) {
                                        slow = 'finished'
                                    }
                                }}
                                style={{
                                    x: slowX,
                                    padding: '18px',
                                    borderRadius: '8px',
                                    background: 'var(--brut-ink, #222)',
                                    color: 'white'
                                }}>Slow exit</motion.div
                            >
                        </div>
                    {/snippet}
                </AnimatePresence>
            {/key}
        {/if}
    </div>
    <div class="progress">
        <label>Fast <progress max="100" value={fastProgress}></progress> {fastProgress}%</label>
        <label>Slow <progress max="100" value={slowProgress}></progress> {slowProgress}%</label>
    </div>
    <p class="note">
        Progress follows the animated position. Completion states come from animation callbacks; the
        mounted state follows the actual wrapper.
    </p>
</div>

<style>
    .group-demo {
        width: 100%;
        max-width: 640px;
        margin: auto;
        padding: 24px;
        color: var(--brut-ink, #222);
    }
    p {
        line-height: 1.6;
        margin: 0 0 16px;
    }
    .controls {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 20px;
    }
    button {
        font: inherit;
        padding: 8px 12px;
        border-radius: 6px;
        border: 1px solid var(--brut-rule-2, #bbc4c0);
        background: var(--brut-accent-soft, #edf6f3);
        color: inherit;
        cursor: pointer;
    }
    button:disabled {
        opacity: 0.45;
        cursor: default;
    }
    .metrics {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
        margin: 0 0 20px;
    }
    .metrics div {
        padding: 12px;
        border: 1px solid var(--brut-rule-2, #bbc4c0);
        border-radius: 6px;
    }
    dt {
        font-size: 12px;
        opacity: 0.7;
    }
    dd {
        margin: 6px 0 0;
        font-weight: 600;
    }
    .stage {
        min-height: 152px;
        overflow: hidden;
    }
    .cards {
        display: grid;
        gap: 12px;
        padding-right: 100px;
    }
    .progress {
        display: grid;
        gap: 10px;
        margin: 16px 0;
    }
    label {
        display: flex;
        align-items: center;
        gap: 10px;
        font-variant-numeric: tabular-nums;
    }
    progress {
        flex: 1;
        min-width: 0;
        accent-color: var(--brut-accent, #247768);
    }
    .note {
        font-size: 12px;
        opacity: 0.7;
    }
</style>
```
