magic-pill 9.0.0-next.2 → 9.0.0-next.3

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.
@@ -1,9 +1,11 @@
1
1
  "use client";
2
2
 
3
3
  import { forwardRef, useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
4
+ import { isOnBackdrop, useModal } from "./modal.mjs";
5
+ import { PlacementWatch, useSizeMorph } from "./morph.mjs";
4
6
  import { PillContext } from "./PillContext.mjs";
5
7
  import { inertProps, mergeRefs } from "../utils/react.mjs";
6
- import { jsx } from "react/jsx-runtime";
8
+ import { jsx, jsxs } from "react/jsx-runtime";
7
9
 
8
10
  // src/Pill/Pill.tsx
9
11
  const defaultOrientation = (placement) => placement === "left" || placement === "right" ? "vertical" : "horizontal";
@@ -11,7 +13,7 @@ const defaultOrientation = (placement) => placement === "left" || placement ===
11
13
  * The pill: a container with the Magic Pill design language. Put any parts
12
14
  * (or anything else) inside. Its look and animations follow its data attributes.
13
15
  */
14
- const Pill = forwardRef(function Pill({ presence: presenceProp, defaultPresence = "compact", onPresenceChange, placement = "inline", orientation, variant = "neutral", unstyled = false, children, onKeyDown, ...rest }, forwardedRef) {
16
+ const Pill = forwardRef(function Pill({ presence: presenceProp, defaultPresence = "compact", onPresenceChange, placement = "inline", closeOnBackdropClick = false, orientation, variant = "neutral", unstyled = false, children, onKeyDown, ...rest }, forwardedRef) {
15
17
  const [uncontrolledPresence, setUncontrolledPresence] = useState(defaultPresence);
16
18
  const isControlled = presenceProp !== void 0;
17
19
  const presence = isControlled ? presenceProp : uncontrolledPresence;
@@ -22,6 +24,9 @@ const Pill = forwardRef(function Pill({ presence: presenceProp, defaultPresence
22
24
  const ref = useMemo(() => mergeRefs(rootRef, forwardedRef), [forwardedRef]);
23
25
  const panelTriggerRef = useRef(null);
24
26
  const panelId = useId();
27
+ const lastSize = useRef(null);
28
+ useModal(rootRef, isOverlay, presence, lastSize);
29
+ useSizeMorph(rootRef, presence, !unstyled, lastSize);
25
30
  const returnPresenceRef = useRef("compact");
26
31
  useEffect(() => {
27
32
  if (presence !== "panel" && presence !== "hidden") returnPresenceRef.current = presence;
@@ -38,12 +43,6 @@ const Pill = forwardRef(function Pill({ presence: presenceProp, defaultPresence
38
43
  const closePanel = useCallback(() => {
39
44
  if (presence === "panel") setPresence(returnPresenceRef.current);
40
45
  }, [presence, setPresence]);
41
- useEffect(() => {
42
- const dialog = rootRef.current;
43
- if (!isOverlay || !dialog || typeof dialog.showModal !== "function") return;
44
- if (isVisible && !dialog.open) dialog.showModal();
45
- else if (!isVisible && dialog.open) dialog.close();
46
- }, [isOverlay, isVisible]);
47
46
  const handleKeyDown = (event) => {
48
47
  onKeyDown?.(event);
49
48
  if (event.defaultPrevented || isOverlay) return;
@@ -58,8 +57,19 @@ const Pill = forwardRef(function Pill({ presence: presenceProp, defaultPresence
58
57
  if (presence === "panel") closePanel();
59
58
  else setPresence("hidden");
60
59
  };
61
- const handleClose = () => {
62
- if (presence !== "hidden") setPresence("hidden");
60
+ const handleClose = (event) => {
61
+ if (!event.currentTarget.open) setPresence("hidden");
62
+ };
63
+ const pressedBackdrop = useRef(false);
64
+ const handlePointerDown = (event) => {
65
+ rest.onPointerDown?.(event);
66
+ pressedBackdrop.current = isOnBackdrop(event);
67
+ };
68
+ const handleClick = (event) => {
69
+ rest.onClick?.(event);
70
+ const pressed = pressedBackdrop.current;
71
+ pressedBackdrop.current = false;
72
+ if (pressed && event.detail < 2 && !event.defaultPrevented && isOnBackdrop(event)) handleCancel(event);
63
73
  };
64
74
  const context = useMemo(() => ({
65
75
  presence,
@@ -83,7 +93,7 @@ const Pill = forwardRef(function Pill({ presence: presenceProp, defaultPresence
83
93
  const Element = isOverlay ? "dialog" : "div";
84
94
  return /* @__PURE__ */ jsx(PillContext.Provider, {
85
95
  value: context,
86
- children: /* @__PURE__ */ jsx(Element, {
96
+ children: /* @__PURE__ */ jsxs(Element, {
87
97
  ...rest,
88
98
  ref,
89
99
  "data-mp": "pill",
@@ -92,13 +102,20 @@ const Pill = forwardRef(function Pill({ presence: presenceProp, defaultPresence
92
102
  "data-orientation": resolvedOrientation,
93
103
  "data-variant": variant,
94
104
  "data-unstyled": unstyled ? "" : void 0,
95
- ...inertProps(!isVisible && !isOverlay),
105
+ ...inertProps(!isVisible),
96
106
  onKeyDown: handleKeyDown,
97
- ...isOverlay ? {
107
+ ...isOverlay && {
98
108
  onCancel: handleCancel,
99
- onClose: handleClose
100
- } : {},
101
- children
109
+ onClose: handleClose,
110
+ ...closeOnBackdropClick && {
111
+ onPointerDown: handlePointerDown,
112
+ onClick: handleClick
113
+ }
114
+ },
115
+ children: [/* @__PURE__ */ jsx(PlacementWatch, {
116
+ placement: `${placement} ${resolvedOrientation}`,
117
+ target: rootRef
118
+ }), children]
102
119
  })
103
120
  });
104
121
  });
@@ -23,7 +23,7 @@ const PillAction = (0, react.forwardRef)(function PillAction(props, ref) {
23
23
  children: icon
24
24
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
25
25
  "data-mp": "label",
26
- children: label
26
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: label })
27
27
  })]
28
28
  });
29
29
  if (props.href !== void 0) {
@@ -23,7 +23,7 @@ const PillAction = forwardRef(function PillAction(props, ref) {
23
23
  children: icon
24
24
  }), /* @__PURE__ */ jsx("span", {
25
25
  "data-mp": "label",
26
- children: label
26
+ children: /* @__PURE__ */ jsx("span", { children: label })
27
27
  })]
28
28
  });
29
29
  if (props.href !== void 0) {
@@ -0,0 +1,55 @@
1
+ "use client";
2
+
3
+ let react = require("react");
4
+
5
+ // src/Pill/modal.ts
6
+ /**
7
+ * Whether the pointer is on the backdrop: its events target the <dialog>, as
8
+ * those on the pill's own padding do, but fall outside its box.
9
+ */
10
+ function isOnBackdrop({ target, currentTarget, clientX, clientY }) {
11
+ const { left, right, top, bottom } = currentTarget.getBoundingClientRect();
12
+ return target === currentTarget && (clientX < left || clientX > right || clientY < top || clientY > bottom);
13
+ }
14
+ /**
15
+ * Keeps the overlay's <dialog> in step with the presence. Call it before
16
+ * `useSizeMorph`, which then animates from the closed size measured here.
17
+ */
18
+ function useModal(rootRef, isOverlay, presence, lastSize) {
19
+ const isVisible = presence !== "hidden";
20
+ const show = () => {
21
+ const dialog = rootRef.current;
22
+ if (!isOverlay || !isVisible || !dialog?.isConnected || typeof dialog.showModal !== "function") return;
23
+ if (!dialog.open) {
24
+ dialog.dataset.presence = "hidden";
25
+ dialog.showModal();
26
+ lastSize.current = {
27
+ width: dialog.offsetWidth,
28
+ height: dialog.offsetHeight
29
+ };
30
+ dialog.dataset.presence = presence;
31
+ }
32
+ if (presence === "rest" || !dialog.contains(document.activeElement)) dialog.focus();
33
+ };
34
+ (0, react.useLayoutEffect)(() => {
35
+ show();
36
+ const dialog = rootRef.current;
37
+ if (!isOverlay || isVisible || !dialog?.open) return;
38
+ let reopened = false;
39
+ const close = () => {
40
+ if (!reopened && dialog.open) dialog.close();
41
+ };
42
+ const exit = (dialog.getAnimations?.() ?? []).filter(({ effect }) => effect?.getComputedTiming().endTime !== 1e400);
43
+ if (exit.length === 0) close();
44
+ else Promise.allSettled(exit.map(({ finished }) => finished)).then(close);
45
+ return () => {
46
+ reopened = true;
47
+ };
48
+ }, [isOverlay, isVisible]);
49
+ (0, react.useEffect)(() => {
50
+ if (!rootRef.current?.open) show();
51
+ }, [isOverlay, isVisible]);
52
+ }
53
+
54
+ exports.isOnBackdrop = isOnBackdrop;
55
+ exports.useModal = useModal;
@@ -0,0 +1,54 @@
1
+ "use client";
2
+
3
+ import { useEffect, useLayoutEffect } from "react";
4
+
5
+ // src/Pill/modal.ts
6
+ /**
7
+ * Whether the pointer is on the backdrop: its events target the <dialog>, as
8
+ * those on the pill's own padding do, but fall outside its box.
9
+ */
10
+ function isOnBackdrop({ target, currentTarget, clientX, clientY }) {
11
+ const { left, right, top, bottom } = currentTarget.getBoundingClientRect();
12
+ return target === currentTarget && (clientX < left || clientX > right || clientY < top || clientY > bottom);
13
+ }
14
+ /**
15
+ * Keeps the overlay's <dialog> in step with the presence. Call it before
16
+ * `useSizeMorph`, which then animates from the closed size measured here.
17
+ */
18
+ function useModal(rootRef, isOverlay, presence, lastSize) {
19
+ const isVisible = presence !== "hidden";
20
+ const show = () => {
21
+ const dialog = rootRef.current;
22
+ if (!isOverlay || !isVisible || !dialog?.isConnected || typeof dialog.showModal !== "function") return;
23
+ if (!dialog.open) {
24
+ dialog.dataset.presence = "hidden";
25
+ dialog.showModal();
26
+ lastSize.current = {
27
+ width: dialog.offsetWidth,
28
+ height: dialog.offsetHeight
29
+ };
30
+ dialog.dataset.presence = presence;
31
+ }
32
+ if (presence === "rest" || !dialog.contains(document.activeElement)) dialog.focus();
33
+ };
34
+ useLayoutEffect(() => {
35
+ show();
36
+ const dialog = rootRef.current;
37
+ if (!isOverlay || isVisible || !dialog?.open) return;
38
+ let reopened = false;
39
+ const close = () => {
40
+ if (!reopened && dialog.open) dialog.close();
41
+ };
42
+ const exit = (dialog.getAnimations?.() ?? []).filter(({ effect }) => effect?.getComputedTiming().endTime !== 1e400);
43
+ if (exit.length === 0) close();
44
+ else Promise.allSettled(exit.map(({ finished }) => finished)).then(close);
45
+ return () => {
46
+ reopened = true;
47
+ };
48
+ }, [isOverlay, isVisible]);
49
+ useEffect(() => {
50
+ if (!rootRef.current?.open) show();
51
+ }, [isOverlay, isVisible]);
52
+ }
53
+
54
+ export { isOnBackdrop, useModal };
@@ -0,0 +1,405 @@
1
+ "use client";
2
+
3
+ let react = require("react");
4
+ const require_timing = require("../utils/timing.js");
5
+
6
+ // src/Pill/morph.ts
7
+ const CLOSED = /* @__PURE__ */ new Set(["rest", "hidden"]);
8
+ /** Tags this module's animations, so a size change can stop the one before it. */
9
+ const MORPH = "mp-morph";
10
+ /** The length of the fading edge over the panel's clipped content. */
11
+ const EDGE = 48;
12
+ const EASING = "ease-in-out";
13
+ /** Rounded up: a hair narrower, and a message that just fits would wrap. */
14
+ const px = (value) => `${Math.max(0, Math.ceil(value * 100) / 100)}px`;
15
+ /**
16
+ * The pill at a size. Nothing in the stylesheet may cap it meanwhile (the
17
+ * circle clamps both axes, a panel scrolls past a maximum height).
18
+ */
19
+ const sized = (size) => ({
20
+ minWidth: "0px",
21
+ minHeight: "0px",
22
+ maxWidth: "none",
23
+ maxHeight: "none",
24
+ overflow: "hidden",
25
+ width: px(size.width),
26
+ height: px(size.height)
27
+ });
28
+ /**
29
+ * A part held at its final width while the pill resizes, so a message doesn't
30
+ * rewrap at every frame.
31
+ */
32
+ const held = (width) => ({
33
+ flexShrink: 0,
34
+ width: px(width)
35
+ });
36
+ /**
37
+ * Measures the pill's messages now (at their final width: before the pill's
38
+ * own animation starts), to hold them there during an animation.
39
+ */
40
+ function holdMessages(element) {
41
+ const messages = [...element.querySelectorAll(":scope > [data-mp=\"message\"]")].map((message) => [message, held(message.getBoundingClientRect().width)]);
42
+ return (options) => messages.map(([message, frame]) => message.animate([frame, frame], options));
43
+ }
44
+ const sameSize = (a, b) => Math.abs(a.width - b.width) < 1 && Math.abs(a.height - b.height) < 1;
45
+ /**
46
+ * The panel's content, cut by the pill's edges while it grows or shrinks: a
47
+ * mask that shows what's inside the pill, and fades it out along the bottom
48
+ * and the inline-end edges instead of cutting it (the corner stays hidden).
49
+ */
50
+ function revealMask(panel, size, edges) {
51
+ const visibleHeight = Math.max(0, size.height - panel.top);
52
+ const visibleWidth = Math.min(panel.width, size.width);
53
+ const fadeY = Math.min(edges, visibleHeight);
54
+ const fadeX = visibleWidth < panel.width ? Math.min(edges, visibleWidth) : 0;
55
+ const solidW = visibleWidth - fadeX;
56
+ const solidH = visibleHeight - fadeY;
57
+ const startX = panel.rtl ? panel.width - visibleWidth : 0;
58
+ const solidX = panel.rtl ? startX + fadeX : startX;
59
+ const sideX = panel.rtl ? startX : startX + solidW;
60
+ return {
61
+ width: px(panel.width),
62
+ maskImage: `linear-gradient(#000,#000),linear-gradient(to top,transparent,#000),linear-gradient(to ${panel.rtl ? "right" : "left"},transparent,#000)`,
63
+ maskRepeat: "no-repeat",
64
+ maskSize: `${px(solidW)} ${px(solidH)},${px(solidW)} ${px(fadeY)},${px(fadeX)} ${px(solidH)}`,
65
+ maskPosition: `${px(solidX)} 0px,${px(solidX)} ${px(solidH)},${px(sideX)} 0px`
66
+ };
67
+ }
68
+ /**
69
+ * How the pill goes from `from` (on screen) to `to` (its new natural size),
70
+ * or null when there's nothing to animate. Pure, so it can be tested.
71
+ */
72
+ function planMorph(from, to, previous, next, timings, panel) {
73
+ if (timings.change <= 0 || sameSize(from, to)) return null;
74
+ const delay = CLOSED.has(next) && !CLOSED.has(previous) ? timings.fade : 0;
75
+ const plan = {
76
+ pill: [sized(from), sized(to)],
77
+ options: {
78
+ duration: timings.change,
79
+ delay,
80
+ easing: EASING,
81
+ fill: "backwards"
82
+ }
83
+ };
84
+ const opening = next === "panel" && previous !== "panel";
85
+ const closing = previous === "panel" && next !== "panel";
86
+ if (panel && (opening || closing)) plan.panel = opening ? [revealMask(panel, from, EDGE), revealMask(panel, to, 0)] : [revealMask(panel, from, 0), revealMask(panel, to, EDGE)];
87
+ if (closing && !CLOSED.has(next)) {
88
+ const total = timings.change + timings.fade;
89
+ plan.content = {
90
+ keyframes: [
91
+ { opacity: 0 },
92
+ {
93
+ opacity: 0,
94
+ offset: timings.change / total
95
+ },
96
+ { opacity: 1 }
97
+ ],
98
+ options: {
99
+ duration: total,
100
+ easing: "ease-out"
101
+ }
102
+ };
103
+ }
104
+ return plan;
105
+ }
106
+ const readSize = (element) => ({
107
+ width: element.offsetWidth,
108
+ height: element.offsetHeight
109
+ });
110
+ /**
111
+ * Stops the size animations running on the pill (and in it), and drops the
112
+ * copy of the content a swap slides out (but `keep`). Returns whether anything ran.
113
+ */
114
+ function cancel(element, id, subtree) {
115
+ let cancelled = false;
116
+ for (const animation of element.getAnimations?.({ subtree }) ?? []) if (animation.id === id) {
117
+ animation.cancel();
118
+ cancelled = true;
119
+ }
120
+ return cancelled;
121
+ }
122
+ function stopMorphs(element, keep) {
123
+ let stopped = cancel(element, MORPH, true);
124
+ for (const outgoing of element.querySelectorAll(":scope > [data-mp=\"outgoing\"]")) if (outgoing !== keep) {
125
+ outgoing.remove();
126
+ stopped = true;
127
+ }
128
+ return stopped;
129
+ }
130
+ /**
131
+ * The size to the fraction of a pixel (offsetWidth rounds it): the copy of a
132
+ * message that just fits would wrap otherwise. An open pill isn't scaled.
133
+ */
134
+ const readExactSize = (element) => {
135
+ const { width, height } = element.getBoundingClientRect();
136
+ return {
137
+ width,
138
+ height
139
+ };
140
+ };
141
+ /**
142
+ * One content replacing another in an open pill, in one overlapping movement
143
+ * (the "rubik's cube"): the old content slides out through the top, the pill
144
+ * resizes, the new content comes in from the bottom (`down`: the other way
145
+ * round, for a pill at the top of the screen). A row's content lines up on
146
+ * the anchor side (`undefined`: a column, left alone). Pure, so it can be tested.
147
+ */
148
+ function planSwap(from, to, timings, anchor, down = false) {
149
+ const total = timings.fade + timings.change;
150
+ if (total <= 0) return null;
151
+ const out = down ? "" : "-";
152
+ const into = down ? "-" : "";
153
+ const justify = anchor && { justifyContent: anchor === "center" ? anchor : `flex-${anchor}` };
154
+ return {
155
+ pill: {
156
+ keyframes: [{
157
+ ...sized(from),
158
+ ...justify
159
+ }, {
160
+ ...sized(to),
161
+ ...justify
162
+ }],
163
+ options: {
164
+ id: MORPH,
165
+ duration: total * .6,
166
+ delay: total * .15,
167
+ easing: EASING,
168
+ fill: "backwards"
169
+ }
170
+ },
171
+ outgoing: {
172
+ keyframes: [{}, {
173
+ transform: `translateY(${out}${px(from.height)})`,
174
+ opacity: 0
175
+ }],
176
+ options: {
177
+ id: MORPH,
178
+ duration: total * .45,
179
+ easing: "ease-in",
180
+ fill: "forwards"
181
+ }
182
+ },
183
+ incoming: (width) => ({
184
+ keyframes: [{
185
+ ...held(width),
186
+ transform: `translateY(${into}${px(to.height)})`,
187
+ opacity: 0
188
+ }, {
189
+ ...held(width),
190
+ transform: "none",
191
+ opacity: 1
192
+ }],
193
+ options: {
194
+ id: MORPH,
195
+ duration: total * .65,
196
+ delay: total * .35,
197
+ easing: "ease-out",
198
+ fill: "backwards"
199
+ }
200
+ })
201
+ };
202
+ }
203
+ /**
204
+ * Before new content replaces the pill's: a still copy of what's on screen,
205
+ * laid over it, to slide out once the new content is in. Null when there's
206
+ * nothing to animate (unstyled, reduced motion, no Web Animations API).
207
+ */
208
+ function captureSwap(element) {
209
+ if (!element || element.hasAttribute("data-unstyled") || !element.animate || require_timing.prefersReducedMotion()) return null;
210
+ const from = readExactSize(element);
211
+ const outgoing = document.createElement("div");
212
+ for (const child of element.children) if (child.getAttribute("data-mp") !== "outgoing") outgoing.append(child.cloneNode(true));
213
+ stopMorphs(element);
214
+ for (const node of outgoing.querySelectorAll("[id], [name]")) {
215
+ node.removeAttribute("id");
216
+ node.removeAttribute("name");
217
+ }
218
+ outgoing.setAttribute("data-mp", "outgoing");
219
+ outgoing.setAttribute("aria-hidden", "true");
220
+ outgoing.setAttribute("inert", "");
221
+ const style = getComputedStyle(element);
222
+ const row = style.flexDirection.startsWith("row");
223
+ const placement = element.dataset.placement ?? "";
224
+ const side = row ? placement.replace("inline", "-start") : style.alignItems;
225
+ const anchor = /start$/.test(side) ? "start" : /end$/.test(side) ? "end" : "center";
226
+ outgoing.style.cssText = `position:absolute;inset-block:0;margin-block:auto;${anchor === "center" ? "inset-inline:0;margin-inline:auto" : `inset-inline-${anchor}:0`};box-sizing:border-box;width:${held(from.width).width};height:${px(from.height)};display:flex;flex-direction:inherit;align-items:inherit;justify-content:inherit;gap:inherit;padding:inherit;pointer-events:none`;
227
+ element.append(outgoing);
228
+ return {
229
+ from,
230
+ outgoing,
231
+ anchor: row ? anchor : void 0,
232
+ down: placement.startsWith("top")
233
+ };
234
+ }
235
+ /** Once the new content is in: the swap prepared by `captureSwap`, played. */
236
+ function playSwap(element, { from, outgoing, anchor, down }) {
237
+ stopMorphs(element, outgoing);
238
+ const plan = planSwap(from, readExactSize(element), readMorphTimings(element), anchor, down);
239
+ const done = () => outgoing.remove();
240
+ if (!plan) return done();
241
+ const incoming = [...element.children].filter((child) => child !== outgoing);
242
+ const widths = incoming.map((child) => child.getBoundingClientRect().width);
243
+ element.animate(plan.pill.keyframes, plan.pill.options);
244
+ incoming.forEach((child, index) => {
245
+ const { keyframes, options } = plan.incoming(widths[index]);
246
+ child.animate(keyframes, options);
247
+ });
248
+ outgoing.animate(plan.outgoing.keyframes, plan.outgoing.options).finished.then(done, done);
249
+ }
250
+ function readMorphTimings(element) {
251
+ const style = getComputedStyle(element);
252
+ return {
253
+ fade: require_timing.parseDuration(style.getPropertyValue("--_mp-fade"), 150),
254
+ change: require_timing.parseDuration(style.getPropertyValue("--_mp-change"), 250)
255
+ };
256
+ }
257
+ function readPanel(pill) {
258
+ const element = pill.querySelector(":scope > [data-mp=\"panel\"]");
259
+ if (!element || getComputedStyle(element).display === "none") return void 0;
260
+ const pillRect = pill.getBoundingClientRect();
261
+ const rect = element.getBoundingClientRect();
262
+ return {
263
+ element,
264
+ box: {
265
+ top: rect.top - pillRect.top,
266
+ width: rect.width,
267
+ rtl: getComputedStyle(pill).direction === "rtl"
268
+ }
269
+ };
270
+ }
271
+ /**
272
+ * Animates the pill's size on each presence change. Off for `unstyled` pills,
273
+ * with reduced motion, and where the Web Animations API is missing.
274
+ */
275
+ function useSizeMorph(rootRef, presence, enabled, lastSize) {
276
+ const lastPresence = (0, react.useRef)(presence);
277
+ const running = (0, react.useRef)([]);
278
+ const openPanel = (0, react.useRef)(void 0);
279
+ (0, react.useLayoutEffect)(() => {
280
+ const element = rootRef.current;
281
+ if (!element || typeof ResizeObserver === "undefined") return;
282
+ const observer = new ResizeObserver((entries) => {
283
+ const size = readSize(element);
284
+ const box = entries?.[0]?.borderBoxSize?.[0];
285
+ const exact = box && {
286
+ width: box.inlineSize,
287
+ height: box.blockSize
288
+ };
289
+ lastSize.current = exact && sameSize(exact, size) ? exact : size;
290
+ if (lastPresence.current === "panel" && running.current.length === 0) openPanel.current = readPanel(element)?.box;
291
+ });
292
+ observer.observe(element);
293
+ return () => {
294
+ observer.disconnect();
295
+ running.current.forEach((animation) => animation.cancel());
296
+ };
297
+ }, [rootRef, lastSize]);
298
+ (0, react.useLayoutEffect)(() => {
299
+ const element = rootRef.current;
300
+ const previous = lastPresence.current;
301
+ lastPresence.current = presence;
302
+ if (!element || previous === presence) return;
303
+ if (!enabled || typeof element.animate !== "function" || require_timing.prefersReducedMotion()) {
304
+ running.current.forEach((animation) => animation.cancel());
305
+ running.current = [];
306
+ return;
307
+ }
308
+ const current = readSize(element);
309
+ const from = stopMorphs(element) || running.current.length > 0 ? current : lastSize.current;
310
+ running.current.forEach((animation) => animation.cancel());
311
+ running.current = [];
312
+ const to = readSize(element);
313
+ lastSize.current = to;
314
+ if (!from) return;
315
+ const panel = readPanel(element);
316
+ if (presence === "panel") openPanel.current = panel?.box;
317
+ const panelBox = previous === "panel" ? openPanel.current : panel?.box;
318
+ const plan = planMorph(from, to, previous, presence, readMorphTimings(element), panelBox);
319
+ if (!plan) return;
320
+ const hold = holdMessages(element);
321
+ const options = {
322
+ ...plan.options,
323
+ id: MORPH
324
+ };
325
+ const animations = [element.animate(plan.pill, options)];
326
+ if (plan.panel && panel) {
327
+ animations.push(panel.element.animate(plan.panel, options));
328
+ const footer = panel.element.querySelector("[data-mp=\"panel-footer\"]");
329
+ if (footer) animations.push(footer.animate([{ position: "static" }, { position: "static" }], options));
330
+ }
331
+ if (!CLOSED.has(presence) && presence !== "panel") animations.push(...hold(options));
332
+ if (plan.content) {
333
+ const { keyframes, options } = plan.content;
334
+ for (const child of element.children) if (child !== panel?.element) animations.push(child.animate(keyframes, {
335
+ ...options,
336
+ id: MORPH
337
+ }));
338
+ }
339
+ running.current = animations;
340
+ animations[0].finished.then(() => {
341
+ if (running.current === animations) running.current = [];
342
+ }).catch(() => {});
343
+ }, [
344
+ rootRef,
345
+ presence,
346
+ enabled,
347
+ lastSize
348
+ ]);
349
+ }
350
+ /** Tags the placement animation, which runs alongside the size ones. */
351
+ const MOVE = "mp-move";
352
+ /**
353
+ * The pill moved to another placement (or orientation): it travels there
354
+ * from where it was (`from`), resizing on the way if its size changed.
355
+ */
356
+ function animateMove(element, from) {
357
+ if (!from.width || element.hasAttribute("data-unstyled") || !element.animate || require_timing.prefersReducedMotion()) return;
358
+ cancel(element, MOVE);
359
+ const to = readExactSize(element);
360
+ const resized = !sameSize(from, to);
361
+ const hold = holdMessages(element);
362
+ const style = element.style.cssText;
363
+ if (resized) Object.assign(element.style, sized(from));
364
+ const start = element.getBoundingClientRect();
365
+ element.style.cssText = style;
366
+ const shift = `${from.left - start.left}px ${from.top - start.top}px`;
367
+ const { fade, change } = readMorphTimings(element);
368
+ const options = {
369
+ id: MOVE,
370
+ duration: fade + change,
371
+ easing: EASING
372
+ };
373
+ element.animate([{
374
+ translate: shift,
375
+ ...resized && sized(from)
376
+ }, {
377
+ translate: "0px 0px",
378
+ ...resized && sized(to)
379
+ }], options);
380
+ if (resized) hold(options);
381
+ }
382
+ /**
383
+ * Remembers where the pill is just before its placement changes (React calls
384
+ * this before it updates the page), then moves it from there.
385
+ */
386
+ var PlacementWatch = class extends react.Component {
387
+ getSnapshotBeforeUpdate(previous) {
388
+ return previous.placement !== this.props.placement ? this.props.target.current?.getBoundingClientRect() ?? null : null;
389
+ }
390
+ componentDidUpdate(_props, _state, from) {
391
+ const element = this.props.target.current;
392
+ if (from && element) animateMove(element, from);
393
+ }
394
+ render() {
395
+ return null;
396
+ }
397
+ };
398
+
399
+ exports.PlacementWatch = PlacementWatch;
400
+ exports.animateMove = animateMove;
401
+ exports.captureSwap = captureSwap;
402
+ exports.planMorph = planMorph;
403
+ exports.planSwap = planSwap;
404
+ exports.playSwap = playSwap;
405
+ exports.useSizeMorph = useSizeMorph;