@ds-mo/ui 12.4.0 → 12.4.1

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.
@@ -72,6 +72,7 @@
72
72
  ],
73
73
  "responsiveBehavior": [
74
74
  "The global stack stays at the viewport bottom-end with token-based inset and never exceeds the available viewport width.",
75
+ "Set avoid-mobile-shell-bar when the application uses the persistent shell bottom bar. Below 768px the global stack clears the complete safe-area-aware bar container by 16px; tablet and desktop positioning remain unchanged.",
75
76
  "Anchored toasts flip on their placement axis and clamp to viewport padding when the preferred side does not fit.",
76
77
  "The owner does not create separate mobile and desktop managers; one queue preserves ordering across responsive layouts.",
77
78
  "Pointer swipe remains optional input. Close and action controls retain keyboard access through the notification region."
@@ -107,6 +108,15 @@
107
108
  },
108
109
  "api": {
109
110
  "props": {
111
+ "avoidMobileShellBar": {
112
+ "type": "boolean",
113
+ "resolvedType": "boolean",
114
+ "attribute": "avoid-mobile-shell-bar",
115
+ "default": "false",
116
+ "required": false,
117
+ "mutable": false,
118
+ "description": "Keep the global stack 16px above the persistent mobile shell bar below 768px."
119
+ },
110
120
  "closeLabel": {
111
121
  "type": "string",
112
122
  "resolvedType": "string",
@@ -187,6 +197,15 @@
187
197
  "slots": []
188
198
  },
189
199
  "props": {
200
+ "avoidMobileShellBar": {
201
+ "type": "boolean",
202
+ "resolvedType": "boolean",
203
+ "attribute": "avoid-mobile-shell-bar",
204
+ "default": "false",
205
+ "required": false,
206
+ "mutable": false,
207
+ "description": "Keep the global stack 16px above the persistent mobile shell bar below 768px."
208
+ },
190
209
  "closeLabel": {
191
210
  "type": "string",
192
211
  "resolvedType": "string",
@@ -306,12 +325,12 @@
306
325
  "files": [
307
326
  {
308
327
  "path": "src/wc/components/Toast/Toast.css",
309
- "content": ":host {\n display: contents;\n}\n\n.toast-region {\n position: fixed;\n inset: 0;\n z-index: var(--dimension-z-index-floating);\n pointer-events: none;\n outline: none;\n}\n\n.toast-viewport {\n position: absolute;\n right: var(--dimension-space-200);\n bottom: var(--dimension-space-200);\n display: grid;\n width: min(\n var(--dimension-card-width-sm),\n calc(100vw - 2 * var(--dimension-space-200))\n );\n}\n\n.toast-positioner {\n grid-area: 1 / 1;\n align-self: end;\n justify-self: center;\n width: 100%;\n pointer-events: auto;\n transform: translateY(\n calc(-1 * var(--toast-index) * var(--dimension-space-100))\n );\n transition:\n transform var(--effect-motion-short-3),\n width var(--effect-motion-short-3);\n}\n\n.toast-viewport:not([data-expanded]) .toast-positioner {\n width: calc(\n 100% - 2 * var(--toast-index) * var(--dimension-space-100)\n );\n}\n\n.toast-viewport[data-expanded] .toast-positioner {\n transform: translateY(calc(-1 * var(--toast-offset-y)));\n}\n\n.toast-positioner[data-limited] {\n visibility: hidden;\n pointer-events: none;\n}\n\n.toast-positioner--anchored {\n position: fixed;\n width: min(\n var(--dimension-card-width-sm),\n calc(100vw - 2 * var(--dimension-space-200))\n );\n transform: none;\n}\n\n.toast-positioner--anchored[data-positioned='false'] {\n visibility: hidden;\n}\n\n.toast-surface {\n position: relative;\n display: block;\n box-sizing: border-box;\n width: 100%;\n height: var(--toast-height, auto);\n padding: var(--dimension-space-200);\n overflow: hidden;\n color: var(--color-foreground-primary);\n background-color: var(--color-background-primary);\n border-radius: var(--dimension-radius-050);\n box-shadow: var(--effect-elevation-elevated-floating);\n transform: translate(\n var(--toast-swipe-movement-x),\n var(--toast-swipe-movement-y)\n );\n animation: toast-enter var(--effect-motion-short-2) both;\n}\n\n.toast-positioner--ending .toast-surface {\n animation: toast-exit var(--effect-motion-short-3) both;\n}\n\n.toast-surface--swiping {\n transition: none;\n user-select: none;\n}\n\n.toast-content {\n display: flex;\n flex-direction: column;\n min-width: 0;\n padding-inline-end: var(--dimension-size-500);\n transition: opacity var(--effect-motion-short-3);\n}\n\n.toast-copy {\n display: flex;\n flex-direction: column;\n min-width: 0;\n min-height: var(--typography-lineheight-md);\n margin-block: calc(-1 * var(--dimension-space-025));\n gap: var(--dimension-space-050);\n}\n\n.toast-title,\n.toast-description {\n min-width: 0;\n}\n\n.toast-action {\n align-self: start;\n margin-top: calc(\n var(--dimension-space-200) + var(--dimension-space-025)\n );\n}\n\n.toast-close {\n position: absolute;\n top: var(--dimension-space-100);\n right: var(--dimension-space-100);\n transition: opacity var(--effect-motion-short-3);\n}\n\n.toast-viewport:not([data-expanded]) .toast-positioner[data-behind] .toast-content,\n.toast-viewport:not([data-expanded]) .toast-positioner[data-behind] .toast-close {\n opacity: 0;\n}\n\n.toast-assertive-announcer {\n position: absolute;\n width: var(--dimension-size-100);\n height: var(--dimension-size-100);\n padding: 0;\n overflow: hidden;\n white-space: nowrap;\n clip-path: inset(50%);\n}\n\n@keyframes toast-enter {\n from {\n opacity: 0;\n transform: translateY(var(--dimension-space-100));\n }\n\n to {\n opacity: 1;\n transform: translateY(0);\n }\n}\n\n@keyframes toast-exit {\n from {\n opacity: 1;\n }\n\n to {\n opacity: 0;\n }\n}\n\n@media (prefers-reduced-motion: reduce) {\n .toast-positioner,\n .toast-surface,\n .toast-content,\n .toast-close,\n .toast-positioner--ending .toast-surface {\n transition: none;\n animation: none;\n }\n\n .toast-positioner--ending .toast-surface {\n opacity: 0;\n }\n}\n",
328
+ "content": ":host {\n display: contents;\n}\n\n.toast-region {\n position: fixed;\n inset: 0;\n z-index: var(--dimension-z-index-floating);\n pointer-events: none;\n outline: none;\n}\n\n.toast-viewport {\n position: absolute;\n right: var(--dimension-space-200);\n bottom: var(--dimension-space-200);\n display: grid;\n width: min(\n var(--dimension-card-width-sm),\n calc(100vw - 2 * var(--dimension-space-200))\n );\n}\n\n@media (max-width: 767px) {\n :host([avoid-mobile-shell-bar]) .toast-viewport {\n bottom: calc(\n var(--dimension-space-200) +\n var(--dimension-stroke-width-012) +\n var(--dimension-space-050) +\n var(--dimension-size-600) +\n max(var(--dimension-space-050), env(safe-area-inset-bottom))\n );\n }\n}\n\n.toast-positioner {\n grid-area: 1 / 1;\n align-self: end;\n justify-self: center;\n width: 100%;\n pointer-events: auto;\n transform: translateY(\n calc(-1 * var(--toast-index) * var(--dimension-space-100))\n );\n transition:\n transform var(--effect-motion-short-3),\n width var(--effect-motion-short-3);\n}\n\n.toast-viewport:not([data-expanded]) .toast-positioner {\n width: calc(\n 100% - 2 * var(--toast-index) * var(--dimension-space-100)\n );\n}\n\n.toast-viewport[data-expanded] .toast-positioner {\n transform: translateY(calc(-1 * var(--toast-offset-y)));\n}\n\n.toast-positioner[data-limited] {\n visibility: hidden;\n pointer-events: none;\n}\n\n.toast-positioner--anchored {\n position: fixed;\n width: min(\n var(--dimension-card-width-sm),\n calc(100vw - 2 * var(--dimension-space-200))\n );\n transform: none;\n}\n\n.toast-positioner--anchored[data-positioned='false'] {\n visibility: hidden;\n}\n\n.toast-surface {\n position: relative;\n display: block;\n box-sizing: border-box;\n width: 100%;\n height: var(--toast-height, auto);\n padding: var(--dimension-space-200);\n overflow: hidden;\n color: var(--color-foreground-primary);\n background-color: var(--color-background-primary);\n border-radius: var(--dimension-radius-050);\n box-shadow: var(--effect-elevation-elevated-floating);\n transform: translate(\n var(--toast-swipe-movement-x),\n var(--toast-swipe-movement-y)\n );\n animation: toast-enter var(--effect-motion-short-2) both;\n}\n\n.toast-positioner--ending .toast-surface {\n animation: toast-exit var(--effect-motion-short-3) both;\n}\n\n.toast-surface--swiping {\n transition: none;\n user-select: none;\n}\n\n.toast-content {\n display: flex;\n flex-direction: column;\n min-width: 0;\n padding-inline-end: var(--dimension-size-500);\n transition: opacity var(--effect-motion-short-3);\n}\n\n.toast-copy {\n display: flex;\n flex-direction: column;\n min-width: 0;\n min-height: var(--typography-lineheight-md);\n margin-block: calc(-1 * var(--dimension-space-025));\n gap: var(--dimension-space-050);\n}\n\n.toast-title,\n.toast-description {\n min-width: 0;\n}\n\n.toast-action {\n align-self: start;\n margin-top: calc(\n var(--dimension-space-200) + var(--dimension-space-025)\n );\n}\n\n.toast-close {\n position: absolute;\n top: var(--dimension-space-100);\n right: var(--dimension-space-100);\n transition: opacity var(--effect-motion-short-3);\n}\n\n.toast-viewport:not([data-expanded]) .toast-positioner[data-behind] .toast-content,\n.toast-viewport:not([data-expanded]) .toast-positioner[data-behind] .toast-close {\n opacity: 0;\n}\n\n.toast-assertive-announcer {\n position: absolute;\n width: var(--dimension-size-100);\n height: var(--dimension-size-100);\n padding: 0;\n overflow: hidden;\n white-space: nowrap;\n clip-path: inset(50%);\n}\n\n@keyframes toast-enter {\n from {\n opacity: 0;\n transform: translateY(var(--dimension-space-100));\n }\n\n to {\n opacity: 1;\n transform: translateY(0);\n }\n}\n\n@keyframes toast-exit {\n from {\n opacity: 1;\n }\n\n to {\n opacity: 0;\n }\n}\n\n@media (prefers-reduced-motion: reduce) {\n .toast-positioner,\n .toast-surface,\n .toast-content,\n .toast-close,\n .toast-positioner--ending .toast-surface {\n transition: none;\n animation: none;\n }\n\n .toast-positioner--ending .toast-surface {\n opacity: 0;\n }\n}\n",
310
329
  "type": "registry:ui"
311
330
  },
312
331
  {
313
332
  "path": "src/wc/components/Toast/Toast.tsx",
314
- "content": "import {\n Component,\n Element,\n Event,\n EventEmitter,\n h,\n Host,\n Prop,\n State,\n Watch,\n} from '@stencil/core';\nimport {\n resolveCssLengthPx,\n resolveCssTimeMs,\n resolveMotionTimeMs,\n TOKEN_DEFAULTS,\n} from '../../utils';\nimport {\n toastManager as defaultToastManager,\n type ToastActionEventDetail,\n type ToastCloseContext,\n type ToastCloseEventDetail,\n type ToastEventDetail,\n type ToastManager,\n type ToastRecord,\n type ToastSwipeDirection,\n} from '../../toast';\nimport { computeTooltipPosition } from '../Tooltip/tooltip-position';\n\ninterface ToastTimer {\n timerKey: number;\n remaining: number;\n startedAt: number;\n handle: ReturnType<typeof setTimeout> | null;\n}\n\ninterface SwipeState {\n id: string;\n x: number;\n y: number;\n direction?: ToastSwipeDirection;\n}\n\ninterface AnchoredPosition {\n x: number;\n y: number;\n side: 'top' | 'right' | 'bottom' | 'left';\n}\n\ninterface ActiveSwipe {\n id: string;\n pointerId: number;\n pointerType: string;\n startX: number;\n startY: number;\n maxDistance: number;\n cancelled: boolean;\n axis: 'x' | 'y' | null;\n}\n\nconst SWIPE_THRESHOLD = 40;\nconst SWIPE_REVERSE_CANCEL_THRESHOLD = 10;\nconst GLOBAL_STACK_HOVER = '__global-stack__';\nconst INTERACTIVE_SWIPE_SELECTOR =\n 'button,a,input,textarea,select,[role=\"button\"],[data-ds-toast-swipe-ignore]';\n\nconst attachedManagers = new WeakMap<ToastManager, Toast>();\nconst connectedToastRegions = new Set<Toast>();\nlet activeToastRegion: Toast | null = null;\nlet toastInstanceCounter = 0;\n\n@Component({\n tag: 'ds-toast',\n styleUrl: 'Toast.css',\n scoped: true,\n})\nexport class Toast {\n @Element() el!: HTMLElement;\n\n /** Manager that supplies toast records. Assign as a JavaScript property. */\n @Prop() manager: ToastManager = defaultToastManager;\n /** Maximum visible global-stack records. Limited records remain mounted and inert. */\n @Prop() limit: number = 3;\n /** Default auto-dismiss delay. Use 0 for persistent records. */\n @Prop() timeout: number | string = TOKEN_DEFAULTS.animationDelayLong2;\n /** Accessible label for the notification region. */\n @Prop() label: string = 'Notifications';\n /** Localized accessible label for every toast close action. */\n @Prop() closeLabel: string = 'Close notification';\n /** Allowed swipe-to-dismiss directions. Assign as a JavaScript property. */\n @Prop() swipeDirections: ToastSwipeDirection[] = ['down', 'right'];\n\n @State() private records: readonly ToastRecord[] = [];\n @State() private expanded = false;\n @State() private keyboardActive = false;\n @State() private swipe: SwipeState | null = null;\n @State() private layoutVersion = 0;\n\n @Event() dsToastClose!: EventEmitter<ToastCloseEventDetail>;\n @Event() dsToastRemove!: EventEmitter<ToastEventDetail>;\n @Event() dsToastAction!: EventEmitter<ToastActionEventDetail>;\n\n private readonly instanceId = ++toastInstanceCounter;\n private readonly domIds = new Map<string, number>();\n private readonly timers = new Map<string, ToastTimer>();\n private readonly closeWatchdogs = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly closeFrames = new Map<string, number>();\n private readonly closeEvents = new Set<string>();\n private readonly activationFrames = new Map<string, number>();\n private readonly pauseReasons = new Set<string>();\n private readonly hoveredIds = new Set<string>();\n private readonly heights = new Map<string, number>();\n private readonly measuredUpdateKeys = new Map<string, number>();\n private readonly anchoredPositions = new Map<string, AnchoredPosition>();\n private readonly dismissedSwipeDirections = new Map<string, ToastSwipeDirection>();\n private readonly observedElements = new Set<Element>();\n private readonly pendingRemovals: Array<{\n manager: ToastManager;\n context: ToastCloseContext;\n }> = [];\n\n private unsubscribe: (() => void) | null = null;\n private attachedManager: ToastManager | null = null;\n private previousFocus: HTMLElement | null = null;\n private resizeObserver: ResizeObserver | null = null;\n private mutationObserver: MutationObserver | null = null;\n private layoutFrame: number | null = null;\n private activeSwipe: ActiveSwipe | null = null;\n private nextDomId = 0;\n private connected = false;\n private pendingHoverLeave = false;\n\n connectedCallback() {\n this.connect();\n }\n\n componentDidLoad() {\n this.connect();\n }\n\n private connect() {\n if (this.connected) return;\n this.connected = true;\n this.resizeObserver ??= new ResizeObserver(() => this.scheduleLayout());\n this.mutationObserver ??= new MutationObserver(() => this.scheduleLayout());\n this.mutationObserver.observe(document.body, { childList: true, subtree: true });\n if (!this.unsubscribe) this.attachManager(this.manager);\n window.addEventListener('blur', this.handleWindowBlur);\n window.addEventListener('focus', this.handleWindowFocus);\n window.addEventListener('resize', this.handleWindowResize);\n window.addEventListener('scroll', this.scheduleLayout, true);\n document.addEventListener('keydown', this.handleDocumentKeyDown);\n document.addEventListener('visibilitychange', this.handleVisibilityChange);\n connectedToastRegions.add(this);\n // eslint-disable-next-line @typescript-eslint/no-this-alias -- module coordinator tracks the active connected viewport\n if (!activeToastRegion) activeToastRegion = this;\n }\n\n componentDidRender() {\n this.syncObservedElements();\n this.flushPendingRemovals();\n this.scheduleLayout();\n }\n\n disconnectedCallback() {\n this.connected = false;\n this.flushPendingRemovals();\n this.detachManager();\n this.resetManagerState();\n this.resizeObserver?.disconnect();\n this.resizeObserver = null;\n this.mutationObserver?.disconnect();\n this.mutationObserver = null;\n this.observedElements.clear();\n if (this.layoutFrame !== null) cancelAnimationFrame(this.layoutFrame);\n this.layoutFrame = null;\n window.removeEventListener('blur', this.handleWindowBlur);\n window.removeEventListener('focus', this.handleWindowFocus);\n window.removeEventListener('resize', this.handleWindowResize);\n window.removeEventListener('scroll', this.scheduleLayout, true);\n document.removeEventListener('keydown', this.handleDocumentKeyDown);\n document.removeEventListener('visibilitychange', this.handleVisibilityChange);\n connectedToastRegions.delete(this);\n if (activeToastRegion === this) {\n const remaining = Array.from(connectedToastRegions);\n activeToastRegion = remaining[remaining.length - 1] ?? null;\n }\n }\n\n @Watch('manager')\n onManagerChange(next: ToastManager) {\n this.detachManager();\n this.resetManagerState();\n if (this.connected) this.attachManager(next);\n }\n\n @Watch('timeout')\n onTimeoutChange() {\n for (const timer of this.timers.values()) {\n if (timer.handle) clearTimeout(timer.handle);\n }\n this.timers.clear();\n this.syncTimers();\n }\n\n private attachManager(manager: ToastManager) {\n const attached = attachedManagers.get(manager);\n if (attached && attached !== this) {\n console.warn('[ds-toast] A manager can control only one connected ds-toast instance.');\n return;\n }\n attachedManagers.set(manager, this);\n this.attachedManager = manager;\n this.unsubscribe = manager.subscribe(records => {\n this.records = records;\n this.syncLifecycle(records);\n this.scheduleLayout();\n });\n }\n\n private detachManager() {\n this.unsubscribe?.();\n this.unsubscribe = null;\n if (this.attachedManager && attachedManagers.get(this.attachedManager) === this) {\n attachedManagers.delete(this.attachedManager);\n }\n this.attachedManager = null;\n }\n\n private resetManagerState() {\n this.flushPendingRemovals();\n if (this.el.contains(document.activeElement)) this.restorePreviousFocus();\n this.clearAllTimers();\n for (const frame of this.activationFrames.values()) cancelAnimationFrame(frame);\n for (const frame of this.closeFrames.values()) cancelAnimationFrame(frame);\n this.activationFrames.clear();\n this.closeFrames.clear();\n this.closeEvents.clear();\n this.pauseReasons.clear();\n this.hoveredIds.clear();\n this.pendingHoverLeave = false;\n this.heights.clear();\n this.measuredUpdateKeys.clear();\n this.anchoredPositions.clear();\n this.dismissedSwipeDirections.clear();\n this.domIds.clear();\n this.activeSwipe = null;\n this.swipe = null;\n this.expanded = false;\n this.keyboardActive = false;\n this.records = [];\n this.resizeObserver?.disconnect();\n this.observedElements.clear();\n }\n\n private syncObservedElements() {\n const next = new Set<Element>(\n this.el.querySelectorAll<HTMLElement>('.toast-positioner'),\n );\n for (const record of this.records) {\n if (!record.positioner) continue;\n const anchor = this.resolveAnchor(record.positioner.anchor);\n if (anchor) next.add(anchor);\n }\n\n for (const element of this.observedElements) {\n if (!next.has(element)) {\n this.resizeObserver?.unobserve(element);\n this.observedElements.delete(element);\n }\n }\n for (const element of next) {\n if (this.observedElements.has(element)) continue;\n this.resizeObserver?.observe(element);\n this.observedElements.add(element);\n }\n }\n\n private flushPendingRemovals() {\n for (const pending of this.pendingRemovals.splice(0)) {\n pending.manager.notifyRemove(pending.context);\n this.dsToastRemove.emit({\n id: pending.context.id,\n toast: pending.context.toast,\n });\n }\n }\n\n private syncLifecycle(records: readonly ToastRecord[]) {\n const recordIds = new Set(records.map(record => record.id));\n for (const id of this.hoveredIds) {\n if (id !== GLOBAL_STACK_HOVER && !recordIds.has(id)) this.hoveredIds.delete(id);\n }\n const hasEndingRecords = records.some(\n record => record.transitionStatus === 'ending',\n );\n if (this.pendingHoverLeave && !hasEndingRecords && !this.hoveredIds.size) {\n this.pendingHoverLeave = false;\n this.expanded = false;\n this.resumeTimers('hover');\n } else if (!this.hoveredIds.size && !this.pendingHoverLeave) {\n this.resumeTimers('hover');\n }\n\n for (const [id, timer] of this.timers) {\n if (recordIds.has(id)) continue;\n if (timer.handle) clearTimeout(timer.handle);\n this.timers.delete(id);\n }\n\n for (const [id, watchdog] of this.closeWatchdogs) {\n if (recordIds.has(id)) continue;\n clearTimeout(watchdog);\n this.closeWatchdogs.delete(id);\n }\n\n for (const [id, frame] of this.activationFrames) {\n if (recordIds.has(id)) continue;\n cancelAnimationFrame(frame);\n this.activationFrames.delete(id);\n }\n\n for (const [id, frame] of this.closeFrames) {\n if (recordIds.has(id)) continue;\n cancelAnimationFrame(frame);\n this.closeFrames.delete(id);\n }\n\n for (const id of this.domIds.keys()) {\n if (recordIds.has(id)) continue;\n this.closeEvents.delete(id);\n this.domIds.delete(id);\n this.heights.delete(id);\n this.measuredUpdateKeys.delete(id);\n this.anchoredPositions.delete(id);\n this.dismissedSwipeDirections.delete(id);\n }\n\n for (const record of records) {\n this.ensureDomId(record.id);\n if (\n record.transitionStatus === 'starting' &&\n !this.activationFrames.has(record.id)\n ) {\n const manager = this.attachedManager;\n const frame = requestAnimationFrame(() => {\n this.activationFrames.delete(record.id);\n manager?.activate(record.id);\n });\n this.activationFrames.set(record.id, frame);\n }\n\n if (record.transitionStatus === 'ending') {\n this.clearToastTimer(record.id);\n this.beginRemoval(record);\n } else {\n const watchdog = this.closeWatchdogs.get(record.id);\n if (watchdog) clearTimeout(watchdog);\n this.closeWatchdogs.delete(record.id);\n const closeFrame = this.closeFrames.get(record.id);\n if (closeFrame) cancelAnimationFrame(closeFrame);\n this.closeFrames.delete(record.id);\n this.closeEvents.delete(record.id);\n }\n }\n\n this.syncTimers();\n }\n\n private syncTimers() {\n const activeIds = new Set<string>();\n for (const record of this.records) {\n if (record.transitionStatus !== 'active') continue;\n activeIds.add(record.id);\n const duration = this.resolveToastTimeout(record);\n if (duration <= 0) {\n this.clearToastTimer(record.id);\n continue;\n }\n\n const existing = this.timers.get(record.id);\n if (!existing || existing.timerKey !== record.timerKey) {\n this.clearToastTimer(record.id);\n this.timers.set(record.id, {\n timerKey: record.timerKey,\n remaining: duration,\n startedAt: 0,\n handle: null,\n });\n }\n if (!this.isPaused) this.startToastTimer(record.id);\n }\n\n for (const id of this.timers.keys()) {\n if (!activeIds.has(id)) this.clearToastTimer(id);\n }\n }\n\n private resolveToastTimeout(record: ToastRecord): number {\n const value = record.timeout ?? this.timeout;\n if (typeof value === 'number') return Math.max(0, value);\n return resolveCssTimeMs(value, TOKEN_DEFAULTS.animationDelayLong2);\n }\n\n private startToastTimer(id: string) {\n const timer = this.timers.get(id);\n if (!timer || timer.handle || timer.remaining <= 0) return;\n timer.startedAt = Date.now();\n timer.handle = setTimeout(() => {\n timer.handle = null;\n timer.remaining = 0;\n this.manager.close(id, 'timeout');\n }, timer.remaining);\n }\n\n private pauseTimers(reason: string) {\n const wasPaused = this.isPaused;\n this.pauseReasons.add(reason);\n if (wasPaused) return;\n const now = Date.now();\n for (const timer of this.timers.values()) {\n if (!timer.handle) continue;\n clearTimeout(timer.handle);\n timer.handle = null;\n timer.remaining = Math.max(0, timer.remaining - (now - timer.startedAt));\n }\n }\n\n private resumeTimers(reason: string) {\n this.pauseReasons.delete(reason);\n if (this.isPaused) return;\n for (const id of this.timers.keys()) this.startToastTimer(id);\n }\n\n private get isPaused(): boolean {\n return this.pauseReasons.size > 0;\n }\n\n private clearToastTimer(id: string) {\n const timer = this.timers.get(id);\n if (timer?.handle) clearTimeout(timer.handle);\n this.timers.delete(id);\n }\n\n private clearAllTimers() {\n for (const timer of this.timers.values()) {\n if (timer.handle) clearTimeout(timer.handle);\n }\n for (const watchdog of this.closeWatchdogs.values()) clearTimeout(watchdog);\n this.timers.clear();\n this.closeWatchdogs.clear();\n }\n\n private beginRemoval(record: ToastRecord) {\n if (!this.closeEvents.has(record.id)) {\n this.closeEvents.add(record.id);\n this.dsToastClose.emit({\n id: record.id,\n reason: record.closeReason ?? 'programmatic',\n toast: record,\n });\n this.moveFocusAfterClose(record.id);\n }\n if (\n this.closeWatchdogs.has(record.id) ||\n this.closeFrames.has(record.id)\n ) return;\n\n const duration = resolveMotionTimeMs(\n TOKEN_DEFAULTS.motionShort3,\n TOKEN_DEFAULTS.animationDurationShort3,\n );\n if (duration <= 0) {\n queueMicrotask(() => this.completeRemoval(record));\n return;\n }\n const frame = requestAnimationFrame(() => {\n this.closeFrames.delete(record.id);\n const current = this.records.find(candidate => candidate.id === record.id);\n if (!current || current.transitionStatus !== 'ending') return;\n this.closeWatchdogs.set(\n record.id,\n setTimeout(() => this.completeRemoval(current), duration),\n );\n });\n this.closeFrames.set(record.id, frame);\n }\n\n private completeRemoval(record: ToastRecord) {\n const current = this.records.find(candidate => candidate.id === record.id);\n if (!current || current.transitionStatus !== 'ending') return;\n const watchdog = this.closeWatchdogs.get(record.id);\n if (watchdog) clearTimeout(watchdog);\n this.closeWatchdogs.delete(record.id);\n const closeFrame = this.closeFrames.get(record.id);\n if (closeFrame) cancelAnimationFrame(closeFrame);\n this.closeFrames.delete(record.id);\n const manager = this.attachedManager;\n const context = manager?.remove(record.id);\n if (manager && context) this.pendingRemovals.push({ manager, context });\n }\n\n private handleAnimationComplete(record: ToastRecord) {\n if (record.transitionStatus === 'ending') this.completeRemoval(record);\n }\n\n private bindAnimationCancel(element: HTMLDivElement | undefined, id: string) {\n if (!element || element.dataset['cancelBound'] === 'true') return;\n element.dataset['cancelBound'] = 'true';\n element.addEventListener('animationcancel', () => {\n const record = this.records.find(candidate => candidate.id === id);\n if (record) this.handleAnimationComplete(record);\n });\n }\n\n private handleWindowBlur = () => this.pauseTimers('window');\n private handleWindowFocus = () => this.resumeTimers('window');\n private handleVisibilityChange = () => {\n if (document.hidden) this.pauseTimers('document');\n else this.resumeTimers('document');\n };\n\n private handlePointerEnter(id: string) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias -- pointer interaction selects the viewport that receives F6\n activeToastRegion = this;\n this.pendingHoverLeave = false;\n this.hoveredIds.add(id);\n this.expanded = true;\n this.pauseTimers('hover');\n }\n\n private handlePointerLeave(id: string) {\n this.hoveredIds.delete(id);\n if (this.hoveredIds.size) return;\n if (this.records.some(record => record.transitionStatus === 'ending')) {\n this.pendingHoverLeave = true;\n return;\n }\n this.expanded = false;\n this.resumeTimers('hover');\n }\n\n private handleFocusIn = () => {\n const active = document.activeElement;\n if (!(active instanceof HTMLElement) || !active.matches(':focus-visible')) return;\n // eslint-disable-next-line @typescript-eslint/no-this-alias -- module coordinator routes F6 to the last focused viewport\n activeToastRegion = this;\n this.keyboardActive = true;\n this.expanded = true;\n this.pauseTimers('focus');\n };\n\n private handleFocusOut = (event: FocusEvent) => {\n const next = event.relatedTarget;\n if (next instanceof Node && this.el.contains(next)) return;\n if (!this.keyboardActive) return;\n this.keyboardActive = false;\n this.expanded = this.hoveredIds.size > 0;\n this.resumeTimers('focus');\n };\n\n private handleDocumentKeyDown = (event: KeyboardEvent) => {\n if (event.key !== 'F6') return;\n const eligible = Array.from(connectedToastRegions).filter(\n region => region.activeRecords.length > 0,\n );\n const target =\n activeToastRegion && activeToastRegion.activeRecords.length\n ? activeToastRegion\n : eligible[eligible.length - 1];\n if (target !== this) return;\n event.preventDefault();\n if (!this.el.contains(document.activeElement)) {\n this.previousFocus = document.activeElement as HTMLElement | null;\n }\n this.keyboardActive = true;\n this.regionElement?.focus();\n };\n\n private handleRegionKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n const target = event.target as HTMLElement;\n const positioner = target.closest<HTMLElement>('.toast-positioner');\n const id = positioner?.dataset['toastId'] ?? this.activeRecords[0]?.id;\n if (id) {\n event.preventDefault();\n this.manager.close(id, 'escape');\n }\n return;\n }\n\n if (event.key === 'Tab' && event.shiftKey && event.target === this.regionElement) {\n event.preventDefault();\n this.restorePreviousFocus();\n }\n };\n\n private get regionElement(): HTMLElement | null {\n return this.el.querySelector<HTMLElement>('.toast-region');\n }\n\n private restorePreviousFocus() {\n this.previousFocus?.focus?.();\n this.previousFocus = null;\n this.keyboardActive = false;\n }\n\n private moveFocusAfterClose(id: string) {\n const active = document.activeElement;\n const closing = this.positionerElement(id);\n if (!active || !closing?.contains(active)) return;\n requestAnimationFrame(() => {\n const next = this.activeRecords.find(record => record.id !== id);\n const control = next\n ? this.positionerElement(next.id)?.querySelector<\n HTMLElement & { setFocus?: () => Promise<void> }\n >('ds-button-unfilled')\n : null;\n if (control?.setFocus) void control.setFocus();\n else if (next) this.regionElement?.focus();\n else this.restorePreviousFocus();\n });\n }\n\n private handleAction(record: ToastRecord, event: CustomEvent<MouseEvent>) {\n const detail: ToastActionEventDetail = {\n id: record.id,\n toast: record,\n originalEvent: event.detail,\n };\n this.dsToastAction.emit(detail);\n record.action?.onAction?.({\n id: record.id,\n data: record.data,\n manager: this.manager,\n originalEvent: event.detail,\n });\n }\n\n private handlePointerDown(record: ToastRecord, event: PointerEvent) {\n if (event.button !== 0) return;\n const target = event.target as Element;\n if (target.closest(INTERACTIVE_SWIPE_SELECTOR)) return;\n\n const surface = event.currentTarget as HTMLElement;\n surface.setPointerCapture(event.pointerId);\n this.activeSwipe = {\n id: record.id,\n pointerId: event.pointerId,\n pointerType: event.pointerType,\n startX: event.clientX,\n startY: event.clientY,\n maxDistance: 0,\n cancelled: false,\n axis: null,\n };\n this.swipe = { id: record.id, x: 0, y: 0 };\n if (event.pointerType === 'touch') this.pauseTimers('swipe');\n }\n\n private handlePointerMove(event: PointerEvent) {\n const active = this.activeSwipe;\n if (!active || active.pointerId !== event.pointerId || active.cancelled) return;\n const dx = event.clientX - active.startX;\n const dy = event.clientY - active.startY;\n if (!active.axis && Math.max(Math.abs(dx), Math.abs(dy)) > 1) {\n active.axis = Math.abs(dx) >= Math.abs(dy) ? 'x' : 'y';\n }\n if (!active.axis) return;\n const horizontal = active.axis === 'x';\n const direction: ToastSwipeDirection = horizontal\n ? dx >= 0 ? 'right' : 'left'\n : dy >= 0 ? 'down' : 'up';\n const allowed = this.swipeDirections.includes(direction);\n const rawDistance = horizontal ? Math.abs(dx) : Math.abs(dy);\n const distance = allowed ? rawDistance : Math.sqrt(rawDistance);\n const signed = (horizontal ? dx : dy) < 0 ? -distance : distance;\n const x = horizontal ? signed : 0;\n const y = horizontal ? 0 : signed;\n\n if (active.maxDistance - distance >= SWIPE_REVERSE_CANCEL_THRESHOLD) {\n active.cancelled = true;\n this.cancelSwipe();\n return;\n }\n active.maxDistance = Math.max(active.maxDistance, distance);\n if (rawDistance > 1) event.preventDefault();\n this.swipe = { id: active.id, x, y, direction: allowed ? direction : undefined };\n }\n\n private handlePointerUp(event: PointerEvent) {\n const active = this.activeSwipe;\n if (!active || active.pointerId !== event.pointerId) return;\n const swipe = this.swipe;\n const distance = swipe ? Math.max(Math.abs(swipe.x), Math.abs(swipe.y)) : 0;\n const shouldDismiss =\n !active.cancelled &&\n !!swipe?.direction &&\n distance >= SWIPE_THRESHOLD;\n const id = active.id;\n const wasTouch = active.pointerType === 'touch';\n this.activeSwipe = null;\n this.swipe = null;\n if (wasTouch) this.resumeTimers('swipe');\n if (shouldDismiss && swipe.direction) {\n this.dismissedSwipeDirections.set(id, swipe.direction);\n this.manager.close(id, 'swipe');\n }\n }\n\n private handlePointerCancel(event: PointerEvent) {\n if (this.activeSwipe?.pointerId !== event.pointerId) return;\n this.cancelSwipe();\n }\n\n private cancelSwipe() {\n const wasTouch = this.activeSwipe?.pointerType === 'touch';\n this.activeSwipe = null;\n this.swipe = null;\n if (wasTouch) this.resumeTimers('swipe');\n }\n\n private get touchAction(): string {\n const horizontal =\n this.swipeDirections.includes('left') || this.swipeDirections.includes('right');\n const vertical =\n this.swipeDirections.includes('up') || this.swipeDirections.includes('down');\n if (horizontal && vertical) return 'none';\n if (horizontal) return 'pan-y';\n if (vertical) return 'pan-x';\n return 'auto';\n }\n\n private handleWindowResize = () => {\n this.heights.clear();\n this.measuredUpdateKeys.clear();\n this.layoutVersion += 1;\n this.scheduleLayout();\n };\n\n private scheduleLayout = () => {\n if (this.layoutFrame !== null) return;\n this.layoutFrame = requestAnimationFrame(() => {\n this.layoutFrame = null;\n this.measureLayout();\n });\n };\n\n private measureNaturalHeight(element: HTMLElement, expandedWidth: boolean): number {\n const surface = element.querySelector<HTMLElement>('.toast-surface');\n if (!surface) return 0;\n const previousWidth = element.style.width;\n const previousTransition = element.style.transition;\n const previousHeight = surface.style.height;\n\n if (expandedWidth) {\n element.style.transition = 'none';\n element.style.width = '100%';\n }\n surface.style.height = 'auto';\n const height = surface.getBoundingClientRect().height;\n\n surface.style.height = previousHeight;\n if (expandedWidth) {\n element.style.width = previousWidth;\n element.getBoundingClientRect();\n element.style.transition = previousTransition;\n }\n return height;\n }\n\n private measureLayout() {\n let changed = false;\n for (const record of this.records) {\n const element = this.positionerElement(record.id);\n if (!element) continue;\n let height = this.heights.get(record.id) ?? 0;\n const needsHeightMeasurement =\n height <= 0 || this.measuredUpdateKeys.get(record.id) !== record.updateKey;\n if (needsHeightMeasurement) {\n height = this.measureNaturalHeight(element, !record.positioner);\n if (height > 0) {\n if (this.heights.get(record.id) !== height) changed = true;\n this.heights.set(record.id, height);\n this.measuredUpdateKeys.set(record.id, record.updateKey);\n }\n }\n\n if (!record.positioner) continue;\n const anchor = this.resolveAnchor(record.positioner.anchor);\n if (!anchor || height <= 0) {\n if (this.anchoredPositions.delete(record.id)) changed = true;\n continue;\n }\n const rect = element.getBoundingClientRect();\n const sideOffset = resolveCssLengthPx(\n record.positioner.sideOffset,\n TOKEN_DEFAULTS.space050,\n );\n const alignOffset = resolveCssLengthPx(record.positioner.alignOffset, 0);\n const position = computeTooltipPosition({\n anchorRect: anchor.getBoundingClientRect(),\n popupWidth: rect.width,\n popupHeight: height,\n side: record.positioner.side ?? 'top',\n align: record.positioner.align ?? 'center',\n sideOffsetPx: sideOffset,\n alignOffsetPx: alignOffset,\n viewportPadPx: resolveCssLengthPx(undefined, TOKEN_DEFAULTS.space200),\n viewportWidth: window.innerWidth,\n viewportHeight: window.innerHeight,\n });\n const current = this.anchoredPositions.get(record.id);\n if (\n !current ||\n current.x !== position.x ||\n current.y !== position.y ||\n current.side !== position.resolvedSide\n ) {\n this.anchoredPositions.set(record.id, {\n x: position.x,\n y: position.y,\n side: position.resolvedSide,\n });\n changed = true;\n }\n }\n if (changed) this.layoutVersion += 1;\n }\n\n private resolveAnchor(anchor: HTMLElement | string): HTMLElement | null {\n return typeof anchor === 'string' ? document.getElementById(anchor) : anchor;\n }\n\n private positionerElement(id: string): HTMLElement | null {\n return (\n Array.from(this.el.querySelectorAll<HTMLElement>('.toast-positioner'))\n .find(element => element.dataset['toastId'] === id) ?? null\n );\n }\n\n private ensureDomId(id: string): number {\n const current = this.domIds.get(id);\n if (current) return current;\n const next = ++this.nextDomId;\n this.domIds.set(id, next);\n return next;\n }\n\n private get activeRecords(): ToastRecord[] {\n return this.records.filter(record => record.transitionStatus !== 'ending');\n }\n\n private globalLayout() {\n const globalRecords = this.records.filter(record => !record.positioner);\n let offset = 0;\n let visibleIndex = 0;\n const gap = resolveCssLengthPx(undefined, TOKEN_DEFAULTS.space200);\n const layouts = new Map<string, { index: number; offset: number; limited: boolean }>();\n\n globalRecords.forEach((record, domIndex) => {\n if (record.transitionStatus === 'ending') {\n layouts.set(record.id, { index: domIndex, offset, limited: false });\n return;\n }\n\n const limited = visibleIndex >= Math.max(1, this.limit);\n layouts.set(record.id, { index: visibleIndex, offset, limited });\n offset += (this.heights.get(record.id) ?? 0) + gap;\n visibleIndex += 1;\n });\n return layouts;\n }\n\n private renderToast(\n record: ToastRecord,\n layout: { index: number; offset: number; limited: boolean },\n ) {\n const domId = this.ensureDomId(record.id);\n const titleId = `ds-toast-${this.instanceId}-${domId}-title`;\n const descriptionId = `ds-toast-${this.instanceId}-${domId}-description`;\n const swipe = this.swipe?.id === record.id ? this.swipe : null;\n const swipeDirection = swipe?.direction ?? this.dismissedSwipeDirections.get(record.id);\n const anchored = !!record.positioner;\n const anchoredPosition = this.anchoredPositions.get(record.id);\n const hiddenHighPriority = record.priority === 'high' && !this.keyboardActive;\n const focusTabIndex = this.keyboardActive && !layout.limited ? 0 : -1;\n const toastHeight = this.heights.get(record.id);\n\n return (\n <div\n ref={(element?: HTMLDivElement) => this.bindAnimationCancel(element, record.id)}\n class={{\n 'toast-positioner': true,\n 'toast-positioner--anchored': anchored,\n 'toast-positioner--ending': record.transitionStatus === 'ending',\n }}\n data-toast-id={record.id}\n data-behind={!anchored && layout.index > 0 ? '' : undefined}\n data-limited={layout.limited ? '' : undefined}\n data-positioned={anchored ? String(!!anchoredPosition) : undefined}\n data-side={anchoredPosition?.side}\n inert={layout.limited ? true : undefined}\n aria-hidden={layout.limited ? 'true' : undefined}\n style={{\n '--toast-index': String(layout.index),\n '--toast-offset-y': `${layout.offset}px`,\n '--toast-height': toastHeight ? `${toastHeight}px` : undefined,\n zIndex: String(this.records.length - layout.index),\n left: anchoredPosition ? `${anchoredPosition.x}px` : undefined,\n top: anchoredPosition ? `${anchoredPosition.y}px` : undefined,\n }}\n onAnimationEnd={() => this.handleAnimationComplete(record)}\n >\n <div\n class={{\n 'toast-surface': true,\n 'toast-surface--swiping': !!swipe,\n }}\n role={record.priority === 'high' ? 'alertdialog' : 'dialog'}\n aria-modal=\"false\"\n aria-labelledby={\n record.title ? titleId : record.description ? descriptionId : undefined\n }\n aria-describedby={record.title && record.description ? descriptionId : undefined}\n aria-hidden={hiddenHighPriority ? 'true' : undefined}\n data-type={record.type}\n data-priority={record.priority}\n data-transition-status={record.transitionStatus}\n data-swiping={swipe ? '' : undefined}\n data-swipe-direction={swipeDirection}\n style={{\n '--toast-swipe-movement-x': `${swipe?.x ?? 0}px`,\n '--toast-swipe-movement-y': `${swipe?.y ?? 0}px`,\n touchAction: this.touchAction,\n }}\n onPointerDown={(event: PointerEvent) => this.handlePointerDown(record, event)}\n onPointerMove={(event: PointerEvent) => this.handlePointerMove(event)}\n onPointerUp={(event: PointerEvent) => this.handlePointerUp(event)}\n onPointerCancel={(event: PointerEvent) => this.handlePointerCancel(event)}\n onPointerEnter={\n anchored ? () => this.handlePointerEnter(record.id) : undefined\n }\n onPointerLeave={\n anchored ? () => this.handlePointerLeave(record.id) : undefined\n }\n >\n <div class=\"toast-content\">\n <div class=\"toast-copy\">\n {record.title && (\n <ds-text\n class=\"toast-title\"\n as=\"div\"\n variant=\"text-title-small\"\n color=\"primary\"\n textId={titleId}\n >\n {record.title}\n </ds-text>\n )}\n {record.description && (\n <ds-text\n class=\"toast-description\"\n as=\"div\"\n variant=\"text-body-medium\"\n color=\"secondary\"\n textId={descriptionId}\n >\n {record.description}\n </ds-text>\n )}\n </div>\n {record.action && (\n <ds-button-unfilled\n class=\"toast-action\"\n variant=\"label\"\n size=\"md\"\n type=\"button\"\n label={record.action.label}\n aria-label={record.action.ariaLabel}\n hasBorder\n focusTabIndex={focusTabIndex}\n aria-hidden={!this.keyboardActive ? 'true' : undefined}\n onDsClick={(event: CustomEvent<MouseEvent>) =>\n this.handleAction(record, event)\n }\n />\n )}\n </div>\n <ds-button-unfilled\n class=\"toast-close\"\n variant=\"icon\"\n size=\"md\"\n type=\"button\"\n icon=\"Cross\"\n aria-label={this.closeLabel}\n hasBorder={false}\n activeFill={false}\n focusTabIndex={focusTabIndex}\n aria-hidden={!this.keyboardActive ? 'true' : undefined}\n onDsClick={() => this.manager.close(record.id, 'close-button')}\n />\n </div>\n </div>\n );\n }\n\n render() {\n void this.layoutVersion;\n const globalLayouts = this.globalLayout();\n const globalRecords = this.records.filter(record => !record.positioner);\n const anchoredRecords = this.records.filter(record => !!record.positioner);\n const highPriority = this.records.filter(\n record =>\n record.priority === 'high' &&\n record.transitionStatus !== 'ending' &&\n !globalLayouts.get(record.id)?.limited,\n );\n\n return (\n <Host>\n <section\n class=\"toast-region\"\n role=\"region\"\n aria-label={this.label}\n aria-live=\"polite\"\n aria-atomic=\"false\"\n aria-relevant=\"additions text\"\n tabIndex={-1}\n onFocusin={this.handleFocusIn}\n onFocusout={(event: FocusEvent) => this.handleFocusOut(event)}\n onKeyDown={(event: KeyboardEvent) => this.handleRegionKeyDown(event)}\n >\n <div\n class=\"toast-viewport\"\n data-expanded={this.expanded ? '' : undefined}\n onPointerEnter={() => this.handlePointerEnter(GLOBAL_STACK_HOVER)}\n onPointerLeave={() => this.handlePointerLeave(GLOBAL_STACK_HOVER)}\n >\n {globalRecords.map(record =>\n this.renderToast(\n record,\n globalLayouts.get(record.id) ?? { index: 0, offset: 0, limited: false },\n )\n )}\n </div>\n <div class=\"toast-anchored-layer\">\n {anchoredRecords.map(record =>\n this.renderToast(record, { index: 0, offset: 0, limited: false })\n )}\n </div>\n <div class=\"toast-assertive-announcer\">\n {highPriority.map(record => (\n <div role=\"alert\" aria-atomic=\"true\">\n {[record.title, record.description].filter(Boolean).join('. ')}\n </div>\n ))}\n </div>\n </section>\n </Host>\n );\n }\n}\n",
333
+ "content": "import {\n Component,\n Element,\n Event,\n EventEmitter,\n h,\n Host,\n Prop,\n State,\n Watch,\n} from '@stencil/core';\nimport {\n resolveCssLengthPx,\n resolveCssTimeMs,\n resolveMotionTimeMs,\n TOKEN_DEFAULTS,\n} from '../../utils';\nimport {\n toastManager as defaultToastManager,\n type ToastActionEventDetail,\n type ToastCloseContext,\n type ToastCloseEventDetail,\n type ToastEventDetail,\n type ToastManager,\n type ToastRecord,\n type ToastSwipeDirection,\n} from '../../toast';\nimport { computeTooltipPosition } from '../Tooltip/tooltip-position';\n\ninterface ToastTimer {\n timerKey: number;\n remaining: number;\n startedAt: number;\n handle: ReturnType<typeof setTimeout> | null;\n}\n\ninterface SwipeState {\n id: string;\n x: number;\n y: number;\n direction?: ToastSwipeDirection;\n}\n\ninterface AnchoredPosition {\n x: number;\n y: number;\n side: 'top' | 'right' | 'bottom' | 'left';\n}\n\ninterface ActiveSwipe {\n id: string;\n pointerId: number;\n pointerType: string;\n startX: number;\n startY: number;\n maxDistance: number;\n cancelled: boolean;\n axis: 'x' | 'y' | null;\n}\n\nconst SWIPE_THRESHOLD = 40;\nconst SWIPE_REVERSE_CANCEL_THRESHOLD = 10;\nconst GLOBAL_STACK_HOVER = '__global-stack__';\nconst INTERACTIVE_SWIPE_SELECTOR =\n 'button,a,input,textarea,select,[role=\"button\"],[data-ds-toast-swipe-ignore]';\n\nconst attachedManagers = new WeakMap<ToastManager, Toast>();\nconst connectedToastRegions = new Set<Toast>();\nlet activeToastRegion: Toast | null = null;\nlet toastInstanceCounter = 0;\n\n@Component({\n tag: 'ds-toast',\n styleUrl: 'Toast.css',\n scoped: true,\n})\nexport class Toast {\n @Element() el!: HTMLElement;\n\n /** Manager that supplies toast records. Assign as a JavaScript property. */\n @Prop() manager: ToastManager = defaultToastManager;\n /** Maximum visible global-stack records. Limited records remain mounted and inert. */\n @Prop() limit: number = 3;\n /** Default auto-dismiss delay. Use 0 for persistent records. */\n @Prop() timeout: number | string = TOKEN_DEFAULTS.animationDelayLong2;\n /** Accessible label for the notification region. */\n @Prop() label: string = 'Notifications';\n /** Localized accessible label for every toast close action. */\n @Prop() closeLabel: string = 'Close notification';\n /** Keep the global stack 16px above the persistent mobile shell bar below 768px. */\n @Prop({ attribute: 'avoid-mobile-shell-bar', reflect: true })\n avoidMobileShellBar: boolean = false;\n /** Allowed swipe-to-dismiss directions. Assign as a JavaScript property. */\n @Prop() swipeDirections: ToastSwipeDirection[] = ['down', 'right'];\n\n @State() private records: readonly ToastRecord[] = [];\n @State() private expanded = false;\n @State() private keyboardActive = false;\n @State() private swipe: SwipeState | null = null;\n @State() private layoutVersion = 0;\n\n @Event() dsToastClose!: EventEmitter<ToastCloseEventDetail>;\n @Event() dsToastRemove!: EventEmitter<ToastEventDetail>;\n @Event() dsToastAction!: EventEmitter<ToastActionEventDetail>;\n\n private readonly instanceId = ++toastInstanceCounter;\n private readonly domIds = new Map<string, number>();\n private readonly timers = new Map<string, ToastTimer>();\n private readonly closeWatchdogs = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly closeFrames = new Map<string, number>();\n private readonly closeEvents = new Set<string>();\n private readonly activationFrames = new Map<string, number>();\n private readonly pauseReasons = new Set<string>();\n private readonly hoveredIds = new Set<string>();\n private readonly heights = new Map<string, number>();\n private readonly measuredUpdateKeys = new Map<string, number>();\n private readonly anchoredPositions = new Map<string, AnchoredPosition>();\n private readonly dismissedSwipeDirections = new Map<string, ToastSwipeDirection>();\n private readonly observedElements = new Set<Element>();\n private readonly pendingRemovals: Array<{\n manager: ToastManager;\n context: ToastCloseContext;\n }> = [];\n\n private unsubscribe: (() => void) | null = null;\n private attachedManager: ToastManager | null = null;\n private previousFocus: HTMLElement | null = null;\n private resizeObserver: ResizeObserver | null = null;\n private mutationObserver: MutationObserver | null = null;\n private layoutFrame: number | null = null;\n private activeSwipe: ActiveSwipe | null = null;\n private nextDomId = 0;\n private connected = false;\n private pendingHoverLeave = false;\n\n connectedCallback() {\n this.connect();\n }\n\n componentDidLoad() {\n this.connect();\n }\n\n private connect() {\n if (this.connected) return;\n this.connected = true;\n this.resizeObserver ??= new ResizeObserver(() => this.scheduleLayout());\n this.mutationObserver ??= new MutationObserver(() => this.scheduleLayout());\n this.mutationObserver.observe(document.body, { childList: true, subtree: true });\n if (!this.unsubscribe) this.attachManager(this.manager);\n window.addEventListener('blur', this.handleWindowBlur);\n window.addEventListener('focus', this.handleWindowFocus);\n window.addEventListener('resize', this.handleWindowResize);\n window.addEventListener('scroll', this.scheduleLayout, true);\n document.addEventListener('keydown', this.handleDocumentKeyDown);\n document.addEventListener('visibilitychange', this.handleVisibilityChange);\n connectedToastRegions.add(this);\n // eslint-disable-next-line @typescript-eslint/no-this-alias -- module coordinator tracks the active connected viewport\n if (!activeToastRegion) activeToastRegion = this;\n }\n\n componentDidRender() {\n this.syncObservedElements();\n this.flushPendingRemovals();\n this.scheduleLayout();\n }\n\n disconnectedCallback() {\n this.connected = false;\n this.flushPendingRemovals();\n this.detachManager();\n this.resetManagerState();\n this.resizeObserver?.disconnect();\n this.resizeObserver = null;\n this.mutationObserver?.disconnect();\n this.mutationObserver = null;\n this.observedElements.clear();\n if (this.layoutFrame !== null) cancelAnimationFrame(this.layoutFrame);\n this.layoutFrame = null;\n window.removeEventListener('blur', this.handleWindowBlur);\n window.removeEventListener('focus', this.handleWindowFocus);\n window.removeEventListener('resize', this.handleWindowResize);\n window.removeEventListener('scroll', this.scheduleLayout, true);\n document.removeEventListener('keydown', this.handleDocumentKeyDown);\n document.removeEventListener('visibilitychange', this.handleVisibilityChange);\n connectedToastRegions.delete(this);\n if (activeToastRegion === this) {\n const remaining = Array.from(connectedToastRegions);\n activeToastRegion = remaining[remaining.length - 1] ?? null;\n }\n }\n\n @Watch('manager')\n onManagerChange(next: ToastManager) {\n this.detachManager();\n this.resetManagerState();\n if (this.connected) this.attachManager(next);\n }\n\n @Watch('timeout')\n onTimeoutChange() {\n for (const timer of this.timers.values()) {\n if (timer.handle) clearTimeout(timer.handle);\n }\n this.timers.clear();\n this.syncTimers();\n }\n\n private attachManager(manager: ToastManager) {\n const attached = attachedManagers.get(manager);\n if (attached && attached !== this) {\n console.warn('[ds-toast] A manager can control only one connected ds-toast instance.');\n return;\n }\n attachedManagers.set(manager, this);\n this.attachedManager = manager;\n this.unsubscribe = manager.subscribe(records => {\n this.records = records;\n this.syncLifecycle(records);\n this.scheduleLayout();\n });\n }\n\n private detachManager() {\n this.unsubscribe?.();\n this.unsubscribe = null;\n if (this.attachedManager && attachedManagers.get(this.attachedManager) === this) {\n attachedManagers.delete(this.attachedManager);\n }\n this.attachedManager = null;\n }\n\n private resetManagerState() {\n this.flushPendingRemovals();\n if (this.el.contains(document.activeElement)) this.restorePreviousFocus();\n this.clearAllTimers();\n for (const frame of this.activationFrames.values()) cancelAnimationFrame(frame);\n for (const frame of this.closeFrames.values()) cancelAnimationFrame(frame);\n this.activationFrames.clear();\n this.closeFrames.clear();\n this.closeEvents.clear();\n this.pauseReasons.clear();\n this.hoveredIds.clear();\n this.pendingHoverLeave = false;\n this.heights.clear();\n this.measuredUpdateKeys.clear();\n this.anchoredPositions.clear();\n this.dismissedSwipeDirections.clear();\n this.domIds.clear();\n this.activeSwipe = null;\n this.swipe = null;\n this.expanded = false;\n this.keyboardActive = false;\n this.records = [];\n this.resizeObserver?.disconnect();\n this.observedElements.clear();\n }\n\n private syncObservedElements() {\n const next = new Set<Element>(\n this.el.querySelectorAll<HTMLElement>('.toast-positioner'),\n );\n for (const record of this.records) {\n if (!record.positioner) continue;\n const anchor = this.resolveAnchor(record.positioner.anchor);\n if (anchor) next.add(anchor);\n }\n\n for (const element of this.observedElements) {\n if (!next.has(element)) {\n this.resizeObserver?.unobserve(element);\n this.observedElements.delete(element);\n }\n }\n for (const element of next) {\n if (this.observedElements.has(element)) continue;\n this.resizeObserver?.observe(element);\n this.observedElements.add(element);\n }\n }\n\n private flushPendingRemovals() {\n for (const pending of this.pendingRemovals.splice(0)) {\n pending.manager.notifyRemove(pending.context);\n this.dsToastRemove.emit({\n id: pending.context.id,\n toast: pending.context.toast,\n });\n }\n }\n\n private syncLifecycle(records: readonly ToastRecord[]) {\n const recordIds = new Set(records.map(record => record.id));\n for (const id of this.hoveredIds) {\n if (id !== GLOBAL_STACK_HOVER && !recordIds.has(id)) this.hoveredIds.delete(id);\n }\n const hasEndingRecords = records.some(\n record => record.transitionStatus === 'ending',\n );\n if (this.pendingHoverLeave && !hasEndingRecords && !this.hoveredIds.size) {\n this.pendingHoverLeave = false;\n this.expanded = false;\n this.resumeTimers('hover');\n } else if (!this.hoveredIds.size && !this.pendingHoverLeave) {\n this.resumeTimers('hover');\n }\n\n for (const [id, timer] of this.timers) {\n if (recordIds.has(id)) continue;\n if (timer.handle) clearTimeout(timer.handle);\n this.timers.delete(id);\n }\n\n for (const [id, watchdog] of this.closeWatchdogs) {\n if (recordIds.has(id)) continue;\n clearTimeout(watchdog);\n this.closeWatchdogs.delete(id);\n }\n\n for (const [id, frame] of this.activationFrames) {\n if (recordIds.has(id)) continue;\n cancelAnimationFrame(frame);\n this.activationFrames.delete(id);\n }\n\n for (const [id, frame] of this.closeFrames) {\n if (recordIds.has(id)) continue;\n cancelAnimationFrame(frame);\n this.closeFrames.delete(id);\n }\n\n for (const id of this.domIds.keys()) {\n if (recordIds.has(id)) continue;\n this.closeEvents.delete(id);\n this.domIds.delete(id);\n this.heights.delete(id);\n this.measuredUpdateKeys.delete(id);\n this.anchoredPositions.delete(id);\n this.dismissedSwipeDirections.delete(id);\n }\n\n for (const record of records) {\n this.ensureDomId(record.id);\n if (\n record.transitionStatus === 'starting' &&\n !this.activationFrames.has(record.id)\n ) {\n const manager = this.attachedManager;\n const frame = requestAnimationFrame(() => {\n this.activationFrames.delete(record.id);\n manager?.activate(record.id);\n });\n this.activationFrames.set(record.id, frame);\n }\n\n if (record.transitionStatus === 'ending') {\n this.clearToastTimer(record.id);\n this.beginRemoval(record);\n } else {\n const watchdog = this.closeWatchdogs.get(record.id);\n if (watchdog) clearTimeout(watchdog);\n this.closeWatchdogs.delete(record.id);\n const closeFrame = this.closeFrames.get(record.id);\n if (closeFrame) cancelAnimationFrame(closeFrame);\n this.closeFrames.delete(record.id);\n this.closeEvents.delete(record.id);\n }\n }\n\n this.syncTimers();\n }\n\n private syncTimers() {\n const activeIds = new Set<string>();\n for (const record of this.records) {\n if (record.transitionStatus !== 'active') continue;\n activeIds.add(record.id);\n const duration = this.resolveToastTimeout(record);\n if (duration <= 0) {\n this.clearToastTimer(record.id);\n continue;\n }\n\n const existing = this.timers.get(record.id);\n if (!existing || existing.timerKey !== record.timerKey) {\n this.clearToastTimer(record.id);\n this.timers.set(record.id, {\n timerKey: record.timerKey,\n remaining: duration,\n startedAt: 0,\n handle: null,\n });\n }\n if (!this.isPaused) this.startToastTimer(record.id);\n }\n\n for (const id of this.timers.keys()) {\n if (!activeIds.has(id)) this.clearToastTimer(id);\n }\n }\n\n private resolveToastTimeout(record: ToastRecord): number {\n const value = record.timeout ?? this.timeout;\n if (typeof value === 'number') return Math.max(0, value);\n return resolveCssTimeMs(value, TOKEN_DEFAULTS.animationDelayLong2);\n }\n\n private startToastTimer(id: string) {\n const timer = this.timers.get(id);\n if (!timer || timer.handle || timer.remaining <= 0) return;\n timer.startedAt = Date.now();\n timer.handle = setTimeout(() => {\n timer.handle = null;\n timer.remaining = 0;\n this.manager.close(id, 'timeout');\n }, timer.remaining);\n }\n\n private pauseTimers(reason: string) {\n const wasPaused = this.isPaused;\n this.pauseReasons.add(reason);\n if (wasPaused) return;\n const now = Date.now();\n for (const timer of this.timers.values()) {\n if (!timer.handle) continue;\n clearTimeout(timer.handle);\n timer.handle = null;\n timer.remaining = Math.max(0, timer.remaining - (now - timer.startedAt));\n }\n }\n\n private resumeTimers(reason: string) {\n this.pauseReasons.delete(reason);\n if (this.isPaused) return;\n for (const id of this.timers.keys()) this.startToastTimer(id);\n }\n\n private get isPaused(): boolean {\n return this.pauseReasons.size > 0;\n }\n\n private clearToastTimer(id: string) {\n const timer = this.timers.get(id);\n if (timer?.handle) clearTimeout(timer.handle);\n this.timers.delete(id);\n }\n\n private clearAllTimers() {\n for (const timer of this.timers.values()) {\n if (timer.handle) clearTimeout(timer.handle);\n }\n for (const watchdog of this.closeWatchdogs.values()) clearTimeout(watchdog);\n this.timers.clear();\n this.closeWatchdogs.clear();\n }\n\n private beginRemoval(record: ToastRecord) {\n if (!this.closeEvents.has(record.id)) {\n this.closeEvents.add(record.id);\n this.dsToastClose.emit({\n id: record.id,\n reason: record.closeReason ?? 'programmatic',\n toast: record,\n });\n this.moveFocusAfterClose(record.id);\n }\n if (\n this.closeWatchdogs.has(record.id) ||\n this.closeFrames.has(record.id)\n ) return;\n\n const duration = resolveMotionTimeMs(\n TOKEN_DEFAULTS.motionShort3,\n TOKEN_DEFAULTS.animationDurationShort3,\n );\n if (duration <= 0) {\n queueMicrotask(() => this.completeRemoval(record));\n return;\n }\n const frame = requestAnimationFrame(() => {\n this.closeFrames.delete(record.id);\n const current = this.records.find(candidate => candidate.id === record.id);\n if (!current || current.transitionStatus !== 'ending') return;\n this.closeWatchdogs.set(\n record.id,\n setTimeout(() => this.completeRemoval(current), duration),\n );\n });\n this.closeFrames.set(record.id, frame);\n }\n\n private completeRemoval(record: ToastRecord) {\n const current = this.records.find(candidate => candidate.id === record.id);\n if (!current || current.transitionStatus !== 'ending') return;\n const watchdog = this.closeWatchdogs.get(record.id);\n if (watchdog) clearTimeout(watchdog);\n this.closeWatchdogs.delete(record.id);\n const closeFrame = this.closeFrames.get(record.id);\n if (closeFrame) cancelAnimationFrame(closeFrame);\n this.closeFrames.delete(record.id);\n const manager = this.attachedManager;\n const context = manager?.remove(record.id);\n if (manager && context) this.pendingRemovals.push({ manager, context });\n }\n\n private handleAnimationComplete(record: ToastRecord) {\n if (record.transitionStatus === 'ending') this.completeRemoval(record);\n }\n\n private bindAnimationCancel(element: HTMLDivElement | undefined, id: string) {\n if (!element || element.dataset['cancelBound'] === 'true') return;\n element.dataset['cancelBound'] = 'true';\n element.addEventListener('animationcancel', () => {\n const record = this.records.find(candidate => candidate.id === id);\n if (record) this.handleAnimationComplete(record);\n });\n }\n\n private handleWindowBlur = () => this.pauseTimers('window');\n private handleWindowFocus = () => this.resumeTimers('window');\n private handleVisibilityChange = () => {\n if (document.hidden) this.pauseTimers('document');\n else this.resumeTimers('document');\n };\n\n private handlePointerEnter(id: string) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias -- pointer interaction selects the viewport that receives F6\n activeToastRegion = this;\n this.pendingHoverLeave = false;\n this.hoveredIds.add(id);\n this.expanded = true;\n this.pauseTimers('hover');\n }\n\n private handlePointerLeave(id: string) {\n this.hoveredIds.delete(id);\n if (this.hoveredIds.size) return;\n if (this.records.some(record => record.transitionStatus === 'ending')) {\n this.pendingHoverLeave = true;\n return;\n }\n this.expanded = false;\n this.resumeTimers('hover');\n }\n\n private handleFocusIn = () => {\n const active = document.activeElement;\n if (!(active instanceof HTMLElement) || !active.matches(':focus-visible')) return;\n // eslint-disable-next-line @typescript-eslint/no-this-alias -- module coordinator routes F6 to the last focused viewport\n activeToastRegion = this;\n this.keyboardActive = true;\n this.expanded = true;\n this.pauseTimers('focus');\n };\n\n private handleFocusOut = (event: FocusEvent) => {\n const next = event.relatedTarget;\n if (next instanceof Node && this.el.contains(next)) return;\n if (!this.keyboardActive) return;\n this.keyboardActive = false;\n this.expanded = this.hoveredIds.size > 0;\n this.resumeTimers('focus');\n };\n\n private handleDocumentKeyDown = (event: KeyboardEvent) => {\n if (event.key !== 'F6') return;\n const eligible = Array.from(connectedToastRegions).filter(\n region => region.activeRecords.length > 0,\n );\n const target =\n activeToastRegion && activeToastRegion.activeRecords.length\n ? activeToastRegion\n : eligible[eligible.length - 1];\n if (target !== this) return;\n event.preventDefault();\n if (!this.el.contains(document.activeElement)) {\n this.previousFocus = document.activeElement as HTMLElement | null;\n }\n this.keyboardActive = true;\n this.regionElement?.focus();\n };\n\n private handleRegionKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n const target = event.target as HTMLElement;\n const positioner = target.closest<HTMLElement>('.toast-positioner');\n const id = positioner?.dataset['toastId'] ?? this.activeRecords[0]?.id;\n if (id) {\n event.preventDefault();\n this.manager.close(id, 'escape');\n }\n return;\n }\n\n if (event.key === 'Tab' && event.shiftKey && event.target === this.regionElement) {\n event.preventDefault();\n this.restorePreviousFocus();\n }\n };\n\n private get regionElement(): HTMLElement | null {\n return this.el.querySelector<HTMLElement>('.toast-region');\n }\n\n private restorePreviousFocus() {\n this.previousFocus?.focus?.();\n this.previousFocus = null;\n this.keyboardActive = false;\n }\n\n private moveFocusAfterClose(id: string) {\n const active = document.activeElement;\n const closing = this.positionerElement(id);\n if (!active || !closing?.contains(active)) return;\n requestAnimationFrame(() => {\n const next = this.activeRecords.find(record => record.id !== id);\n const control = next\n ? this.positionerElement(next.id)?.querySelector<\n HTMLElement & { setFocus?: () => Promise<void> }\n >('ds-button-unfilled')\n : null;\n if (control?.setFocus) void control.setFocus();\n else if (next) this.regionElement?.focus();\n else this.restorePreviousFocus();\n });\n }\n\n private handleAction(record: ToastRecord, event: CustomEvent<MouseEvent>) {\n const detail: ToastActionEventDetail = {\n id: record.id,\n toast: record,\n originalEvent: event.detail,\n };\n this.dsToastAction.emit(detail);\n record.action?.onAction?.({\n id: record.id,\n data: record.data,\n manager: this.manager,\n originalEvent: event.detail,\n });\n }\n\n private handlePointerDown(record: ToastRecord, event: PointerEvent) {\n if (event.button !== 0) return;\n const target = event.target as Element;\n if (target.closest(INTERACTIVE_SWIPE_SELECTOR)) return;\n\n const surface = event.currentTarget as HTMLElement;\n surface.setPointerCapture(event.pointerId);\n this.activeSwipe = {\n id: record.id,\n pointerId: event.pointerId,\n pointerType: event.pointerType,\n startX: event.clientX,\n startY: event.clientY,\n maxDistance: 0,\n cancelled: false,\n axis: null,\n };\n this.swipe = { id: record.id, x: 0, y: 0 };\n if (event.pointerType === 'touch') this.pauseTimers('swipe');\n }\n\n private handlePointerMove(event: PointerEvent) {\n const active = this.activeSwipe;\n if (!active || active.pointerId !== event.pointerId || active.cancelled) return;\n const dx = event.clientX - active.startX;\n const dy = event.clientY - active.startY;\n if (!active.axis && Math.max(Math.abs(dx), Math.abs(dy)) > 1) {\n active.axis = Math.abs(dx) >= Math.abs(dy) ? 'x' : 'y';\n }\n if (!active.axis) return;\n const horizontal = active.axis === 'x';\n const direction: ToastSwipeDirection = horizontal\n ? dx >= 0 ? 'right' : 'left'\n : dy >= 0 ? 'down' : 'up';\n const allowed = this.swipeDirections.includes(direction);\n const rawDistance = horizontal ? Math.abs(dx) : Math.abs(dy);\n const distance = allowed ? rawDistance : Math.sqrt(rawDistance);\n const signed = (horizontal ? dx : dy) < 0 ? -distance : distance;\n const x = horizontal ? signed : 0;\n const y = horizontal ? 0 : signed;\n\n if (active.maxDistance - distance >= SWIPE_REVERSE_CANCEL_THRESHOLD) {\n active.cancelled = true;\n this.cancelSwipe();\n return;\n }\n active.maxDistance = Math.max(active.maxDistance, distance);\n if (rawDistance > 1) event.preventDefault();\n this.swipe = { id: active.id, x, y, direction: allowed ? direction : undefined };\n }\n\n private handlePointerUp(event: PointerEvent) {\n const active = this.activeSwipe;\n if (!active || active.pointerId !== event.pointerId) return;\n const swipe = this.swipe;\n const distance = swipe ? Math.max(Math.abs(swipe.x), Math.abs(swipe.y)) : 0;\n const shouldDismiss =\n !active.cancelled &&\n !!swipe?.direction &&\n distance >= SWIPE_THRESHOLD;\n const id = active.id;\n const wasTouch = active.pointerType === 'touch';\n this.activeSwipe = null;\n this.swipe = null;\n if (wasTouch) this.resumeTimers('swipe');\n if (shouldDismiss && swipe.direction) {\n this.dismissedSwipeDirections.set(id, swipe.direction);\n this.manager.close(id, 'swipe');\n }\n }\n\n private handlePointerCancel(event: PointerEvent) {\n if (this.activeSwipe?.pointerId !== event.pointerId) return;\n this.cancelSwipe();\n }\n\n private cancelSwipe() {\n const wasTouch = this.activeSwipe?.pointerType === 'touch';\n this.activeSwipe = null;\n this.swipe = null;\n if (wasTouch) this.resumeTimers('swipe');\n }\n\n private get touchAction(): string {\n const horizontal =\n this.swipeDirections.includes('left') || this.swipeDirections.includes('right');\n const vertical =\n this.swipeDirections.includes('up') || this.swipeDirections.includes('down');\n if (horizontal && vertical) return 'none';\n if (horizontal) return 'pan-y';\n if (vertical) return 'pan-x';\n return 'auto';\n }\n\n private handleWindowResize = () => {\n this.heights.clear();\n this.measuredUpdateKeys.clear();\n this.layoutVersion += 1;\n this.scheduleLayout();\n };\n\n private scheduleLayout = () => {\n if (this.layoutFrame !== null) return;\n this.layoutFrame = requestAnimationFrame(() => {\n this.layoutFrame = null;\n this.measureLayout();\n });\n };\n\n private measureNaturalHeight(element: HTMLElement, expandedWidth: boolean): number {\n const surface = element.querySelector<HTMLElement>('.toast-surface');\n if (!surface) return 0;\n const previousWidth = element.style.width;\n const previousTransition = element.style.transition;\n const previousHeight = surface.style.height;\n\n if (expandedWidth) {\n element.style.transition = 'none';\n element.style.width = '100%';\n }\n surface.style.height = 'auto';\n const height = surface.getBoundingClientRect().height;\n\n surface.style.height = previousHeight;\n if (expandedWidth) {\n element.style.width = previousWidth;\n element.getBoundingClientRect();\n element.style.transition = previousTransition;\n }\n return height;\n }\n\n private measureLayout() {\n let changed = false;\n for (const record of this.records) {\n const element = this.positionerElement(record.id);\n if (!element) continue;\n let height = this.heights.get(record.id) ?? 0;\n const needsHeightMeasurement =\n height <= 0 || this.measuredUpdateKeys.get(record.id) !== record.updateKey;\n if (needsHeightMeasurement) {\n height = this.measureNaturalHeight(element, !record.positioner);\n if (height > 0) {\n if (this.heights.get(record.id) !== height) changed = true;\n this.heights.set(record.id, height);\n this.measuredUpdateKeys.set(record.id, record.updateKey);\n }\n }\n\n if (!record.positioner) continue;\n const anchor = this.resolveAnchor(record.positioner.anchor);\n if (!anchor || height <= 0) {\n if (this.anchoredPositions.delete(record.id)) changed = true;\n continue;\n }\n const rect = element.getBoundingClientRect();\n const sideOffset = resolveCssLengthPx(\n record.positioner.sideOffset,\n TOKEN_DEFAULTS.space050,\n );\n const alignOffset = resolveCssLengthPx(record.positioner.alignOffset, 0);\n const position = computeTooltipPosition({\n anchorRect: anchor.getBoundingClientRect(),\n popupWidth: rect.width,\n popupHeight: height,\n side: record.positioner.side ?? 'top',\n align: record.positioner.align ?? 'center',\n sideOffsetPx: sideOffset,\n alignOffsetPx: alignOffset,\n viewportPadPx: resolveCssLengthPx(undefined, TOKEN_DEFAULTS.space200),\n viewportWidth: window.innerWidth,\n viewportHeight: window.innerHeight,\n });\n const current = this.anchoredPositions.get(record.id);\n if (\n !current ||\n current.x !== position.x ||\n current.y !== position.y ||\n current.side !== position.resolvedSide\n ) {\n this.anchoredPositions.set(record.id, {\n x: position.x,\n y: position.y,\n side: position.resolvedSide,\n });\n changed = true;\n }\n }\n if (changed) this.layoutVersion += 1;\n }\n\n private resolveAnchor(anchor: HTMLElement | string): HTMLElement | null {\n return typeof anchor === 'string' ? document.getElementById(anchor) : anchor;\n }\n\n private positionerElement(id: string): HTMLElement | null {\n return (\n Array.from(this.el.querySelectorAll<HTMLElement>('.toast-positioner'))\n .find(element => element.dataset['toastId'] === id) ?? null\n );\n }\n\n private ensureDomId(id: string): number {\n const current = this.domIds.get(id);\n if (current) return current;\n const next = ++this.nextDomId;\n this.domIds.set(id, next);\n return next;\n }\n\n private get activeRecords(): ToastRecord[] {\n return this.records.filter(record => record.transitionStatus !== 'ending');\n }\n\n private globalLayout() {\n const globalRecords = this.records.filter(record => !record.positioner);\n let offset = 0;\n let visibleIndex = 0;\n const gap = resolveCssLengthPx(undefined, TOKEN_DEFAULTS.space200);\n const layouts = new Map<string, { index: number; offset: number; limited: boolean }>();\n\n globalRecords.forEach((record, domIndex) => {\n if (record.transitionStatus === 'ending') {\n layouts.set(record.id, { index: domIndex, offset, limited: false });\n return;\n }\n\n const limited = visibleIndex >= Math.max(1, this.limit);\n layouts.set(record.id, { index: visibleIndex, offset, limited });\n offset += (this.heights.get(record.id) ?? 0) + gap;\n visibleIndex += 1;\n });\n return layouts;\n }\n\n private renderToast(\n record: ToastRecord,\n layout: { index: number; offset: number; limited: boolean },\n ) {\n const domId = this.ensureDomId(record.id);\n const titleId = `ds-toast-${this.instanceId}-${domId}-title`;\n const descriptionId = `ds-toast-${this.instanceId}-${domId}-description`;\n const swipe = this.swipe?.id === record.id ? this.swipe : null;\n const swipeDirection = swipe?.direction ?? this.dismissedSwipeDirections.get(record.id);\n const anchored = !!record.positioner;\n const anchoredPosition = this.anchoredPositions.get(record.id);\n const hiddenHighPriority = record.priority === 'high' && !this.keyboardActive;\n const focusTabIndex = this.keyboardActive && !layout.limited ? 0 : -1;\n const toastHeight = this.heights.get(record.id);\n\n return (\n <div\n ref={(element?: HTMLDivElement) => this.bindAnimationCancel(element, record.id)}\n class={{\n 'toast-positioner': true,\n 'toast-positioner--anchored': anchored,\n 'toast-positioner--ending': record.transitionStatus === 'ending',\n }}\n data-toast-id={record.id}\n data-behind={!anchored && layout.index > 0 ? '' : undefined}\n data-limited={layout.limited ? '' : undefined}\n data-positioned={anchored ? String(!!anchoredPosition) : undefined}\n data-side={anchoredPosition?.side}\n inert={layout.limited ? true : undefined}\n aria-hidden={layout.limited ? 'true' : undefined}\n style={{\n '--toast-index': String(layout.index),\n '--toast-offset-y': `${layout.offset}px`,\n '--toast-height': toastHeight ? `${toastHeight}px` : undefined,\n zIndex: String(this.records.length - layout.index),\n left: anchoredPosition ? `${anchoredPosition.x}px` : undefined,\n top: anchoredPosition ? `${anchoredPosition.y}px` : undefined,\n }}\n onAnimationEnd={() => this.handleAnimationComplete(record)}\n >\n <div\n class={{\n 'toast-surface': true,\n 'toast-surface--swiping': !!swipe,\n }}\n role={record.priority === 'high' ? 'alertdialog' : 'dialog'}\n aria-modal=\"false\"\n aria-labelledby={\n record.title ? titleId : record.description ? descriptionId : undefined\n }\n aria-describedby={record.title && record.description ? descriptionId : undefined}\n aria-hidden={hiddenHighPriority ? 'true' : undefined}\n data-type={record.type}\n data-priority={record.priority}\n data-transition-status={record.transitionStatus}\n data-swiping={swipe ? '' : undefined}\n data-swipe-direction={swipeDirection}\n style={{\n '--toast-swipe-movement-x': `${swipe?.x ?? 0}px`,\n '--toast-swipe-movement-y': `${swipe?.y ?? 0}px`,\n touchAction: this.touchAction,\n }}\n onPointerDown={(event: PointerEvent) => this.handlePointerDown(record, event)}\n onPointerMove={(event: PointerEvent) => this.handlePointerMove(event)}\n onPointerUp={(event: PointerEvent) => this.handlePointerUp(event)}\n onPointerCancel={(event: PointerEvent) => this.handlePointerCancel(event)}\n onPointerEnter={\n anchored ? () => this.handlePointerEnter(record.id) : undefined\n }\n onPointerLeave={\n anchored ? () => this.handlePointerLeave(record.id) : undefined\n }\n >\n <div class=\"toast-content\">\n <div class=\"toast-copy\">\n {record.title && (\n <ds-text\n class=\"toast-title\"\n as=\"div\"\n variant=\"text-title-small\"\n color=\"primary\"\n textId={titleId}\n >\n {record.title}\n </ds-text>\n )}\n {record.description && (\n <ds-text\n class=\"toast-description\"\n as=\"div\"\n variant=\"text-body-medium\"\n color=\"secondary\"\n textId={descriptionId}\n >\n {record.description}\n </ds-text>\n )}\n </div>\n {record.action && (\n <ds-button-unfilled\n class=\"toast-action\"\n variant=\"label\"\n size=\"md\"\n type=\"button\"\n label={record.action.label}\n aria-label={record.action.ariaLabel}\n hasBorder\n focusTabIndex={focusTabIndex}\n aria-hidden={!this.keyboardActive ? 'true' : undefined}\n onDsClick={(event: CustomEvent<MouseEvent>) =>\n this.handleAction(record, event)\n }\n />\n )}\n </div>\n <ds-button-unfilled\n class=\"toast-close\"\n variant=\"icon\"\n size=\"md\"\n type=\"button\"\n icon=\"Cross\"\n aria-label={this.closeLabel}\n hasBorder={false}\n activeFill={false}\n focusTabIndex={focusTabIndex}\n aria-hidden={!this.keyboardActive ? 'true' : undefined}\n onDsClick={() => this.manager.close(record.id, 'close-button')}\n />\n </div>\n </div>\n );\n }\n\n render() {\n void this.layoutVersion;\n const globalLayouts = this.globalLayout();\n const globalRecords = this.records.filter(record => !record.positioner);\n const anchoredRecords = this.records.filter(record => !!record.positioner);\n const highPriority = this.records.filter(\n record =>\n record.priority === 'high' &&\n record.transitionStatus !== 'ending' &&\n !globalLayouts.get(record.id)?.limited,\n );\n\n return (\n <Host>\n <section\n class=\"toast-region\"\n role=\"region\"\n aria-label={this.label}\n aria-live=\"polite\"\n aria-atomic=\"false\"\n aria-relevant=\"additions text\"\n tabIndex={-1}\n onFocusin={this.handleFocusIn}\n onFocusout={(event: FocusEvent) => this.handleFocusOut(event)}\n onKeyDown={(event: KeyboardEvent) => this.handleRegionKeyDown(event)}\n >\n <div\n class=\"toast-viewport\"\n data-expanded={this.expanded ? '' : undefined}\n onPointerEnter={() => this.handlePointerEnter(GLOBAL_STACK_HOVER)}\n onPointerLeave={() => this.handlePointerLeave(GLOBAL_STACK_HOVER)}\n >\n {globalRecords.map(record =>\n this.renderToast(\n record,\n globalLayouts.get(record.id) ?? { index: 0, offset: 0, limited: false },\n )\n )}\n </div>\n <div class=\"toast-anchored-layer\">\n {anchoredRecords.map(record =>\n this.renderToast(record, { index: 0, offset: 0, limited: false })\n )}\n </div>\n <div class=\"toast-assertive-announcer\">\n {highPriority.map(record => (\n <div role=\"alert\" aria-atomic=\"true\">\n {[record.title, record.description].filter(Boolean).join('. ')}\n </div>\n ))}\n </div>\n </section>\n </Host>\n );\n }\n}\n",
315
334
  "type": "registry:ui"
316
335
  }
317
336
  ]
@@ -12,6 +12,8 @@ export declare class Toast {
12
12
  label: string;
13
13
  /** Localized accessible label for every toast close action. */
14
14
  closeLabel: string;
15
+ /** Keep the global stack 16px above the persistent mobile shell bar below 768px. */
16
+ avoidMobileShellBar: boolean;
15
17
  /** Allowed swipe-to-dismiss directions. Assign as a JavaScript property. */
16
18
  swipeDirections: ToastSwipeDirection[];
17
19
  private records;
@@ -2658,6 +2658,11 @@ export namespace Components {
2658
2658
  "wrap": TextWrap | undefined;
2659
2659
  }
2660
2660
  interface DsToast {
2661
+ /**
2662
+ * Keep the global stack 16px above the persistent mobile shell bar below 768px.
2663
+ * @default false
2664
+ */
2665
+ "avoidMobileShellBar": boolean;
2661
2666
  /**
2662
2667
  * Localized accessible label for every toast close action.
2663
2668
  * @default 'Close notification'
@@ -6756,6 +6761,11 @@ declare namespace LocalJSX {
6756
6761
  "wrap"?: TextWrap | undefined;
6757
6762
  }
6758
6763
  interface DsToast {
6764
+ /**
6765
+ * Keep the global stack 16px above the persistent mobile shell bar below 768px.
6766
+ * @default false
6767
+ */
6768
+ "avoidMobileShellBar"?: boolean;
6759
6769
  /**
6760
6770
  * Localized accessible label for every toast close action.
6761
6771
  * @default 'Close notification'
@@ -7507,6 +7517,7 @@ declare namespace LocalJSX {
7507
7517
  "timeout": string;
7508
7518
  "label": string;
7509
7519
  "closeLabel": string;
7520
+ "avoidMobileShellBar": boolean;
7510
7521
  }
7511
7522
  interface DsTooltipAttributes {
7512
7523
  "label": string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ds-mo/ui",
3
- "version": "12.4.0",
3
+ "version": "12.4.1",
4
4
  "description": "CompoMo — composable web components styled with TokoMo design tokens",
5
5
  "keywords": [
6
6
  "web-components",