@krate/motion 0.0.0-bootstrap.0 → 0.5.0-rc.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,229 @@
1
+ // Gesture helpers: hover() and press() filter touch-emulated and secondary
2
+ // pointers and interoperate with drag; inView() wraps IntersectionObserver.
3
+ // Ported from motion-dom and framer-motion (MIT, Copyright (c) 2018 Framer
4
+ // B.V.), see NOTICE.
5
+
6
+ export type ElementOrSelector = Element | Element[] | NodeListOf<Element> | string;
7
+
8
+ export interface EventInfo {
9
+ point: { x: number; y: number };
10
+ }
11
+
12
+ export const isDragging = { x: false, y: false };
13
+ export const isDragActive = (): boolean => isDragging.x || isDragging.y;
14
+
15
+ /** Claims the drag lock for an axis (or both); returns the release, or null when taken. */
16
+ export function setDragLock(axis: boolean | 'x' | 'y' | 'lockDirection' | undefined): (() => void) | null {
17
+ if (axis === 'x' || axis === 'y') {
18
+ if (isDragging[axis]) return null;
19
+ isDragging[axis] = true;
20
+ return () => {
21
+ isDragging[axis] = false;
22
+ };
23
+ }
24
+ if (isDragging.x || isDragging.y) return null;
25
+ isDragging.x = isDragging.y = true;
26
+ return () => {
27
+ isDragging.x = isDragging.y = false;
28
+ };
29
+ }
30
+
31
+ export function resolveElements(target: ElementOrSelector | EventTarget, scope?: { current: Element | null }, cache?: Record<string, NodeListOf<Element>>): Element[] {
32
+ if ((typeof EventTarget !== 'undefined' && target instanceof EventTarget) || typeof (target as EventTarget).addEventListener === 'function') return [target as Element];
33
+ if (typeof target === 'string') {
34
+ const root: ParentNode = scope && scope.current ? scope.current : document;
35
+ const els = cache?.[target] ?? root.querySelectorAll(target);
36
+ return els ? Array.from(els) : [];
37
+ }
38
+ return Array.from(target as ArrayLike<Element>);
39
+ }
40
+
41
+ export const isPrimaryPointer = (e: PointerEvent | MouseEvent): boolean => {
42
+ if ((e as PointerEvent).pointerType === 'mouse') return typeof e.button !== 'number' || e.button <= 0;
43
+ return (e as PointerEvent).isPrimary !== false;
44
+ };
45
+
46
+ export function extractEventInfo(e: PointerEvent | MouseEvent): EventInfo {
47
+ // Page coordinates; environments without pageX (DOM emulations) derive them.
48
+ const sx = typeof window !== 'undefined' ? window.scrollX || 0 : 0;
49
+ const sy = typeof window !== 'undefined' ? window.scrollY || 0 : 0;
50
+ const x = e.pageX || (e.clientX ? e.clientX + sx : 0);
51
+ const y = e.pageY || (e.clientY ? e.clientY + sy : 0);
52
+ return { point: { x, y } };
53
+ }
54
+
55
+ export function addDomEvent(target: EventTarget, name: string, handler: EventListener, options: AddEventListenerOptions = { passive: true }): () => void {
56
+ target.addEventListener(name, handler, options);
57
+ return () => target.removeEventListener(name, handler);
58
+ }
59
+
60
+ export function addPointerEvent(target: EventTarget, name: string, handler: (e: PointerEvent, info: EventInfo) => void, options?: AddEventListenerOptions): () => void {
61
+ return addDomEvent(target, name, ((e: PointerEvent) => isPrimaryPointer(e) && handler(e, extractEventInfo(e))) as EventListener, options);
62
+ }
63
+
64
+ function setupGesture(target: ElementOrSelector, options: AddEventListenerOptions): [Element[], AddEventListenerOptions, () => void] {
65
+ const elements = resolveElements(target);
66
+ const ctrl = new AbortController();
67
+ return [elements, { passive: true, ...options, signal: ctrl.signal }, () => ctrl.abort()];
68
+ }
69
+
70
+ /** Calls onHoverStart when a (non-touch) pointer enters; the function it returns runs on leave. */
71
+ export function hover(
72
+ target: ElementOrSelector,
73
+ onHoverStart: (el: Element, e: PointerEvent) => void | ((e: PointerEvent) => void),
74
+ options: AddEventListenerOptions = {},
75
+ ): () => void {
76
+ const [elements, eventOptions, cancel] = setupGesture(target, options);
77
+ const valid = (e: PointerEvent): boolean => !(e.pointerType === 'touch' || isDragActive());
78
+ const onEnter = (enter: Event): void => {
79
+ const e = enter as PointerEvent;
80
+ if (!valid(e)) return;
81
+ const el = e.currentTarget as Element;
82
+ const onEnd = onHoverStart(el, e);
83
+ if (typeof onEnd !== 'function' || !el) return;
84
+ const onLeave = (leave: Event): void => {
85
+ if (!valid(leave as PointerEvent)) return;
86
+ onEnd(leave as PointerEvent);
87
+ el.removeEventListener('pointerleave', onLeave);
88
+ };
89
+ el.addEventListener('pointerleave', onLeave, eventOptions);
90
+ };
91
+ for (const el of elements) el.addEventListener('pointerenter', onEnter, eventOptions);
92
+ return cancel;
93
+ }
94
+
95
+ const isPressing = new WeakSet<EventTarget>();
96
+ const keyboardFocusable = new Set(['BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'A']);
97
+
98
+ const isNodeOrChild = (parent: Element, child: Element | null): boolean => {
99
+ for (let n: Element | null = child; n; n = n.parentElement) if (n === parent) return true;
100
+ return false;
101
+ };
102
+
103
+ function firePointerEvent(target: Element, type: string): void {
104
+ const Ctor: typeof PointerEvent = typeof PointerEvent !== 'undefined' ? PointerEvent : (MouseEvent as any);
105
+ target.dispatchEvent(new Ctor('pointer' + type, { isPrimary: true, bubbles: true } as PointerEventInit));
106
+ }
107
+
108
+ function enableKeyboardPress(focus: Event, options: AddEventListenerOptions): void {
109
+ const el = focus.currentTarget as Element | null;
110
+ if (!el) return;
111
+ const onKeyDown = (e: Event): void => {
112
+ if ((e as KeyboardEvent).key !== 'Enter' || isPressing.has(el)) return;
113
+ firePointerEvent(el, 'down');
114
+ const onKeyUp = (u: Event): void => {
115
+ if ((u as KeyboardEvent).key === 'Enter') firePointerEvent(el, 'up');
116
+ };
117
+ el.addEventListener('keyup', onKeyUp, options);
118
+ el.addEventListener('blur', () => firePointerEvent(el, 'cancel'), options);
119
+ };
120
+ el.addEventListener('keydown', onKeyDown, options);
121
+ el.addEventListener('blur', () => el.removeEventListener('keydown', onKeyDown), options);
122
+ }
123
+
124
+ export interface PressOptions extends AddEventListenerOptions {
125
+ useGlobalTarget?: boolean;
126
+ }
127
+
128
+ /**
129
+ * Calls onPressStart on a primary pointer down (or Enter on a focused
130
+ * element); the function it returns runs on release with `success` when the
131
+ * pointer was released over the element.
132
+ */
133
+ export function press(
134
+ target: ElementOrSelector,
135
+ onPressStart: (el: Element, e: PointerEvent) => void | ((e: PointerEvent, info: { success: boolean }) => void),
136
+ options: PressOptions = {},
137
+ ): () => void {
138
+ const [targets, eventOptions, cancel] = setupGesture(target, options);
139
+ const valid = (e: PointerEvent): boolean => isPrimaryPointer(e) && !isDragActive();
140
+ const start = (startEvent: Event): void => {
141
+ const e = startEvent as PointerEvent;
142
+ const el = e.currentTarget as Element;
143
+ if (!valid(e)) return;
144
+ isPressing.add(el);
145
+ const onEnd = onPressStart(el, e);
146
+ const end = (endEvent: PointerEvent, success: boolean): void => {
147
+ window.removeEventListener('pointerup', onUp);
148
+ window.removeEventListener('pointercancel', onCancel);
149
+ isPressing.delete(el);
150
+ if (!valid(endEvent)) return;
151
+ if (typeof onEnd === 'function') onEnd(endEvent, { success });
152
+ };
153
+ const onUp = (up: Event): void =>
154
+ end(up as PointerEvent, (el as unknown) === window || (el as unknown) === document || !!options.useGlobalTarget || isNodeOrChild(el, up.target as Element));
155
+ const onCancel = (c: Event): void => end(c as PointerEvent, false);
156
+ window.addEventListener('pointerup', onUp, eventOptions);
157
+ window.addEventListener('pointercancel', onCancel, eventOptions);
158
+ };
159
+ for (const t of targets) {
160
+ const downTarget: EventTarget = options.useGlobalTarget ? window : t;
161
+ downTarget.addEventListener('pointerdown', start, eventOptions);
162
+ if (t instanceof HTMLElement) {
163
+ t.addEventListener('focus', (e) => enableKeyboardPress(e, eventOptions), eventOptions);
164
+ if (!keyboardFocusable.has(t.tagName) && t.tabIndex === -1 && !t.hasAttribute('tabindex')) t.tabIndex = 0;
165
+ }
166
+ }
167
+ return cancel;
168
+ }
169
+
170
+ export interface InViewOptions {
171
+ root?: Element | Document;
172
+ margin?: string;
173
+ amount?: 'some' | 'all' | number;
174
+ }
175
+
176
+ const thresholds = { some: 0, all: 1 };
177
+
178
+ /** Calls onStart when an element enters the viewport; the function it returns runs when it leaves. */
179
+ export function inView(
180
+ target: ElementOrSelector,
181
+ onStart: (el: Element, entry: IntersectionObserverEntry) => void | ((entry: IntersectionObserverEntry) => void),
182
+ { root, margin: rootMargin, amount = 'some' }: InViewOptions = {},
183
+ ): () => void {
184
+ const elements = resolveElements(target);
185
+ const active = new WeakMap<Element, (entry: IntersectionObserverEntry) => void>();
186
+ const observer = new IntersectionObserver(
187
+ (entries) => {
188
+ for (const entry of entries) {
189
+ const onEnd = active.get(entry.target);
190
+ if (entry.isIntersecting === Boolean(onEnd)) continue;
191
+ if (entry.isIntersecting) {
192
+ const next = onStart(entry.target, entry);
193
+ if (typeof next === 'function') active.set(entry.target, next);
194
+ else observer.unobserve(entry.target);
195
+ } else if (typeof onEnd === 'function') {
196
+ onEnd(entry);
197
+ active.delete(entry.target);
198
+ }
199
+ }
200
+ },
201
+ { root: root as Element | Document | null | undefined, rootMargin, threshold: typeof amount === 'number' ? amount : thresholds[amount] },
202
+ );
203
+ for (const el of elements) observer.observe(el);
204
+ return () => observer.disconnect();
205
+ }
206
+
207
+ const observerCallbacks = new WeakMap<Element, (entry: IntersectionObserverEntry) => void>();
208
+ const observers = new WeakMap<Element | Document, Record<string, IntersectionObserver>>();
209
+
210
+ /** One shared IntersectionObserver per root and options for whileInView. */
211
+ export function observeIntersection(el: Element, options: IntersectionObserverInit, cb: (entry: IntersectionObserverEntry) => void): () => void {
212
+ const lookup = (options.root as Element | Document) || document;
213
+ let byKey = observers.get(lookup);
214
+ if (!byKey) observers.set(lookup, (byKey = {}));
215
+ const { root: _r, ...rest } = options;
216
+ const key = JSON.stringify(rest);
217
+ if (!byKey[key]) {
218
+ byKey[key] = new IntersectionObserver((entries) => {
219
+ for (const entry of entries) observerCallbacks.get(entry.target)?.(entry);
220
+ }, options);
221
+ }
222
+ const observer = byKey[key];
223
+ observerCallbacks.set(el, cb);
224
+ observer.observe(el);
225
+ return () => {
226
+ observerCallbacks.delete(el);
227
+ observer.unobserve(el);
228
+ };
229
+ }
@@ -0,0 +1,22 @@
1
+ // @krate/motion/engine: the framework-free animation engine shared by the
2
+ // Krate build and the Preact island build of @krate/motion.
3
+
4
+ export * from './utils.js';
5
+ export * from './easing.js';
6
+ export * from './frameloop.js';
7
+ export * from './values.js';
8
+ export * from './generators.js';
9
+ export * from './motion-value.js';
10
+ export * from './animation.js';
11
+ export * from './render.js';
12
+ export * from './gestures.js';
13
+ export * from './node.js';
14
+ export * from './animate.js';
15
+ export * from './scroll.js';
16
+ export * from './scope.js';
17
+ export * from './factories.js';
18
+ export { __kmRef, __kmScope, flushMotionMounts, motionExitHook } from './krate.js';
19
+ export { rt, effect, setRef, installExitHook, type ExitHook } from './runtime.js';
20
+ export { motionNamespace, mNamespace } from './fallback.js';
21
+ export { createReorderGroup, checkReorder, type ReorderContext } from './reorder.js';
22
+ export { useInView, useCycle, createReducedMotion, motionValueSignal, type UseInViewOptions } from './signals.js';
@@ -0,0 +1,402 @@
1
+ // The Krate host. The compiler turns `<motion.div ...>` into a plain `<div>`
2
+ // whose server style is the initial state and whose ref is __kmRef(props):
3
+ // when the element is in the document the ref creates its MotionNode, links
4
+ // it to the nearest motion ancestor in the DOM, and re-applies the props
5
+ // whenever a signal they read changes (no re-render, no diff). Removal by a
6
+ // conditional or a list asks the runtime's exit hook, which keeps the element
7
+ // for its AnimatePresence exit animation.
8
+
9
+ import { frame } from './frameloop.js';
10
+ import { isForcedMotionValue, MotionNode, nodeStore, styleObject, type FeatureDefinition, type PresenceContext } from './node.js';
11
+ import { isMotionValue } from './motion-value.js';
12
+ import { setStyle } from './render.js';
13
+ import { warnOnce } from './utils.js';
14
+ import { effect, installExitHook, setRef, untrack } from './runtime.js';
15
+ import { batches, configFromScope, createScope, findScope, resolveScope, type Scope, type ScopeKind } from './scope.js';
16
+
17
+ export type PropsGetter = () => Record<string, any>;
18
+
19
+ interface Host {
20
+ el: HTMLElement | SVGElement;
21
+ getProps: PropsGetter;
22
+ scope: unknown;
23
+ tag: string;
24
+ features?: Record<string, FeatureDefinition | undefined>;
25
+ strictCheck: boolean;
26
+ node?: MotionNode;
27
+ dispose?: () => void;
28
+ presenceScope?: Scope | null;
29
+ exiting?: ExitRecord;
30
+ unmounted?: boolean;
31
+ waiting?: boolean;
32
+ pendingUnmount?: boolean;
33
+ /** The plain (non motion value) style last written. */
34
+ style?: Record<string, any>;
35
+ }
36
+
37
+ interface ExitRecord {
38
+ el: Element;
39
+ hosts: Host[];
40
+ done: () => void;
41
+ cancelled: boolean;
42
+ group: Scope | null;
43
+ restore?: () => void;
44
+ }
45
+
46
+ const hostOf = new WeakMap<Element, Host>();
47
+ let queue: Host[] = [];
48
+ let scheduled = false;
49
+
50
+ function presenceState(scope: Scope): { exiting: Set<ExitRecord>; waiting: Host[]; mounted: boolean } {
51
+ const st = scope.state;
52
+ st.exiting ??= new Set();
53
+ st.waiting ??= [];
54
+ return st as any;
55
+ }
56
+
57
+ function schedule(): void {
58
+ if (scheduled) return;
59
+ scheduled = true;
60
+ queueMicrotask(flush);
61
+ }
62
+
63
+ /** Mounts the queued elements: parents before children, then initial animations children first. */
64
+ function flush(): void {
65
+ scheduled = false;
66
+ const hosts = queue.filter((h) => !h.unmounted && h.el.isConnected);
67
+ queue = [];
68
+ if (!hosts.length) return;
69
+ hosts.sort((a, b) => (a.el === b.el ? 0 : a.el.compareDocumentPosition(b.el) & 4 ? -1 : 1));
70
+ const started: Host[] = [];
71
+ for (const h of hosts) if (create(h)) started.push(h);
72
+ for (let i = started.length - 1; i >= 0; i--) start(started[i]);
73
+ batches.current++;
74
+ batches.hydrated = true;
75
+ }
76
+
77
+ function parentNodeOf(el: Element): MotionNode | null {
78
+ for (let p = el.parentElement; p; p = p.parentElement) {
79
+ const n = nodeStore.get(p);
80
+ if (n) return n;
81
+ }
82
+ return null;
83
+ }
84
+
85
+ function presenceFor(h: Host, initial: boolean): PresenceContext | null {
86
+ const scope = h.presenceScope;
87
+ if (!scope) return null;
88
+ const props = scope.get() || {};
89
+ // initial={false} only holds for the children the AnimatePresence renders
90
+ // with itself: elements mounted in the batch that created it.
91
+ const first = scope.batch === batches.current || (scope.batch === 0 && !batches.hydrated);
92
+ return { isPresent: true, initial: initial && first ? props.initial : undefined, custom: props.custom };
93
+ }
94
+
95
+ function create(h: Host): boolean {
96
+ const scope = resolveScope(h.scope);
97
+ h.presenceScope = findScope(scope, 'presence');
98
+ if (h.strictCheck) {
99
+ const lazy = findScope(scope, 'lazy');
100
+ if (lazy && lazy.get().strict) {
101
+ throw new Error('@krate/motion: you have rendered a `motion` component within a `LazyMotion` component with strict mode. Use `m` instead.');
102
+ }
103
+ }
104
+ if (h.presenceScope) {
105
+ const st = presenceState(h.presenceScope);
106
+ const mode = (h.presenceScope.get() || {}).mode;
107
+ if (mode === 'wait' && st.exiting.size) {
108
+ // Enter after the exiting children have left.
109
+ h.waiting = true;
110
+ (h.el as HTMLElement).style.setProperty('display', 'none');
111
+ st.waiting.push(h);
112
+ return false;
113
+ }
114
+ }
115
+ const config = configFromScope(scope);
116
+ bindProps(h, config);
117
+ return true;
118
+ }
119
+
120
+ /** Creates the node on the first run of the props effect, then re-applies props when they change. */
121
+ function bindProps(h: Host, config: Record<string, any>): void {
122
+ let first = !h.node;
123
+ let skip = !first;
124
+ h.dispose = effect(() => {
125
+ const props = h.getProps();
126
+ if (skip) {
127
+ // A rebind after a remount: the node already has these props.
128
+ skip = false;
129
+ untrack(() => h.node!.update(props, h.node!.presence));
130
+ return;
131
+ }
132
+ if (first) {
133
+ first = false;
134
+ untrack(() => {
135
+ const presence = presenceFor(h, true);
136
+ const parent = parentNodeOf(h.el);
137
+ const node = new MotionNode({
138
+ parent,
139
+ // Elements mounted together start like a React render: the parent
140
+ // runs the variant animations of its children.
141
+ manuallyAnimateOnMount: !!parent && parent.mountBatch !== batches.current,
142
+ props,
143
+ presence,
144
+ config,
145
+ blockInitialAnimation: presence?.initial === false,
146
+ tag: h.tag,
147
+ features: h.features,
148
+ });
149
+ h.node = node;
150
+ node.mountBatch = batches.current;
151
+ warnMissingFeatures(props, h.features);
152
+ h.style = styleObject(props.style);
153
+ node.mount(h.el);
154
+ node.render();
155
+ });
156
+ return;
157
+ }
158
+ untrack(() => {
159
+ const node = h.node!;
160
+ applyStyle(h, props.style, node);
161
+ node.update(props, node.presence);
162
+ node.updateFeatures();
163
+ void node.animationState.animateChanges();
164
+ });
165
+ });
166
+ }
167
+
168
+ const unitless = new Set(['animationIterationCount', 'aspectRatio', 'columnCount', 'columns', 'flex', 'flexGrow', 'flexShrink', 'fontWeight', 'gridArea', 'gridColumn', 'gridRow', 'lineClamp', 'lineHeight', 'opacity', 'order', 'orphans', 'scale', 'tabSize', 'widows', 'zIndex', 'zoom', 'fillOpacity', 'floodOpacity', 'stopOpacity', 'strokeDasharray', 'strokeDashoffset', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth']);
169
+
170
+ /**
171
+ * Writes the plain values of a changed style prop (the compiled style
172
+ * binding ran once, for the first render). Motion values and the values
173
+ * Motion animates are left to the node.
174
+ */
175
+ function applyStyle(h: Host, style: unknown, node: MotionNode): void {
176
+ const next = styleObject(style) || {};
177
+ const prev = h.style || {};
178
+ const el = h.el;
179
+ for (const key in next) {
180
+ const v = next[key];
181
+ if (isMotionValue(v) || isForcedMotionValue(key, node.props) || node.hasValue(key) || v === prev[key]) continue;
182
+ if (v == null || v === false || v === '') setStyle(el, key, '');
183
+ else setStyle(el, key, typeof v === 'number' && v !== 0 && !unitless.has(key) && !key.startsWith('--') ? v + 'px' : String(v));
184
+ }
185
+ for (const key in prev) {
186
+ if (next[key] === undefined && !isMotionValue(prev[key]) && !isForcedMotionValue(key, node.props) && !node.hasValue(key)) setStyle(el, key, '');
187
+ }
188
+ h.style = next;
189
+ }
190
+
191
+ const featureProps: Array<[string, string, (p: Record<string, any>) => boolean]> = [
192
+ ['drag', 'drag', (p) => !!(p.drag || p.dragControls || p.onPan || p.onPanStart || p.onPanEnd)],
193
+ ['layout', 'layout', (p) => !!(p.layout || p.layoutId !== undefined)],
194
+ ['hover', 'gesture', (p) => !!(p.whileHover || p.whileTap || p.whileFocus || p.whileInView || p.onHoverStart || p.onTap || p.onViewportEnter)],
195
+ ];
196
+
197
+ // The compiler loads a feature for the props it sees on the element; one that
198
+ // only arrives through a spread ({...props}) has no feature to run it.
199
+ function warnMissingFeatures(props: Record<string, any>, features: Record<string, unknown> | undefined): void {
200
+ for (const [key, name, uses] of featureProps) {
201
+ if (uses(props) && !(features && features[key])) {
202
+ warnOnce(false, `a motion element received ${name} props through a spread, so the compiler did not load the ${name} feature for it. Write one of those props on the element itself.`);
203
+ }
204
+ }
205
+ }
206
+
207
+ function start(h: Host): void {
208
+ const node = h.node;
209
+ if (!node || h.unmounted) return;
210
+ node.updateFeatures();
211
+ void node.animationState.animateChanges();
212
+ }
213
+
214
+ function unmountHost(h: Host): void {
215
+ if (h.unmounted) return;
216
+ h.unmounted = true;
217
+ h.dispose?.();
218
+ h.node?.unmount();
219
+ if (hostOf.get(h.el) === h) hostOf.delete(h.el);
220
+ }
221
+
222
+ /**
223
+ * The ref of a compiled motion element. `getProps` returns its Motion props
224
+ * (reading the signals they depend on); `userRef` is the element's own ref;
225
+ * `scope` the nearest AnimatePresence/MotionConfig/LayoutGroup/LazyMotion;
226
+ * `features` the drag/layout features its props use.
227
+ */
228
+ export function __kmRef(
229
+ getProps: PropsGetter,
230
+ userRef?: unknown,
231
+ scope?: unknown,
232
+ tag?: string,
233
+ features?: Array<Record<string, FeatureDefinition>>,
234
+ strict?: boolean,
235
+ ): (el: Element | null) => (() => void) | void {
236
+ installExitHook(exitHook);
237
+ let merged: Record<string, FeatureDefinition | undefined> | undefined;
238
+ if (features && features.length) {
239
+ merged = {};
240
+ for (const f of features) Object.assign(merged, f);
241
+ }
242
+ return (el) => {
243
+ if (!el) return;
244
+ const prev = hostOf.get(el);
245
+ if (prev && prev.exiting) {
246
+ // Shown again while leaving: the node stays and animates back in.
247
+ cancelExit(prev.exiting);
248
+ }
249
+ if (prev && !prev.unmounted) {
250
+ if (prev.getProps !== getProps && prev.node) {
251
+ // The component was mounted again around the same element (a
252
+ // conditional shown during the exit): read the new instance's props.
253
+ prev.dispose?.();
254
+ prev.getProps = getProps;
255
+ prev.scope = scope;
256
+ bindProps(prev, prev.node.config);
257
+ }
258
+ prev.pendingUnmount = false;
259
+ return detach(prev, setRef(userRef, el));
260
+ }
261
+ const h: Host = { el: el as HTMLElement, getProps, scope, tag: tag || el.localName, features: merged, strictCheck: !!strict };
262
+ hostOf.set(el, h);
263
+ queue.push(h);
264
+ schedule();
265
+ return detach(h, setRef(userRef, el));
266
+ };
267
+ }
268
+
269
+ /** The ref cleanup of a host: release the user's ref, then unmount unless it is leaving. */
270
+ function detach(h: Host, releaseUser: () => void): () => void {
271
+ return () => {
272
+ releaseUser();
273
+ if (h.exiting && !h.exiting.cancelled) return;
274
+ if (h.waiting && h.presenceScope) {
275
+ const st = presenceState(h.presenceScope);
276
+ st.waiting = st.waiting.filter((w) => w !== h);
277
+ }
278
+ if (h.presenceScope && h.node && h.el.isConnected) {
279
+ // A component unmounts before its conditional or list removes its
280
+ // element: wait a microtask, so the exit hook can still keep it.
281
+ h.pendingUnmount = true;
282
+ queueMicrotask(() => {
283
+ if (h.pendingUnmount && !h.exiting) unmountHost(h);
284
+ h.pendingUnmount = false;
285
+ });
286
+ return;
287
+ }
288
+ unmountHost(h);
289
+ };
290
+ }
291
+
292
+ /** Creates a provider scope (compiled code calls it at the top of the component that writes the provider). */
293
+ export function __kmScope(kind: ScopeKind, get: () => Record<string, any>, parent?: unknown): Scope {
294
+ return createScope(kind, get, parent);
295
+ }
296
+
297
+ function hostsIn(el: Element): Host[] {
298
+ const out: Host[] = [];
299
+ const self = hostOf.get(el);
300
+ if (self) out.push(self);
301
+ const all = el.getElementsByTagName('*');
302
+ for (let i = 0; i < all.length; i++) {
303
+ const h = hostOf.get(all[i]);
304
+ if (h) out.push(h);
305
+ }
306
+ return out;
307
+ }
308
+
309
+ function popLayout(el: HTMLElement): () => void {
310
+ const parent = el.offsetParent as HTMLElement | null;
311
+ const width = el.offsetWidth;
312
+ const height = el.offsetHeight;
313
+ const top = el.offsetTop;
314
+ const left = el.offsetLeft;
315
+ const keys = ['position', 'top', 'left', 'width', 'height'];
316
+ const prev = keys.map((k) => [el.style.getPropertyValue(k), el.style.getPropertyPriority(k)] as const);
317
+ el.style.setProperty('position', 'absolute', 'important');
318
+ el.style.setProperty('top', top + 'px', 'important');
319
+ el.style.setProperty('left', left + 'px', 'important');
320
+ el.style.setProperty('width', width + 'px', 'important');
321
+ el.style.setProperty('height', height + 'px', 'important');
322
+ void parent;
323
+ return () => keys.forEach((k, i) => el.style.setProperty(k, prev[i][0], prev[i][1]));
324
+ }
325
+
326
+ const exitHook = {
327
+ exit(el: Element, done: () => void): boolean {
328
+ const all = hostsIn(el);
329
+ // Already leaving (removed again by a later update): its first exit removes it.
330
+ if (all.some((h) => h.exiting && !h.exiting.cancelled && h.exiting.el === el)) return true;
331
+ const hosts = all.filter((h) => h.node && !h.unmounted && !h.exiting && h.presenceScope);
332
+ if (!hosts.length) return false;
333
+ // The outermost AnimatePresence in the removed subtree runs the exit;
334
+ // nested ones join when they set `propagate`.
335
+ const group = hosts[0].presenceScope!;
336
+ const exiting = hosts.filter((h) => h.presenceScope === group || !!(h.presenceScope!.get() || {}).propagate);
337
+ if (!exiting.length) return false;
338
+ const rec: ExitRecord = { el, hosts: exiting, done, cancelled: false, group };
339
+ const st = presenceState(group);
340
+ st.exiting.add(rec);
341
+ if ((group.get() || {}).mode === 'popLayout' && el instanceof HTMLElement) rec.restore = popLayout(el);
342
+ const custom = (group.get() || {}).custom;
343
+ const animations: Array<Promise<any>> = [];
344
+ for (const h of exiting) {
345
+ h.exiting = rec;
346
+ h.pendingUnmount = false;
347
+ const node = h.node!;
348
+ node.update(node.props, { isPresent: false, custom });
349
+ animations.push(node.animationState.setActive('exit', true));
350
+ }
351
+ void Promise.all(animations).then(() => {
352
+ if (rec.cancelled) return;
353
+ finishExit(rec);
354
+ });
355
+ return true;
356
+ },
357
+ cancel(el: Element): void {
358
+ for (const h of hostsIn(el)) if (h.exiting) cancelExit(h.exiting);
359
+ },
360
+ };
361
+
362
+ function finishExit(rec: ExitRecord): void {
363
+ const st = rec.group ? presenceState(rec.group) : null;
364
+ st?.exiting.delete(rec);
365
+ rec.restore?.();
366
+ rec.done();
367
+ for (const h of rec.hosts) if (!h.unmounted && h.exiting === rec && !h.el.isConnected) unmountHost(h);
368
+ if (st && rec.group && !st.exiting.size) {
369
+ const props = rec.group.get() || {};
370
+ if (props.onExitComplete) frame.postRender(() => props.onExitComplete());
371
+ const waiting = st.waiting.splice(0);
372
+ for (const h of waiting) {
373
+ h.waiting = false;
374
+ (h.el as HTMLElement).style.removeProperty('display');
375
+ if (h.el.isConnected && !h.unmounted) queue.push(h);
376
+ }
377
+ if (waiting.length) schedule();
378
+ }
379
+ }
380
+
381
+ function cancelExit(rec: ExitRecord): void {
382
+ if (rec.cancelled) return;
383
+ rec.cancelled = true;
384
+ rec.restore?.();
385
+ const st = rec.group ? presenceState(rec.group) : null;
386
+ st?.exiting.delete(rec);
387
+ for (const h of rec.hosts) {
388
+ if (h.exiting !== rec) continue;
389
+ h.exiting = undefined;
390
+ const node = h.node;
391
+ if (!node || h.unmounted) continue;
392
+ node.update(node.props, { isPresent: true, custom: node.presence?.custom });
393
+ void node.animationState.setActive('exit', false);
394
+ }
395
+ }
396
+
397
+ /** For tests: mounts queued elements now. */
398
+ export function flushMotionMounts(): void {
399
+ flush();
400
+ }
401
+
402
+ export { exitHook as motionExitHook };