Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/presence-zero-duration-exit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@solid-primitives/presence": patch
---

Unmount timer-only zero-duration exits in the same reactive flush instead of deferring with `setTimeout(..., 0)`
67 changes: 46 additions & 21 deletions packages/presence/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ function createPresenceBase(
/** Indicates whether the component that the resulting values will be used upon should be visible to the user. */
source: Accessor<boolean>,
options: Options,
/** Called from the exit timer, right after it has written that the exit is over (`isMounted` turns false). */
/** Called when an exit completes. */
onExited?: VoidFunction,
) {
const exitDuration = asAccessor(
Expand All @@ -132,54 +132,79 @@ function createPresenceBase(
const initialSource = untrack(source);
const initialState = options.initialEnter ? false : initialSource;

// Everything below is derived from `source`, except the time-driven facts ("the exit finished",
// Everything below is derived from `source`, except the time-driven facts ("a timed exit finished",
// "the next frame arrived", "the enter timer fired"). Those can only be learned from a timer or
// an animation frame, so they are written from those callbacks and nowhere else.
//
// `generation` counts the changes of `source`, and each time-driven fact records the generation
// `transition` counts the changes of `source`, and each time-driven fact records the generation
// it was reached in. Any later change of `source` therefore invalidates it without anything
// having to reset it, so no effect has to copy `source` into other signals (which Solid 2
// reports as EFFECT_RELAY_TEAR: the first frame would show the new `source` with stale state).
const generation = createMemo<number>(previous => {
source();
return (previous ?? -1) + 1;
});
const transition = createMemo<{ generation: number; timerExitDuration: number | undefined }>(
previous => {
const shouldMount = source();
const generation = (previous?.generation ?? -1) + 1;
// Sample timer-only exits at the source change so later duration updates cannot affect them.
const timerExitDuration =
shouldMount || generation === 0
? undefined
: untrack(() => (options.animations ? undefined : exitDuration()));
return { generation, timerExitDuration };
},
);
const generation = () => transition().generation;
// Written from timer / animation frame callbacks only, which run outside any owner, so these
// deliberately do not opt in to `ownedWrite`: a write from an owned scope should still be flagged.
const [exitedIn, setExitedIn] = createSignal<number>(0);
const [visibleIn, setVisibleIn] = createSignal<number>(initialState ? 0 : -1);
const [enteredIn, setEnteredIn] = createSignal<number>(initialState ? 0 : -1);

const isMounted = createMemo(() => source() || exitedIn() !== generation());
const isImmediateExit = (duration: number | undefined) => duration !== undefined && duration <= 0;
const isMounted = createMemo(() => {
if (source()) return true;
const { generation, timerExitDuration } = transition();
return !isImmediateExit(timerExitDuration) && exitedIn() !== generation;
});
const isVisible = createMemo(() => source() && visibleIn() === generation());
const hasEntered = createMemo(() => source() && enteredIn() === generation());

const isExiting = createMemo(() => isMounted() && !source());
const isEntering = createMemo(() => source() && !hasEntered());
const isAnimating = createMemo(() => isEntering() || isExiting());

// A timer and done() can both complete before the signal write commits.
let finishedExitIn = 0;
const finishExit = (generation: number) => {
if (finishedExitIn === generation) return;
finishedExitIn = generation;
setExitedIn(generation);
onExited?.();
};

// Exit: unmount once the exit duration is over, unless `source` came back in the meantime.
createEffect(
() => (source() ? undefined : generation()),
exitingIn => {
if (exitingIn === undefined) return;
const finishExit = () => {
if (untrack(exitedIn) === exitingIn) return;
setExitedIn(exitingIn);
() => (source() ? undefined : transition()),
exit => {
if (!exit || exit.generation === 0) return;
const { generation, timerExitDuration } = exit;
if (isImmediateExit(timerExitDuration)) {
// The derived state has already unmounted. Notify without writing a signal in the effect.
onExited?.();
};
return;
}
const el = observableElement();
const duration = timerExitDuration ?? untrack(exitDuration);
if (el) {
// Cleanup runs when `source` comes back (or on dispose), which cancels the wait.
let cancelled = false;
settleAnimations(el, () => cancelled, exitDuration()).then(
() => !cancelled && finishExit(),
settleAnimations(el, () => cancelled, duration).then(
() => !cancelled && finishExit(generation),
);
return () => {
cancelled = true;
};
}
const timeoutId = setTimeout(finishExit, exitDuration());
const timeoutId = setTimeout(() => finishExit(generation), duration);
return () => clearTimeout(timeoutId);
},
);
Expand Down Expand Up @@ -236,9 +261,8 @@ function createPresenceBase(
if (untrack(hasEntered)) return;
setVisibleIn(current);
setEnteredIn(current);
} else if (untrack(exitedIn) !== current) {
setExitedIn(current);
onExited?.();
} else if (untrack(isMounted)) {
finishExit(current);
}
};

Expand Down Expand Up @@ -332,6 +356,7 @@ export type PresenceResult<TItem> = {

/**
* Utility to animate the presence of an element based on the existence of data or lack thereof.
* Timer-only exits with a nonpositive duration unmount in the same reactive flush.
*
* @param item a reactive value driving the transition
* @param options options to configure the transition, see {@link Options}
Expand Down
Loading