@funstack/ui 0.1.0-alpha.16 → 0.1.0-alpha.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.
- package/dist/accordion/accordion-root.mjs +1 -1
- package/dist/accordion/accordion-root.mjs.map +1 -1
- package/dist/button/button.d.mts +21 -8
- package/dist/button/button.d.mts.map +1 -1
- package/dist/button/button.mjs +8 -6
- package/dist/button/button.mjs.map +1 -1
- package/dist/checkbox-group/checkbox-group-root.mjs +5 -1
- package/dist/checkbox-group/checkbox-group-root.mjs.map +1 -1
- package/dist/combobox/combobox-popup.d.mts +4 -1
- package/dist/combobox/combobox-popup.d.mts.map +1 -1
- package/dist/combobox/combobox-popup.mjs.map +1 -1
- package/dist/combobox/combobox-root.d.mts +15 -5
- package/dist/combobox/combobox-root.d.mts.map +1 -1
- package/dist/combobox/combobox-root.mjs +9 -11
- package/dist/combobox/combobox-root.mjs.map +1 -1
- package/dist/combobox/combobox-trigger.mjs +7 -2
- package/dist/combobox/combobox-trigger.mjs.map +1 -1
- package/dist/dialog/dialog-close.d.mts +13 -3
- package/dist/dialog/dialog-close.d.mts.map +1 -1
- package/dist/dialog/dialog-close.mjs +3 -2
- package/dist/dialog/dialog-close.mjs.map +1 -1
- package/dist/dialog/dialog-context.mjs.map +1 -1
- package/dist/dialog/dialog-form.d.mts +2 -1
- package/dist/dialog/dialog-form.d.mts.map +1 -1
- package/dist/dialog/dialog-form.mjs.map +1 -1
- package/dist/dialog/dialog-popup.d.mts +9 -4
- package/dist/dialog/dialog-popup.d.mts.map +1 -1
- package/dist/dialog/dialog-popup.mjs +12 -20
- package/dist/dialog/dialog-popup.mjs.map +1 -1
- package/dist/dialog/dialog-root.d.mts +38 -24
- package/dist/dialog/dialog-root.d.mts.map +1 -1
- package/dist/dialog/dialog-root.mjs +10 -8
- package/dist/dialog/dialog-root.mjs.map +1 -1
- package/dist/dialog/dialog-trigger.d.mts +3 -3
- package/dist/dialog/dialog-trigger.mjs.map +1 -1
- package/dist/dialog/index.d.mts +5 -5
- package/dist/dialog/index.mjs +5 -5
- package/dist/dialog/index.mjs.map +1 -1
- package/dist/docs/components/button.md +65 -21
- package/dist/docs/components/checkbox-group.md +12 -3
- package/dist/docs/components/combobox.md +85 -22
- package/dist/docs/components/context-menu.md +8 -8
- package/dist/docs/components/dialog.md +42 -36
- package/dist/docs/components/menu.md +106 -25
- package/dist/docs/components/popover.md +101 -36
- package/dist/docs/components/progress.md +1 -1
- package/dist/docs/components/slider.md +1 -1
- package/dist/docs/components/toast.md +37 -14
- package/dist/docs/components/toolbar.md +2 -1
- package/dist/docs/components/tooltip.md +1 -1
- package/dist/docs/concepts/action-props.md +55 -25
- package/dist/docs/concepts/browser-owned-state.md +27 -12
- package/dist/docs/concepts/pending-and-optimistic.md +15 -2
- package/dist/docs/concepts/render.md +23 -0
- package/dist/docs/concepts/server-components.md +15 -1
- package/dist/docs/concepts/suspense.md +8 -3
- package/dist/docs/concepts/transitions.md +3 -9
- package/dist/docs/getting-started.md +9 -22
- package/dist/docs/index.md +5 -4
- package/dist/docs/roadmap.md +54 -0
- package/dist/docs/why.md +7 -3
- package/dist/index.d.mts +2 -2
- package/dist/internal/call-urgent-handler.mjs +37 -0
- package/dist/internal/call-urgent-handler.mjs.map +1 -0
- package/dist/internal/css-transition-cut.mjs +66 -0
- package/dist/internal/css-transition-cut.mjs.map +1 -0
- package/dist/internal/overlay-popup.mjs.map +1 -1
- package/dist/internal/report-dropped.mjs +45 -0
- package/dist/internal/report-dropped.mjs.map +1 -0
- package/dist/internal/types.d.mts +33 -7
- package/dist/internal/types.d.mts.map +1 -1
- package/dist/internal/use-action-trigger.mjs +32 -17
- package/dist/internal/use-action-trigger.mjs.map +1 -1
- package/dist/internal/use-controllable-action.mjs +52 -16
- package/dist/internal/use-controllable-action.mjs.map +1 -1
- package/dist/internal/use-exit-animation.mjs +1 -1
- package/dist/internal/use-exit-animation.mjs.map +1 -1
- package/dist/internal/use-native-group-reconciliation.mjs +4 -2
- package/dist/internal/use-native-group-reconciliation.mjs.map +1 -1
- package/dist/internal/use-overlay-close.mjs +10 -4
- package/dist/internal/use-overlay-close.mjs.map +1 -1
- package/dist/internal/use-overlay-root.mjs +40 -7
- package/dist/internal/use-overlay-root.mjs.map +1 -1
- package/dist/internal/use-popover-popup.mjs +22 -7
- package/dist/internal/use-popover-popup.mjs.map +1 -1
- package/dist/internal/use-popover-trigger.d.mts +1 -1
- package/dist/internal/use-popover-trigger.d.mts.map +1 -1
- package/dist/internal/use-popover-trigger.mjs +11 -3
- package/dist/internal/use-popover-trigger.mjs.map +1 -1
- package/dist/menu/menu-checkbox-item.d.mts +1 -1
- package/dist/menu/menu-checkbox-item.mjs.map +1 -1
- package/dist/menu/menu-item.d.mts +15 -4
- package/dist/menu/menu-item.d.mts.map +1 -1
- package/dist/menu/menu-item.mjs +10 -5
- package/dist/menu/menu-item.mjs.map +1 -1
- package/dist/menu/menu-outside.mjs +2 -2
- package/dist/menu/menu-outside.mjs.map +1 -1
- package/dist/menu/menu-popup.d.mts +3 -0
- package/dist/menu/menu-popup.d.mts.map +1 -1
- package/dist/menu/menu-popup.mjs.map +1 -1
- package/dist/menu/menu-root.d.mts +27 -12
- package/dist/menu/menu-root.d.mts.map +1 -1
- package/dist/menu/menu-root.mjs +5 -4
- package/dist/menu/menu-root.mjs.map +1 -1
- package/dist/number-field/number-field-root.d.mts.map +1 -1
- package/dist/number-field/number-field-root.mjs +2 -8
- package/dist/number-field/number-field-root.mjs.map +1 -1
- package/dist/popover/index.d.mts +3 -3
- package/dist/popover/index.mjs +3 -3
- package/dist/popover/index.mjs.map +1 -1
- package/dist/popover/popover-close.d.mts +14 -3
- package/dist/popover/popover-close.d.mts.map +1 -1
- package/dist/popover/popover-close.mjs +4 -2
- package/dist/popover/popover-close.mjs.map +1 -1
- package/dist/popover/popover-popup.d.mts +6 -3
- package/dist/popover/popover-popup.d.mts.map +1 -1
- package/dist/popover/popover-popup.mjs +3 -2
- package/dist/popover/popover-popup.mjs.map +1 -1
- package/dist/popover/popover-root.d.mts +31 -18
- package/dist/popover/popover-root.d.mts.map +1 -1
- package/dist/popover/popover-root.mjs +9 -7
- package/dist/popover/popover-root.mjs.map +1 -1
- package/dist/slider/slider-root.d.mts.map +1 -1
- package/dist/slider/slider-root.mjs +2 -8
- package/dist/slider/slider-root.mjs.map +1 -1
- package/dist/toast/toast-action.d.mts +14 -3
- package/dist/toast/toast-action.d.mts.map +1 -1
- package/dist/toast/toast-action.mjs +6 -4
- package/dist/toast/toast-action.mjs.map +1 -1
- package/dist/toast/toast-context.mjs.map +1 -1
- package/dist/toast/toast-queue.mjs.map +1 -1
- package/dist/toast/toast-viewport.d.mts.map +1 -1
- package/dist/toast/toast-viewport.mjs +15 -15
- package/dist/toast/toast-viewport.mjs.map +1 -1
- package/dist/toast/toast.d.mts +10 -7
- package/dist/toast/toast.d.mts.map +1 -1
- package/dist/toast/toast.mjs.map +1 -1
- package/dist/toggle-group/toggle-group-root.mjs +1 -1
- package/dist/toggle-group/toggle-group-root.mjs.map +1 -1
- package/package.json +1 -1
- package/skills/funstack-ui-knowledge/SKILL.md +6 -6
- package/dist/internal/use-superseded-rejection.mjs +0 -47
- package/dist/internal/use-superseded-rejection.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Action, RenderProp, StateValue } from "../internal/types.mjs";
|
|
1
|
+
import { Action, RenderProp, StateValue, WhilePending } from "../internal/types.mjs";
|
|
2
2
|
import { ToastActionDetails, ToastItem } from "./toast.mjs";
|
|
3
3
|
import { CSSProperties, ComponentPropsWithRef, ReactNode } from "react";
|
|
4
4
|
//#region src/toast/toast-action.d.ts
|
|
@@ -34,6 +34,16 @@ export interface ToastActionProps extends Omit<ComponentPropsWithRef<"button">,
|
|
|
34
34
|
* @defaultValue `true`
|
|
35
35
|
*/
|
|
36
36
|
closeOnSettle?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* What a click does while this part's action is pending. `"ignore"`: nothing (the click is
|
|
39
|
+
* cancelled, `aria-disabled="true"` meanwhile): one Undo, one Retry. `"run"`: the action runs
|
|
40
|
+
* again; the Action and the Root stay `data-pending` and the timer paused until every run has
|
|
41
|
+
* settled. With `closeOnSettle` the toast then closes once, if the latest run resolved; a
|
|
42
|
+
* rejected latest run keeps it, as in `"ignore"` mode.
|
|
43
|
+
*
|
|
44
|
+
* @defaultValue `"ignore"`, or `"run"` with `closeOnSettle={false}`
|
|
45
|
+
*/
|
|
46
|
+
whilePending?: WhilePending;
|
|
37
47
|
/**
|
|
38
48
|
* The button's content, or a function of the part's state.
|
|
39
49
|
*
|
|
@@ -50,14 +60,15 @@ export interface ToastActionProps extends Omit<ComponentPropsWithRef<"button">,
|
|
|
50
60
|
/**
|
|
51
61
|
* The toast's action button (Undo, Retry, View): a `button type="button"` whose `action` runs as
|
|
52
62
|
* a transition. Renders nothing when neither the part nor the toast has an action. Never natively
|
|
53
|
-
* disabled while pending: a second click meanwhile is ignored and the Action is `aria-disabled
|
|
63
|
+
* disabled while pending: a second click meanwhile is ignored and the Action is `aria-disabled`,
|
|
64
|
+
* unless `whilePending` is `"run"` (the default with `closeOnSettle={false}`).
|
|
54
65
|
*
|
|
55
66
|
* Owned keys (conventions 1.2): `type` (on a `<button>` only), `onClick`, `aria-disabled`,
|
|
56
67
|
* `data-pending`.
|
|
57
68
|
*
|
|
58
69
|
* @see https://ui.funstack.work/components/toast
|
|
59
70
|
*/
|
|
60
|
-
export declare function ToastAction({ action, closeOnSettle, children, className, style, render, ...rest }: ToastActionProps): ReactNode;
|
|
71
|
+
export declare function ToastAction({ action, closeOnSettle, whilePending, children, className, style, render, ...rest }: ToastActionProps): ReactNode;
|
|
61
72
|
export declare namespace ToastAction {
|
|
62
73
|
var displayName: string;
|
|
63
74
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toast-action.d.mts","names":[],"sources":["../../src/toast/toast-action.tsx"],"mappings":";;;;;;;;iBAgBiB;;WAEN;;WAEA,OAAO;;;;;;;iBAQD,yBAAyB,KACxC;;;;;;;;;;EAYA,SAAS,QAAQ,SAAS;;;;;;EAM1B;;;;;;
|
|
1
|
+
{"version":3,"file":"toast-action.d.mts","names":[],"sources":["../../src/toast/toast-action.tsx"],"mappings":";;;;;;;;iBAgBiB;;WAEN;;WAEA,OAAO;;;;;;;iBAQD,yBAAyB,KACxC;;;;;;;;;;EAYA,SAAS,QAAQ,SAAS;;;;;;EAM1B;;;;;;;;;;EAUA,eAAe;;;;;;EAMf,WAAW,WAAW,WAAW;;EAEjC,YAAY,+BAA+B;;EAE3C,QAAQ,WAAW,2BAA2B;;EAE9C,SAAS,WAAW,iCAAiC;;;;;;;;;;;;;wBAcvC,cACd,QACA,eACA,cACA,UACA,WACA,OACA,WACG,QACF,mBAAgB;yBATH"}
|
|
@@ -10,16 +10,18 @@ import { useLayoutEffect, useState } from "react";
|
|
|
10
10
|
/**
|
|
11
11
|
* The toast's action button (Undo, Retry, View): a `button type="button"` whose `action` runs as
|
|
12
12
|
* a transition. Renders nothing when neither the part nor the toast has an action. Never natively
|
|
13
|
-
* disabled while pending: a second click meanwhile is ignored and the Action is `aria-disabled
|
|
13
|
+
* disabled while pending: a second click meanwhile is ignored and the Action is `aria-disabled`,
|
|
14
|
+
* unless `whilePending` is `"run"` (the default with `closeOnSettle={false}`).
|
|
14
15
|
*
|
|
15
16
|
* Owned keys (conventions 1.2): `type` (on a `<button>` only), `onClick`, `aria-disabled`,
|
|
16
17
|
* `data-pending`.
|
|
17
18
|
*
|
|
18
19
|
* @see https://ui.funstack.work/components/toast
|
|
19
20
|
*/
|
|
20
|
-
function ToastAction({ action, closeOnSettle = true, children, className, style, render, ...rest }) {
|
|
21
|
+
function ToastAction({ action, closeOnSettle = true, whilePending, children, className, style, render, ...rest }) {
|
|
21
22
|
const root = useToastRootContext("Toast.Action");
|
|
22
|
-
const
|
|
23
|
+
const ignoring = (whilePending ?? (closeOnSettle ? "ignore" : "run")) === "ignore";
|
|
24
|
+
const { pending, run } = useActionTrigger({ ignoreWhilePending: ignoring });
|
|
23
25
|
const [token] = useState(() => ({}));
|
|
24
26
|
const effective = action ?? root.toast.action?.action;
|
|
25
27
|
const { setActionPending } = root;
|
|
@@ -47,7 +49,7 @@ function ToastAction({ action, closeOnSettle = true, children, className, style,
|
|
|
47
49
|
const libraryProps = {
|
|
48
50
|
...rendersButton(render) && { type: "button" },
|
|
49
51
|
onClick,
|
|
50
|
-
"aria-disabled": pending ? true : void 0,
|
|
52
|
+
"aria-disabled": pending && ignoring ? true : void 0,
|
|
51
53
|
"data-pending": dataAttr(pending)
|
|
52
54
|
};
|
|
53
55
|
const element = useRender({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toast-action.mjs","names":[],"sources":["../../src/toast/toast-action.tsx"],"sourcesContent":["\"use client\";\nimport { useLayoutEffect, useState } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, MouseEvent, ReactNode } from \"react\";\nimport { createActionDetails } from \"../internal/action-details.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport type { Action, RenderProp, StateValue } from \"../internal/types.js\";\nimport { useActionTrigger } from \"../internal/use-action-trigger.js\";\nimport { rendersButton, useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport type { ToastActionDetails, ToastItem } from \"./toast.js\";\nimport { useToastRootContext } from \"./toast-context.js\";\n\n/**\n * State of `Toast.Action`, passed to the function forms of `className`, `style`, `children` and\n * `render`.\n */\nexport interface ToastActionState {\n /** This part's action is in flight. */\n readonly pending: boolean;\n /** The toast this Action belongs to. */\n readonly toast: ToastItem;\n}\n\n/**\n * Props of `Toast.Action`.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport interface ToastActionProps extends Omit<\n ComponentPropsWithRef<\"button\">,\n \"onClick\" | \"className\" | \"style\" | \"children\"\n> {\n /**\n * Runs in this part's own transition: `data-pending` on the Action and the Root, the toast's\n * timer paused. When it resolves the toast closes with `reason: \"activate\"` (unless\n * `closeOnSettle` is `false`); a rejection keeps the toast and reaches the nearest Error\n * Boundary above the Viewport. A caught error counts as success and closes the toast: rethrow\n * after `toast.update`, or use `closeOnSettle={false}`.\n *\n * @defaultValue the toast's `action.action`\n */\n action?: Action<[details: ToastActionDetails]>;\n /**\n * Close the toast when the action resolves.\n *\n * @defaultValue `true`\n */\n closeOnSettle?: boolean;\n /**\n * The button's content, or a function of the part's state.\n *\n * @defaultValue the toast's `action.label`\n */\n children?: StateValue<ReactNode, ToastActionState>;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, ToastActionState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, ToastActionState>;\n /** Replace the default `<button>` (element form) or take over rendering (function form). */\n render?: RenderProp<ComponentPropsWithRef<\"button\">, ToastActionState>;\n}\n\n/**\n * The toast's action button (Undo, Retry, View): a `button type=\"button\"` whose `action` runs as\n * a transition. Renders nothing when neither the part nor the toast has an action. Never natively\n * disabled while pending: a second click meanwhile is ignored and the Action is `aria-disabled
|
|
1
|
+
{"version":3,"file":"toast-action.mjs","names":[],"sources":["../../src/toast/toast-action.tsx"],"sourcesContent":["\"use client\";\nimport { useLayoutEffect, useState } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, MouseEvent, ReactNode } from \"react\";\nimport { createActionDetails } from \"../internal/action-details.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport type { Action, RenderProp, StateValue, WhilePending } from \"../internal/types.js\";\nimport { useActionTrigger } from \"../internal/use-action-trigger.js\";\nimport { rendersButton, useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport type { ToastActionDetails, ToastItem } from \"./toast.js\";\nimport { useToastRootContext } from \"./toast-context.js\";\n\n/**\n * State of `Toast.Action`, passed to the function forms of `className`, `style`, `children` and\n * `render`.\n */\nexport interface ToastActionState {\n /** This part's action is in flight. */\n readonly pending: boolean;\n /** The toast this Action belongs to. */\n readonly toast: ToastItem;\n}\n\n/**\n * Props of `Toast.Action`.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport interface ToastActionProps extends Omit<\n ComponentPropsWithRef<\"button\">,\n \"onClick\" | \"className\" | \"style\" | \"children\"\n> {\n /**\n * Runs in this part's own transition: `data-pending` on the Action and the Root, the toast's\n * timer paused. When it resolves the toast closes with `reason: \"activate\"` (unless\n * `closeOnSettle` is `false`); a rejection keeps the toast and reaches the nearest Error\n * Boundary above the Viewport. A caught error counts as success and closes the toast: rethrow\n * after `toast.update`, or use `closeOnSettle={false}`.\n *\n * @defaultValue the toast's `action.action`\n */\n action?: Action<[details: ToastActionDetails]>;\n /**\n * Close the toast when the action resolves.\n *\n * @defaultValue `true`\n */\n closeOnSettle?: boolean;\n /**\n * What a click does while this part's action is pending. `\"ignore\"`: nothing (the click is\n * cancelled, `aria-disabled=\"true\"` meanwhile): one Undo, one Retry. `\"run\"`: the action runs\n * again; the Action and the Root stay `data-pending` and the timer paused until every run has\n * settled. With `closeOnSettle` the toast then closes once, if the latest run resolved; a\n * rejected latest run keeps it, as in `\"ignore\"` mode.\n *\n * @defaultValue `\"ignore\"`, or `\"run\"` with `closeOnSettle={false}`\n */\n whilePending?: WhilePending;\n /**\n * The button's content, or a function of the part's state.\n *\n * @defaultValue the toast's `action.label`\n */\n children?: StateValue<ReactNode, ToastActionState>;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, ToastActionState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, ToastActionState>;\n /** Replace the default `<button>` (element form) or take over rendering (function form). */\n render?: RenderProp<ComponentPropsWithRef<\"button\">, ToastActionState>;\n}\n\n/**\n * The toast's action button (Undo, Retry, View): a `button type=\"button\"` whose `action` runs as\n * a transition. Renders nothing when neither the part nor the toast has an action. Never natively\n * disabled while pending: a second click meanwhile is ignored and the Action is `aria-disabled`,\n * unless `whilePending` is `\"run\"` (the default with `closeOnSettle={false}`).\n *\n * Owned keys (conventions 1.2): `type` (on a `<button>` only), `onClick`, `aria-disabled`,\n * `data-pending`.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport function ToastAction({\n action,\n closeOnSettle = true,\n whilePending,\n children,\n className,\n style,\n render,\n ...rest\n}: ToastActionProps) {\n const root = useToastRootContext(\"Toast.Action\");\n // Mixed ownership (conventions 2.5.1): ignore while the library closes the toast after the\n // action; a toast that stays makes the Action a user-owned trigger.\n const ignoring = (whilePending ?? (closeOnSettle ? \"ignore\" : \"run\")) === \"ignore\";\n const { pending, run } = useActionTrigger({ ignoreWhilePending: ignoring });\n const [token] = useState(() => ({}));\n const effective = action ?? root.toast.action?.action;\n const { setActionPending } = root;\n\n // The Root (and through it the Viewport's timer) sees this part's pending state.\n useLayoutEffect(() => {\n if (!pending) return;\n setActionPending(token, true);\n return () => setActionPending(token, false);\n }, [pending, setActionPending, token]);\n\n const state: ToastActionState = { pending, toast: root.toast };\n\n const onClick = (event: MouseEvent<HTMLElement>): void => {\n if (effective === undefined || rest.disabled === true) return;\n const native = event.nativeEvent;\n const details = createActionDetails(native, { id: root.toast.id });\n // When ignoring, a second click while this Action's own run is in flight starts nothing and\n // is cancelled (the hook's guard): one Undo, one Retry.\n const started = run(\n () => effective(details),\n () => {\n // Closing is idempotent: a dismissal meanwhile already closed it.\n if (closeOnSettle) root.close(\"activate\", native);\n },\n );\n if (!started) event.preventDefault();\n };\n\n const libraryProps: ComponentPropsWithRef<\"button\"> & DataAttributes = {\n ...(rendersButton(render) && { type: \"button\" as const }),\n onClick,\n // Exactly while `data-pending` when ignoring. Owned, so an idle Action removes a render\n // element's own.\n \"aria-disabled\": pending && ignoring ? true : undefined,\n \"data-pending\": dataAttr(pending),\n };\n\n const element = useRender<ComponentPropsWithRef<\"button\">, ToastActionState>({\n defaultElement: \"button\",\n render,\n state,\n className,\n style,\n children: children ?? root.toast.action?.label,\n props: rest,\n libraryProps,\n });\n return effective === undefined ? null : element;\n}\n\nToastAction.displayName = \"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
1
|
-
{"version":3,"file":"toast-context.mjs","names":[],"sources":["../../src/toast/toast-context.ts"],"sourcesContent":["\"use client\";\nimport { createContext, use } from \"react\";\nimport type { ChangeReason } from \"../internal/types.js\";\nimport type { ToastRootState } from \"./toast-root.js\";\nimport type { ToastItem, ToastPriority } from \"./toast.js\";\n\n/** What a Root (and the parts under it) need from the Viewport. Stable for the Viewport's life. */\nexport interface ToastViewportContextValue {\n /** Close toasts (`ending: true`), moving focus out first and
|
|
1
|
+
{"version":3,"file":"toast-context.mjs","names":[],"sources":["../../src/toast/toast-context.ts"],"sourcesContent":["\"use client\";\nimport { createContext, use } from \"react\";\nimport type { ChangeReason } from \"../internal/types.js\";\nimport type { ToastRootState } from \"./toast-root.js\";\nimport type { ToastItem, ToastPriority } from \"./toast.js\";\n\n/** What a Root (and the parts under it) need from the Viewport. Stable for the Viewport's life. */\nexport interface ToastViewportContextValue {\n /** Close toasts (`ending: true`), moving focus out first and calling each `onClose`. */\n readonly close: (ids: readonly string[], reason: ChangeReason, event: Event | undefined) => void;\n /** Remove an ending toast once its exit animations finished. */\n readonly drop: (id: string) => void;\n /** An action dispatched through the toast's Action part is (no longer) in flight. */\n readonly setActionPending: (id: string, pending: boolean) => void;\n /** The toast's content is (no longer) suspended behind the Root's guard. */\n readonly setSuspended: (id: string, suspended: boolean) => void;\n /** The Root's element, for arrow keys, the hotkey and focus moves; `null` to unregister. */\n readonly registerRoot: (id: string, element: HTMLElement | null) => void;\n /** Focus the next (`1`) or previous (`-1`) toast's Root, without wrapping. */\n readonly focusSibling: (id: string, direction: 1 | -1) => void;\n /** Queue an announcement; skipped when `text` equals the last one announced for `id`. */\n readonly announce: (id: string, text: string | null, priority: ToastPriority) => void;\n /** The Viewport's `announce` prop, read at announcement time. */\n readonly announcer: () => ((toast: ToastItem) => string | null) | undefined;\n /**\n * The animations that ran in the toast before it was marked ending (kept until it is dropped\n * or replaced): its exit waits only for the others.\n */\n readonly exitBaseline: (id: string) => ReadonlySet<Animation> | undefined;\n}\n\nexport const ToastViewportContext = createContext<ToastViewportContextValue | null>(null);\n\nexport function useToastViewportContext(part: string): ToastViewportContextValue {\n const context = use(ToastViewportContext);\n if (context === null) {\n throw new Error(`${part} must be rendered inside a Toast.Viewport.`);\n }\n return context;\n}\n\n/** What the parts inside a Root need. */\nexport interface ToastRootContextValue {\n readonly toast: ToastItem;\n readonly ids: { readonly title: string; readonly description: string };\n /** Root state, so Title and Description can resolve their function props against it. */\n readonly state: ToastRootState;\n readonly registerTitle: (element: HTMLElement | null) => void;\n readonly registerDescription: (element: HTMLElement | null) => void;\n /** An Action part's run is (no longer) in flight; `token` identifies the part. */\n readonly setActionPending: (token: object, pending: boolean) => void;\n /**\n * A Title or Description committed: mounted, or shown again by a Suspense boundary inside the\n * Root (the consumer's skeleton), so the Root announces the text that now exists.\n */\n readonly contentCommitted: () => void;\n /** The Suspense guard mounted (`true`) or unmounted (`false`). */\n readonly setSuspended: (suspended: boolean) => void;\n /** Close this toast. */\n readonly close: (reason: ChangeReason, event: Event | undefined) => void;\n}\n\nexport const ToastRootContext = createContext<ToastRootContextValue | null>(null);\n\nexport function useToastRootContext(part: string): ToastRootContextValue {\n const context = use(ToastRootContext);\n if (context === null) {\n throw new Error(`${part} must be rendered inside a Toast.Root.`);\n }\n return context;\n}\n"],"mappings":";;;AA+BA,MAAa,uBAAuB,cAAgD,IAAI;AAExF,SAAgB,wBAAwB,MAAyC;CAC/E,MAAM,UAAU,IAAI,oBAAoB;CACxC,IAAI,YAAY,MACd,MAAM,IAAI,MAAM,GAAG,KAAK,2CAA2C;CAErE,OAAO;AACT;AAuBA,MAAa,mBAAmB,cAA4C,IAAI;AAEhF,SAAgB,oBAAoB,MAAqC;CACvE,MAAM,UAAU,IAAI,gBAAgB;CACpC,IAAI,YAAY,MACd,MAAM,IAAI,MAAM,GAAG,KAAK,uCAAuC;CAEjE,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toast-queue.mjs","names":[],"sources":["../../src/toast/toast-queue.ts"],"sourcesContent":["// The Viewport's queue model (design/components/toast.md 8, 12): entries, their public items, and\n// which of them render. No \"use client\" directive: pure (conventions 7.1).\nimport type { ToastCommand, ToastItem, ToastOptions } from \"./toast.js\";\n\n/** One queue entry: the toast's options and the flags its `ToastItem` is built from. */\nexport interface Entry {\n readonly options: ToastOptions & { readonly id: string };\n readonly promisePending: boolean;\n readonly actionPending: boolean;\n readonly ending: boolean;\n /** The public item, rebuilt whenever any of the above changes (stable identity otherwise). */\n readonly item: ToastItem;\n}\n\nexport function makeEntry(\n options: ToastOptions & { readonly id: string },\n flags: { promisePending: boolean; actionPending: boolean; ending: boolean },\n): Entry {\n return {\n options,\n ...flags,\n item: {\n ...options,\n id: options.id,\n pending: flags.promisePending || flags.actionPending,\n ending: flags.ending,\n },\n };\n}\n\nexport function withFlags(\n entry: Entry,\n flags: Partial<{ promisePending: boolean; actionPending: boolean; ending: boolean }>,\n): Entry {\n return makeEntry(entry.options, {\n promisePending: flags.promisePending ?? entry.promisePending,\n actionPending: flags.actionPending ?? entry.actionPending,\n ending: flags.ending ?? entry.ending,\n });\n}\n\n/** Rendered entries (the first `limit` open ones plus every ending one) and the queued count. */\nexport function partition(\n entries: readonly Entry[],\n limit: number,\n): { visible: Entry[]; queued: Entry[] } {\n const visible: Entry[] = [];\n const queued: Entry[] = [];\n let open = 0;\n for (const entry of entries) {\n if (entry.ending) visible.push(entry);\n else if (open < limit) {\n visible.push(entry);\n open++;\n } else queued.push(entry);\n }\n return { visible, queued };\n}\n\n/** Plain text of a `ReactNode` that is text (queued toasts have no DOM to read yet). */\nexport function plainText(node: unknown): string {\n if (typeof node === \"string\") return node;\n if (typeof node === \"number\" || typeof node === \"bigint\") return String(node);\n if (Array.isArray(node)) return node.map(plainText).join(\"\");\n return \"\";\n}\n\nexport interface AppliedCommands {\n readonly next: readonly Entry[];\n /** The open toasts the batch dismissed, in order (their `
|
|
1
|
+
{"version":3,"file":"toast-queue.mjs","names":[],"sources":["../../src/toast/toast-queue.ts"],"sourcesContent":["// The Viewport's queue model (design/components/toast.md 8, 12): entries, their public items, and\n// which of them render. No \"use client\" directive: pure (conventions 7.1).\nimport type { ToastCommand, ToastItem, ToastOptions } from \"./toast.js\";\n\n/** One queue entry: the toast's options and the flags its `ToastItem` is built from. */\nexport interface Entry {\n readonly options: ToastOptions & { readonly id: string };\n readonly promisePending: boolean;\n readonly actionPending: boolean;\n readonly ending: boolean;\n /** The public item, rebuilt whenever any of the above changes (stable identity otherwise). */\n readonly item: ToastItem;\n}\n\nexport function makeEntry(\n options: ToastOptions & { readonly id: string },\n flags: { promisePending: boolean; actionPending: boolean; ending: boolean },\n): Entry {\n return {\n options,\n ...flags,\n item: {\n ...options,\n id: options.id,\n pending: flags.promisePending || flags.actionPending,\n ending: flags.ending,\n },\n };\n}\n\nexport function withFlags(\n entry: Entry,\n flags: Partial<{ promisePending: boolean; actionPending: boolean; ending: boolean }>,\n): Entry {\n return makeEntry(entry.options, {\n promisePending: flags.promisePending ?? entry.promisePending,\n actionPending: flags.actionPending ?? entry.actionPending,\n ending: flags.ending ?? entry.ending,\n });\n}\n\n/** Rendered entries (the first `limit` open ones plus every ending one) and the queued count. */\nexport function partition(\n entries: readonly Entry[],\n limit: number,\n): { visible: Entry[]; queued: Entry[] } {\n const visible: Entry[] = [];\n const queued: Entry[] = [];\n let open = 0;\n for (const entry of entries) {\n if (entry.ending) visible.push(entry);\n else if (open < limit) {\n visible.push(entry);\n open++;\n } else queued.push(entry);\n }\n return { visible, queued };\n}\n\n/** Plain text of a `ReactNode` that is text (queued toasts have no DOM to read yet). */\nexport function plainText(node: unknown): string {\n if (typeof node === \"string\") return node;\n if (typeof node === \"number\" || typeof node === \"bigint\") return String(node);\n if (Array.isArray(node)) return node.map(plainText).join(\"\");\n return \"\";\n}\n\nexport interface AppliedCommands {\n readonly next: readonly Entry[];\n /** The open toasts the batch dismissed, in order (their `onClose` handlers run). */\n readonly dismissed: readonly Entry[];\n /** Dismissed ids that leave the DOM: not those replaced by a later add with the id. */\n readonly leaving: ReadonlySet<string>;\n /**\n * Ids whose announcement and exit baseline start over: dismissed before they rendered, or an\n * ending toast replaced by a new one with its id (listed in `replaced` too).\n */\n readonly forgotten: readonly string[];\n /** Ending toasts replaced by a new add with their id: their timer starts over. */\n readonly replaced: readonly string[];\n /** The batch added a toast (the region re-raises). */\n readonly added: boolean;\n /** Ids of updates that found no toast (a promise settle excepted). */\n readonly missing: readonly string[];\n}\n\n/**\n * Applies a batch of manager commands to the queue. Dismissals apply in order: each closes the\n * toasts open at that point of the batch, never one added after it. A dismissed toast with a\n * rendered Root (`isRendered`) turns ending; one never rendered (queued beyond `limit`, or added\n * in this tick) leaves at once instead of mounting once as an ending Root. An add with the id of\n * an open toast updates it (\"one toast per key\"); with the id of an ending one it replaces it\n * (the keyed Root may be reused): a fresh timer, a fresh announcement, no exit.\n */\nexport function applyCommands(\n entries: readonly Entry[],\n commands: readonly ToastCommand[],\n isRendered: (id: string) => boolean,\n): AppliedCommands {\n const next = [...entries];\n const dismissed: Entry[] = [];\n const forgotten: string[] = [];\n const replaced: string[] = [];\n const missing: string[] = [];\n let added = false;\n for (const command of commands) {\n if (command.kind === \"dismiss\") {\n for (let i = 0; i < next.length; i++) {\n const entry = next[i]!;\n if (entry.ending) continue;\n const id = entry.options.id;\n if (command.id !== undefined && id !== command.id) continue;\n dismissed.push(entry);\n if (isRendered(id)) {\n next[i] = withFlags(entry, { ending: true });\n } else {\n next.splice(i--, 1);\n forgotten.push(id);\n }\n }\n continue;\n }\n const index = next.findIndex((e) => e.options.id === command.id);\n const existing = index === -1 ? undefined : next[index]!;\n if (command.kind === \"add\") {\n const options = { ...command.options, id: command.id };\n if (existing !== undefined && !existing.ending) {\n next[index] = makeEntry(\n { ...existing.options, ...options },\n {\n promisePending: command.pending || existing.promisePending,\n actionPending: existing.actionPending,\n ending: false,\n },\n );\n continue;\n }\n if (existing !== undefined) {\n next.splice(index, 1);\n replaced.push(command.id);\n forgotten.push(command.id);\n }\n next.push(\n makeEntry(options, {\n promisePending: command.pending,\n actionPending: false,\n ending: false,\n }),\n );\n added = true;\n } else {\n if (existing === undefined) {\n if (!command.settle) missing.push(command.id);\n continue;\n }\n if (existing.ending) continue;\n const options = command.settle\n ? { ...command.options, id: command.id }\n : { ...existing.options, ...command.options, id: command.id };\n next[index] = makeEntry(options, {\n promisePending: command.settle ? false : existing.promisePending,\n actionPending: existing.actionPending,\n ending: false,\n });\n }\n }\n const stays = new Set(next.filter((e) => !e.ending).map((e) => e.options.id));\n const leaving = new Set(dismissed.map((e) => e.options.id).filter((id) => !stays.has(id)));\n return { next, dismissed, leaving, forgotten, replaced, added, missing };\n}\n"],"mappings":";AAcA,SAAgB,UACd,SACA,OACO;CACP,OAAO;EACL;EACA,GAAG;EACH,MAAM;GACJ,GAAG;GACH,IAAI,QAAQ;GACZ,SAAS,MAAM,kBAAkB,MAAM;GACvC,QAAQ,MAAM;EAChB;CACF;AACF;AAEA,SAAgB,UACd,OACA,OACO;CACP,OAAO,UAAU,MAAM,SAAS;EAC9B,gBAAgB,MAAM,kBAAkB,MAAM;EAC9C,eAAe,MAAM,iBAAiB,MAAM;EAC5C,QAAQ,MAAM,UAAU,MAAM;CAChC,CAAC;AACH;;AAGA,SAAgB,UACd,SACA,OACuC;CACvC,MAAM,UAAmB,CAAC;CAC1B,MAAM,SAAkB,CAAC;CACzB,IAAI,OAAO;CACX,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,QAAQ,QAAQ,KAAK,KAAK;MAC/B,IAAI,OAAO,OAAO;EACrB,QAAQ,KAAK,KAAK;EAClB;CACF,OAAO,OAAO,KAAK,KAAK;CAE1B,OAAO;EAAE;EAAS;CAAO;AAC3B;;AAGA,SAAgB,UAAU,MAAuB;CAC/C,IAAI,OAAO,SAAS,UAAU,OAAO;CACrC,IAAI,OAAO,SAAS,YAAY,OAAO,SAAS,UAAU,OAAO,OAAO,IAAI;CAC5E,IAAI,MAAM,QAAQ,IAA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UAAU,KAAK,QAAQ,EAAE;GAC3B;GACA,KAAK,KACH,UAAU,SAAS;IACjB,gBAAgB,QAAQ;IACxB,eAAe;IACf,QAAQ;GACV,CAAC,CACH;GACA,QAAQ;EACV,OAAO;GACL,IAAI,aAAa,KAAA,GAAW;IAC1B,IAAI,CAAC,QAAQ,QAAQ,QAAQ,KAAK,QAAQ,EAAE;IAC5C;GACF;GACA,IAAI,SAAS,QAAQ;GAIrB,KAAK,SAAS,UAHE,QAAQ,SACpB;IAAE,GAAG,QAAQ;IAAS,IAAI,QAAQ;GAAG,IACrC;IAAE,GAAG,SAAS;IAAS,GAAG,QAAQ;IAAS,IAAI,QAAQ;GAAG,GAC7B;IAC/B,gBAAgB,QAAQ,SAAS,QAAQ,SAAS;IAClD,eAAe,SAAS;IACxB,QAAQ;GACV,CAAC;EACH;CACF;CACA,MAAM,QAAQ,IAAI,IAAI,KAAK,QAAQ,MAAM,CAAC,EAAE,MAAM,CAAC,CAAC,KAAK,MAAM,EAAE,QAAQ,EAAE,CAAC;CAE5E,OAAO;EAAE;EAAM;EAAW,SAAA,IADN,IAAI,UAAU,KAAK,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CACxD;EAAG;EAAW;EAAU;EAAO;CAAQ;AACzE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toast-viewport.d.mts","names":[],"sources":["../../src/toast/toast-viewport.tsx"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"toast-viewport.d.mts","names":[],"sources":["../../src/toast/toast-viewport.tsx"],"mappings":";;;;;;;;iBAsCiB;;WAEN,iBAAiB;;WAEjB;;WAEA;;;;;;;iBAQM,2BAA2B,KAC1C;;;;;;EAgBA,UAAU;;;;;;EAMV;;;;;;EAMA;;;;;;;;EAQA;;;;;;;EAOA,YAAY,OAAO;;EAEnB,WAAW,WAAW,WAAW;;EAEjC,YAAY,+BAA+B;;EAE3C,QAAQ,WAAW,2BAA2B;;EAE9C,SAAS,WAAW,kCAAkC;;;;;;;;;;;;;wBAiCxC,gBACd,SACA,OACA,UACA,QACA,UACA,UACA,WACA,OACA,WACG,QACF,qCAAkB,IAAA;yBAXL"}
|
|
@@ -7,6 +7,7 @@ import { useLatest } from "../internal/use-latest.mjs";
|
|
|
7
7
|
import { isPopoverOpen } from "../internal/popover-open.mjs";
|
|
8
8
|
import { DialogContext } from "../dialog/dialog-context.mjs";
|
|
9
9
|
import { animationBaseline } from "../internal/use-exit-animation.mjs";
|
|
10
|
+
import { callUrgentHandler } from "../internal/call-urgent-handler.mjs";
|
|
10
11
|
import { announce } from "../internal/announce.mjs";
|
|
11
12
|
import { ToastViewportContext } from "./toast-context.mjs";
|
|
12
13
|
import { toast, toastManagerInternals } from "./toast.mjs";
|
|
@@ -14,7 +15,7 @@ import { DEFAULT_HOTKEY, matchesHotkey, regionLabel } from "./toast-hotkey.mjs";
|
|
|
14
15
|
import { clearToastTimers, syncToastTimers } from "./toast-timers.mjs";
|
|
15
16
|
import { useModalPortalHost } from "./use-modal-portal-host.mjs";
|
|
16
17
|
import { applyCommands, makeEntry, partition, plainText, withFlags } from "./toast-queue.mjs";
|
|
17
|
-
import { use, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState
|
|
18
|
+
import { use, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
18
19
|
import { createPortal } from "react-dom";
|
|
19
20
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
20
21
|
//#region src/toast/toast-viewport.tsx
|
|
@@ -48,7 +49,6 @@ function ToastViewport({ manager = toast, limit = 3, duration = 5e3, hotkey = DE
|
|
|
48
49
|
retain: () => handlers.current.retain()
|
|
49
50
|
};
|
|
50
51
|
const [rejected, setRejected] = useState(() => toastManagerInternals(manager).isTaken(listener.current));
|
|
51
|
-
const [, startCloseTransition] = useTransition();
|
|
52
52
|
const regionRef = useRef(null);
|
|
53
53
|
const roots = useRef(/* @__PURE__ */ new Map());
|
|
54
54
|
const suspended = useRef(/* @__PURE__ */ new Set());
|
|
@@ -141,20 +141,20 @@ function ToastViewport({ manager = toast, limit = 3, duration = 5e3, hotkey = DE
|
|
|
141
141
|
exitBaselines.current.set(id, animationBaseline(element));
|
|
142
142
|
}
|
|
143
143
|
};
|
|
144
|
-
|
|
144
|
+
/**
|
|
145
|
+
* A toast's `onClose` (#148: a handler, not an action): called synchronously where the close is
|
|
146
|
+
* applied to the queue, after the entry is marked ending, outside any transition, and not
|
|
147
|
+
* awaited (`callUrgentHandler`: a throw or a returned promise's rejection goes to
|
|
148
|
+
* `reportError`, the queue write above stands).
|
|
149
|
+
*/
|
|
150
|
+
const callCloseHandlers = (closed, reason, event) => {
|
|
145
151
|
for (const entry of closed) {
|
|
146
|
-
const
|
|
147
|
-
if (
|
|
148
|
-
|
|
152
|
+
const onClose = entry.options.onClose;
|
|
153
|
+
if (onClose === void 0) continue;
|
|
154
|
+
callUrgentHandler(onClose, createActionDetails(event, {
|
|
149
155
|
id: entry.options.id,
|
|
150
156
|
reason
|
|
151
|
-
});
|
|
152
|
-
queueMicrotask(() => {
|
|
153
|
-
if (!mounted.current) return;
|
|
154
|
-
startCloseTransition(async () => {
|
|
155
|
-
await closeAction(details);
|
|
156
|
-
});
|
|
157
|
-
});
|
|
157
|
+
}));
|
|
158
158
|
}
|
|
159
159
|
};
|
|
160
160
|
const close = (ids, reason, event) => {
|
|
@@ -166,7 +166,7 @@ function ToastViewport({ manager = toast, limit = 3, duration = 5e3, hotkey = DE
|
|
|
166
166
|
snapshotExitBaselines(closingIds);
|
|
167
167
|
write(entriesRef.current.map((e) => closingIds.has(e.options.id) ? withFlags(e, { ending: true }) : e));
|
|
168
168
|
syncTimers();
|
|
169
|
-
|
|
169
|
+
callCloseHandlers(closing, reason, event);
|
|
170
170
|
};
|
|
171
171
|
const drop = (id) => {
|
|
172
172
|
const next = entriesRef.current.filter((e) => !(e.ending && e.options.id === id));
|
|
@@ -192,7 +192,7 @@ function ToastViewport({ manager = toast, limit = 3, duration = 5e3, hotkey = DE
|
|
|
192
192
|
snapshotExitBaselines(result.leaving);
|
|
193
193
|
write(result.next);
|
|
194
194
|
syncTimers();
|
|
195
|
-
|
|
195
|
+
callCloseHandlers(result.dismissed, "dismiss", void 0);
|
|
196
196
|
};
|
|
197
197
|
const setActionPending = (id, pending) => {
|
|
198
198
|
const index = entriesRef.current.findIndex((e) => e.options.id === id);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toast-viewport.mjs","names":["defaultManager"],"sources":["../../src/toast/toast-viewport.tsx"],"sourcesContent":["\"use client\";\nimport {\n use,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n} from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, FocusEvent, ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { DialogContext } from \"../dialog/dialog-context.js\";\nimport { createActionDetails } from \"../internal/action-details.js\";\nimport { announce as speak } from \"../internal/announce.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { isPopoverOpen } from \"../internal/popover-open.js\";\nimport type { ChangeReason, RenderProp, StateValue } from \"../internal/types.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { animationBaseline } from \"../internal/use-exit-animation.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { toast as defaultManager, toastManagerInternals } from \"./toast.js\";\nimport type {\n RetainedToast,\n ToastCommand,\n ToastItem,\n ToastListener,\n ToastManager,\n ToastPriority,\n} from \"./toast.js\";\nimport { ToastViewportContext } from \"./toast-context.js\";\nimport type { ToastViewportContextValue } from \"./toast-context.js\";\nimport { DEFAULT_HOTKEY, matchesHotkey, regionLabel } from \"./toast-hotkey.js\";\nimport { clearToastTimers, syncToastTimers } from \"./toast-timers.js\";\nimport type { ToastTimer } from \"./toast-timers.js\";\nimport { useModalPortalHost } from \"./use-modal-portal-host.js\";\nimport { applyCommands, makeEntry, partition, plainText, withFlags } from \"./toast-queue.js\";\nimport type { Entry } from \"./toast-queue.js\";\n\n/**\n * State of `Toast.Viewport`, passed to the function forms of `className`, `style`, `children` and\n * `render`.\n */\nexport interface ToastViewportState {\n /** Rendered toasts, chronological (oldest first), exiting ones included. */\n readonly toasts: readonly ToastItem[];\n /** Toasts waiting beyond `limit`. */\n readonly queued: number;\n /** A viewport-wide pause holds (pointer over the region, focus inside, hidden document, blurred window). */\n readonly paused: boolean;\n}\n\n/**\n * Props of `Toast.Viewport`.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport interface ToastViewportProps extends Omit<\n ComponentPropsWithRef<\"section\">,\n | \"popover\"\n | \"className\"\n | \"style\"\n | \"children\"\n | \"onPointerEnter\"\n | \"onPointerLeave\"\n | \"onFocus\"\n | \"onBlur\"\n | \"onKeyDown\"\n> {\n /**\n * The queue to render (from `createToastManager()`).\n *\n * @defaultValue the module-level `toast`\n */\n manager?: ToastManager;\n /**\n * Toasts rendered at once; further ones wait in order (never dropped).\n *\n * @defaultValue `3`\n */\n limit?: number;\n /**\n * Default `duration` of a toast in milliseconds; `null` for persistent.\n *\n * @defaultValue `5000`\n */\n duration?: number | null;\n /**\n * Keys that focus the newest toast: `event.code` values and modifier names (`\"altKey\"`,\n * `\"ctrlKey\"`, `\"metaKey\"`, `\"shiftKey\"`), all of which must match, with no other modifier\n * held. `null` installs no listener.\n *\n * @defaultValue `[\"F8\"]`\n */\n hotkey?: readonly string[] | null;\n /**\n * The text `document.ariaNotify()` speaks for a toast (localisation); `null` announces nothing.\n * A toast's own `announce` wins.\n *\n * @defaultValue the text of the toast's Title and Description\n */\n announce?: (toast: ToastItem) => string | null;\n /** Usually a function of the state mapping `state.toasts` to `Toast.Root`s. */\n children?: StateValue<ReactNode, ToastViewportState>;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, ToastViewportState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, ToastViewportState>;\n /** Must render an element that can carry `popover` (a `<section>` by default). */\n render?: RenderProp<ComponentPropsWithRef<\"section\">, ToastViewportState>;\n}\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** Document order. */\nfunction byDocumentPosition(a: Element, b: Element): number {\n if (a === b) return 0;\n return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;\n}\n\ninterface PauseSources {\n hover: boolean;\n focus: boolean;\n hidden: boolean;\n blurred: boolean;\n}\n\nfunction anyPause(sources: PauseSources): boolean {\n return sources.hover || sources.focus || sources.hidden || sources.blurred;\n}\n\n/**\n * The toast region: a `<section popover=\"manual\">` named \"Notifications (F8)\", shown in the top\n * layer while it has toasts. Owns the queue (urgent state fed by `toast()`), the timers and their\n * pausing, the hotkey, focus return, announcements through `document.ariaNotify()`, and the move\n * into the topmost open modal `Dialog` (a region outside it would be inert).\n *\n * Owned keys (conventions 1.2): `popover`, `aria-label` (the consumer's own `aria-label` wins\n * verbatim), `data-paused`, `data-empty`, and the pointer / focus handlers.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport function ToastViewport({\n manager = defaultManager,\n limit = 3,\n duration = 5000,\n hotkey = DEFAULT_HOTKEY,\n announce,\n children,\n className,\n style,\n render,\n ...rest\n}: ToastViewportProps) {\n // --- The queue: urgent state, written only from handlers, microtasks and effects -----------\n const [entries, setEntries] = useState<readonly Entry[]>([]);\n // The latest queue, written together with every `setEntries`: the dispatchers read and write\n // it synchronously so a burst of commands composes (and side effects stay out of updaters).\n const entriesRef = useRef<readonly Entry[]>(entries);\n const listener = useRef<ToastListener | null>(null);\n listener.current ??= {\n restore: (toasts: readonly RetainedToast[]) => handlers.current.restore(toasts),\n apply: (commands: readonly ToastCommand[]) => handlers.current.apply(commands),\n retain: () => handlers.current.retain(),\n };\n // A second Viewport on a taken manager renders nothing from its first render on (the effect\n // below confirms or clears it once the subscription is attempted).\n const [rejected, setRejected] = useState(() =>\n toastManagerInternals(manager).isTaken(listener.current!),\n );\n const [, startCloseTransition] = useTransition();\n\n const regionRef = useRef<HTMLElement | null>(null);\n const roots = useRef(new Map<string, HTMLElement>());\n const suspended = useRef(new Set<string>());\n const timers = useRef(new Map<string, ToastTimer>());\n const pauses = useRef<PauseSources>({\n hover: false,\n focus: false,\n hidden: false,\n blurred: false,\n });\n const [paused, setPaused] = useState(false);\n /** Where focus goes back to once the last toast holding it leaves (design 7). */\n const returnTarget = useRef<HTMLElement | null>(null);\n const lastAnnounced = useRef(new Map<string, string | null>());\n /** Per closing toast: the animations already running before `data-ending` applied. */\n const exitBaselines = useRef(new Map<string, ReadonlySet<Animation>>());\n const announceBatch = useRef<{ text: string; priority: ToastPriority }[]>([]);\n const addedSinceEffect = useRef(false);\n const mounted = useRef(false);\n\n const latest = useLatest({ limit, duration, hotkey, announce });\n\n const write = (next: readonly Entry[]): void => {\n entriesRef.current = next;\n setEntries(next);\n };\n\n // --- Timers (design 6) ----------------------------------------------------------------------\n\n const syncTimers = (): void => {\n syncToastTimers(timers.current, partition(entriesRef.current, latest.current.limit).visible, {\n halted: !mounted.current || anyPause(pauses.current),\n suspended: suspended.current,\n defaultDuration: latest.current.duration,\n expire: (id) => close([id], \"timeout\", undefined),\n });\n };\n\n const setPause = (source: keyof PauseSources, value: boolean): void => {\n if (pauses.current[source] === value) return;\n pauses.current[source] = value;\n // Applied synchronously in the event, before any timer callback can run (design 14 item 9).\n syncTimers();\n setPaused(anyPause(pauses.current));\n };\n\n // --- Focus ----------------------------------------------------------------------------------\n\n /** Open toasts' Root elements in document order. */\n const sortedRoots = (exclude?: ReadonlySet<string>): { id: string; element: HTMLElement }[] => {\n const open = new Set(entriesRef.current.filter((e) => !e.ending).map((e) => e.options.id));\n const list: { id: string; element: HTMLElement }[] = [];\n for (const [id, element] of roots.current) {\n if (!open.has(id) || exclude?.has(id) || !element.isConnected) continue;\n list.push({ id, element });\n }\n return list.sort((a, b) => byDocumentPosition(a.element, b.element));\n };\n\n /**\n * Before toasts close: if focus is inside one of them, move it to the next toast, else the\n * previous one, else where it was before the region was entered, else the body (design 7).\n */\n const moveFocusOut = (closing: ReadonlySet<string>): void => {\n const doc = regionRef.current?.ownerDocument ?? document;\n const active = doc.activeElement;\n if (!(active instanceof HTMLElement)) return;\n const all = sortedRoots();\n const index = all.findIndex(({ element }) => element.contains(active));\n if (index === -1 || !closing.has(all[index]!.id)) return;\n const after = all.slice(index + 1).find(({ id }) => !closing.has(id));\n const before = all\n .slice(0, index)\n .reverse()\n .find(({ id }) => !closing.has(id));\n const target = after ?? before;\n if (target !== undefined) {\n target.element.focus();\n return;\n }\n const stored = returnTarget.current;\n if (stored !== null && stored.isConnected && !regionRef.current?.contains(stored)) {\n stored.focus();\n if (doc.activeElement === stored) return;\n }\n active.blur();\n };\n\n // --- Queue writes ---------------------------------------------------------------------------\n\n /**\n * Records the animations running in each closing toast before `data-ending` applies: the exit\n * waits only for the ones the ending state started, not for a running progress bar.\n */\n const snapshotExitBaselines = (ids: Iterable<string>): void => {\n for (const id of ids) {\n const element = roots.current.get(id);\n if (element === undefined) continue;\n exitBaselines.current.set(id, animationBaseline(element));\n }\n };\n\n const scheduleCloseActions = (\n closed: readonly Entry[],\n reason: ChangeReason,\n event: Event | undefined,\n ): void => {\n for (const entry of closed) {\n const closeAction = entry.options.closeAction;\n if (closeAction === undefined) continue;\n const details = createActionDetails(event, { id: entry.options.id, reason });\n // Not in the closing handler itself: the toast is gone first, then the action runs in the\n // Viewport's own transition (its rejection reaches the boundary above the Viewport).\n queueMicrotask(() => {\n if (!mounted.current) return;\n startCloseTransition(async () => {\n await closeAction(details);\n });\n });\n }\n };\n\n const close = (ids: readonly string[], reason: ChangeReason, event: Event | undefined): void => {\n const wanted = new Set(ids);\n const closing = entriesRef.current.filter((e) => !e.ending && wanted.has(e.options.id));\n if (closing.length === 0) return;\n const closingIds = new Set(closing.map((e) => e.options.id));\n moveFocusOut(closingIds);\n snapshotExitBaselines(closingIds);\n write(\n entriesRef.current.map((e) =>\n closingIds.has(e.options.id) ? withFlags(e, { ending: true }) : e,\n ),\n );\n syncTimers();\n scheduleCloseActions(closing, reason, event);\n };\n\n const drop = (id: string): void => {\n const next = entriesRef.current.filter((e) => !(e.ending && e.options.id === id));\n if (next.length === entriesRef.current.length) return;\n lastAnnounced.current.delete(id);\n exitBaselines.current.delete(id);\n write(next);\n };\n\n const apply = (commands: readonly ToastCommand[]): void => {\n const result = applyCommands(entriesRef.current, commands, (id) => roots.current.has(id));\n for (const id of result.replaced) clearToastTimers(timers.current, id);\n for (const id of result.forgotten) {\n lastAnnounced.current.delete(id);\n exitBaselines.current.delete(id);\n }\n if (result.added) addedSinceEffect.current = true;\n if (isDev) {\n for (const id of result.missing) {\n console.error(`toast.update: no toast with id \"${id}\"; the update is ignored.`);\n }\n }\n if (result.dismissed.length === 0) {\n write(result.next);\n return;\n }\n moveFocusOut(result.leaving);\n snapshotExitBaselines(result.leaving);\n write(result.next);\n syncTimers();\n scheduleCloseActions(result.dismissed, \"dismiss\", undefined);\n };\n\n const setActionPending = (id: string, pending: boolean): void => {\n const index = entriesRef.current.findIndex((e) => e.options.id === id);\n if (index === -1) return;\n const entry = entriesRef.current[index]!;\n if (entry.actionPending === pending) return;\n const next = [...entriesRef.current];\n next[index] = withFlags(entry, { actionPending: pending });\n write(next);\n };\n\n // --- Announcements (design 5) ---------------------------------------------------------------\n\n const flushAnnouncements = (): void => {\n const batch = announceBatch.current;\n announceBatch.current = [];\n if (batch.length === 0) return;\n const priority = batch.some((a) => a.priority === \"high\") ? \"high\" : \"normal\";\n speak(\n regionRef.current?.ownerDocument ?? document,\n batch.map((a) => a.text).join(\" \"),\n priority,\n );\n };\n\n const queueAnnouncement = (id: string, text: string | null, priority: ToastPriority): void => {\n const map = lastAnnounced.current;\n if (map.has(id) && map.get(id) === text) return;\n map.set(id, text);\n if (text === null || text.trim() === \"\") return;\n if (announceBatch.current.length === 0) queueMicrotask(flushAnnouncements);\n announceBatch.current.push({ text, priority });\n };\n\n // The callbacks below read only refs, so one context value serves the Viewport's whole life.\n const restore = (toasts: readonly RetainedToast[]): void => {\n if (entriesRef.current.length > 0) return;\n // Already announced by the previous Viewport: not again on every remount.\n for (const t of toasts) {\n if (t.announced !== undefined) lastAnnounced.current.set(t.options.id, t.announced);\n }\n write(\n toasts.map((t) =>\n makeEntry(t.options, { promisePending: t.pending, actionPending: false, ending: false }),\n ),\n );\n addedSinceEffect.current = true;\n };\n\n const retain = (): readonly RetainedToast[] => {\n const announced = lastAnnounced.current;\n return entriesRef.current\n .filter((e) => !e.ending)\n .map((e) => ({\n options: e.options,\n pending: e.promisePending,\n announced: announced.has(e.options.id) ? announced.get(e.options.id) : undefined,\n }));\n };\n\n /** Forgets the queue of the previous manager (its own copy is retained by that manager). */\n const reset = (): void => {\n moveFocusOut(new Set(entriesRef.current.filter((e) => !e.ending).map((e) => e.options.id)));\n clearToastTimers(timers.current);\n lastAnnounced.current.clear();\n exitBaselines.current.clear();\n write([]);\n };\n\n const handlers = useLatest({\n apply,\n restore,\n retain,\n reset,\n close,\n drop,\n setActionPending,\n queueAnnouncement,\n setPause,\n syncTimers,\n });\n\n const context = useMemo<ToastViewportContextValue>(\n () => ({\n close: (ids, reason, event) => handlers.current.close(ids, reason, event),\n drop: (id) => handlers.current.drop(id),\n setActionPending: (id, pending) => handlers.current.setActionPending(id, pending),\n setSuspended: (id, value) => {\n if (value) suspended.current.add(id);\n else suspended.current.delete(id);\n handlers.current.syncTimers();\n },\n registerRoot: (id, element) => {\n if (element === null) roots.current.delete(id);\n else roots.current.set(id, element);\n },\n focusSibling: (id, direction) => {\n const all = sortedRoots();\n const index = all.findIndex((r) => r.id === id);\n if (index === -1) return;\n all[index + direction]?.element.focus();\n },\n announce: (id, text, priority) => handlers.current.queueAnnouncement(id, text, priority),\n exitBaseline: (id) => exitBaselines.current.get(id),\n announcer: () => latest.current.announce,\n }),\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- refs only (`sortedRoots` reads refs)\n [handlers, latest],\n );\n\n // --- Subscription ---------------------------------------------------------------------------\n\n const subscribedManager = useRef<ToastManager | null>(null);\n useEffect(() => {\n // A new `manager`: the previous one kept its toasts on unsubscribe (the previous run's\n // cleanup); start empty so the new one's retained toasts are restored and no command of\n // one queue reaches the other's toasts. The same manager again (StrictMode, Activity) keeps\n // the entries.\n if (subscribedManager.current !== null && subscribedManager.current !== manager) {\n handlers.current.reset();\n }\n subscribedManager.current = manager;\n const unsubscribe = toastManagerInternals(manager).subscribe(listener.current!);\n if (unsubscribe === null) {\n setRejected(true);\n if (isDev) {\n console.error(\n \"Toast.Viewport: another Toast.Viewport already renders this manager; this one renders \" +\n \"nothing. Use one Viewport per manager, or `createToastManager()` for a second queue.\",\n );\n }\n return;\n }\n setRejected(false);\n return unsubscribe;\n }, [manager, handlers]);\n\n // --- Lifecycle, pause sources, hotkey --------------------------------------------------------\n\n useEffect(() => {\n if (rejected) return;\n mounted.current = true;\n const doc = regionRef.current?.ownerDocument ?? document;\n const view = doc.defaultView ?? window;\n pauses.current.hidden = doc.visibilityState === \"hidden\";\n const onVisibility = (): void =>\n handlers.current.setPause(\"hidden\", doc.visibilityState === \"hidden\");\n // The window's own focus and blur; an element's (which do not bubble) never reach here.\n const onWindowBlur = (event: Event): void => {\n if (!(event.target instanceof Node)) handlers.current.setPause(\"blurred\", true);\n };\n const onWindowFocus = (event: Event): void => {\n if (!(event.target instanceof Node)) handlers.current.setPause(\"blurred\", false);\n };\n doc.addEventListener(\"visibilitychange\", onVisibility);\n view.addEventListener(\"blur\", onWindowBlur);\n view.addEventListener(\"focus\", onWindowFocus);\n handlers.current.syncTimers();\n setPaused(anyPause(pauses.current));\n const map = timers.current;\n return () => {\n mounted.current = false;\n doc.removeEventListener(\"visibilitychange\", onVisibility);\n view.removeEventListener(\"blur\", onWindowBlur);\n view.removeEventListener(\"focus\", onWindowFocus);\n // Unmounting stops the timers; the queue itself is retained by the manager.\n clearToastTimers(map);\n };\n }, [handlers, rejected]);\n\n const hotkeyKey = hotkey === null ? null : hotkey.join(\"\\u0000\");\n useEffect(() => {\n if (hotkeyKey === null || rejected) return;\n const keys = hotkeyKey.split(\"\\u0000\");\n const doc = regionRef.current?.ownerDocument ?? document;\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.defaultPrevented || !matchesHotkey(keys, event)) return;\n const all = sortedRoots();\n const newest = all.at(-1);\n if (newest === undefined) return;\n event.preventDefault();\n const active = doc.activeElement;\n if (active instanceof HTMLElement && !regionRef.current?.contains(active)) {\n returnTarget.current = active;\n }\n newest.element.focus();\n };\n doc.addEventListener(\"keydown\", onKeyDown);\n return () => doc.removeEventListener(\"keydown\", onKeyDown);\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- `sortedRoots` reads refs only\n }, [hotkeyKey, rejected]);\n\n // --- The portal host (design 4.3) ------------------------------------------------------------\n\n // Keep this call before the region layout effect below: the host's move hides the popover\n // (removal steps), which that effect shows again in the same commit. A moved region gets no\n // `pointerleave`: drop the hover pause; a pointer still over it enters it again on its next move.\n const { portalled, host, anchorRef } = useModalPortalHost(() => setPause(\"hover\", false));\n\n // --- After every commit: region, timers, queued announcements, orphan exits ----------------\n\n useLayoutEffect(() => {\n const region = regionRef.current;\n const current = entriesRef.current;\n // Focus that left with a remount (a move into or out of a dialog) fires no `focusout`.\n if (\n pauses.current.focus &&\n (region === null || !region.contains(region.ownerDocument.activeElement))\n ) {\n returnTarget.current = null;\n setPause(\"focus\", false);\n }\n if (region !== null && region.isConnected && region.hasAttribute(\"popover\")) {\n const open = isPopoverOpen(region);\n try {\n if (current.length > 0) {\n if (!open) region.showPopover();\n else if (addedSinceEffect.current) {\n // Re-raise to the top of the top layer, above a menu or popover opened since\n // (design 4.2). No style flush in between, so nothing is re-created.\n region.hidePopover();\n region.showPopover();\n }\n } else if (open) {\n region.hidePopover();\n }\n } catch {\n // A render element without popover support; nothing to show.\n }\n }\n // An emptied region is hidden, often right under the pointer (its last toast's Close), and\n // a hidden element gets no `pointerleave`: the next toast must not start paused.\n if (current.length === 0 && pauses.current.hover) setPause(\"hover\", false);\n addedSinceEffect.current = false;\n\n const { visible, queued } = partition(current, latest.current.limit);\n // Queued toasts are announced on add (design 5): from their plain-text fields, since they\n // have no DOM yet. Visible ones announce from their Root once their content committed.\n for (const entry of queued) {\n const id = entry.options.id;\n if (lastAnnounced.current.has(id)) continue;\n const resolver = entry.options.announce ?? latest.current.announce;\n const text = resolver\n ? resolver(entry.item)\n : [plainText(entry.options.title), plainText(entry.options.description)]\n .filter((t) => t !== \"\")\n .join(\" \");\n queueAnnouncement(id, text, entry.options.priority ?? \"normal\");\n }\n // An ending toast without a Root (the consumer did not render one) has nothing to animate.\n for (const entry of visible) {\n if (entry.ending && !roots.current.has(entry.options.id)) drop(entry.options.id);\n }\n syncTimers();\n });\n\n // --- Development checks ---------------------------------------------------------------------\n\n // A Viewport inside a library Dialog would close (and unmount) with it.\n const insideDialog = use(DialogContext) !== null;\n useDevWarning(\n insideDialog,\n isDev &&\n \"Toast.Viewport: rendered inside a Dialog. The region would close with the dialog; render \" +\n \"the Viewport once near the root of the app (it moves into open modal Dialogs by itself).\",\n );\n\n // --- Render ---------------------------------------------------------------------------------\n\n const { visible, queued } = partition(entries, limit);\n const state: ToastViewportState = {\n toasts: visible.map((e) => e.item),\n queued: queued.length,\n paused,\n };\n\n const regionCallbackRef = useCallback((element: HTMLElement) => {\n regionRef.current = element;\n return () => {\n if (regionRef.current === element) regionRef.current = null;\n };\n }, []);\n\n // Touch lifts the pointer at once (`pointerleave` follows `pointerup`), so a tap never sticks.\n const onPointerEnter = (): void => setPause(\"hover\", true);\n const onPointerLeave = (): void => setPause(\"hover\", false);\n const onFocus = (event: FocusEvent<HTMLElement>): void => {\n const region = event.currentTarget;\n const from = event.relatedTarget;\n if (!(from instanceof Node) || !region.contains(from)) {\n returnTarget.current ??= from instanceof HTMLElement ? from : null;\n }\n setPause(\"focus\", true);\n };\n const onBlur = (event: FocusEvent<HTMLElement>): void => {\n const to = event.relatedTarget;\n if (to instanceof Node && event.currentTarget.contains(to)) return;\n returnTarget.current = null;\n setPause(\"focus\", false);\n };\n\n const libraryProps: ComponentPropsWithRef<\"section\"> & DataAttributes = {\n popover: \"manual\",\n \"aria-label\": rest[\"aria-label\"] ?? regionLabel(hotkey),\n \"data-paused\": dataAttr(paused),\n \"data-empty\": dataAttr(state.toasts.length === 0),\n onPointerEnter,\n onPointerLeave,\n onFocus,\n onBlur,\n };\n\n const region = useRender<ComponentPropsWithRef<\"section\">, ToastViewportState>({\n defaultElement: \"section\",\n render,\n state,\n className,\n style,\n children,\n props: rest,\n libraryProps,\n ref: regionCallbackRef,\n });\n\n if (rejected) return null;\n const content = <ToastViewportContext value={context}>{region}</ToastViewportContext>;\n if (!portalled || host === null) return content;\n return (\n <>\n <div ref={anchorRef} style={ANCHOR_STYLE} />\n {createPortal(content, host)}\n </>\n );\n}\n\nconst ANCHOR_STYLE: CSSProperties = { display: \"contents\" };\n\nToastViewport.displayName = \"ToastViewport\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmHA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AAGvC,SAAS,mBAAmB,GAAY,GAAoB;CAC1D,IAAI,MAAM,GAAG,OAAO;CACpB,OAAO,EAAE,wBAAwB,CAAC,IAAI,KAAK,8BAA8B,KAAK;AAChF;AASA,SAAS,SAAS,SAAgC;CAChD,OAAO,QAAQ,SAAS,QAAQ,SAAS,QAAQ,UAAU,QAAQ;AACrE;;;;;;;;;;;;AAaA,SAAgB,cAAc,EAC5B,UAAUA,OACV,QAAQ,GACR,WAAW,KACX,SAAS,gBACT,UAAA,YACA,UACA,WACA,OACA,QACA,GAAG,QACkB;CAErB,MAAM,CAAC,SAAS,cAAc,SAA2B,CAAC,CAAC;CAG3D,MAAM,aAAa,OAAyB,OAAO;CACnD,MAAM,WAAW,OAA6B,IAAI;CAClD,SAAS,YAAY;EACnB,UAAU,WAAq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gB;EAChB;EACA;EACA;EACA;EACA;EACA,OAAO;EACP;EACA,KAAK;CACP,CAAC;CAED,IAAI,UAAU,OAAO;CACrB,MAAM,UAAU,oBAAC,sBAAD;EAAsB,OAAO;EAAU,UAAA;CAA6B,CAAA;CACpF,IAAI,CAAC,aAAa,SAAS,MAAM,OAAO;CACxC,OACE,qBAAA,UAAA,EAAA,UAAA,CACE,oBAAC,OAAD;EAAK,KAAK;EAAW,OAAO;CAAe,CAAA,GAC1C,aAAa,SAAS,IAAI,CAC3B,EAAA,CAAA;AAEN;AAEA,MAAM,eAA8B,EAAE,SAAS,WAAW;AAE1D,cAAc,cAAc"}
|
|
1
|
+
{"version":3,"file":"toast-viewport.mjs","names":["defaultManager"],"sources":["../../src/toast/toast-viewport.tsx"],"sourcesContent":["\"use client\";\nimport { use, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, FocusEvent, ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { DialogContext } from \"../dialog/dialog-context.js\";\nimport { createActionDetails } from \"../internal/action-details.js\";\nimport { announce as speak } from \"../internal/announce.js\";\nimport { callUrgentHandler } from \"../internal/call-urgent-handler.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { isPopoverOpen } from \"../internal/popover-open.js\";\nimport type { ChangeReason, RenderProp, StateValue } from \"../internal/types.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { animationBaseline } from \"../internal/use-exit-animation.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { toast as defaultManager, toastManagerInternals } from \"./toast.js\";\nimport type {\n RetainedToast,\n ToastCommand,\n ToastItem,\n ToastListener,\n ToastManager,\n ToastPriority,\n} from \"./toast.js\";\nimport { ToastViewportContext } from \"./toast-context.js\";\nimport type { ToastViewportContextValue } from \"./toast-context.js\";\nimport { DEFAULT_HOTKEY, matchesHotkey, regionLabel } from \"./toast-hotkey.js\";\nimport { clearToastTimers, syncToastTimers } from \"./toast-timers.js\";\nimport type { ToastTimer } from \"./toast-timers.js\";\nimport { useModalPortalHost } from \"./use-modal-portal-host.js\";\nimport { applyCommands, makeEntry, partition, plainText, withFlags } from \"./toast-queue.js\";\nimport type { Entry } from \"./toast-queue.js\";\n\n/**\n * State of `Toast.Viewport`, passed to the function forms of `className`, `style`, `children` and\n * `render`.\n */\nexport interface ToastViewportState {\n /** Rendered toasts, chronological (oldest first), exiting ones included. */\n readonly toasts: readonly ToastItem[];\n /** Toasts waiting beyond `limit`. */\n readonly queued: number;\n /** A viewport-wide pause holds (pointer over the region, focus inside, hidden document, blurred window). */\n readonly paused: boolean;\n}\n\n/**\n * Props of `Toast.Viewport`.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport interface ToastViewportProps extends Omit<\n ComponentPropsWithRef<\"section\">,\n | \"popover\"\n | \"className\"\n | \"style\"\n | \"children\"\n | \"onPointerEnter\"\n | \"onPointerLeave\"\n | \"onFocus\"\n | \"onBlur\"\n | \"onKeyDown\"\n> {\n /**\n * The queue to render (from `createToastManager()`).\n *\n * @defaultValue the module-level `toast`\n */\n manager?: ToastManager;\n /**\n * Toasts rendered at once; further ones wait in order (never dropped).\n *\n * @defaultValue `3`\n */\n limit?: number;\n /**\n * Default `duration` of a toast in milliseconds; `null` for persistent.\n *\n * @defaultValue `5000`\n */\n duration?: number | null;\n /**\n * Keys that focus the newest toast: `event.code` values and modifier names (`\"altKey\"`,\n * `\"ctrlKey\"`, `\"metaKey\"`, `\"shiftKey\"`), all of which must match, with no other modifier\n * held. `null` installs no listener.\n *\n * @defaultValue `[\"F8\"]`\n */\n hotkey?: readonly string[] | null;\n /**\n * The text `document.ariaNotify()` speaks for a toast (localisation); `null` announces nothing.\n * A toast's own `announce` wins.\n *\n * @defaultValue the text of the toast's Title and Description\n */\n announce?: (toast: ToastItem) => string | null;\n /** Usually a function of the state mapping `state.toasts` to `Toast.Root`s. */\n children?: StateValue<ReactNode, ToastViewportState>;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, ToastViewportState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, ToastViewportState>;\n /** Must render an element that can carry `popover` (a `<section>` by default). */\n render?: RenderProp<ComponentPropsWithRef<\"section\">, ToastViewportState>;\n}\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** Document order. */\nfunction byDocumentPosition(a: Element, b: Element): number {\n if (a === b) return 0;\n return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;\n}\n\ninterface PauseSources {\n hover: boolean;\n focus: boolean;\n hidden: boolean;\n blurred: boolean;\n}\n\nfunction anyPause(sources: PauseSources): boolean {\n return sources.hover || sources.focus || sources.hidden || sources.blurred;\n}\n\n/**\n * The toast region: a `<section popover=\"manual\">` named \"Notifications (F8)\", shown in the top\n * layer while it has toasts. Owns the queue (urgent state fed by `toast()`), the timers and their\n * pausing, the hotkey, focus return, announcements through `document.ariaNotify()`, and the move\n * into the topmost open modal `Dialog` (a region outside it would be inert).\n *\n * Owned keys (conventions 1.2): `popover`, `aria-label` (the consumer's own `aria-label` wins\n * verbatim), `data-paused`, `data-empty`, and the pointer / focus handlers.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport function ToastViewport({\n manager = defaultManager,\n limit = 3,\n duration = 5000,\n hotkey = DEFAULT_HOTKEY,\n announce,\n children,\n className,\n style,\n render,\n ...rest\n}: ToastViewportProps) {\n // --- The queue: urgent state, written only from handlers, microtasks and effects -----------\n const [entries, setEntries] = useState<readonly Entry[]>([]);\n // The latest queue, written together with every `setEntries`: the dispatchers read and write\n // it synchronously so a burst of commands composes (and side effects stay out of updaters).\n const entriesRef = useRef<readonly Entry[]>(entries);\n const listener = useRef<ToastListener | null>(null);\n listener.current ??= {\n restore: (toasts: readonly RetainedToast[]) => handlers.current.restore(toasts),\n apply: (commands: readonly ToastCommand[]) => handlers.current.apply(commands),\n retain: () => handlers.current.retain(),\n };\n // A second Viewport on a taken manager renders nothing from its first render on (the effect\n // below confirms or clears it once the subscription is attempted).\n const [rejected, setRejected] = useState(() =>\n toastManagerInternals(manager).isTaken(listener.current!),\n );\n\n const regionRef = useRef<HTMLElement | null>(null);\n const roots = useRef(new Map<string, HTMLElement>());\n const suspended = useRef(new Set<string>());\n const timers = useRef(new Map<string, ToastTimer>());\n const pauses = useRef<PauseSources>({\n hover: false,\n focus: false,\n hidden: false,\n blurred: false,\n });\n const [paused, setPaused] = useState(false);\n /** Where focus goes back to once the last toast holding it leaves (design 7). */\n const returnTarget = useRef<HTMLElement | null>(null);\n const lastAnnounced = useRef(new Map<string, string | null>());\n /** Per closing toast: the animations already running before `data-ending` applied. */\n const exitBaselines = useRef(new Map<string, ReadonlySet<Animation>>());\n const announceBatch = useRef<{ text: string; priority: ToastPriority }[]>([]);\n const addedSinceEffect = useRef(false);\n const mounted = useRef(false);\n\n const latest = useLatest({ limit, duration, hotkey, announce });\n\n const write = (next: readonly Entry[]): void => {\n entriesRef.current = next;\n setEntries(next);\n };\n\n // --- Timers (design 6) ----------------------------------------------------------------------\n\n const syncTimers = (): void => {\n syncToastTimers(timers.current, partition(entriesRef.current, latest.current.limit).visible, {\n halted: !mounted.current || anyPause(pauses.current),\n suspended: suspended.current,\n defaultDuration: latest.current.duration,\n expire: (id) => close([id], \"timeout\", undefined),\n });\n };\n\n const setPause = (source: keyof PauseSources, value: boolean): void => {\n if (pauses.current[source] === value) return;\n pauses.current[source] = value;\n // Applied synchronously in the event, before any timer callback can run (design 14 item 9).\n syncTimers();\n setPaused(anyPause(pauses.current));\n };\n\n // --- Focus ----------------------------------------------------------------------------------\n\n /** Open toasts' Root elements in document order. */\n const sortedRoots = (exclude?: ReadonlySet<string>): { id: string; element: HTMLElement }[] => {\n const open = new Set(entriesRef.current.filter((e) => !e.ending).map((e) => e.options.id));\n const list: { id: string; element: HTMLElement }[] = [];\n for (const [id, element] of roots.current) {\n if (!open.has(id) || exclude?.has(id) || !element.isConnected) continue;\n list.push({ id, element });\n }\n return list.sort((a, b) => byDocumentPosition(a.element, b.element));\n };\n\n /**\n * Before toasts close: if focus is inside one of them, move it to the next toast, else the\n * previous one, else where it was before the region was entered, else the body (design 7).\n */\n const moveFocusOut = (closing: ReadonlySet<string>): void => {\n const doc = regionRef.current?.ownerDocument ?? document;\n const active = doc.activeElement;\n if (!(active instanceof HTMLElement)) return;\n const all = sortedRoots();\n const index = all.findIndex(({ element }) => element.contains(active));\n if (index === -1 || !closing.has(all[index]!.id)) return;\n const after = all.slice(index + 1).find(({ id }) => !closing.has(id));\n const before = all\n .slice(0, index)\n .reverse()\n .find(({ id }) => !closing.has(id));\n const target = after ?? before;\n if (target !== undefined) {\n target.element.focus();\n return;\n }\n const stored = returnTarget.current;\n if (stored !== null && stored.isConnected && !regionRef.current?.contains(stored)) {\n stored.focus();\n if (doc.activeElement === stored) return;\n }\n active.blur();\n };\n\n // --- Queue writes ---------------------------------------------------------------------------\n\n /**\n * Records the animations running in each closing toast before `data-ending` applies: the exit\n * waits only for the ones the ending state started, not for a running progress bar.\n */\n const snapshotExitBaselines = (ids: Iterable<string>): void => {\n for (const id of ids) {\n const element = roots.current.get(id);\n if (element === undefined) continue;\n exitBaselines.current.set(id, animationBaseline(element));\n }\n };\n\n /**\n * A toast's `onClose` (#148: a handler, not an action): called synchronously where the close is\n * applied to the queue, after the entry is marked ending, outside any transition, and not\n * awaited (`callUrgentHandler`: a throw or a returned promise's rejection goes to\n * `reportError`, the queue write above stands).\n */\n const callCloseHandlers = (\n closed: readonly Entry[],\n reason: ChangeReason,\n event: Event | undefined,\n ): void => {\n for (const entry of closed) {\n const onClose = entry.options.onClose;\n if (onClose === undefined) continue;\n callUrgentHandler(onClose, createActionDetails(event, { id: entry.options.id, reason }));\n }\n };\n\n const close = (ids: readonly string[], reason: ChangeReason, event: Event | undefined): void => {\n const wanted = new Set(ids);\n const closing = entriesRef.current.filter((e) => !e.ending && wanted.has(e.options.id));\n if (closing.length === 0) return;\n const closingIds = new Set(closing.map((e) => e.options.id));\n moveFocusOut(closingIds);\n snapshotExitBaselines(closingIds);\n write(\n entriesRef.current.map((e) =>\n closingIds.has(e.options.id) ? withFlags(e, { ending: true }) : e,\n ),\n );\n syncTimers();\n callCloseHandlers(closing, reason, event);\n };\n\n const drop = (id: string): void => {\n const next = entriesRef.current.filter((e) => !(e.ending && e.options.id === id));\n if (next.length === entriesRef.current.length) return;\n lastAnnounced.current.delete(id);\n exitBaselines.current.delete(id);\n write(next);\n };\n\n const apply = (commands: readonly ToastCommand[]): void => {\n const result = applyCommands(entriesRef.current, commands, (id) => roots.current.has(id));\n for (const id of result.replaced) clearToastTimers(timers.current, id);\n for (const id of result.forgotten) {\n lastAnnounced.current.delete(id);\n exitBaselines.current.delete(id);\n }\n if (result.added) addedSinceEffect.current = true;\n if (isDev) {\n for (const id of result.missing) {\n console.error(`toast.update: no toast with id \"${id}\"; the update is ignored.`);\n }\n }\n if (result.dismissed.length === 0) {\n write(result.next);\n return;\n }\n moveFocusOut(result.leaving);\n snapshotExitBaselines(result.leaving);\n write(result.next);\n syncTimers();\n callCloseHandlers(result.dismissed, \"dismiss\", undefined);\n };\n\n const setActionPending = (id: string, pending: boolean): void => {\n const index = entriesRef.current.findIndex((e) => e.options.id === id);\n if (index === -1) return;\n const entry = entriesRef.current[index]!;\n if (entry.actionPending === pending) return;\n const next = [...entriesRef.current];\n next[index] = withFlags(entry, { actionPending: pending });\n write(next);\n };\n\n // --- Announcements (design 5) ---------------------------------------------------------------\n\n const flushAnnouncements = (): void => {\n const batch = announceBatch.current;\n announceBatch.current = [];\n if (batch.length === 0) return;\n const priority = batch.some((a) => a.priority === \"high\") ? \"high\" : \"normal\";\n speak(\n regionRef.current?.ownerDocument ?? document,\n batch.map((a) => a.text).join(\" \"),\n priority,\n );\n };\n\n const queueAnnouncement = (id: string, text: string | null, priority: ToastPriority): void => {\n const map = lastAnnounced.current;\n if (map.has(id) && map.get(id) === text) return;\n map.set(id, text);\n if (text === null || text.trim() === \"\") return;\n if (announceBatch.current.length === 0) queueMicrotask(flushAnnouncements);\n announceBatch.current.push({ text, priority });\n };\n\n // The callbacks below read only refs, so one context value serves the Viewport's whole life.\n const restore = (toasts: readonly RetainedToast[]): void => {\n if (entriesRef.current.length > 0) return;\n // Already announced by the previous Viewport: not again on every remount.\n for (const t of toasts) {\n if (t.announced !== undefined) lastAnnounced.current.set(t.options.id, t.announced);\n }\n write(\n toasts.map((t) =>\n makeEntry(t.options, { promisePending: t.pending, actionPending: false, ending: false }),\n ),\n );\n addedSinceEffect.current = true;\n };\n\n const retain = (): readonly RetainedToast[] => {\n const announced = lastAnnounced.current;\n return entriesRef.current\n .filter((e) => !e.ending)\n .map((e) => ({\n options: e.options,\n pending: e.promisePending,\n announced: announced.has(e.options.id) ? announced.get(e.options.id) : undefined,\n }));\n };\n\n /** Forgets the queue of the previous manager (its own copy is retained by that manager). */\n const reset = (): void => {\n moveFocusOut(new Set(entriesRef.current.filter((e) => !e.ending).map((e) => e.options.id)));\n clearToastTimers(timers.current);\n lastAnnounced.current.clear();\n exitBaselines.current.clear();\n write([]);\n };\n\n const handlers = useLatest({\n apply,\n restore,\n retain,\n reset,\n close,\n drop,\n setActionPending,\n queueAnnouncement,\n setPause,\n syncTimers,\n });\n\n const context = useMemo<ToastViewportContextValue>(\n () => ({\n close: (ids, reason, event) => handlers.current.close(ids, reason, event),\n drop: (id) => handlers.current.drop(id),\n setActionPending: (id, pending) => handlers.current.setActionPending(id, pending),\n setSuspended: (id, value) => {\n if (value) suspended.current.add(id);\n else suspended.current.delete(id);\n handlers.current.syncTimers();\n },\n registerRoot: (id, element) => {\n if (element === null) roots.current.delete(id);\n else roots.current.set(id, element);\n },\n focusSibling: (id, direction) => {\n const all = sortedRoots();\n const index = all.findIndex((r) => r.id === id);\n if (index === -1) return;\n all[index + direction]?.element.focus();\n },\n announce: (id, text, priority) => handlers.current.queueAnnouncement(id, text, priority),\n exitBaseline: (id) => exitBaselines.current.get(id),\n announcer: () => latest.current.announce,\n }),\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- refs only (`sortedRoots` reads refs)\n [handlers, latest],\n );\n\n // --- Subscription ---------------------------------------------------------------------------\n\n const subscribedManager = useRef<ToastManager | null>(null);\n useEffect(() => {\n // A new `manager`: the previous one kept its toasts on unsubscribe (the previous run's\n // cleanup); start empty so the new one's retained toasts are restored and no command of\n // one queue reaches the other's toasts. The same manager again (StrictMode, Activity) keeps\n // the entries.\n if (subscribedManager.current !== null && subscribedManager.current !== manager) {\n handlers.current.reset();\n }\n subscribedManager.current = manager;\n const unsubscribe = toastManagerInternals(manager).subscribe(listener.current!);\n if (unsubscribe === null) {\n setRejected(true);\n if (isDev) {\n console.error(\n \"Toast.Viewport: another Toast.Viewport already renders this manager; this one renders \" +\n \"nothing. Use one Viewport per manager, or `createToastManager()` for a second queue.\",\n );\n }\n return;\n }\n setRejected(false);\n return unsubscribe;\n }, [manager, handlers]);\n\n // --- Lifecycle, pause sources, hotkey --------------------------------------------------------\n\n useEffect(() => {\n if (rejected) return;\n mounted.current = true;\n const doc = regionRef.current?.ownerDocument ?? document;\n const view = doc.defaultView ?? window;\n pauses.current.hidden = doc.visibilityState === \"hidden\";\n const onVisibility = (): void =>\n handlers.current.setPause(\"hidden\", doc.visibilityState === \"hidden\");\n // The window's own focus and blur; an element's (which do not bubble) never reach here.\n const onWindowBlur = (event: Event): void => {\n if (!(event.target instanceof Node)) handlers.current.setPause(\"blurred\", true);\n };\n const onWindowFocus = (event: Event): void => {\n if (!(event.target instanceof Node)) handlers.current.setPause(\"blurred\", false);\n };\n doc.addEventListener(\"visibilitychange\", onVisibility);\n view.addEventListener(\"blur\", onWindowBlur);\n view.addEventListener(\"focus\", onWindowFocus);\n handlers.current.syncTimers();\n setPaused(anyPause(pauses.current));\n const map = timers.current;\n return () => {\n mounted.current = false;\n doc.removeEventListener(\"visibilitychange\", onVisibility);\n view.removeEventListener(\"blur\", onWindowBlur);\n view.removeEventListener(\"focus\", onWindowFocus);\n // Unmounting stops the timers; the queue itself is retained by the manager.\n clearToastTimers(map);\n };\n }, [handlers, rejected]);\n\n const hotkeyKey = hotkey === null ? null : hotkey.join(\"\\u0000\");\n useEffect(() => {\n if (hotkeyKey === null || rejected) return;\n const keys = hotkeyKey.split(\"\\u0000\");\n const doc = regionRef.current?.ownerDocument ?? document;\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.defaultPrevented || !matchesHotkey(keys, event)) return;\n const all = sortedRoots();\n const newest = all.at(-1);\n if (newest === undefined) return;\n event.preventDefault();\n const active = doc.activeElement;\n if (active instanceof HTMLElement && !regionRef.current?.contains(active)) {\n returnTarget.current = active;\n }\n newest.element.focus();\n };\n doc.addEventListener(\"keydown\", onKeyDown);\n return () => doc.removeEventListener(\"keydown\", onKeyDown);\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- `sortedRoots` reads refs only\n }, [hotkeyKey, rejected]);\n\n // --- The portal host (design 4.3) ------------------------------------------------------------\n\n // Keep this call before the region layout effect below: the host's move hides the popover\n // (removal steps), which that effect shows again in the same commit. A moved region gets no\n // `pointerleave`: drop the hover pause; a pointer still over it enters it again on its next move.\n const { portalled, host, anchorRef } = useModalPortalHost(() => setPause(\"hover\", false));\n\n // --- After every commit: region, timers, queued announcements, orphan exits ----------------\n\n useLayoutEffect(() => {\n const region = regionRef.current;\n const current = entriesRef.current;\n // Focus that left with a remount (a move into or out of a dialog) fires no `focusout`.\n if (\n pauses.current.focus &&\n (region === null || !region.contains(region.ownerDocument.activeElement))\n ) {\n returnTarget.current = null;\n setPause(\"focus\", false);\n }\n if (region !== null && region.isConnected && region.hasAttribute(\"popover\")) {\n const open = isPopoverOpen(region);\n try {\n if (current.length > 0) {\n if (!open) region.showPopover();\n else if (addedSinceEffect.current) {\n // Re-raise to the top of the top layer, above a menu or popover opened since\n // (design 4.2). No style flush in between, so nothing is re-created.\n region.hidePopover();\n region.showPopover();\n }\n } else if (open) {\n region.hidePopover();\n }\n } catch {\n // A render element without popover support; nothing to show.\n }\n }\n // An emptied region is hidden, often right under the pointer (its last toast's Close), and\n // a hidden element gets no `pointerleave`: the next toast must not start paused.\n if (current.length === 0 && pauses.current.hover) setPause(\"hover\", false);\n addedSinceEffect.current = false;\n\n const { visible, queued } = partition(current, latest.current.limit);\n // Queued toasts are announced on add (design 5): from their plain-text fields, since they\n // have no DOM yet. Visible ones announce from their Root once their content committed.\n for (const entry of queued) {\n const id = entry.options.id;\n if (lastAnnounced.current.has(id)) continue;\n const resolver = entry.options.announce ?? latest.current.announce;\n const text = resolver\n ? resolver(entry.item)\n : [plainText(entry.options.title), plainText(entry.options.description)]\n .filter((t) => t !== \"\")\n .join(\" \");\n queueAnnouncement(id, text, entry.options.priority ?? \"normal\");\n }\n // An ending toast without a Root (the consumer did not render one) has nothing to animate.\n for (const entry of visible) {\n if (entry.ending && !roots.current.has(entry.options.id)) drop(entry.options.id);\n }\n syncTimers();\n });\n\n // --- Development checks ---------------------------------------------------------------------\n\n // A Viewport inside a library Dialog would close (and unmount) with it.\n const insideDialog = use(DialogContext) !== null;\n useDevWarning(\n insideDialog,\n isDev &&\n \"Toast.Viewport: rendered inside a Dialog. The region would close with the dialog; render \" +\n \"the Viewport once near the root of the app (it moves into open modal Dialogs by itself).\",\n );\n\n // --- Render ---------------------------------------------------------------------------------\n\n const { visible, queued } = partition(entries, limit);\n const state: ToastViewportState = {\n toasts: visible.map((e) => e.item),\n queued: queued.length,\n paused,\n };\n\n const regionCallbackRef = useCallback((element: HTMLElement) => {\n regionRef.current = element;\n return () => {\n if (regionRef.current === element) regionRef.current = null;\n };\n }, []);\n\n // Touch lifts the pointer at once (`pointerleave` follows `pointerup`), so a tap never sticks.\n const onPointerEnter = (): void => setPause(\"hover\", true);\n const onPointerLeave = (): void => setPause(\"hover\", false);\n const onFocus = (event: FocusEvent<HTMLElement>): void => {\n const region = event.currentTarget;\n const from = event.relatedTarget;\n if (!(from instanceof Node) || !region.contains(from)) {\n returnTarget.current ??= from instanceof HTMLElement ? from : null;\n }\n setPause(\"focus\", true);\n };\n const onBlur = (event: FocusEvent<HTMLElement>): void => {\n const to = event.relatedTarget;\n if (to instanceof Node && event.currentTarget.contains(to)) return;\n returnTarget.current = null;\n setPause(\"focus\", false);\n };\n\n const libraryProps: ComponentPropsWithRef<\"section\"> & DataAttributes = {\n popover: \"manual\",\n \"aria-label\": rest[\"aria-label\"] ?? regionLabel(hotkey),\n \"data-paused\": dataAttr(paused),\n \"data-empty\": dataAttr(state.toasts.length === 0),\n onPointerEnter,\n onPointerLeave,\n onFocus,\n onBlur,\n };\n\n const region = useRender<ComponentPropsWithRef<\"section\">, ToastViewportState>({\n defaultElement: \"section\",\n render,\n state,\n className,\n style,\n children,\n props: rest,\n libraryProps,\n ref: regionCallbackRef,\n });\n\n if (rejected) return null;\n const content = <ToastViewportContext value={context}>{region}</ToastViewportContext>;\n if (!portalled || host === null) return content;\n return (\n <>\n <div ref={anchorRef} style={ANCHOR_STYLE} />\n {createPortal(content, host)}\n </>\n );\n}\n\nconst ANCHOR_STYLE: CSSProperties = { display: \"contents\" };\n\nToastViewport.displayName = \"ToastViewport\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA2GA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AAGvC,SAAS,mBAAmB,GAAY,GAAoB;CAC1D,IAAI,MAAM,GAAG,OAAO;CACpB,OAAO,EAAE,wBAAwB,CAAC,IAAI,KAAK,8BAA8B,KAAK;AAChF;AASA,SAAS,SAAS,SAAgC;CAChD,OAAO,QAAQ,SAAS,QAAQ,SAAS,QAAQ,UAAU,QAAQ;AACrE;;;;;;;;;;;;AAaA,SAAgB,cAAc,EAC5B,UAAUA,OACV,QAAQ,GACR,WAAW,KACX,SAAS,gBACT,UAAA,YACA,UACA,WACA,OACA,QACA,GAAG,QACkB;CAErB,MAAM,CAAC,SAAS,cAAc,SAA2B,CAAC,CAAC;CA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O;EACP;EACA,KAAK;CACP,CAAC;CAED,IAAI,UAAU,OAAO;CACrB,MAAM,UAAU,oBAAC,sBAAD;EAAsB,OAAO;EAAU,UAAA;CAA6B,CAAA;CACpF,IAAI,CAAC,aAAa,SAAS,MAAM,OAAO;CACxC,OACE,qBAAA,UAAA,EAAA,UAAA,CACE,oBAAC,OAAD;EAAK,KAAK;EAAW,OAAO;CAAe,CAAA,GAC1C,aAAa,SAAS,IAAI,CAC3B,EAAA,CAAA;AAEN;AAEA,MAAM,eAA8B,EAAE,SAAS,WAAW;AAE1D,cAAc,cAAc"}
|
package/dist/toast/toast.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Action, ActionDetails, ChangeReason } from "../internal/types.mjs";
|
|
1
|
+
import { Action, ActionDetails, ChangeReason, UrgentHandler } from "../internal/types.mjs";
|
|
2
2
|
import { ReactNode } from "react";
|
|
3
3
|
//#region src/toast/toast.d.ts
|
|
4
4
|
/** Announcement priority and role of a toast. */
|
|
@@ -54,12 +54,15 @@ export interface ToastOptions {
|
|
|
54
54
|
*/
|
|
55
55
|
readonly action?: ToastActionOptions | undefined;
|
|
56
56
|
/**
|
|
57
|
-
*
|
|
58
|
-
* `"
|
|
59
|
-
*
|
|
60
|
-
*
|
|
57
|
+
* A handler, not an action: called once when the toast leaves,
|
|
58
|
+
* with the reason: `"activate"` (the Action part settled), `"dismiss"` (Close, Escape,
|
|
59
|
+
* `toast.dismiss()`, a promise toast with no message for its outcome) or `"timeout"`. Called
|
|
60
|
+
* synchronously where the close happens, outside any Transition, and not awaited: a slow
|
|
61
|
+
* `deleteForReal` holds no other transition. May return a promise (a Server Function); a
|
|
62
|
+
* rejection or a throw goes to `reportError`, never to an Error Boundary. Not called when the
|
|
63
|
+
* Viewport unmounts.
|
|
61
64
|
*/
|
|
62
|
-
readonly
|
|
65
|
+
readonly onClose?: UrgentHandler<ToastCloseDetails> | undefined;
|
|
63
66
|
/**
|
|
64
67
|
* The text `document.ariaNotify()` speaks for this toast; `null` announces nothing.
|
|
65
68
|
*
|
|
@@ -85,7 +88,7 @@ export interface ToastActionDetails extends ActionDetails {
|
|
|
85
88
|
/** The toast's id, so an inline action can `toast.update` or `toast.dismiss` its own toast. */
|
|
86
89
|
readonly id: string;
|
|
87
90
|
}
|
|
88
|
-
/** Details passed to a toast's `
|
|
91
|
+
/** Details passed to a toast's `onClose`. */
|
|
89
92
|
export interface ToastCloseDetails extends ActionDetails {
|
|
90
93
|
/** The id of the toast that closed. */
|
|
91
94
|
readonly id: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toast.d.mts","names":[],"sources":["../../src/toast/toast.ts"],"mappings":";;;;YAOY;;iBAGK;;WAEN,OAAO;;;;;;;WAOP,QAAQ,QAAQ,SAAS;;;;;;;;iBASnB;;;;;;WAMN;;WAEA,QAAQ;;WAER,cAAc;;WAEd;;;;;;;WAOA,WAAW;;;;;;;WAOX;;;;;WAKA,SAAS
|
|
1
|
+
{"version":3,"file":"toast.d.mts","names":[],"sources":["../../src/toast/toast.ts"],"mappings":";;;;YAOY;;iBAGK;;WAEN,OAAO;;;;;;;WAOP,QAAQ,QAAQ,SAAS;;;;;;;;iBASnB;;;;;;WAMN;;WAEA,QAAQ;;WAER,cAAc;;WAEd;;;;;;;WAOA,WAAW;;;;;;;WAOX;;;;;WAKA,SAAS;;;;;;;;;;WAUT,UAAU,cAAc;;;;;;WAMxB,aAAa,OAAO;;WAEpB;;;iBAIM,kBAAkB;WACxB;;;;;WAKA;;WAEA;;;iBAIM,2BAA2B;;WAEjC;;;iBAIM,0BAA0B;;WAEhC;;WAEA,QAAQ;;;;;;;;iBASF,oBAAoB;;WAE1B,SAAS;;;;;WAKT,UAAU,iBAAiB,OAAO,MAAM;;;;;;;WAOxC,QAAQ,iBAAiB,oBAAoB;;;;;;WAM7C;;;iBAIM;;GAEd,SAAS;;;;;WAKD,MAAM,SAAS;;;;;;WAMf,UAAU,GACjB,SAAS,YAAY,IACrB,SAAS,oBAAoB,OAC1B,QAAQ;;WAEJ,SAAS,YAAY,SAAS,QAAQ;;WAEtC,UAAU;;;;;;;;wBA8GL,sBAAsB;;;;;;;;qBAsIzB,OAAO"}
|
package/dist/toast/toast.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toast.mjs","names":[],"sources":["../../src/toast/toast.ts"],"sourcesContent":["// No \"use client\" directive: the manager uses no React and no DOM API beyond `queueMicrotask`,\n// so a Server Component may import `toast` (for its type, or to pass nothing) without a client\n// reference (design/components/toast.md 13). The parts are client modules.\nimport type { ReactNode } from \"react\";\nimport type { Action, ActionDetails, ChangeReason } from \"../internal/types.js\";\n\n/** Announcement priority and role of a toast. */\nexport type ToastPriority = \"normal\" | \"high\";\n\n/** The `action` of a toast: what `Toast.Action` renders and runs by default. */\nexport interface ToastActionOptions {\n /** The Action button's content. */\n readonly label: ReactNode;\n /**\n * Runs in the Action part's own transition (`data-pending` on the Action and the Root, the\n * timer paused). The toast closes with `reason: \"activate\"` when it resolves; a rejection\n * keeps the toast and reaches the nearest Error Boundary above the Viewport. A caught error\n * resolves the action and therefore closes the toast: rethrow after `toast.update` to keep it.\n */\n readonly action: Action<[details: ToastActionDetails]>;\n}\n\n/**\n * What `toast(options)` shows: the content and behaviour of one toast. `toast.update(id, options)`\n * takes a partial of it.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport interface ToastOptions {\n /**\n * Explicit id: an existing one updates that toast.\n *\n * @defaultValue generated\n */\n readonly id?: string | undefined;\n /** Rendered by `Toast.Title`, which names the Root (`aria-labelledby`). */\n readonly title?: ReactNode;\n /** Rendered by `Toast.Description`, which describes the Root (`aria-describedby`). */\n readonly description?: ReactNode;\n /** Free-form, rendered as `data-type` on the Root (`\"success\"`, `\"error\"`, ...). */\n readonly type?: string | undefined;\n /**\n * Announcement priority and role: `\"high\"` announces with `ariaNotify` priority `\"high\"` and\n * renders the Root as an `alertdialog`.\n *\n * @defaultValue `\"normal\"`\n */\n readonly priority?: ToastPriority | undefined;\n /**\n * Milliseconds before the toast closes with `reason: \"timeout\"`; `null` never. A timed action\n * toast must keep its action reachable elsewhere too (WCAG 2.2.1).\n *\n * @defaultValue the Viewport's `duration`, or `null` (persistent) when the toast has an `action`\n */\n readonly duration?: number | null | undefined;\n /**\n * A button the toast offers (Undo, Retry), rendered and run by `Toast.Action`. A toast with an\n * action is persistent unless `duration` is set.\n */\n readonly action?: ToastActionOptions | undefined;\n /**\n * Called once when the toast leaves, with the reason: `\"activate\"` (the Action part settled),\n * `\"dismiss\"` (Close, Escape, `toast.dismiss()`, a promise toast with no message for its\n * outcome) or `\"timeout\"`. Runs in the Viewport's transition; a rejection reaches the boundary\n * above the Viewport. Not called when the Viewport unmounts.\n */\n readonly closeAction?: Action<[details: ToastCloseDetails]> | undefined;\n /**\n * The text `document.ariaNotify()` speaks for this toast; `null` announces nothing.\n *\n * @defaultValue the Viewport's `announce`, else the text of the toast's Title and Description\n */\n readonly announce?: ((toast: ToastItem) => string | null) | undefined;\n /** Anything the Viewport's children want to render. */\n readonly data?: unknown;\n}\n\n/** A toast in the queue, as the Viewport's `children(state)` receives it. */\nexport interface ToastItem extends ToastOptions {\n readonly id: string;\n /**\n * The promise given to `toast.promise` is unsettled, or an action dispatched through this\n * toast's Action part is in flight.\n */\n readonly pending: boolean;\n /** Closed; kept mounted (and `inert`) for its exit animation. */\n readonly ending: boolean;\n}\n\n/** Details passed to a toast's Action. */\nexport interface ToastActionDetails extends ActionDetails {\n /** The toast's id, so an inline action can `toast.update` or `toast.dismiss` its own toast. */\n readonly id: string;\n}\n\n/** Details passed to a toast's `closeAction`. */\nexport interface ToastCloseDetails extends ActionDetails {\n /** The id of the toast that closed. */\n readonly id: string;\n /** `\"activate\"`, `\"dismiss\"` or `\"timeout\"`. */\n readonly reason: ChangeReason;\n}\n\n/**\n * The second argument of `toast.promise(promise, options)`: the toast to show while `promise` is\n * pending and the ones that replace it when it settles.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport interface ToastPromiseOptions<T> {\n /** Shown at once, with `data-pending`; no timer until the promise settles. */\n readonly pending: ToastOptions;\n /**\n * Replaces the toast when the promise fulfils; omitted: the toast is dismissed. A function that\n * throws dismisses the toast, and the returned promise rejects with what it threw.\n */\n readonly success?: ToastOptions | ((value: T) => ToastOptions) | undefined;\n /**\n * Replaces the toast when the promise rejects; the returned promise then resolves with\n * `undefined` (the toast is the handler). Omitted: the toast is dismissed and the returned\n * promise rejects with the same reason. A function that throws dismisses the toast, and the\n * returned promise rejects with what it threw.\n */\n readonly error?: ToastOptions | ((reason: unknown) => ToastOptions) | undefined;\n /**\n * Explicit id of the toast; an existing one is updated.\n *\n * @defaultValue generated\n */\n readonly id?: string | undefined;\n}\n\n/** The queue's input: `toast(options)` and its methods. */\nexport interface ToastManager {\n /** Adds a toast (or updates the one with `options.id`) and returns its id. */\n (options: ToastOptions): string;\n /**\n * The same as calling the manager: adds a toast (or updates the one with `options.id`) and\n * returns its id.\n */\n readonly add: (options: ToastOptions) => string;\n /**\n * Shows `options.pending` at once and swaps to `success` / `error` when `promise` settles.\n * Returns a promise that settles with `promise`, except that a rejection resolves with\n * `undefined` when `error` was given.\n */\n readonly promise: <T>(\n promise: PromiseLike<T>,\n options: ToastPromiseOptions<T>,\n ) => Promise<T | undefined>;\n /** Changes a toast in place (same position, same element). Unknown or closed ids are ignored. */\n readonly update: (id: string, options: Partial<ToastOptions>) => void;\n /** Closes one toast, or every toast when `id` is omitted, with `reason: \"dismiss\"`. */\n readonly dismiss: (id?: string) => void;\n}\n\n// --- Internal: the command channel between a manager and its Viewport --------------------------\n\n/** A queue mutation, applied by the subscribed Viewport (or buffered until one subscribes). */\nexport type ToastCommand =\n | {\n readonly kind: \"add\";\n readonly id: string;\n readonly options: ToastOptions;\n /** Added by `toast.promise`: pending until the promise settles. */\n readonly pending: boolean;\n }\n | {\n readonly kind: \"update\";\n readonly id: string;\n readonly options: Partial<ToastOptions>;\n /** A promise settle: the options replace the toast's (keeping its id), pending ends. */\n readonly settle: boolean;\n }\n | { readonly kind: \"dismiss\"; readonly id: string | undefined };\n\n/** What a Viewport hands its manager. */\nexport interface ToastListener {\n /**\n * Takes over the toasts a previous Viewport left behind (called on subscribe, before the\n * buffer is applied).\n */\n readonly restore: (toasts: readonly RetainedToast[]) => void;\n /** Applies a batch of commands, in dispatch order. */\n readonly apply: (commands: readonly ToastCommand[]) => void;\n /** The toasts to keep when this Viewport unsubscribes. */\n readonly retain: () => readonly RetainedToast[];\n}\n\n/** A retained queue entry: what a Viewport leaves behind when it unmounts (design 14 item 11). */\nexport interface RetainedToast {\n readonly options: ToastOptions & { readonly id: string };\n readonly pending: boolean;\n /**\n * The text last announced for it (`null`: silenced), so the next Viewport does not announce\n * it again; `undefined` when nothing was announced yet.\n */\n readonly announced?: string | null | undefined;\n}\n\nexport interface ToastManagerInternals {\n /**\n * Sets the listener, hands it the retained toasts and drains the buffer into it. Returns the\n * unsubscribe function, or `null` (changing nothing) when a different listener is subscribed:\n * the second-Viewport case.\n */\n readonly subscribe: (listener: ToastListener) => (() => void) | null;\n /** Whether a listener other than `listener` is subscribed (read during render). */\n readonly isTaken: (listener: ToastListener) => boolean;\n}\n\nconst internals = new WeakMap<ToastManager, ToastManagerInternals>();\n\n/** The command channel of `manager` (library-internal). */\nexport function toastManagerInternals(manager: ToastManager): ToastManagerInternals {\n const value = internals.get(manager);\n if (value === undefined) {\n throw new TypeError(\"Toast.Viewport: `manager` must come from `createToastManager()`.\");\n }\n return value;\n}\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nlet warnedServer = false;\n\n/**\n * Generated ids are unique across managers, so a Viewport whose `manager` prop changes never\n * mistakes a late close from the old queue (an Undo settling) for one of the new queue's toasts.\n */\nlet nextId = 0;\n\n/** On the server every method is a no-op, never buffered (design 13). */\nfunction onServer(): boolean {\n if (typeof document !== \"undefined\") return false;\n if (isDev && !warnedServer) {\n warnedServer = true;\n console.error(\n \"toast(): called on the server. Toasts are client-only; the call does nothing. Return data \" +\n \"from the Server Function and call `toast()` on the client.\",\n );\n }\n return true;\n}\n\n/** Resets the once-per-process server warning (tests only). */\nexport function resetToastServerWarning(): void {\n warnedServer = false;\n}\n\nfunction resolveOptions<V>(\n options: ToastOptions | ((value: V) => ToastOptions),\n value: V,\n): ToastOptions {\n return typeof options === \"function\" ? options(value) : options;\n}\n\n/**\n * Creates an isolated queue: `<Toast.Viewport manager={m}>` renders it. For a second React root,\n * a micro-frontend, or a test that wants a clean queue. `toast` is the default manager.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport function createToastManager(): ToastManager {\n let listener: ToastListener | null = null;\n let retained: readonly RetainedToast[] = [];\n /** Commands issued before any Viewport subscribed (client only). */\n let buffer: ToastCommand[] = [];\n /** Commands of the current tick, flushed together from one microtask. */\n let batch: ToastCommand[] = [];\n let scheduled = false;\n\n const flush = (): void => {\n scheduled = false;\n const commands = batch;\n batch = [];\n if (commands.length === 0) return;\n if (listener !== null) listener.apply(commands);\n else buffer.push(...commands);\n };\n\n // A microtask, not a synchronous dispatch: a call made inside a `startTransition` scope (an\n // action's sync prefix) is no longer inside it when the microtask runs, so the queue update is\n // urgent and shows at once even while the action is pending (design 3.4).\n const dispatch = (command: ToastCommand): void => {\n batch.push(command);\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(flush);\n };\n\n const generateId = (): string => `fsui-toast-${++nextId}`;\n\n const add = (options: ToastOptions): string => {\n const id = options.id ?? generateId();\n if (onServer()) return id;\n dispatch({ kind: \"add\", id, options, pending: false });\n return id;\n };\n\n const update = (id: string, options: Partial<ToastOptions>): void => {\n if (onServer()) return;\n dispatch({ kind: \"update\", id, options, settle: false });\n };\n\n const dismiss = (id?: string): void => {\n if (onServer()) return;\n dispatch({ kind: \"dismiss\", id });\n };\n\n const promise = <T>(\n input: PromiseLike<T>,\n options: ToastPromiseOptions<T>,\n ): Promise<T | undefined> => {\n const { success, error } = options;\n if (onServer()) {\n return Promise.resolve(input).then(\n (value) => value,\n (reason: unknown) => {\n if (error !== undefined) return undefined;\n throw reason;\n },\n );\n }\n const id = options.id ?? options.pending.id ?? generateId();\n dispatch({ kind: \"add\", id, options: options.pending, pending: true });\n // The returned promise is built from the same `then`, so it settles in the same tick as the\n // toast's update and an awaiting action prop is pending exactly as long as the toast.\n // A `success` / `error` function that throws dismisses the toast (it must not stay pending\n // forever) and the returned promise rejects with what it threw: the operation's outcome is\n // known, but its message is not, and the `error` message would misreport a fulfilment.\n const settle = <V>(options: ToastOptions | ((value: V) => ToastOptions), value: V): void => {\n let resolved: ToastOptions;\n try {\n resolved = resolveOptions(options, value);\n } catch (thrown) {\n dismiss(id);\n throw thrown;\n }\n dispatch({ kind: \"update\", id, options: resolved, settle: true });\n };\n return Promise.resolve(input).then(\n (value) => {\n if (success === undefined) dismiss(id);\n else settle(success, value);\n return value;\n },\n (reason: unknown) => {\n if (error === undefined) {\n dismiss(id);\n throw reason;\n }\n settle(error, reason);\n return undefined;\n },\n );\n };\n\n const manager = Object.assign((options: ToastOptions) => add(options), {\n add,\n promise,\n update,\n dismiss,\n }) as ToastManager;\n\n internals.set(manager, {\n subscribe: (next) => {\n if (listener !== null && listener !== next) return null;\n listener = next;\n const handedOver = retained;\n retained = [];\n if (handedOver.length > 0) next.restore(handedOver);\n // Commands issued before this Viewport subscribed, in order.\n const pending = buffer;\n buffer = [];\n if (pending.length > 0) next.apply(pending);\n return () => {\n if (listener !== next) return;\n // The queue survives the Viewport (a route-level Viewport remounting on navigation does\n // not lose an Undo); timers and `closeAction`s do not.\n retained = next.retain();\n listener = null;\n };\n },\n isTaken: (candidate) => listener !== null && listener !== candidate,\n });\n\n return manager;\n}\n\n/**\n * The default toast manager: `toast({ title: \"Saved\" })` from anywhere on the client (action\n * bodies, stores, effects). `<Toast.Viewport>` without `manager` renders it. On the server every\n * call is a no-op.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport const toast: ToastManager = createToastManager();\n"],"mappings":";AAmNA,MAAM,4BAAY,IAAI,QAA6C;;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,MAAM,OAAO;GAC1C,aAAa;IACX,IAAI,aAAa,MAAM;IAGvB,WAAW,KAAK,OAAO;IACvB,WAAW;GACb;EACF;EACA,UAAU,cAAc,aAAa,QAAQ,aAAa;CAC5D,CAAC;CAED,OAAO;AACT;;;;;;;;AASA,MAAa,QAAsB,mBAAmB"}
|
|
1
|
+
{"version":3,"file":"toast.mjs","names":[],"sources":["../../src/toast/toast.ts"],"sourcesContent":["// No \"use client\" directive: the manager uses no React and no DOM API beyond `queueMicrotask`,\n// so a Server Component may import `toast` (for its type, or to pass nothing) without a client\n// reference (design/components/toast.md 13). The parts are client modules.\nimport type { ReactNode } from \"react\";\nimport type { Action, ActionDetails, ChangeReason, UrgentHandler } from \"../internal/types.js\";\n\n/** Announcement priority and role of a toast. */\nexport type ToastPriority = \"normal\" | \"high\";\n\n/** The `action` of a toast: what `Toast.Action` renders and runs by default. */\nexport interface ToastActionOptions {\n /** The Action button's content. */\n readonly label: ReactNode;\n /**\n * Runs in the Action part's own transition (`data-pending` on the Action and the Root, the\n * timer paused). The toast closes with `reason: \"activate\"` when it resolves; a rejection\n * keeps the toast and reaches the nearest Error Boundary above the Viewport. A caught error\n * resolves the action and therefore closes the toast: rethrow after `toast.update` to keep it.\n */\n readonly action: Action<[details: ToastActionDetails]>;\n}\n\n/**\n * What `toast(options)` shows: the content and behaviour of one toast. `toast.update(id, options)`\n * takes a partial of it.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport interface ToastOptions {\n /**\n * Explicit id: an existing one updates that toast.\n *\n * @defaultValue generated\n */\n readonly id?: string | undefined;\n /** Rendered by `Toast.Title`, which names the Root (`aria-labelledby`). */\n readonly title?: ReactNode;\n /** Rendered by `Toast.Description`, which describes the Root (`aria-describedby`). */\n readonly description?: ReactNode;\n /** Free-form, rendered as `data-type` on the Root (`\"success\"`, `\"error\"`, ...). */\n readonly type?: string | undefined;\n /**\n * Announcement priority and role: `\"high\"` announces with `ariaNotify` priority `\"high\"` and\n * renders the Root as an `alertdialog`.\n *\n * @defaultValue `\"normal\"`\n */\n readonly priority?: ToastPriority | undefined;\n /**\n * Milliseconds before the toast closes with `reason: \"timeout\"`; `null` never. A timed action\n * toast must keep its action reachable elsewhere too (WCAG 2.2.1).\n *\n * @defaultValue the Viewport's `duration`, or `null` (persistent) when the toast has an `action`\n */\n readonly duration?: number | null | undefined;\n /**\n * A button the toast offers (Undo, Retry), rendered and run by `Toast.Action`. A toast with an\n * action is persistent unless `duration` is set.\n */\n readonly action?: ToastActionOptions | undefined;\n /**\n * A handler, not an action: called once when the toast leaves,\n * with the reason: `\"activate\"` (the Action part settled), `\"dismiss\"` (Close, Escape,\n * `toast.dismiss()`, a promise toast with no message for its outcome) or `\"timeout\"`. Called\n * synchronously where the close happens, outside any Transition, and not awaited: a slow\n * `deleteForReal` holds no other transition. May return a promise (a Server Function); a\n * rejection or a throw goes to `reportError`, never to an Error Boundary. Not called when the\n * Viewport unmounts.\n */\n readonly onClose?: UrgentHandler<ToastCloseDetails> | undefined;\n /**\n * The text `document.ariaNotify()` speaks for this toast; `null` announces nothing.\n *\n * @defaultValue the Viewport's `announce`, else the text of the toast's Title and Description\n */\n readonly announce?: ((toast: ToastItem) => string | null) | undefined;\n /** Anything the Viewport's children want to render. */\n readonly data?: unknown;\n}\n\n/** A toast in the queue, as the Viewport's `children(state)` receives it. */\nexport interface ToastItem extends ToastOptions {\n readonly id: string;\n /**\n * The promise given to `toast.promise` is unsettled, or an action dispatched through this\n * toast's Action part is in flight.\n */\n readonly pending: boolean;\n /** Closed; kept mounted (and `inert`) for its exit animation. */\n readonly ending: boolean;\n}\n\n/** Details passed to a toast's Action. */\nexport interface ToastActionDetails extends ActionDetails {\n /** The toast's id, so an inline action can `toast.update` or `toast.dismiss` its own toast. */\n readonly id: string;\n}\n\n/** Details passed to a toast's `onClose`. */\nexport interface ToastCloseDetails extends ActionDetails {\n /** The id of the toast that closed. */\n readonly id: string;\n /** `\"activate\"`, `\"dismiss\"` or `\"timeout\"`. */\n readonly reason: ChangeReason;\n}\n\n/**\n * The second argument of `toast.promise(promise, options)`: the toast to show while `promise` is\n * pending and the ones that replace it when it settles.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport interface ToastPromiseOptions<T> {\n /** Shown at once, with `data-pending`; no timer until the promise settles. */\n readonly pending: ToastOptions;\n /**\n * Replaces the toast when the promise fulfils; omitted: the toast is dismissed. A function that\n * throws dismisses the toast, and the returned promise rejects with what it threw.\n */\n readonly success?: ToastOptions | ((value: T) => ToastOptions) | undefined;\n /**\n * Replaces the toast when the promise rejects; the returned promise then resolves with\n * `undefined` (the toast is the handler). Omitted: the toast is dismissed and the returned\n * promise rejects with the same reason. A function that throws dismisses the toast, and the\n * returned promise rejects with what it threw.\n */\n readonly error?: ToastOptions | ((reason: unknown) => ToastOptions) | undefined;\n /**\n * Explicit id of the toast; an existing one is updated.\n *\n * @defaultValue generated\n */\n readonly id?: string | undefined;\n}\n\n/** The queue's input: `toast(options)` and its methods. */\nexport interface ToastManager {\n /** Adds a toast (or updates the one with `options.id`) and returns its id. */\n (options: ToastOptions): string;\n /**\n * The same as calling the manager: adds a toast (or updates the one with `options.id`) and\n * returns its id.\n */\n readonly add: (options: ToastOptions) => string;\n /**\n * Shows `options.pending` at once and swaps to `success` / `error` when `promise` settles.\n * Returns a promise that settles with `promise`, except that a rejection resolves with\n * `undefined` when `error` was given.\n */\n readonly promise: <T>(\n promise: PromiseLike<T>,\n options: ToastPromiseOptions<T>,\n ) => Promise<T | undefined>;\n /** Changes a toast in place (same position, same element). Unknown or closed ids are ignored. */\n readonly update: (id: string, options: Partial<ToastOptions>) => void;\n /** Closes one toast, or every toast when `id` is omitted, with `reason: \"dismiss\"`. */\n readonly dismiss: (id?: string) => void;\n}\n\n// --- Internal: the command channel between a manager and its Viewport --------------------------\n\n/** A queue mutation, applied by the subscribed Viewport (or buffered until one subscribes). */\nexport type ToastCommand =\n | {\n readonly kind: \"add\";\n readonly id: string;\n readonly options: ToastOptions;\n /** Added by `toast.promise`: pending until the promise settles. */\n readonly pending: boolean;\n }\n | {\n readonly kind: \"update\";\n readonly id: string;\n readonly options: Partial<ToastOptions>;\n /** A promise settle: the options replace the toast's (keeping its id), pending ends. */\n readonly settle: boolean;\n }\n | { readonly kind: \"dismiss\"; readonly id: string | undefined };\n\n/** What a Viewport hands its manager. */\nexport interface ToastListener {\n /**\n * Takes over the toasts a previous Viewport left behind (called on subscribe, before the\n * buffer is applied).\n */\n readonly restore: (toasts: readonly RetainedToast[]) => void;\n /** Applies a batch of commands, in dispatch order. */\n readonly apply: (commands: readonly ToastCommand[]) => void;\n /** The toasts to keep when this Viewport unsubscribes. */\n readonly retain: () => readonly RetainedToast[];\n}\n\n/** A retained queue entry: what a Viewport leaves behind when it unmounts (design 14 item 11). */\nexport interface RetainedToast {\n readonly options: ToastOptions & { readonly id: string };\n readonly pending: boolean;\n /**\n * The text last announced for it (`null`: silenced), so the next Viewport does not announce\n * it again; `undefined` when nothing was announced yet.\n */\n readonly announced?: string | null | undefined;\n}\n\nexport interface ToastManagerInternals {\n /**\n * Sets the listener, hands it the retained toasts and drains the buffer into it. Returns the\n * unsubscribe function, or `null` (changing nothing) when a different listener is subscribed:\n * the second-Viewport case.\n */\n readonly subscribe: (listener: ToastListener) => (() => void) | null;\n /** Whether a listener other than `listener` is subscribed (read during render). */\n readonly isTaken: (listener: ToastListener) => boolean;\n}\n\nconst internals = new WeakMap<ToastManager, ToastManagerInternals>();\n\n/** The command channel of `manager` (library-internal). */\nexport function toastManagerInternals(manager: ToastManager): ToastManagerInternals {\n const value = internals.get(manager);\n if (value === undefined) {\n throw new TypeError(\"Toast.Viewport: `manager` must come from `createToastManager()`.\");\n }\n return value;\n}\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nlet warnedServer = false;\n\n/**\n * Generated ids are unique across managers, so a Viewport whose `manager` prop changes never\n * mistakes a late close from the old queue (an Undo settling) for one of the new queue's toasts.\n */\nlet nextId = 0;\n\n/** On the server every method is a no-op, never buffered (design 13). */\nfunction onServer(): boolean {\n if (typeof document !== \"undefined\") return false;\n if (isDev && !warnedServer) {\n warnedServer = true;\n console.error(\n \"toast(): called on the server. Toasts are client-only; the call does nothing. Return data \" +\n \"from the Server Function and call `toast()` on the client.\",\n );\n }\n return true;\n}\n\n/** Resets the once-per-process server warning (tests only). */\nexport function resetToastServerWarning(): void {\n warnedServer = false;\n}\n\nfunction resolveOptions<V>(\n options: ToastOptions | ((value: V) => ToastOptions),\n value: V,\n): ToastOptions {\n return typeof options === \"function\" ? options(value) : options;\n}\n\n/**\n * Creates an isolated queue: `<Toast.Viewport manager={m}>` renders it. For a second React root,\n * a micro-frontend, or a test that wants a clean queue. `toast` is the default manager.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport function createToastManager(): ToastManager {\n let listener: ToastListener | null = null;\n let retained: readonly RetainedToast[] = [];\n /** Commands issued before any Viewport subscribed (client only). */\n let buffer: ToastCommand[] = [];\n /** Commands of the current tick, flushed together from one microtask. */\n let batch: ToastCommand[] = [];\n let scheduled = false;\n\n const flush = (): void => {\n scheduled = false;\n const commands = batch;\n batch = [];\n if (commands.length === 0) return;\n if (listener !== null) listener.apply(commands);\n else buffer.push(...commands);\n };\n\n // A microtask, not a synchronous dispatch: a call made inside a `startTransition` scope (an\n // action's sync prefix) is no longer inside it when the microtask runs, so the queue update is\n // urgent and shows at once even while the action is pending (design 3.4).\n const dispatch = (command: ToastCommand): void => {\n batch.push(command);\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(flush);\n };\n\n const generateId = (): string => `fsui-toast-${++nextId}`;\n\n const add = (options: ToastOptions): string => {\n const id = options.id ?? generateId();\n if (onServer()) return id;\n dispatch({ kind: \"add\", id, options, pending: false });\n return id;\n };\n\n const update = (id: string, options: Partial<ToastOptions>): void => {\n if (onServer()) return;\n dispatch({ kind: \"update\", id, options, settle: false });\n };\n\n const dismiss = (id?: string): void => {\n if (onServer()) return;\n dispatch({ kind: \"dismiss\", id });\n };\n\n const promise = <T>(\n input: PromiseLike<T>,\n options: ToastPromiseOptions<T>,\n ): Promise<T | undefined> => {\n const { success, error } = options;\n if (onServer()) {\n return Promise.resolve(input).then(\n (value) => value,\n (reason: unknown) => {\n if (error !== undefined) return undefined;\n throw reason;\n },\n );\n }\n const id = options.id ?? options.pending.id ?? generateId();\n dispatch({ kind: \"add\", id, options: options.pending, pending: true });\n // The returned promise is built from the same `then`, so it settles in the same tick as the\n // toast's update and an awaiting action prop is pending exactly as long as the toast.\n // A `success` / `error` function that throws dismisses the toast (it must not stay pending\n // forever) and the returned promise rejects with what it threw: the operation's outcome is\n // known, but its message is not, and the `error` message would misreport a fulfilment.\n const settle = <V>(options: ToastOptions | ((value: V) => ToastOptions), value: V): void => {\n let resolved: ToastOptions;\n try {\n resolved = resolveOptions(options, value);\n } catch (thrown) {\n dismiss(id);\n throw thrown;\n }\n dispatch({ kind: \"update\", id, options: resolved, settle: true });\n };\n return Promise.resolve(input).then(\n (value) => {\n if (success === undefined) dismiss(id);\n else settle(success, value);\n return value;\n },\n (reason: unknown) => {\n if (error === undefined) {\n dismiss(id);\n throw reason;\n }\n settle(error, reason);\n return undefined;\n },\n );\n };\n\n const manager = Object.assign((options: ToastOptions) => add(options), {\n add,\n promise,\n update,\n dismiss,\n }) as ToastManager;\n\n internals.set(manager, {\n subscribe: (next) => {\n if (listener !== null && listener !== next) return null;\n listener = next;\n const handedOver = retained;\n retained = [];\n if (handedOver.length > 0) next.restore(handedOver);\n // Commands issued before this Viewport subscribed, in order.\n const pending = buffer;\n buffer = [];\n if (pending.length > 0) next.apply(pending);\n return () => {\n if (listener !== next) return;\n // The queue survives the Viewport (a route-level Viewport remounting on navigation does\n // not lose an Undo); timers and `onClose` calls do not.\n retained = next.retain();\n listener = null;\n };\n },\n isTaken: (candidate) => listener !== null && listener !== candidate,\n });\n\n return manager;\n}\n\n/**\n * The default toast manager: `toast({ title: \"Saved\" })` from anywhere on the client (action\n * bodies, stores, effects). `<Toast.Viewport>` without `manager` renders it. On the server every\n * call is a no-op.\n *\n * @see https://ui.funstack.work/components/toast\n */\nexport const toast: ToastManager = createToastManager();\n"],"mappings":";AAsNA,MAAM,4BAAY,IAAI,QAA6C;;AAGnE,SAAgB,sBAAsB,SAA8C;CAClF,MAAM,QAAQ,UAAU,IAAI,OAAO;CACnC,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,UAAU,kEAAkE;CAExF,OAAO;AACT;AAEA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AAEvC,IAAI,eAAe;;;;;AAMnB,IAAI,SAAS;;AAGb,SAAS,WAAoB;CAC3B,IAAI,OAAO,aAAa,aAAa,OAAO;CAC5C,IAAI,SAAS,CAAC,cAAc;EAC1B,eAAe;EACf,QAAQ,MACN,sJAEF;CACF;CACA,OAAO;AACT;AAOA,SAAS,eACP,SACA,OACc;CACd,OAAO,OAAO,YAAY,aAAa,QAAQ,KAAK,IAAI;AAC1D;;;;;;;AAQA,SAAgB,qBAAmC;CACjD,IAAI,WAAiC;CACrC,IAAI,WAAqC,CAAC;;CAE1C,IAAI,SAAyB,CAAC;;CAE9B,IAAI,QAAwB,CAAC;CAC7B,IAAI,YAAY;CAEhB,MAAM,cAAoB;EACxB,YAAY;EACZ,MAAM,WAAW;EACjB,QAAQ,CAAC;EACT,IAAI,SAAS,WAAW,GAAG;EAC3B,IAAI,aAAa,MAAM,SAAS,MAAM,QAAQ;OACzC,OAAO,KAAK,GAAG,QAAQ;CAC9B;CAKA,MAAM,YAAY,YAAgC;EAChD,MAAM,KAAK,OAAO;EAClB,IAAI,WAAW;EACf,YAAY;EACZ,eAAe,KAAK;CACtB;CAEA,MAAM,mBAA2B,cAAc,EAAE;CAEjD,MAAM,OAAO,YAAkC;EAC7C,MAAM,KAAK,QAAQ,MAAM,WAAW;EACpC,IAAI,SAAS,GAAG,OAAO;EACvB,SAAS;GAAE,MAAM;GAAO;GAAI;GAAS,SAAS;EAAM,CAAC;EACrD,OAAO;CACT;CAEA,MAAM,UAAU,IAAY,YAAyC;EACn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,WAAW,SAAS,GAAG,KAAK,QAAQ,UAAU;GAElD,MAAM,UAAU;GAChB,SAAS,CAAC;GACV,IAAI,QAAQ,SAAS,GAAG,KAAK,MAAM,OAAO;GAC1C,aAAa;IACX,IAAI,aAAa,MAAM;IAGvB,WAAW,KAAK,OAAO;IACvB,WAAW;GACb;EACF;EACA,UAAU,cAAc,aAAa,QAAQ,aAAa;CAC5D,CAAC;CAED,OAAO;AACT;;;;;;;;AASA,MAAa,QAAsB,mBAAmB"}
|
|
@@ -71,7 +71,7 @@ function ToggleGroupRoot(props) {
|
|
|
71
71
|
...details.added.length > 0 ? ["fsui-toggle-group-press"] : [],
|
|
72
72
|
...details.removed.length > 0 ? ["fsui-toggle-group-release"] : []
|
|
73
73
|
],
|
|
74
|
-
reducer: (prev, _next, details) => applyPatch(prev, details),
|
|
74
|
+
reducer: mountExclusive ? void 0 : (prev, _next, details) => applyPatch(prev, details),
|
|
75
75
|
warn: {
|
|
76
76
|
component: "ToggleGroup.Root",
|
|
77
77
|
prop: "value"
|