@funstack/ui 0.1.0-alpha.14 → 0.1.0-alpha.15
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.d.mts.map +1 -1
- package/dist/accordion/accordion-root.mjs +5 -4
- package/dist/accordion/accordion-root.mjs.map +1 -1
- package/dist/checkbox-group/checkbox-group-root.d.mts.map +1 -1
- package/dist/checkbox-group/checkbox-group-root.mjs +4 -5
- package/dist/checkbox-group/checkbox-group-root.mjs.map +1 -1
- package/dist/combobox/combobox-context.mjs.map +1 -1
- package/dist/combobox/combobox-input.d.mts +7 -6
- package/dist/combobox/combobox-input.d.mts.map +1 -1
- package/dist/combobox/combobox-input.mjs +6 -5
- package/dist/combobox/combobox-input.mjs.map +1 -1
- package/dist/combobox/combobox-label.d.mts +2 -1
- package/dist/combobox/combobox-label.d.mts.map +1 -1
- package/dist/combobox/combobox-label.mjs +2 -1
- package/dist/combobox/combobox-label.mjs.map +1 -1
- package/dist/combobox/combobox-popup.d.mts +1 -1
- package/dist/combobox/combobox-popup.d.mts.map +1 -1
- package/dist/combobox/combobox-popup.mjs +3 -15
- package/dist/combobox/combobox-popup.mjs.map +1 -1
- package/dist/combobox/combobox-root.d.mts.map +1 -1
- package/dist/combobox/combobox-root.mjs +9 -80
- package/dist/combobox/combobox-root.mjs.map +1 -1
- package/dist/combobox/combobox-trigger.d.mts +10 -8
- package/dist/combobox/combobox-trigger.d.mts.map +1 -1
- package/dist/combobox/combobox-trigger.mjs +21 -17
- package/dist/combobox/combobox-trigger.mjs.map +1 -1
- package/dist/combobox/index.d.mts +2 -2
- package/dist/combobox/index.mjs +2 -2
- package/dist/combobox/index.mjs.map +1 -1
- package/dist/combobox/use-deferred-leave.mjs +105 -0
- package/dist/combobox/use-deferred-leave.mjs.map +1 -0
- package/dist/dialog/dialog-context.mjs.map +1 -1
- package/dist/dialog/dialog-popup.d.mts.map +1 -1
- package/dist/dialog/dialog-popup.mjs +2 -2
- package/dist/dialog/dialog-popup.mjs.map +1 -1
- package/dist/dialog/dialog-trigger.mjs.map +1 -1
- package/dist/form/form-root.mjs +1 -1
- package/dist/form/form-root.mjs.map +1 -1
- package/dist/internal/announce.mjs +12 -7
- package/dist/internal/announce.mjs.map +1 -1
- package/dist/internal/focus-first-invalid.mjs +2 -11
- package/dist/internal/focus-first-invalid.mjs.map +1 -1
- package/dist/internal/focus-visible.mjs +26 -0
- package/dist/internal/focus-visible.mjs.map +1 -0
- package/dist/internal/{invoker-press.mjs → invokers.mjs} +22 -5
- package/dist/internal/invokers.mjs.map +1 -0
- package/dist/internal/platform-attributes.d.mts +1 -1
- package/dist/internal/pointer-capture.mjs +1 -1
- package/dist/internal/pointer-capture.mjs.map +1 -1
- package/dist/internal/trigger-ref.mjs +1 -1
- package/dist/internal/trigger-ref.mjs.map +1 -1
- package/dist/internal/use-interest-dismiss.mjs +84 -0
- package/dist/internal/use-interest-dismiss.mjs.map +1 -0
- package/dist/internal/use-overlay-root.mjs.map +1 -1
- package/dist/internal/use-popover-popup.mjs +43 -108
- package/dist/internal/use-popover-popup.mjs.map +1 -1
- package/dist/internal/use-popover-trigger.d.mts.map +1 -1
- package/dist/internal/use-popover-trigger.mjs +29 -10
- package/dist/internal/use-popover-trigger.mjs.map +1 -1
- package/dist/internal/use-value-set.mjs +20 -0
- package/dist/internal/use-value-set.mjs.map +1 -0
- package/dist/menu/menu-popup.d.mts +1 -1
- package/dist/menu/menu-popup.mjs +13 -27
- package/dist/menu/menu-popup.mjs.map +1 -1
- package/dist/menu/menu-submenu-trigger.d.mts +8 -8
- package/dist/menu/menu-submenu-trigger.mjs +9 -10
- package/dist/menu/menu-submenu-trigger.mjs.map +1 -1
- package/dist/menu/menu-trigger.d.mts +8 -7
- package/dist/menu/menu-trigger.d.mts.map +1 -1
- package/dist/menu/menu-trigger.mjs +6 -12
- package/dist/menu/menu-trigger.mjs.map +1 -1
- package/dist/number-field/number-field-root.mjs +1 -1
- package/dist/popover/popover-close.d.mts +3 -3
- package/dist/popover/popover-close.mjs +1 -1
- package/dist/popover/popover-close.mjs.map +1 -1
- package/dist/popover/popover-popup.mjs.map +1 -1
- package/dist/popover/popover-trigger.d.mts +9 -9
- package/dist/popover/popover-trigger.mjs +9 -9
- package/dist/popover/popover-trigger.mjs.map +1 -1
- package/dist/toast/toast-root.mjs.map +1 -1
- package/dist/toast/toast-viewport.d.mts.map +1 -1
- package/dist/toast/toast-viewport.mjs +4 -5
- package/dist/toast/toast-viewport.mjs.map +1 -1
- package/dist/toggle-group/toggle-group-root.d.mts.map +1 -1
- package/dist/toggle-group/toggle-group-root.mjs +4 -5
- package/dist/toggle-group/toggle-group-root.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/internal/invoker-press.mjs.map +0 -1
|
@@ -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 type { AriaNotifyTarget } 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\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\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 /** The queue to render. Default: the module-level `toast`. */\n manager?: ToastManager;\n /** Toasts rendered at once; further ones wait in order (never dropped). Default `3`. */\n limit?: number;\n /** Default `duration` of a toast in milliseconds; `null` for persistent. Default `5000`. */\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. Default `[\"F8\"]`; `null` installs no listener.\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. Default: the text of its 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 className?: StateValue<string | undefined, ToastViewportState>;\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\ntype DocumentWithAriaNotify = Document & AriaNotifyTarget;\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 */\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 doc = (regionRef.current?.ownerDocument ?? document) as DocumentWithAriaNotify;\n if (typeof doc.ariaNotify !== \"function\") return;\n const priority = batch.some((a) => a.priority === \"high\") ? \"high\" : \"normal\";\n doc.ariaNotify(batch.map((a) => a.text).join(\" \"), { priority });\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":";;;;;;;;;;;;;;;;;;;AAwFA,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,UACA,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,UAA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AW,CAAC;EAChD;EACA;EACA;EACA;CACF;CAEA,MAAM,SAAS,UAAgE;EAC7E,gBAAgB;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 {\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\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\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 /** The queue to render. Default: the module-level `toast`. */\n manager?: ToastManager;\n /** Toasts rendered at once; further ones wait in order (never dropped). Default `3`. */\n limit?: number;\n /** Default `duration` of a toast in milliseconds; `null` for persistent. Default `5000`. */\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. Default `[\"F8\"]`; `null` installs no listener.\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. Default: the text of its 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 className?: StateValue<string | undefined, ToastViewportState>;\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 */\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":";;;;;;;;;;;;;;;;;;;;AAwFA,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;;;;;;;;;;AAWA,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,WAAqC,SAAS,QAAQ,QAAQ,MAAM;EAC9E,QAAQ,aAAsC,SAAS,QAAQ,MAAM,QAAQ;EAC7E,cAAc,SAAS,QAAQ,OAAO;CACxC;CA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AD;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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toggle-group-root.d.mts","names":[],"sources":["../../src/toggle-group/toggle-group-root.tsx"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"toggle-group-root.d.mts","names":[],"sources":["../../src/toggle-group/toggle-group-root.tsx"],"mappings":";;;;;iBA4BiB,sCAAsC;;WAE5C;;WAEA;;iBAGM;;;;;;WAMN;;WAEA;WACA;;WAEA,aAAa;;UAGd,iCAAiC,KACzC;;EAYA,cAAc;;EAEd;;EAEA;;;;;;;EAOA;EACA,YAAY,+BAA+B;EAC3C,QAAQ,WAAW,2BAA2B;EAC9C,WAAW,WAAW,WAAW;EACjC,SAAS,WAAW,8BAA8B;;iBAGnC,iCAAiC;EAChD;;EAEA;;EAEA;;;;;;;;;EASA,oBAAoB,uBAAuB;;EAE3C;;iBAGe,kCAAkC;;EAEjD;;EAEA;;EAEA;;;;;;EAMA;;EAEA,oBAAoB,4BAA4B;;;YAItC,uBAAuB,2BAA2B;;;;;;;;;;wBAkC9C,gBAAgB,OAAO,uCAAoB,IAAA;yBAA3C"}
|
|
@@ -9,10 +9,11 @@ import { useLatest } from "../internal/use-latest.mjs";
|
|
|
9
9
|
import { useControllableAction } from "../internal/use-controllable-action.mjs";
|
|
10
10
|
import { ToggleGroupContext } from "./toggle-group-context.mjs";
|
|
11
11
|
import { compareDocumentOrder } from "../internal/dom-order.mjs";
|
|
12
|
-
import { EMPTY_SET, applyPatch, arraysEqual, sortByOrder
|
|
12
|
+
import { EMPTY_SET, applyPatch, arraysEqual, sortByOrder } from "../internal/value-set.mjs";
|
|
13
13
|
import { useItemOrder } from "../internal/use-item-order.mjs";
|
|
14
14
|
import { useNativeFocusgroup } from "../internal/use-native-focusgroup.mjs";
|
|
15
15
|
import { useRovingFocus } from "../internal/use-roving-focus.mjs";
|
|
16
|
+
import { useValueSet } from "../internal/use-value-set.mjs";
|
|
16
17
|
import { useCallback, useMemo, useRef, useState } from "react";
|
|
17
18
|
import { jsx } from "react/jsx-runtime";
|
|
18
19
|
//#region src/toggle-group/toggle-group-root.tsx
|
|
@@ -46,10 +47,8 @@ function ToggleGroupRoot(props) {
|
|
|
46
47
|
const flag = !inToolbar && focusgroupProp === true;
|
|
47
48
|
const [mountExclusive] = useState(exclusive);
|
|
48
49
|
useDevWarning(mountExclusive !== exclusive, isDev && "ToggleGroup.Root: `exclusive` changed after mount. Switching between exclusive and multiple mode is not supported; the group keeps the mode it mounted with.");
|
|
49
|
-
const
|
|
50
|
-
const
|
|
51
|
-
const defaultKey = defaultValue === void 0 ? void 0 : JSON.stringify(defaultValue);
|
|
52
|
-
const defaultSet = useMemo(() => defaultKey === void 0 ? void 0 : toSet(JSON.parse(defaultKey)), [defaultKey]);
|
|
50
|
+
const controlledSet = useValueSet(value);
|
|
51
|
+
const defaultSet = useValueSet(defaultValue);
|
|
53
52
|
const registry = useRef(/* @__PURE__ */ new Map());
|
|
54
53
|
const registerItem = useCallback((element, itemValue) => {
|
|
55
54
|
registry.current.set(element, itemValue);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toggle-group-root.mjs","names":[],"sources":["../../src/toggle-group/toggle-group-root.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode } from \"react\";\nimport { createActionDetails } from \"../internal/action-details.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { compareDocumentOrder } from \"../internal/dom-order.js\";\nimport { useToolbarContext } from \"../internal/toolbar-context.js\";\nimport { transitionTypes } from \"../internal/transition-types.js\";\nimport type { ActionDetails, ChangeAction, RenderProp, StateValue } from \"../internal/types.js\";\nimport { useControllableAction } from \"../internal/use-controllable-action.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { useItemOrder } from \"../internal/use-item-order.js\";\nimport type { ItemLayout } from \"../internal/use-item-order.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useNativeFocusgroup } from \"../internal/use-native-focusgroup.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useRovingFocus } from \"../internal/use-roving-focus.js\";\nimport { applyPatch, EMPTY_SET, arraysEqual, sortByOrder, toSet } from \"../internal/value-set.js\";\nimport type { SetPatch, ValueSet } from \"../internal/value-set.js\";\nimport { ToggleGroupContext } from \"./toggle-group-context.js\";\nimport type { ToggleGroupContextValue, ToggleGroupOrientation } from \"./toggle-group-context.js\";\n\nexport type { ToggleGroupOrientation } from \"./toggle-group-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** Details passed as the second argument of `valueChangeAction`, in both modes. */\nexport interface ToggleGroupValueChangeDetails extends ActionDetails {\n /** Values this dispatch pressed (document order of their Items). Exclusive mode: `[next]` or `[]`. */\n readonly added: readonly string[];\n /** Values this dispatch released. Exclusive mode: `[previous]` or `[]`. */\n readonly removed: readonly string[];\n}\n\nexport interface ToggleGroupRootState {\n /**\n * Optimistic pressed values in document order of the Items (exclusive mode: `[value]` or `[]`,\n * so one state shape serves both modes). The server render and the first client render use the\n * value's own order. Content rendered from it must not suspend.\n */\n readonly value: readonly string[];\n /** An action dispatched through this group is in flight. */\n readonly pending: boolean;\n readonly disabled: boolean;\n /** The effective orientation: the Toolbar's when inside one. */\n readonly orientation: ToggleGroupOrientation;\n}\n\ninterface ToggleGroupRootBaseProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n | \"role\"\n | \"onKeyDown\"\n | \"onFocus\"\n | \"onBlur\"\n | \"onPointerDown\"\n | \"defaultValue\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** Axis of the arrow keys and `data-orientation`. Default `\"horizontal\"`. Ignored inside a Toolbar (dev warning). */\n orientation?: ToggleGroupOrientation;\n /** Whether arrows wrap from the last Item to the first. Default `true`. Ignored inside a Toolbar (dev warning). */\n loop?: boolean;\n /** Disables every Item (native `disabled`). */\n disabled?: boolean;\n /**\n * Render `focusgroup=\"toolbar …\"` and, where the browser implements it, let the browser move\n * focus between the Items. Chromium 150+ only; elsewhere the JS path stays active. Ignored\n * inside a Toolbar (a nested focusgroup would split the Toolbar's sequence; dev warning).\n * Default `false`.\n */\n experimental_focusgroup?: boolean;\n className?: StateValue<string | undefined, ToggleGroupRootState>;\n style?: StateValue<CSSProperties | undefined, ToggleGroupRootState>;\n children?: StateValue<ReactNode, ToggleGroupRootState>;\n render?: RenderProp<ComponentPropsWithRef<\"div\">, ToggleGroupRootState>;\n}\n\nexport interface ToggleGroupMultipleProps extends ToggleGroupRootBaseProps {\n exclusive?: false;\n /** Controlled pressed values. `[]` presses nothing; `undefined` means uncontrolled. Order is not significant; duplicates ignored. */\n value?: string[];\n /** Initial pressed values in uncontrolled mode. Default `[]`. */\n defaultValue?: string[];\n /**\n * Runs inside the Root's transition whenever the set of pressed Items changes. Sync or async (a\n * Server Function may be passed directly); rejections reach the nearest Error Boundary and roll\n * the change back. `next` is the whole set as a fresh array in document order;\n * `details.added` / `details.removed` say what changed. A `setState` after your own `await` is\n * not a Transition update; wrap it in `startTransition`. Prefer a functional update keyed by\n * `added` / `removed` when controlled.\n */\n valueChangeAction?: ChangeAction<string[], ToggleGroupValueChangeDetails>;\n /** Exclusive mode only: a type error here (TypeScript's union excess-property check would let it through otherwise). */\n deselectable?: never;\n}\n\nexport interface ToggleGroupExclusiveProps extends ToggleGroupRootBaseProps {\n /** At most one Item is pressed; `value` is `string | null`. */\n exclusive: true;\n /** Controlled pressed value. `null` presses nothing; `undefined` means uncontrolled. */\n value?: string | null;\n /** Initial pressed value in uncontrolled mode. Default `null`. */\n defaultValue?: string | null;\n /**\n * Whether pressing the pressed Item releases it (`next === null`). Default `true`. With\n * `false` that press is a no-op and dispatches nothing; `value` stays `string | null` because\n * the group may start with nothing pressed, but the action is then never called with `null`.\n */\n deselectable?: boolean;\n /** See {@link ToggleGroupMultipleProps.valueChangeAction}; `next` is the pressed value or `null`. */\n valueChangeAction?: ChangeAction<string | null, ToggleGroupValueChangeDetails>;\n}\n\n/** Props of `ToggleGroup.Root`, discriminated on `exclusive`. */\nexport type ToggleGroupRootProps = ToggleGroupMultipleProps | ToggleGroupExclusiveProps;\n\ntype GroupValue = string[] | string | null;\n\n/** Both variants as one shape, for the implementation. */\ninterface InternalProps extends ToggleGroupRootBaseProps {\n exclusive?: boolean;\n value?: GroupValue;\n defaultValue?: GroupValue;\n deselectable?: boolean;\n valueChangeAction?: ChangeAction<GroupValue, ToggleGroupValueChangeDetails>;\n}\n\n/** Standalone entry (design 6.2): the first pressed item, else the first item (radio-like). */\nfunction pressedFirst(items: readonly HTMLElement[]): HTMLElement | undefined {\n return items.find((el) => el.getAttribute(\"aria-pressed\") === \"true\") ?? items[0];\n}\n\n/** The Items' document order and their disabled values, as of the Root's last commit. */\ninterface ToggleGroupLayout extends ItemLayout {\n readonly disabled: readonly string[];\n}\n\nconst NO_LAYOUT: ToggleGroupLayout = { order: [], disabled: [] };\n\n/**\n * `<div role=\"group\">` that owns the pressed set, the transition and, when standalone, the roving\n * focus over its Items (design/components/toggle-group.md 16.2). Inside a `Toolbar.Root` it runs\n * no engine of its own: its Items are members of the Toolbar's sequence.\n *\n * Owned keys (conventions 1.2): `role`, `data-orientation`, `data-pending`, `data-disabled`;\n * standalone also `onKeyDown`, `onFocus`, `onBlur`, `onPointerDown` and, with the flag,\n * `focusgroup`.\n */\nexport function ToggleGroupRoot(props: ToggleGroupRootProps) {\n const {\n exclusive = false,\n value,\n defaultValue,\n valueChangeAction,\n deselectable = true,\n orientation: orientationProp,\n loop: loopProp,\n disabled = false,\n experimental_focusgroup: focusgroupProp,\n className,\n style,\n children,\n render,\n ...rest\n } = props as InternalProps;\n\n const toolbar = useToolbarContext();\n const inToolbar = toolbar !== null;\n useDevWarning(\n inToolbar && orientationProp !== undefined,\n isDev &&\n \"ToggleGroup.Root: `orientation` is ignored inside a Toolbar.Root; the group follows the \" +\n \"Toolbar's orientation.\",\n );\n useDevWarning(\n inToolbar && loopProp !== undefined,\n isDev &&\n \"ToggleGroup.Root: `loop` is ignored inside a Toolbar.Root; the Toolbar's `loop` applies.\",\n );\n useDevWarning(\n inToolbar && focusgroupProp === true,\n isDev &&\n \"ToggleGroup.Root: `experimental_focusgroup` is ignored inside a Toolbar.Root. A nested \" +\n \"focusgroup would split the Toolbar's single Tab stop; set the flag on the Toolbar.Root.\",\n );\n const orientation: ToggleGroupOrientation =\n toolbar?.orientation ?? orientationProp ?? \"horizontal\";\n const loop = loopProp ?? true;\n const flag = !inToolbar && focusgroupProp === true;\n\n // The mode is fixed at mount (design 3.1).\n const [mountExclusive] = useState(exclusive);\n useDevWarning(\n mountExclusive !== exclusive,\n isDev &&\n \"ToggleGroup.Root: `exclusive` changed after mount. Switching between exclusive and \" +\n \"multiple mode is not supported; the group keeps the mode it mounted with.\",\n );\n\n // Committed set keyed on the contents, so an inline `value={[\"a\"]}` does not re-base every render.\n const controlledKey = value === undefined ? undefined : JSON.stringify(value);\n const controlledSet = useMemo(\n () =>\n controlledKey === undefined ? undefined : toSet(JSON.parse(controlledKey) as GroupValue),\n [controlledKey],\n );\n const defaultKey = defaultValue === undefined ? undefined : JSON.stringify(defaultValue);\n const defaultSet = useMemo(\n () => (defaultKey === undefined ? undefined : toSet(JSON.parse(defaultKey) as GroupValue)),\n [defaultKey],\n );\n\n // Item registration (design 16.2): element → value, written from the Items' callback refs.\n const registry = useRef(new Map<HTMLElement, string>());\n const registerItem = useCallback((element: HTMLElement, itemValue: string) => {\n registry.current.set(element, itemValue);\n return () => {\n registry.current.delete(element);\n };\n }, []);\n const sortedItems = (): [HTMLElement, string][] =>\n [...registry.current].sort(([a], [b]) => compareDocumentOrder(a, b));\n /** Sorts by the Items' current document order. Reads the DOM: handlers and effects only. */\n const sortByDocument = (values: Iterable<string>): string[] =>\n sortByOrder(\n values,\n sortedItems().map(([, v]) => v),\n );\n\n const { optimistic, committed, pending, dispatch } = useControllableAction<\n ValueSet,\n ToggleGroupValueChangeDetails\n >({\n controlled: controlledSet,\n defaultValue: defaultSet,\n initialValue: EMPTY_SET,\n action:\n valueChangeAction &&\n ((next, details) =>\n valueChangeAction(mountExclusive ? ([...next][0] ?? null) : sortByDocument(next), details)),\n transitionTypes: (_next, _prev, details) => [\n ...transitionTypes(\"toggle-group\"),\n ...(details.added.length > 0 ? [\"fsui-toggle-group-press\"] : []),\n ...(details.removed.length > 0 ? [\"fsui-toggle-group-release\"] : []),\n ],\n reducer: (prev, _next, details) => applyPatch(prev, details),\n warn: { component: \"ToggleGroup.Root\", prop: \"value\" },\n });\n\n // Read by the stable `toggle`: a handler only runs against the committed UI.\n const latest = useLatest({ optimistic, exclusive: mountExclusive, deselectable });\n const toggle = useCallback(\n (itemValue: string, event: Event) => {\n const { optimistic, exclusive, deselectable } = latest.current;\n let patch: SetPatch;\n if (optimistic.has(itemValue)) {\n // Exclusive and not deselectable: pressing the pressed Item is a no-op (design 5.2).\n if (exclusive && !deselectable) return;\n patch = { added: [], removed: [itemValue] };\n } else {\n patch = { added: [itemValue], removed: exclusive ? [...optimistic] : [] };\n }\n dispatch(applyPatch(optimistic, patch), createActionDetails(event, patch));\n },\n [dispatch, latest],\n );\n\n // `state.value` is in document order; `focusgroupstart` also renders from which values have a\n // disabled Item.\n const { layout, renderedValue } = useItemOrder<ToggleGroupLayout>({\n optimistic,\n initial: NO_LAYOUT,\n read: () => {\n const items = sortedItems();\n return {\n order: items.map(([, v]) => v),\n disabled: items.filter(([el]) => el.matches(\":disabled\")).map(([, v]) => v),\n };\n },\n changed: (prev, next) =>\n flag && (!arraysEqual(next.order, prev.order) || !arraysEqual(next.disabled, prev.disabled)),\n duplicateMessage:\n isDev &&\n ((duplicate) =>\n `ToggleGroup.Item: two Items share the value \"${duplicate}\" in one ToggleGroup.Root. ` +\n \"Item values must be unique; both follow the same pressed state.\"),\n });\n\n const native = useNativeFocusgroup(flag);\n\n const focusgroupStartValue =\n flag && !disabled\n ? (renderedValue.find(\n (v) =>\n (layout.order.length === 0 || layout.order.includes(v)) && !layout.disabled.includes(v),\n ) ?? null)\n : null;\n\n const rootRef = useRef<HTMLElement | null>(null);\n const roving = useRovingFocus(rootRef, {\n enabled: !inToolbar,\n orientation,\n loop,\n native,\n entry: pressedFirst,\n memory: false,\n });\n\n const context = useMemo<ToggleGroupContextValue>(\n () => ({\n optimistic,\n committed,\n pending,\n disabled,\n orientation,\n focusgroupStartValue,\n toggle,\n registerItem,\n }),\n [\n optimistic,\n committed,\n pending,\n disabled,\n orientation,\n focusgroupStartValue,\n toggle,\n registerItem,\n ],\n );\n\n const state: ToggleGroupRootState = { value: renderedValue, pending, disabled, orientation };\n\n const focusgroup = flag\n ? `toolbar ${orientation === \"vertical\" ? \"block\" : \"inline\"} ${loop ? \"wrap\" : \"nowrap\"} nomemory`\n : undefined;\n\n const element = useRender<ComponentPropsWithRef<\"div\">, ToggleGroupRootState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n style,\n children,\n props: rest,\n libraryProps: {\n role: \"group\",\n \"data-orientation\": orientation,\n \"data-pending\": dataAttr(pending),\n \"data-disabled\": dataAttr(disabled),\n // Inside a Toolbar the group has no engine: the keys are not owned there.\n ...(!inToolbar && roving),\n ...(focusgroup !== undefined && { focusgroup }),\n },\n ref: rootRef,\n });\n\n return <ToggleGroupContext value={context}>{element}</ToggleGroupContext>;\n}\n\nToggleGroupRoot.displayName = \"ToggleGroupRoot\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwBA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AA0GvC,SAAS,aAAa,OAAwD;CAC5E,OAAO,MAAM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,OAAO;EAAU,UAAA;CAA4B,CAAA;AAC1E;AAEA,gBAAgB,cAAc"}
|
|
1
|
+
{"version":3,"file":"toggle-group-root.mjs","names":[],"sources":["../../src/toggle-group/toggle-group-root.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode } from \"react\";\nimport { createActionDetails } from \"../internal/action-details.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { compareDocumentOrder } from \"../internal/dom-order.js\";\nimport { useToolbarContext } from \"../internal/toolbar-context.js\";\nimport { transitionTypes } from \"../internal/transition-types.js\";\nimport type { ActionDetails, ChangeAction, RenderProp, StateValue } from \"../internal/types.js\";\nimport { useControllableAction } from \"../internal/use-controllable-action.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { useItemOrder } from \"../internal/use-item-order.js\";\nimport type { ItemLayout } from \"../internal/use-item-order.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useNativeFocusgroup } from \"../internal/use-native-focusgroup.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useRovingFocus } from \"../internal/use-roving-focus.js\";\nimport { useValueSet } from \"../internal/use-value-set.js\";\nimport { applyPatch, EMPTY_SET, arraysEqual, sortByOrder } from \"../internal/value-set.js\";\nimport type { SetPatch, ValueSet } from \"../internal/value-set.js\";\nimport { ToggleGroupContext } from \"./toggle-group-context.js\";\nimport type { ToggleGroupContextValue, ToggleGroupOrientation } from \"./toggle-group-context.js\";\n\nexport type { ToggleGroupOrientation } from \"./toggle-group-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** Details passed as the second argument of `valueChangeAction`, in both modes. */\nexport interface ToggleGroupValueChangeDetails extends ActionDetails {\n /** Values this dispatch pressed (document order of their Items). Exclusive mode: `[next]` or `[]`. */\n readonly added: readonly string[];\n /** Values this dispatch released. Exclusive mode: `[previous]` or `[]`. */\n readonly removed: readonly string[];\n}\n\nexport interface ToggleGroupRootState {\n /**\n * Optimistic pressed values in document order of the Items (exclusive mode: `[value]` or `[]`,\n * so one state shape serves both modes). The server render and the first client render use the\n * value's own order. Content rendered from it must not suspend.\n */\n readonly value: readonly string[];\n /** An action dispatched through this group is in flight. */\n readonly pending: boolean;\n readonly disabled: boolean;\n /** The effective orientation: the Toolbar's when inside one. */\n readonly orientation: ToggleGroupOrientation;\n}\n\ninterface ToggleGroupRootBaseProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n | \"role\"\n | \"onKeyDown\"\n | \"onFocus\"\n | \"onBlur\"\n | \"onPointerDown\"\n | \"defaultValue\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** Axis of the arrow keys and `data-orientation`. Default `\"horizontal\"`. Ignored inside a Toolbar (dev warning). */\n orientation?: ToggleGroupOrientation;\n /** Whether arrows wrap from the last Item to the first. Default `true`. Ignored inside a Toolbar (dev warning). */\n loop?: boolean;\n /** Disables every Item (native `disabled`). */\n disabled?: boolean;\n /**\n * Render `focusgroup=\"toolbar …\"` and, where the browser implements it, let the browser move\n * focus between the Items. Chromium 150+ only; elsewhere the JS path stays active. Ignored\n * inside a Toolbar (a nested focusgroup would split the Toolbar's sequence; dev warning).\n * Default `false`.\n */\n experimental_focusgroup?: boolean;\n className?: StateValue<string | undefined, ToggleGroupRootState>;\n style?: StateValue<CSSProperties | undefined, ToggleGroupRootState>;\n children?: StateValue<ReactNode, ToggleGroupRootState>;\n render?: RenderProp<ComponentPropsWithRef<\"div\">, ToggleGroupRootState>;\n}\n\nexport interface ToggleGroupMultipleProps extends ToggleGroupRootBaseProps {\n exclusive?: false;\n /** Controlled pressed values. `[]` presses nothing; `undefined` means uncontrolled. Order is not significant; duplicates ignored. */\n value?: string[];\n /** Initial pressed values in uncontrolled mode. Default `[]`. */\n defaultValue?: string[];\n /**\n * Runs inside the Root's transition whenever the set of pressed Items changes. Sync or async (a\n * Server Function may be passed directly); rejections reach the nearest Error Boundary and roll\n * the change back. `next` is the whole set as a fresh array in document order;\n * `details.added` / `details.removed` say what changed. A `setState` after your own `await` is\n * not a Transition update; wrap it in `startTransition`. Prefer a functional update keyed by\n * `added` / `removed` when controlled.\n */\n valueChangeAction?: ChangeAction<string[], ToggleGroupValueChangeDetails>;\n /** Exclusive mode only: a type error here (TypeScript's union excess-property check would let it through otherwise). */\n deselectable?: never;\n}\n\nexport interface ToggleGroupExclusiveProps extends ToggleGroupRootBaseProps {\n /** At most one Item is pressed; `value` is `string | null`. */\n exclusive: true;\n /** Controlled pressed value. `null` presses nothing; `undefined` means uncontrolled. */\n value?: string | null;\n /** Initial pressed value in uncontrolled mode. Default `null`. */\n defaultValue?: string | null;\n /**\n * Whether pressing the pressed Item releases it (`next === null`). Default `true`. With\n * `false` that press is a no-op and dispatches nothing; `value` stays `string | null` because\n * the group may start with nothing pressed, but the action is then never called with `null`.\n */\n deselectable?: boolean;\n /** See {@link ToggleGroupMultipleProps.valueChangeAction}; `next` is the pressed value or `null`. */\n valueChangeAction?: ChangeAction<string | null, ToggleGroupValueChangeDetails>;\n}\n\n/** Props of `ToggleGroup.Root`, discriminated on `exclusive`. */\nexport type ToggleGroupRootProps = ToggleGroupMultipleProps | ToggleGroupExclusiveProps;\n\ntype GroupValue = string[] | string | null;\n\n/** Both variants as one shape, for the implementation. */\ninterface InternalProps extends ToggleGroupRootBaseProps {\n exclusive?: boolean;\n value?: GroupValue;\n defaultValue?: GroupValue;\n deselectable?: boolean;\n valueChangeAction?: ChangeAction<GroupValue, ToggleGroupValueChangeDetails>;\n}\n\n/** Standalone entry (design 6.2): the first pressed item, else the first item (radio-like). */\nfunction pressedFirst(items: readonly HTMLElement[]): HTMLElement | undefined {\n return items.find((el) => el.getAttribute(\"aria-pressed\") === \"true\") ?? items[0];\n}\n\n/** The Items' document order and their disabled values, as of the Root's last commit. */\ninterface ToggleGroupLayout extends ItemLayout {\n readonly disabled: readonly string[];\n}\n\nconst NO_LAYOUT: ToggleGroupLayout = { order: [], disabled: [] };\n\n/**\n * `<div role=\"group\">` that owns the pressed set, the transition and, when standalone, the roving\n * focus over its Items (design/components/toggle-group.md 16.2). Inside a `Toolbar.Root` it runs\n * no engine of its own: its Items are members of the Toolbar's sequence.\n *\n * Owned keys (conventions 1.2): `role`, `data-orientation`, `data-pending`, `data-disabled`;\n * standalone also `onKeyDown`, `onFocus`, `onBlur`, `onPointerDown` and, with the flag,\n * `focusgroup`.\n */\nexport function ToggleGroupRoot(props: ToggleGroupRootProps) {\n const {\n exclusive = false,\n value,\n defaultValue,\n valueChangeAction,\n deselectable = true,\n orientation: orientationProp,\n loop: loopProp,\n disabled = false,\n experimental_focusgroup: focusgroupProp,\n className,\n style,\n children,\n render,\n ...rest\n } = props as InternalProps;\n\n const toolbar = useToolbarContext();\n const inToolbar = toolbar !== null;\n useDevWarning(\n inToolbar && orientationProp !== undefined,\n isDev &&\n \"ToggleGroup.Root: `orientation` is ignored inside a Toolbar.Root; the group follows the \" +\n \"Toolbar's orientation.\",\n );\n useDevWarning(\n inToolbar && loopProp !== undefined,\n isDev &&\n \"ToggleGroup.Root: `loop` is ignored inside a Toolbar.Root; the Toolbar's `loop` applies.\",\n );\n useDevWarning(\n inToolbar && focusgroupProp === true,\n isDev &&\n \"ToggleGroup.Root: `experimental_focusgroup` is ignored inside a Toolbar.Root. A nested \" +\n \"focusgroup would split the Toolbar's single Tab stop; set the flag on the Toolbar.Root.\",\n );\n const orientation: ToggleGroupOrientation =\n toolbar?.orientation ?? orientationProp ?? \"horizontal\";\n const loop = loopProp ?? true;\n const flag = !inToolbar && focusgroupProp === true;\n\n // The mode is fixed at mount (design 3.1).\n const [mountExclusive] = useState(exclusive);\n useDevWarning(\n mountExclusive !== exclusive,\n isDev &&\n \"ToggleGroup.Root: `exclusive` changed after mount. Switching between exclusive and \" +\n \"multiple mode is not supported; the group keeps the mode it mounted with.\",\n );\n\n const controlledSet = useValueSet(value);\n const defaultSet = useValueSet(defaultValue);\n\n // Item registration (design 16.2): element → value, written from the Items' callback refs.\n const registry = useRef(new Map<HTMLElement, string>());\n const registerItem = useCallback((element: HTMLElement, itemValue: string) => {\n registry.current.set(element, itemValue);\n return () => {\n registry.current.delete(element);\n };\n }, []);\n const sortedItems = (): [HTMLElement, string][] =>\n [...registry.current].sort(([a], [b]) => compareDocumentOrder(a, b));\n /** Sorts by the Items' current document order. Reads the DOM: handlers and effects only. */\n const sortByDocument = (values: Iterable<string>): string[] =>\n sortByOrder(\n values,\n sortedItems().map(([, v]) => v),\n );\n\n const { optimistic, committed, pending, dispatch } = useControllableAction<\n ValueSet,\n ToggleGroupValueChangeDetails\n >({\n controlled: controlledSet,\n defaultValue: defaultSet,\n initialValue: EMPTY_SET,\n action:\n valueChangeAction &&\n ((next, details) =>\n valueChangeAction(mountExclusive ? ([...next][0] ?? null) : sortByDocument(next), details)),\n transitionTypes: (_next, _prev, details) => [\n ...transitionTypes(\"toggle-group\"),\n ...(details.added.length > 0 ? [\"fsui-toggle-group-press\"] : []),\n ...(details.removed.length > 0 ? [\"fsui-toggle-group-release\"] : []),\n ],\n reducer: (prev, _next, details) => applyPatch(prev, details),\n warn: { component: \"ToggleGroup.Root\", prop: \"value\" },\n });\n\n // Read by the stable `toggle`: a handler only runs against the committed UI.\n const latest = useLatest({ optimistic, exclusive: mountExclusive, deselectable });\n const toggle = useCallback(\n (itemValue: string, event: Event) => {\n const { optimistic, exclusive, deselectable } = latest.current;\n let patch: SetPatch;\n if (optimistic.has(itemValue)) {\n // Exclusive and not deselectable: pressing the pressed Item is a no-op (design 5.2).\n if (exclusive && !deselectable) return;\n patch = { added: [], removed: [itemValue] };\n } else {\n patch = { added: [itemValue], removed: exclusive ? [...optimistic] : [] };\n }\n dispatch(applyPatch(optimistic, patch), createActionDetails(event, patch));\n },\n [dispatch, latest],\n );\n\n // `state.value` is in document order; `focusgroupstart` also renders from which values have a\n // disabled Item.\n const { layout, renderedValue } = useItemOrder<ToggleGroupLayout>({\n optimistic,\n initial: NO_LAYOUT,\n read: () => {\n const items = sortedItems();\n return {\n order: items.map(([, v]) => v),\n disabled: items.filter(([el]) => el.matches(\":disabled\")).map(([, v]) => v),\n };\n },\n changed: (prev, next) =>\n flag && (!arraysEqual(next.order, prev.order) || !arraysEqual(next.disabled, prev.disabled)),\n duplicateMessage:\n isDev &&\n ((duplicate) =>\n `ToggleGroup.Item: two Items share the value \"${duplicate}\" in one ToggleGroup.Root. ` +\n \"Item values must be unique; both follow the same pressed state.\"),\n });\n\n const native = useNativeFocusgroup(flag);\n\n const focusgroupStartValue =\n flag && !disabled\n ? (renderedValue.find(\n (v) =>\n (layout.order.length === 0 || layout.order.includes(v)) && !layout.disabled.includes(v),\n ) ?? null)\n : null;\n\n const rootRef = useRef<HTMLElement | null>(null);\n const roving = useRovingFocus(rootRef, {\n enabled: !inToolbar,\n orientation,\n loop,\n native,\n entry: pressedFirst,\n memory: false,\n });\n\n const context = useMemo<ToggleGroupContextValue>(\n () => ({\n optimistic,\n committed,\n pending,\n disabled,\n orientation,\n focusgroupStartValue,\n toggle,\n registerItem,\n }),\n [\n optimistic,\n committed,\n pending,\n disabled,\n orientation,\n focusgroupStartValue,\n toggle,\n registerItem,\n ],\n );\n\n const state: ToggleGroupRootState = { value: renderedValue, pending, disabled, orientation };\n\n const focusgroup = flag\n ? `toolbar ${orientation === \"vertical\" ? \"block\" : \"inline\"} ${loop ? \"wrap\" : \"nowrap\"} nomemory`\n : undefined;\n\n const element = useRender<ComponentPropsWithRef<\"div\">, ToggleGroupRootState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n style,\n children,\n props: rest,\n libraryProps: {\n role: \"group\",\n \"data-orientation\": orientation,\n \"data-pending\": dataAttr(pending),\n \"data-disabled\": dataAttr(disabled),\n // Inside a Toolbar the group has no engine: the keys are not owned there.\n ...(!inToolbar && roving),\n ...(focusgroup !== undefined && { focusgroup }),\n },\n ref: rootRef,\n });\n\n return <ToggleGroupContext value={context}>{element}</ToggleGroupContext>;\n}\n\nToggleGroupRoot.displayName = \"ToggleGroupR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AG,OAAO,CAAC;GAC5E;EACF;EACA,UAAU,MAAM,SACd,SAAS,CAAC,YAAY,KAAK,OAAO,KAAK,KAAK,KAAK,CAAC,YAAY,KAAK,UAAU,KAAK,QAAQ;EAC5F,kBACE,WACE,cACA,gDAAgD,UAAU;CAEhE,CAAC;CAED,MAAM,SAAS,oBAAoB,IAAI;CAEvC,MAAM,uBACJ,QAAQ,CAAC,WACJ,cAAc,MACZ,OACE,OAAO,MAAM,WAAW,KAAK,OAAO,MAAM,SAAS,CAAC,MAAM,CAAC,OAAO,SAAS,SAAS,CAAC,CAC1F,KAAK,OACL;CAEN,MAAM,UAAU,OAA2B,IAAI;CAC/C,MAAM,SAAS,eAAe,SAAS;EACrC,SAAS,CAAC;EACV;EACA;EACA;EACA,OAAO;EACP,QAAQ;CACV,CAAC;CAED,MAAM,UAAU,eACP;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,MAAM,QAA8B;EAAE,OAAO;EAAe;EAAS;EAAU;CAAY;CAE3F,MAAM,aAAa,OACf,WAAW,gBAAgB,aAAa,UAAU,SAAS,GAAG,OAAO,SAAS,SAAS,aACvF,KAAA;CAEJ,MAAM,UAAU,UAA8D;EAC5E,gBAAgB;EAChB;EACA;EACA;EACA;EACA;EACA,OAAO;EACP,cAAc;GACZ,MAAM;GACN,oBAAoB;GACpB,gBAAgB,SAAS,OAAO;GAChC,iBAAiB,SAAS,QAAQ;GAElC,GAAI,CAAC,aAAa;GAClB,GAAI,eAAe,KAAA,KAAa,EAAE,WAAW;EAC/C;EACA,KAAK;CACP,CAAC;CAED,OAAO,oBAAC,oBAAD;EAAoB,OAAO;EAAU,UAAA;CAA4B,CAAA;AAC1E;AAEA,gBAAgB,cAAc"}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"invoker-press.mjs","names":[],"sources":["../../src/internal/invoker-press.ts"],"sourcesContent":["// No directive: DOM listeners only (conventions 7.1).\n\n/** An invoker button's IDL; absent where the engine lacks the Popover API or Invoker Commands. */\ninterface InvokerButton {\n readonly popoverTargetElement?: Element | null;\n readonly commandForElement?: Element | null;\n readonly command?: string;\n}\n\n/** The `<input>` types HTML counts as buttons: the ones `popovertarget` applies to. */\nconst INPUT_BUTTON_TYPES = new Set([\"submit\", \"image\", \"reset\", \"button\"]);\n\n/**\n * Whether a press on `target` is a press on a foreign invoker of `popup`: its closest button (a\n * `<button>`, or an `<input>` of a button type) is outside the popup and names it through\n * `popovertarget`, or (a `<button>`) through `commandfor` with a popover command\n * (`toggle-popover`, `show-popover`, `hide-popover`). HTML's invoker relationship, the one light\n * dismiss exempts (conventions 3.5, #126): a disabled button and a submit button with a form owner\n * invoke nothing. Read through the IDL, so an engine without it has no such invoker.\n */\nexport function isPopoverInvoker(target: EventTarget | null, popup: Element): boolean {\n if (!(target instanceof Element)) return false;\n const button = target.closest<HTMLButtonElement | HTMLInputElement>(\"button, input\");\n if (button === null || popup.contains(button)) return false;\n const isInput = button.tagName === \"INPUT\";\n if (isInput && !INPUT_BUTTON_TYPES.has(button.type)) return false;\n if (button.disabled) return false;\n if (button.form !== null && (button.type === \"submit\" || button.type === \"image\")) return false;\n const invoker = button as InvokerButton;\n if (invoker.popoverTargetElement === popup) return true;\n return !isInput && invoker.commandForElement === popup && /-popover$/.test(invoker.command ?? \"\");\n}\n\n/**\n * While a popup that closes on focus leaving is shown: a primary-button `mousedown` on a foreign\n * invoker of it moves no focus (conventions 3.5, #126). Chromium and Firefox focus a button on\n * press, which would close the popup at the `focusout` before the click's own toggle (as\n * `\"dismiss\"`, and the toggle then re-showed it). Returns the cleanup.\n */\nexport function listenInvokerPresses(popup: HTMLElement): () => void {\n const doc = popup.ownerDocument;\n const onMouseDown = (event: MouseEvent) => {\n if (event.button === 0 && isPopoverInvoker(event.target, popup)) event.preventDefault();\n };\n doc.addEventListener(\"mousedown\", onMouseDown, true);\n return () => doc.removeEventListener(\"mousedown\", onMouseDown, true);\n}\n"],"mappings":";;AAUA,MAAM,qCAAqB,IAAI,IAAI;CAAC;CAAU;CAAS;CAAS;AAAQ,CAAC;;;;;;;;;AAUzE,SAAgB,iBAAiB,QAA4B,OAAyB;CACpF,IAAI,EAAE,kBAAkB,UAAU,OAAO;CACzC,MAAM,SAAS,OAAO,QAA8C,eAAe;CACnF,IAAI,WAAW,QAAQ,MAAM,SAAS,MAAM,GAAG,OAAO;CACtD,MAAM,UAAU,OAAO,YAAY;CACnC,IAAI,WAAW,CAAC,mBAAmB,IAAI,OAAO,IAAI,GAAG,OAAO;CAC5D,IAAI,OAAO,UAAU,OAAO;CAC5B,IAAI,OAAO,SAAS,SAAS,OAAO,SAAS,YAAY,OAAO,SAAS,UAAU,OAAO;CAC1F,MAAM,UAAU;CAChB,IAAI,QAAQ,yBAAyB,OAAO,OAAO;CACnD,OAAO,CAAC,WAAW,QAAQ,sBAAsB,SAAS,YAAY,KAAK,QAAQ,WAAW,EAAE;AAClG;;;;;;;AAQA,SAAgB,qBAAqB,OAAgC;CACnE,MAAM,MAAM,MAAM;CAClB,MAAM,eAAe,UAAsB;EACzC,IAAI,MAAM,WAAW,KAAK,iBAAiB,MAAM,QAAQ,KAAK,GAAG,MAAM,eAAe;CACxF;CACA,IAAI,iBAAiB,aAAa,aAAa,IAAI;CACnD,aAAa,IAAI,oBAAoB,aAAa,aAAa,IAAI;AACrE"}
|