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.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,12 @@ Work towards 9.0.0, the first release with a stable API. It's a breaking release
9
9
  - Placements: `inline`, fixed at an edge or corner, or `overlay` (a native modal `<dialog>`)
10
10
  - Horizontal or vertical orientation, and `neutral`, `success`, `danger` or custom variants
11
11
  - Stateless parts and `PillAction` can be rendered by React Server Components without becoming client code
12
+ - The pill animates its real size, width and height together: a message that wraps to several lines, a panel opening or closing, a sidebar's labels unfolding. Its corners stay right at every frame: half the one-line pill's height, so a taller pill is a rounded rectangle, up to `--mp-radius-panel` for a panel
13
+ - Vertical pills line their items up along the screen edge they sit on (`left` or `right`), and a right-hand sidebar opens its labels towards the middle of the screen, so the icons stay in line; mirrored in right-to-left pages. The new `--mp-align` token (`start`, `center`, `end`) changes the alignment; an inline vertical pill stays centred
14
+ - When its `placement` changes, the pill travels to its new place from where it was, resizing on the way (e.g. into a sidebar), instead of jumping there: handy for a pill that follows the scroll, or a guided tour
15
+ - The overlay pops in and scales out like any other pill, and its backdrop fades in and out, in every browser. The dialog closes once its exit has played; its actions stop responding at once. With reduced motion, it all fades briefly
16
+ - `closeOnBackdropClick` closes the overlay (or its panel first, like Escape) with a click outside it. Off by default
17
+ - The panel grows out of the pill (upwards from a bottom pill, sideways from a sidebar) and closes back into it. Its content fades in as it grows, behind an edge that fades out as the panel settles, instead of appearing all at once
12
18
  - Link actions take a `linkComponent` (e.g. Next's `Link`) and only render relative, `http(s):`, `mailto:` and `tel:` URLs. Any other scheme, such as `javascript:`, renders no link
13
19
  - Templates built from those parts:
14
20
  - `PillNotification`: icon, message, an action (`onClick` or `href`) and an optional expandable panel. Every content is a React node, so nothing is parsed as HTML any more
@@ -19,8 +25,9 @@ Work towards 9.0.0, the first release with a stable API. It's a breaking release
19
25
  - `duration` per notification or on the host (`Infinity` keeps it). The countdown pauses on hover, keyboard focus, an open panel and a hidden browser tab
20
26
  - Action clicks dismiss the notification unless the handler calls `event.preventDefault()`; `onDismiss(id, reason)` reports `timeout`, `action`, `dismissed` or `cleared`
21
27
  - `render` for your own template, which keeps the queue, timing and animation
28
+ - `expanded: true` on a notification's action (or its panel trigger) keeps its label open, not only on hover and focus, so phones show it too
22
29
  - Several named hosts per page (`<MagicPill name="sidebar">`), and `idle="rest"` for a discreet resting circle
23
- - Shape changes: the pill collapses to a circle, swaps its content there and grows back; with reduced motion, it fades instead
30
+ - Shape changes: the next notification in the queue replaces the current one in one movement, without closing the pill: the current one slides out through the top while the pill resizes, and the next one comes in from the bottom (the other way round for a pill at the top of the screen). Other changes (the navbar and a notification) collapse to a circle, swap the content there and grow back. `swap="always"` slides between the base layer and notifications too, so it all feels like one pill; `swap="never"` uses the circle everywhere. With reduced motion, the pill fades instead
24
31
  - Announcements go through a separate live region, so a hidden pill can leave the accessibility tree
25
32
  - On the server, `pill()` does nothing (it warns in development), so requests never share notifications
26
33
  - `usePillQueue(name)`: the queue as a hook, to build your own host
@@ -36,16 +43,23 @@ Work towards 9.0.0, the first release with a stable API. It's a breaking release
36
43
 
37
44
  ### Changed
38
45
  - The published JavaScript is readable (not minified) and has no source maps. Your app bundles exactly the same amount of code (your bundler minifies it), and the package is about 40% smaller to install (196 kB unpacked instead of 331 kB in 9.0.0-next.0)
39
- - Size, measured and checked in CI: the quick start (`MagicPill` + `pill()`) adds about 5.3 kB of gzipped JavaScript and 2.3 kB of gzipped CSS to an app (both minified, as your bundler does); a hand-written `Pill` with its parts, about 1.4 kB of JavaScript
46
+ - Size, measured and checked in CI: the quick start (`MagicPill` + `pill()`) adds about 8.25 kB of gzipped JavaScript and 2.45 kB of gzipped CSS to an app (both minified, as your bundler does); a hand-written `Pill` with its parts, about 3.8 kB of JavaScript, most of it the size animation
40
47
 
41
48
  ### Fixed (since 9.0.0-next.0)
42
49
  - Global resets on links and buttons, such as `a { color: inherit }` or `button { background: none }`, no longer blank out the pill's actions: their look now lives on an inner `[data-mp="action-body"]`
43
- - In a narrow container, an inline pill wraps its message instead of cutting off its action. While the pill grows, the message still stays on one line
50
+ - In a narrow container, an inline pill wraps its message instead of cutting off its action
44
51
  - On touchscreens, a tapped action no longer stays open: labels open on hover only on devices that can really hover. Keyboard focus, an expanded panel and the current page still open them everywhere
45
52
  - When a notification takes the pill over (from the navbar, or the next one in the queue), its message no longer wraps one word per line while the pill grows: `<MagicPill>` shows new content closed first, then the pill opens around it
46
53
  - Long text no longer looks clipped while the pill changes size. When the pill closes, its content fades out first, then the pill shrinks; when it opens, the pill grows first, then the content fades in
47
54
  - When the app removes the host's base layer (e.g. `{showNavbar && <PillNavbar … />}`), the pill closes around it into a circle, then scales out, instead of losing its content at once and collapsing into a narrow oval
48
55
  - The pill scales from its centre instead of the edge it sits on (see `--mp-scale-origin`)
56
+ - When the pill grows out of the circle (the navbar giving way to a notification, or the first notification), its message no longer shows on two lines for a moment before settling on one: it's laid out at its final width while the pill grows
57
+ - When a pill closes, its message no longer wraps onto one more line as it fades out: the size it closes from is measured to the fraction of a pixel
58
+ - A notification whose message wraps to two or three lines (e.g. on a phone) no longer jumps in height when it opens and closes: the pill animates to its measured size
59
+ - A panel's corners no longer snap from fully round to their radius at the end of the opening animation
60
+ - In a vertical pill, a label folds once the next one has unfolded, so the pill widens or narrows smoothly when the active item changes instead of narrowing in between. Labels now unfold at their real width
61
+ - A sidebar's panel keeps the panel width cap (`--mp-panel-width`) instead of running to the edge of the screen
62
+ - Security: `PillNavbar` matches paths in linear time. Stripping trailing slashes used a regular expression that could take seconds on a crafted URL made of many slashes (ReDoS)
49
63
  - On touchscreens, a notification whose panel was opened and closed no longer stays until the next tap elsewhere. The countdown pauses for keyboard focus and for a mouse or pen hovering, not for a tap, and after a tap the panel gives the focus back without showing it as keyboard focus
50
64
 
51
65
  ### Removed
package/README.md CHANGED
@@ -11,7 +11,7 @@ Thank you for your patience and to all people who already have shown interest in
11
11
  ![npm downloads](https://img.shields.io/npm/dt/magic-pill?color=green)
12
12
  [![DeepScan grade](https://deepscan.io/api/teams/23515/projects/28307/branches/911491/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=23515&pid=28307&bid=911491)
13
13
  [![Known Vulnerabilities](https://snyk.io/test/github/CedricTheveneau/Magic-Pill/badge.svg)](https://snyk.io/test/github/CedricTheveneau/Magic-Pill)
14
- [![install size](https://packagephobia.com/badge?p=magic-pill@latest)](https://packagephobia.com/result?p=magic-pill@latest)
14
+ [![install size](https://img.shields.io/npm/unpacked-size/magic-pill?label=install%20size)](https://packagephobia.com/result?p=magic-pill@latest)
15
15
 
16
16
  ## Introduction
17
17
  Magic Pill is **a design primitive, not just a notification library.** At its core is *the pill*: a dark, fully rounded, elevated container with a strong design language, and you can put anything inside it.
@@ -23,11 +23,11 @@ On top of it come ready-made **templates** (a notification, a navbar) and a **co
23
23
  - [X] A notification queue on top of a **base layer** (e.g. a navbar): notifications take the pill over, then hand it back
24
24
  - [X] Several named pills on one page, at any edge or corner, inline, or as a modal
25
25
  - [X] Anything inside: messages, icons and panels are React content; build your own templates from the same parts
26
- - [X] Shape-changing animations (circle ↔ pill ↔ panel) that respect reduced motion
26
+ - [X] Shape-changing animations (circle ↔ pill ↔ panel) at the pill's real size, notifications that slide into each other, a pill that travels when its placement changes, all respecting reduced motion
27
27
  - [X] Accessible: screen reader announcements, keyboard focus pauses the countdown, focus handling for panels and modals
28
28
  - [X] Works in any React 18+ app, including React Server Components (Next.js App Router), with any router
29
29
  - [X] Styles you can override without `!important`, design tokens, no fonts loaded behind your back
30
- - [X] Tiny: the quick start adds about **7.5 kB gzipped** to your app (5.3 kB of JavaScript + 2.3 kB of CSS, minified by your bundler), checked in CI. Unused parts are tree-shaken.
30
+ - [X] Tiny: the quick start adds about **10.7 kB gzipped** to your app (8.25 kB of JavaScript + 2.45 kB of CSS, minified by your bundler), checked in CI. Unused parts are tree-shaken.
31
31
  - [X] Written in TypeScript, zero runtime dependencies
32
32
 
33
33
  ## Installation
@@ -110,8 +110,8 @@ const id = pill().notify({
110
110
  |---|---|---|
111
111
  | `message` | `ReactNode` | Required (unless you use `render`). Any content, e.g. `<>Total: <strong>768.99$</strong></>`. Never parsed as HTML. |
112
112
  | `icon` | `ReactNode` | The leading icon, followed by the divider. |
113
- | `action` | `{ icon?, label, onClick }` or `{ icon?, label, href }` | The round button. Its label shows on hover and focus. Clicking it dismisses the notification; call `event.preventDefault()` in `onClick` to keep it open. |
114
- | `panel` | `{ title?, content, trigger?, closeLabel? }` | A "Learn more" action that grows the pill into a panel. `trigger` defaults to `{ icon: <PlusIcon />, label: "Learn more" }`, `closeLabel` to `"Close"`. |
113
+ | `action` | `{ icon?, label, onClick }` or `{ icon?, label, href }`, plus `expanded?` | The round button. Its label shows on hover and focus, or all the time with `expanded: true` (phones don't hover). Clicking it dismisses the notification; call `event.preventDefault()` in `onClick` to keep it open. |
114
+ | `panel` | `{ title?, content, trigger?, closeLabel? }` | A "Learn more" action that grows the pill into a panel. `trigger` defaults to `{ icon: <PlusIcon />, label: "Learn more" }` and takes `expanded` too, `closeLabel` to `"Close"`. |
115
115
  | `variant` | `"neutral"` · `"success"` · `"danger"` · any string | Defaults to the host's variant. |
116
116
  | `duration` | `number` (ms) | Defaults to the host's (5000). `Infinity` keeps it until dismissed. |
117
117
  | `id` | `string` | Notifying again with the same id updates the notification in place. |
@@ -178,6 +178,7 @@ pill().notify({
178
178
  | `duration` | `5000` | Default display time for notifications. |
179
179
  | `idle` | `"hidden"` | With no base layer and nothing queued: `"hidden"`, or `"rest"` for a small resting circle showing `idleIcon`. |
180
180
  | `idleIcon` | none | The icon of the resting circle. |
181
+ | `swap` | `"queue"` | Where new content slides into the open pill (out through the top, in from the bottom, the other way round for a top pill) instead of closing it to a circle and growing back: `"queue"` between notifications, `"always"` also between the base layer and notifications, `"never"` nowhere. |
181
182
  | `linkComponent` | `<a>` | Renders notification actions that have an `href`, e.g. Next's `Link`. |
182
183
  | `classNames` | none | Classes for the notification's parts: `icon`, `divider`, `message`, `actions`, `action`, `panel`. |
183
184
  | `placement` | `"bottom"` | See [placements](#the-primitive). |
@@ -258,8 +259,9 @@ import { Pill, PillActions, PillAction, PhoneIcon, MailIcon, DocumentIcon } from
258
259
 
259
260
  | `<Pill>` prop | Values | Default |
260
261
  |---|---|---|
261
- | `placement` | `"inline"` (in the page flow), `"top"`, `"bottom"`, `"left"`, `"right"`, `"top-start"`, `"top-end"`, `"bottom-start"`, `"bottom-end"` (fixed; `start`/`end` follow the text direction), `"overlay"` (a modal `<dialog>`) | `"inline"` |
262
+ | `placement` | `"inline"` (in the page flow), `"top"`, `"bottom"`, `"left"`, `"right"`, `"top-start"`, `"top-end"`, `"bottom-start"`, `"bottom-end"` (fixed; `start`/`end` follow the text direction), `"overlay"` (a modal `<dialog>`). Change it and the pill travels to its new place (e.g. with the scroll, or for a guided tour), except to or from `"overlay"`. | `"inline"` |
262
263
  | `presence` / `defaultPresence` / `onPresenceChange` | `"hidden"`, `"rest"` (a circle with the icon only), `"compact"`, `"expanded"` (every action label shown), `"panel"` | `"compact"` |
264
+ | `closeOnBackdropClick` | `boolean`, for the `"overlay"` placement: a click outside the modal does what Escape does (closes its panel if it's open, the modal otherwise). Call `event.preventDefault()` in your `onClick` to keep it open | `false` |
263
265
  | `orientation` | `"horizontal"`, `"vertical"` | `"vertical"` for `left`/`right` |
264
266
  | `variant` | `"neutral"`, `"success"`, `"danger"`, or any string (see [Styling](#styling)) | `"neutral"` |
265
267
  | `unstyled` | `boolean`: keep the behaviour, drop the look | `false` |
@@ -273,7 +275,7 @@ Any other prop (`className`, `aria-label`, `ref`…) goes to the element.
273
275
  - `PillActions` and `PillAction`: round buttons. `label` is required: it's the accessible name, and it shows on hover, on focus, with `expanded`, or at the `expanded` level. A `PillAction` is a `<button>` with `onClick`, or a link with `href` (through `linkComponent` if you pass one).
274
276
  - `PillPanel` and `PillPanelTrigger`: content shown at the `panel` level, and the action that opens it. The panel takes the focus when it opens, closes on Escape or with its close button, and gives the focus back to the trigger. One panel per pill.
275
277
 
276
- **A modal:** `placement="overlay"` renders a native modal `<dialog>`, which brings a focus trap, Escape and an inert page with it.
278
+ **A modal:** `placement="overlay"` renders a native modal `<dialog>`, which brings a focus trap, Escape and an inert page with it. It pops in and scales out like any other pill, while its backdrop fades in and out: the dialog closes, and gives the focus back, once the exit has played. Add `closeOnBackdropClick` to also close it with a click outside (off by default, so a confirmation isn't dismissed by accident).
277
279
  ```tsx
278
280
  <Pill placement="overlay" variant="danger" presence={open ? "compact" : "hidden"} onPresenceChange={(p) => setOpen(p !== "hidden")}>
279
281
  <PillMessage>Delete this item?</PillMessage>
@@ -342,9 +344,14 @@ Twelve built-in icons, drawn in `currentColor` and decorative by default (`aria-
342
344
  | `--mp-backdrop` | the overlay's backdrop |
343
345
  | `--mp-duration-enter` / `--mp-duration-change` / `--mp-duration-exit` | `500ms` / `250ms` / `300ms` |
344
346
  | `--mp-scale-origin` | `center`: where the pill pops in from and scales out to (e.g. `bottom` to come out of the edge) |
347
+ | `--mp-align` | How a vertical pill lines up its items: `start`, `center` or `end` (following the text direction). By default, along the screen edge for a `left` or `right` pill, centred otherwise |
345
348
 
346
349
  The pill fits small screens: sizes are in `rem`, fixed pills stay inside the viewport and its safe areas, and long panels scroll.
347
350
 
351
+ **Sidebars:** a `left` or `right` pill lines its items up along the screen edge, and on the right-hand side its labels open towards the middle of the screen, so the icons stay in line (mirrored in right-to-left pages). Set `--mp-align` to change the alignment.
352
+
353
+ **Shape and motion:** the pill animates its real size whenever its presence changes (a script measures it; with `unstyled` or reduced motion it doesn't). Its corners are half the one-line pill's height, so a taller pill, such as a wrapped message, is a rounded rectangle; a panel's corners are `--mp-radius-panel`.
354
+
348
355
  ## Accessibility
349
356
  - **Announcements:** each `<MagicPill>` has a polite live region that reads notifications out (or your `announce` text). A hidden pill leaves the accessibility tree.
350
357
  - **Time to act:** the countdown pauses while a mouse hovers the pill, on keyboard focus, and while a panel is open. A tap doesn't pause it.
@@ -1,6 +1,7 @@
1
1
  import { ReactNode } from "react";
2
2
  import { LinkComponent, PillProps } from "../Pill/types.mjs";
3
3
  import { PillNotificationClassNames } from "../PillNotification/PillNotification.mjs";
4
+ import { SwapMode } from "./choreography.mjs";
4
5
  export interface MagicPillProps extends Omit<PillProps, "presence" | "defaultPresence" | "onPresenceChange" | "children"> {
5
6
  /** Default "main". Two hosts with the same name warn in development. */
6
7
  name?: string;
@@ -15,6 +16,12 @@ export interface MagicPillProps extends Omit<PillProps, "presence" | "defaultPre
15
16
  idle?: "hidden" | "rest";
16
17
  /** The icon shown when `idle="rest"`. */
17
18
  idleIcon?: ReactNode;
19
+ /**
20
+ * Where new content slides into the open pill instead of closing it to a
21
+ * circle and growing back: between queued notifications (default), also
22
+ * between the base layer and notifications ("always"), or nowhere ("never").
23
+ */
24
+ swap?: SwapMode;
18
25
  /** Passed to notification actions that have an `href`. */
19
26
  linkComponent?: LinkComponent;
20
27
  classNames?: PillNotificationClassNames;
@@ -1,6 +1,7 @@
1
1
  import { ReactNode } from "react";
2
2
  import { LinkComponent, PillProps } from "../Pill/types.js";
3
3
  import { PillNotificationClassNames } from "../PillNotification/PillNotification.js";
4
+ import { SwapMode } from "./choreography.js";
4
5
  export interface MagicPillProps extends Omit<PillProps, "presence" | "defaultPresence" | "onPresenceChange" | "children"> {
5
6
  /** Default "main". Two hosts with the same name warn in development. */
6
7
  name?: string;
@@ -15,6 +16,12 @@ export interface MagicPillProps extends Omit<PillProps, "presence" | "defaultPre
15
16
  idle?: "hidden" | "rest";
16
17
  /** The icon shown when `idle="rest"`. */
17
18
  idleIcon?: ReactNode;
19
+ /**
20
+ * Where new content slides into the open pill instead of closing it to a
21
+ * circle and growing back: between queued notifications (default), also
22
+ * between the base layer and notifications ("always"), or nowhere ("never").
23
+ */
24
+ swap?: SwapMode;
18
25
  /** Passed to notification actions that have an `href`. */
19
26
  linkComponent?: LinkComponent;
20
27
  classNames?: PillNotificationClassNames;
@@ -2,6 +2,7 @@
2
2
 
3
3
  let react = require("react");
4
4
  const require_Pill = require("../Pill/Pill.js");
5
+ const require_morph = require("../Pill/morph.js");
5
6
  const require_parts = require("../Pill/parts.js");
6
7
  const require_PillNotification = require("../PillNotification/PillNotification.js");
7
8
  const require_store = require("../store/store.js");
@@ -24,6 +25,12 @@ const VISUALLY_HIDDEN = {
24
25
  whiteSpace: "nowrap",
25
26
  border: 0
26
27
  };
28
+ const isCurrent = (element) => !element.closest("[data-mp=\"outgoing\"]");
29
+ function readMessage(root) {
30
+ if (!root) return "";
31
+ const message = [...root.querySelectorAll("[data-mp=\"message\"]")].find(isCurrent);
32
+ return (message ? [message] : [...root.children].filter(isCurrent)).map((part) => part.textContent).join("").trim();
33
+ }
27
34
  const hasContent = (node) => node !== void 0 && node !== null && node !== false;
28
35
  function useDocumentHidden() {
29
36
  const [hidden, setHidden] = (0, react.useState)(false);
@@ -39,7 +46,7 @@ function useDocumentHidden() {
39
46
  * The batteries-included pill: a <Pill> with a base layer, a queue of
40
47
  * notifications fed by pill(name), and a live region that announces them.
41
48
  */
42
- const MagicPill = (0, react.forwardRef)(function MagicPill({ name = "main", children, duration = DEFAULT_DURATION, idle = "hidden", idleIcon, linkComponent, classNames, placement = "bottom", variant, onPointerEnter, onPointerLeave, onFocus, onBlur, ...rest }, forwardedRef) {
49
+ const MagicPill = (0, react.forwardRef)(function MagicPill({ name = "main", children, duration = DEFAULT_DURATION, idle = "hidden", idleIcon, swap = "queue", linkComponent, classNames, placement = "bottom", variant, onPointerEnter, onPointerLeave, onFocus, onBlur, ...rest }, forwardedRef) {
43
50
  const store = require_store.getStore(name);
44
51
  const { current } = require_usePillQueue.usePillQueue(name);
45
52
  const rootRef = (0, react.useRef)(null);
@@ -64,6 +71,14 @@ const MagicPill = (0, react.forwardRef)(function MagicPill({ name = "main", chil
64
71
  const displayedRef = (0, react.useRef)(displayed);
65
72
  displayedRef.current = displayed;
66
73
  const followUps = (0, react.useRef)([]);
74
+ const capture = (0, react.useRef)(null);
75
+ const swapMode = (0, react.useRef)(swap);
76
+ swapMode.current = swap;
77
+ (0, react.useLayoutEffect)(() => {
78
+ const swapped = capture.current;
79
+ capture.current = null;
80
+ if (swapped && rootRef.current) require_morph.playSwap(rootRef.current, swapped);
81
+ }, [displayed]);
67
82
  (0, react.useEffect)(() => {
68
83
  const next = followUps.current.shift();
69
84
  if (!next) return;
@@ -72,8 +87,9 @@ const MagicPill = (0, react.forwardRef)(function MagicPill({ name = "main", chil
72
87
  }, [displayed]);
73
88
  (0, react.useEffect)(() => {
74
89
  const current = displayedRef.current;
75
- const timers = require_choreography.batchSteps(current, require_choreography.planSteps(current, target, require_choreography.readTimings(rootRef.current))).map(({ at, states }) => {
90
+ const timers = require_choreography.batchSteps(current, require_choreography.planSteps(current, target, require_choreography.readTimings(rootRef.current), swapMode.current)).map(({ at, states }) => {
76
91
  const apply = () => {
92
+ if (require_choreography.isSwap(displayedRef.current, states[0], swapMode.current)) capture.current = require_morph.captureSwap(rootRef.current);
77
93
  followUps.current = states.slice(1);
78
94
  setDisplayed(states[0]);
79
95
  };
@@ -113,8 +129,7 @@ const MagicPill = (0, react.forwardRef)(function MagicPill({ name = "main", chil
113
129
  if (!shown) return;
114
130
  const { announce } = shown.input;
115
131
  if (announce === false) return;
116
- const root = rootRef.current;
117
- const text = typeof announce === "string" ? announce : (root?.querySelector("[data-mp=\"message\"]") ?? root)?.textContent?.trim() ?? "";
132
+ const text = typeof announce === "string" ? announce : readMessage(rootRef.current);
118
133
  if (text) setAnnouncement((previous) => previous?.key === shown ? previous : {
119
134
  key: shown,
120
135
  text
@@ -1,14 +1,15 @@
1
1
  "use client";
2
2
 
3
- import { forwardRef, useEffect, useMemo, useRef, useState } from "react";
3
+ import { forwardRef, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
4
4
  import Pill from "../Pill/Pill.mjs";
5
+ import { captureSwap, playSwap } from "../Pill/morph.mjs";
5
6
  import { PillIcon } from "../Pill/parts.mjs";
6
7
  import { NotificationContent } from "../PillNotification/PillNotification.mjs";
7
8
  import { getStore } from "../store/store.mjs";
8
9
  import { getInputModality, trackInputModality } from "../utils/inputModality.mjs";
9
10
  import { usePillQueue } from "../store/usePillQueue.mjs";
10
11
  import { mergeRefs } from "../utils/react.mjs";
11
- import { BASE, IDLE, NONE, batchSteps, isOpen, planSteps, readTimings } from "./choreography.mjs";
12
+ import { BASE, IDLE, NONE, batchSteps, isOpen, isSwap, planSteps, readTimings } from "./choreography.mjs";
12
13
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
13
14
 
14
15
  // src/MagicPill/MagicPill.tsx
@@ -24,6 +25,12 @@ const VISUALLY_HIDDEN = {
24
25
  whiteSpace: "nowrap",
25
26
  border: 0
26
27
  };
28
+ const isCurrent = (element) => !element.closest("[data-mp=\"outgoing\"]");
29
+ function readMessage(root) {
30
+ if (!root) return "";
31
+ const message = [...root.querySelectorAll("[data-mp=\"message\"]")].find(isCurrent);
32
+ return (message ? [message] : [...root.children].filter(isCurrent)).map((part) => part.textContent).join("").trim();
33
+ }
27
34
  const hasContent = (node) => node !== void 0 && node !== null && node !== false;
28
35
  function useDocumentHidden() {
29
36
  const [hidden, setHidden] = useState(false);
@@ -39,7 +46,7 @@ function useDocumentHidden() {
39
46
  * The batteries-included pill: a <Pill> with a base layer, a queue of
40
47
  * notifications fed by pill(name), and a live region that announces them.
41
48
  */
42
- const MagicPill = forwardRef(function MagicPill({ name = "main", children, duration = DEFAULT_DURATION, idle = "hidden", idleIcon, linkComponent, classNames, placement = "bottom", variant, onPointerEnter, onPointerLeave, onFocus, onBlur, ...rest }, forwardedRef) {
49
+ const MagicPill = forwardRef(function MagicPill({ name = "main", children, duration = DEFAULT_DURATION, idle = "hidden", idleIcon, swap = "queue", linkComponent, classNames, placement = "bottom", variant, onPointerEnter, onPointerLeave, onFocus, onBlur, ...rest }, forwardedRef) {
43
50
  const store = getStore(name);
44
51
  const { current } = usePillQueue(name);
45
52
  const rootRef = useRef(null);
@@ -64,6 +71,14 @@ const MagicPill = forwardRef(function MagicPill({ name = "main", children, durat
64
71
  const displayedRef = useRef(displayed);
65
72
  displayedRef.current = displayed;
66
73
  const followUps = useRef([]);
74
+ const capture = useRef(null);
75
+ const swapMode = useRef(swap);
76
+ swapMode.current = swap;
77
+ useLayoutEffect(() => {
78
+ const swapped = capture.current;
79
+ capture.current = null;
80
+ if (swapped && rootRef.current) playSwap(rootRef.current, swapped);
81
+ }, [displayed]);
67
82
  useEffect(() => {
68
83
  const next = followUps.current.shift();
69
84
  if (!next) return;
@@ -72,8 +87,9 @@ const MagicPill = forwardRef(function MagicPill({ name = "main", children, durat
72
87
  }, [displayed]);
73
88
  useEffect(() => {
74
89
  const current = displayedRef.current;
75
- const timers = batchSteps(current, planSteps(current, target, readTimings(rootRef.current))).map(({ at, states }) => {
90
+ const timers = batchSteps(current, planSteps(current, target, readTimings(rootRef.current), swapMode.current)).map(({ at, states }) => {
76
91
  const apply = () => {
92
+ if (isSwap(displayedRef.current, states[0], swapMode.current)) capture.current = captureSwap(rootRef.current);
77
93
  followUps.current = states.slice(1);
78
94
  setDisplayed(states[0]);
79
95
  };
@@ -113,8 +129,7 @@ const MagicPill = forwardRef(function MagicPill({ name = "main", children, durat
113
129
  if (!shown) return;
114
130
  const { announce } = shown.input;
115
131
  if (announce === false) return;
116
- const root = rootRef.current;
117
- const text = typeof announce === "string" ? announce : (root?.querySelector("[data-mp=\"message\"]") ?? root)?.textContent?.trim() ?? "";
132
+ const text = typeof announce === "string" ? announce : readMessage(rootRef.current);
118
133
  if (text) setAnnouncement((previous) => previous?.key === shown ? previous : {
119
134
  key: shown,
120
135
  text
@@ -0,0 +1,8 @@
1
+ import "../Pill/types.mjs";
2
+ import "../store/store.mjs";
3
+ /**
4
+ * Where new content slides into the open pill (the "rubik's cube") instead of
5
+ * going through the circle: between queued notifications (`queue`), also
6
+ * between the base layer and notifications (`always`), or nowhere (`never`).
7
+ */
8
+ export type SwapMode = "queue" | "always" | "never";
@@ -0,0 +1,9 @@
1
+ import "../Pill/types.js";
2
+ import "../store/store.js";
3
+ import "../utils/timing.js";
4
+ /**
5
+ * Where new content slides into the open pill (the "rubik's cube") instead of
6
+ * going through the circle: between queued notifications (`queue`), also
7
+ * between the base layer and notifications (`always`), or nowhere (`never`).
8
+ */
9
+ export type SwapMode = "queue" | "always" | "never";
@@ -1,3 +1,5 @@
1
+ const require_timing = require("../utils/timing.js");
2
+
1
3
  // src/MagicPill/choreography.ts
2
4
  const NONE = Object.freeze({ kind: "none" });
3
5
  const BASE = Object.freeze({ kind: "base" });
@@ -9,16 +11,19 @@ const OPEN_LEVELS = /* @__PURE__ */ new Set([
9
11
  ]);
10
12
  const isOpen = (presence) => OPEN_LEVELS.has(presence);
11
13
  const sceneKey = (scene) => scene.kind === "notification" ? `notification:${scene.item.id}` : scene.kind;
14
+ /** New content the host slides in, without closing the pill. */
15
+ const isSwap = (from, to, mode = "queue") => mode !== "never" && from.presence === "compact" && to.presence === "compact" && sceneKey(from.scene) !== sceneKey(to.scene) && [from.scene.kind, to.scene.kind].every((kind) => kind === "notification" || mode === "always" && kind === "base");
12
16
  /** Where each scene settles: the base and notifications are pills, idle is a circle. */
13
17
  const settledPresence = (scene) => scene.kind === "none" ? "hidden" : scene.kind === "idle" ? "rest" : "compact";
14
18
  /**
15
19
  * The steps from what's displayed to the target scene:
16
- * - new content: fade it out, collapse to the circle, swap the content there, grow back;
20
+ * - the next notification in the queue (with `always`, the base layer too): swap it in place (the host animates it);
21
+ * - other new content: fade it out, collapse to the circle, swap the content there, grow back;
17
22
  * - nothing left to show: hide (the stylesheet shrinks, then scales out), then drop the content;
18
23
  * - from hidden: pop in as a circle, then grow into the pill.
19
24
  * Open levels the user chose (expanded, panel) are kept while the scene stays the same.
20
25
  */
21
- function planSteps(current, target, timings) {
26
+ function planSteps(current, target, timings, swap) {
22
27
  const steps = [];
23
28
  let { scene, presence } = current;
24
29
  const go = (delay, nextPresence, nextScene = scene) => {
@@ -36,7 +41,14 @@ function planSteps(current, target, timings) {
36
41
  go(timings.reduced ? timings.exit : timings.fade + timings.change + timings.exit, "hidden", target);
37
42
  return steps;
38
43
  }
39
- if (isOpen(presence)) {
44
+ if (!timings.reduced && isSwap({
45
+ scene,
46
+ presence
47
+ }, {
48
+ scene: target,
49
+ presence: "compact"
50
+ }, swap)) go(0, presence, target);
51
+ else if (isOpen(presence)) {
40
52
  if (timings.reduced) {
41
53
  go(0, "hidden");
42
54
  go(timings.exit, "hidden", target);
@@ -95,18 +107,11 @@ function batchSteps(current, steps) {
95
107
  }
96
108
  return batches;
97
109
  }
98
- /** "500ms" or "0.5s" → 500; anything else → the fallback. */
99
- function parseDuration(value, fallback) {
100
- const match = /^\s*([\d.]+)(ms|s)\s*$/.exec(value);
101
- if (!match) return fallback;
102
- const amount = Number.parseFloat(match[1]);
103
- return match[2] === "s" ? amount * 1e3 : amount;
104
- }
105
110
  /** The timings the stylesheet uses for this pill, or its defaults (e.g. when unstyled). */
106
111
  function readTimings(element) {
107
112
  const style = element ? getComputedStyle(element) : null;
108
- const read = (name, fallback) => parseDuration(style?.getPropertyValue(name) ?? "", fallback);
109
- const reduced = typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
113
+ const read = (name, fallback) => require_timing.parseDuration(style?.getPropertyValue(name) ?? "", fallback);
114
+ const reduced = require_timing.prefersReducedMotion();
110
115
  return reduced ? {
111
116
  enter: 0,
112
117
  fade: 0,
@@ -127,6 +132,7 @@ exports.IDLE = IDLE;
127
132
  exports.NONE = NONE;
128
133
  exports.batchSteps = batchSteps;
129
134
  exports.isOpen = isOpen;
130
- exports.parseDuration = parseDuration;
135
+ exports.isSwap = isSwap;
136
+ exports.parseDuration = require_timing.parseDuration;
131
137
  exports.planSteps = planSteps;
132
138
  exports.readTimings = readTimings;
@@ -1,3 +1,5 @@
1
+ import { parseDuration, prefersReducedMotion } from "../utils/timing.mjs";
2
+
1
3
  // src/MagicPill/choreography.ts
2
4
  const NONE = Object.freeze({ kind: "none" });
3
5
  const BASE = Object.freeze({ kind: "base" });
@@ -9,16 +11,19 @@ const OPEN_LEVELS = /* @__PURE__ */ new Set([
9
11
  ]);
10
12
  const isOpen = (presence) => OPEN_LEVELS.has(presence);
11
13
  const sceneKey = (scene) => scene.kind === "notification" ? `notification:${scene.item.id}` : scene.kind;
14
+ /** New content the host slides in, without closing the pill. */
15
+ const isSwap = (from, to, mode = "queue") => mode !== "never" && from.presence === "compact" && to.presence === "compact" && sceneKey(from.scene) !== sceneKey(to.scene) && [from.scene.kind, to.scene.kind].every((kind) => kind === "notification" || mode === "always" && kind === "base");
12
16
  /** Where each scene settles: the base and notifications are pills, idle is a circle. */
13
17
  const settledPresence = (scene) => scene.kind === "none" ? "hidden" : scene.kind === "idle" ? "rest" : "compact";
14
18
  /**
15
19
  * The steps from what's displayed to the target scene:
16
- * - new content: fade it out, collapse to the circle, swap the content there, grow back;
20
+ * - the next notification in the queue (with `always`, the base layer too): swap it in place (the host animates it);
21
+ * - other new content: fade it out, collapse to the circle, swap the content there, grow back;
17
22
  * - nothing left to show: hide (the stylesheet shrinks, then scales out), then drop the content;
18
23
  * - from hidden: pop in as a circle, then grow into the pill.
19
24
  * Open levels the user chose (expanded, panel) are kept while the scene stays the same.
20
25
  */
21
- function planSteps(current, target, timings) {
26
+ function planSteps(current, target, timings, swap) {
22
27
  const steps = [];
23
28
  let { scene, presence } = current;
24
29
  const go = (delay, nextPresence, nextScene = scene) => {
@@ -36,7 +41,14 @@ function planSteps(current, target, timings) {
36
41
  go(timings.reduced ? timings.exit : timings.fade + timings.change + timings.exit, "hidden", target);
37
42
  return steps;
38
43
  }
39
- if (isOpen(presence)) {
44
+ if (!timings.reduced && isSwap({
45
+ scene,
46
+ presence
47
+ }, {
48
+ scene: target,
49
+ presence: "compact"
50
+ }, swap)) go(0, presence, target);
51
+ else if (isOpen(presence)) {
40
52
  if (timings.reduced) {
41
53
  go(0, "hidden");
42
54
  go(timings.exit, "hidden", target);
@@ -95,18 +107,11 @@ function batchSteps(current, steps) {
95
107
  }
96
108
  return batches;
97
109
  }
98
- /** "500ms" or "0.5s" → 500; anything else → the fallback. */
99
- function parseDuration(value, fallback) {
100
- const match = /^\s*([\d.]+)(ms|s)\s*$/.exec(value);
101
- if (!match) return fallback;
102
- const amount = Number.parseFloat(match[1]);
103
- return match[2] === "s" ? amount * 1e3 : amount;
104
- }
105
110
  /** The timings the stylesheet uses for this pill, or its defaults (e.g. when unstyled). */
106
111
  function readTimings(element) {
107
112
  const style = element ? getComputedStyle(element) : null;
108
113
  const read = (name, fallback) => parseDuration(style?.getPropertyValue(name) ?? "", fallback);
109
- const reduced = typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
114
+ const reduced = prefersReducedMotion();
110
115
  return reduced ? {
111
116
  enter: 0,
112
117
  fade: 0,
@@ -122,4 +127,4 @@ function readTimings(element) {
122
127
  };
123
128
  }
124
129
 
125
- export { BASE, IDLE, NONE, batchSteps, isOpen, parseDuration, planSteps, readTimings };
130
+ export { BASE, IDLE, NONE, batchSteps, isOpen, isSwap, parseDuration, planSteps, readTimings };
package/dist/Pill/Pill.js CHANGED
@@ -1,6 +1,8 @@
1
1
  "use client";
2
2
 
3
3
  let react = require("react");
4
+ const require_modal = require("./modal.js");
5
+ const require_morph = require("./morph.js");
4
6
  const require_PillContext = require("./PillContext.js");
5
7
  const require_react = require("../utils/react.js");
6
8
  let react_jsx_runtime = require("react/jsx-runtime");
@@ -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 = (0, react.forwardRef)(function Pill({ presence: presenceProp, defaultPresence = "compact", onPresenceChange, placement = "inline", orientation, variant = "neutral", unstyled = false, children, onKeyDown, ...rest }, forwardedRef) {
16
+ const Pill = (0, react.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] = (0, react.useState)(defaultPresence);
16
18
  const isControlled = presenceProp !== void 0;
17
19
  const presence = isControlled ? presenceProp : uncontrolledPresence;
@@ -22,6 +24,9 @@ const Pill = (0, react.forwardRef)(function Pill({ presence: presenceProp, defau
22
24
  const ref = (0, react.useMemo)(() => require_react.mergeRefs(rootRef, forwardedRef), [forwardedRef]);
23
25
  const panelTriggerRef = (0, react.useRef)(null);
24
26
  const panelId = (0, react.useId)();
27
+ const lastSize = (0, react.useRef)(null);
28
+ require_modal.useModal(rootRef, isOverlay, presence, lastSize);
29
+ require_morph.useSizeMorph(rootRef, presence, !unstyled, lastSize);
25
30
  const returnPresenceRef = (0, react.useRef)("compact");
26
31
  (0, react.useEffect)(() => {
27
32
  if (presence !== "panel" && presence !== "hidden") returnPresenceRef.current = presence;
@@ -38,12 +43,6 @@ const Pill = (0, react.forwardRef)(function Pill({ presence: presenceProp, defau
38
43
  const closePanel = (0, react.useCallback)(() => {
39
44
  if (presence === "panel") setPresence(returnPresenceRef.current);
40
45
  }, [presence, setPresence]);
41
- (0, react.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 = (0, react.forwardRef)(function Pill({ presence: presenceProp, defau
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 = (0, react.useRef)(false);
64
+ const handlePointerDown = (event) => {
65
+ rest.onPointerDown?.(event);
66
+ pressedBackdrop.current = require_modal.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 && require_modal.isOnBackdrop(event)) handleCancel(event);
63
73
  };
64
74
  const context = (0, react.useMemo)(() => ({
65
75
  presence,
@@ -83,7 +93,7 @@ const Pill = (0, react.forwardRef)(function Pill({ presence: presenceProp, defau
83
93
  const Element = isOverlay ? "dialog" : "div";
84
94
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_PillContext.PillContext.Provider, {
85
95
  value: context,
86
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Element, {
96
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Element, {
87
97
  ...rest,
88
98
  ref,
89
99
  "data-mp": "pill",
@@ -92,13 +102,20 @@ const Pill = (0, react.forwardRef)(function Pill({ presence: presenceProp, defau
92
102
  "data-orientation": resolvedOrientation,
93
103
  "data-variant": variant,
94
104
  "data-unstyled": unstyled ? "" : void 0,
95
- ...require_react.inertProps(!isVisible && !isOverlay),
105
+ ...require_react.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__ */ (0, react_jsx_runtime.jsx)(require_morph.PlacementWatch, {
116
+ placement: `${placement} ${resolvedOrientation}`,
117
+ target: rootRef
118
+ }), children]
102
119
  })
103
120
  });
104
121
  });