{"version":3,"file":"AriaLiveAnnouncerProvider.mjs","names":[],"sources":["../../../../src/components/Accessibility/AriaLiveAnnouncerProvider.tsx"],"sourcesContent":["import type { PropsWithChildren } from 'react';\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport {\n  type AnnouncementsByPriority,\n  AriaLiveOutletContext,\n} from './AriaLiveOutletContext';\nimport {\n  type AriaLiveAnnounce,\n  AriaLiveAnnouncerContext,\n  type AriaLivePriority,\n} from './useAriaLiveAnnouncer';\n\n// How long an announcement node stays in the DOM. With `aria-relevant=\"additions\"` a lingering node\n// is never re-announced, so a long value only costs a few hidden nodes. It must outlast verbose\n// screen-reader speech (e.g. typing echo) that a polite message can be queued behind; ~1.5s drops\n// those messages.\nconst LIVE_ANNOUNCEMENT_TTL_MS = 7000;\n\ntype RegisteredOutlet = {\n  id: symbol;\n  layer: number;\n};\n\n/**\n * Owns the aria-live announcement state and the `announce()` API; `Chat` mounts one. It renders no\n * live region itself: the highest-layer registered {@link AriaLiveOutlet} paints the messages.\n * State is per provider instance, so several `Chat` instances on a page never share announcements.\n */\nexport const AriaLiveAnnouncerProvider = ({ children }: PropsWithChildren) => {\n  const [announcementsByPriority, setAnnouncementsByPriority] =\n    useState<AnnouncementsByPriority>({\n      assertive: [],\n      polite: [],\n    });\n  const nextAnnouncementIdRef = useRef(0);\n  const timeoutByAnnouncementIdRef = useRef<Map<number, ReturnType<typeof setTimeout>>>(\n    new Map(),\n  );\n  // Pending `delayMs` timers, cleared on unmount.\n  const delayTimersRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());\n  // Messages emitted within their `dedupeMs` window (message -> expiry timer); an identical repeat\n  // inside the window is suppressed.\n  const dedupeTimersByMessageRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(\n    new Map(),\n  );\n  // Text last rendered into a live region. Screen readers (notably VoiceOver) skip an update whose\n  // text equals the previous one.\n  const lastRenderedMessageRef = useRef('');\n\n  const removeAnnouncement = useCallback((priority: AriaLivePriority, id: number) => {\n    setAnnouncementsByPriority((currentAnnouncements) => ({\n      ...currentAnnouncements,\n      [priority]: currentAnnouncements[priority].filter(\n        (announcement) => announcement.id !== id,\n      ),\n    }));\n\n    const timeout = timeoutByAnnouncementIdRef.current.get(id);\n    if (!timeout) return;\n\n    clearTimeout(timeout);\n    timeoutByAnnouncementIdRef.current.delete(id);\n  }, []);\n\n  const emit = useCallback(\n    (message: string, priority: AriaLivePriority) => {\n      const announcementId = nextAnnouncementIdRef.current++;\n\n      // A repeat gets a trailing zero-width space (U+200B), so consecutive identical messages\n      // alternate between `X` and `X` + U+200B and are each voiced.\n      const ZERO_WIDTH_SPACE = '\\u200B';\n      const renderedMessage =\n        message === lastRenderedMessageRef.current\n          ? `${message}${ZERO_WIDTH_SPACE}`\n          : message;\n      lastRenderedMessageRef.current = renderedMessage;\n\n      setAnnouncementsByPriority((currentAnnouncements) => ({\n        ...currentAnnouncements,\n        [priority]: [\n          ...currentAnnouncements[priority],\n          { id: announcementId, message: renderedMessage },\n        ],\n      }));\n\n      const timeout = setTimeout(() => {\n        removeAnnouncement(priority, announcementId);\n      }, LIVE_ANNOUNCEMENT_TTL_MS);\n\n      timeoutByAnnouncementIdRef.current.set(announcementId, timeout);\n    },\n    [removeAnnouncement],\n  );\n\n  const announce = useCallback<AriaLiveAnnounce>(\n    (message, options) => {\n      const { dedupeMs, delayMs, priority = 'polite' } = options ?? {};\n\n      // The dedupe check runs at emit time, so a delayed announcement cancelled before it fires\n      // never opens the window.\n      const emitMessage = () => {\n        if (dedupeMs) {\n          const recent = dedupeTimersByMessageRef.current;\n          if (recent.has(message)) return; // Identical message within the window.\n          recent.set(\n            message,\n            setTimeout(() => recent.delete(message), dedupeMs),\n          );\n        }\n        emit(message, priority);\n      };\n\n      if (!delayMs) {\n        emitMessage();\n        return () => undefined;\n      }\n\n      const delayTimers = delayTimersRef.current;\n      const delayTimer = setTimeout(() => {\n        delayTimers.delete(delayTimer);\n        emitMessage();\n      }, delayMs);\n      delayTimers.add(delayTimer);\n\n      return () => {\n        clearTimeout(delayTimer);\n        delayTimers.delete(delayTimer);\n      };\n    },\n    [emit],\n  );\n\n  useEffect(() => {\n    const timeoutById = timeoutByAnnouncementIdRef.current;\n    const delayTimers = delayTimersRef.current;\n    const dedupeTimers = dedupeTimersByMessageRef.current;\n    return () => {\n      for (const timeout of timeoutById.values()) {\n        clearTimeout(timeout);\n      }\n      timeoutById.clear();\n      for (const timeout of delayTimers) {\n        clearTimeout(timeout);\n      }\n      delayTimers.clear();\n      for (const timeout of dedupeTimers.values()) {\n        clearTimeout(timeout);\n      }\n      dedupeTimers.clear();\n    };\n  }, []);\n\n  const [outlets, setOutlets] = useState<RegisteredOutlet[]>([]);\n\n  const registerOutlet = useCallback((id: symbol, layer: number) => {\n    setOutlets((currentOutlets) => [...currentOutlets, { id, layer }]);\n  }, []);\n\n  const unregisterOutlet = useCallback((id: symbol) => {\n    setOutlets((currentOutlets) => currentOutlets.filter((outlet) => outlet.id !== id));\n  }, []);\n\n  // Innermost wins: the highest layer, and among equal layers the most recently registered.\n  const activeOutlet = useMemo(() => {\n    let active: RegisteredOutlet | null = null;\n    for (const outlet of outlets) {\n      if (!active || outlet.layer >= active.layer) {\n        active = outlet;\n      }\n    }\n    return active;\n  }, [outlets]);\n  const activeOutletId = activeOutlet?.id ?? null;\n\n  // Drops the rendered announcements when the active outlet falls back to a lower layer (a dialog\n  // closed): they would re-render into the lower outlet and be voiced again. A higher outlet\n  // mounting drops nothing, so an announcement made as a dialog opens still renders in it.\n  const previousActiveLayerRef = useRef(activeOutlet?.layer ?? -1);\n  useEffect(() => {\n    const currentLayer = activeOutlet?.layer ?? -1;\n    const previousLayer = previousActiveLayerRef.current;\n    previousActiveLayerRef.current = currentLayer;\n    if (currentLayer >= previousLayer) return;\n\n    for (const timeout of timeoutByAnnouncementIdRef.current.values()) {\n      clearTimeout(timeout);\n    }\n    timeoutByAnnouncementIdRef.current.clear();\n    lastRenderedMessageRef.current = '';\n    setAnnouncementsByPriority({ assertive: [], polite: [] });\n  }, [activeOutlet]);\n\n  const announcerValue = useMemo(() => ({ announce }), [announce]);\n  const outletValue = useMemo(\n    () => ({\n      activeOutletId,\n      announcementsByPriority,\n      registerOutlet,\n      unregisterOutlet,\n    }),\n    [activeOutletId, announcementsByPriority, registerOutlet, unregisterOutlet],\n  );\n\n  return (\n    <AriaLiveAnnouncerContext.Provider value={announcerValue}>\n      <AriaLiveOutletContext.Provider value={outletValue}>\n        {children}\n      </AriaLiveOutletContext.Provider>\n    </AriaLiveAnnouncerContext.Provider>\n  );\n};\n"],"mappings":";;;;;AAiBA,IAAM,2BAA2B;;;;;;AAYjC,IAAa,6BAA6B,EAAE,eAAkC;CAC5E,MAAM,CAAC,yBAAyB,8BAC9B,SAAkC;EAChC,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX,CAAC;CACH,MAAM,wBAAwB,OAAO,CAAC;CACtC,MAAM,6BAA6B,uBACjC,IAAI,IAAI,CACV;CAEA,MAAM,iBAAiB,uBAA2C,IAAI,IAAI,CAAC;CAG3E,MAAM,2BAA2B,uBAC/B,IAAI,IAAI,CACV;CAGA,MAAM,yBAAyB,OAAO,EAAE;CAExC,MAAM,qBAAqB,aAAa,UAA4B,OAAe;EACjF,4BAA4B,0BAA0B;GACpD,GAAG;IACF,WAAW,qBAAqB,SAAS,CAAC,QACxC,iBAAiB,aAAa,OAAO,EACxC;EACF,EAAE;EAEF,MAAM,UAAU,2BAA2B,QAAQ,IAAI,EAAE;EACzD,IAAI,CAAC,SAAS;EAEd,aAAa,OAAO;EACpB,2BAA2B,QAAQ,OAAO,EAAE;CAC9C,GAAG,CAAC,CAAC;CAEL,MAAM,OAAO,aACV,SAAiB,aAA+B;EAC/C,MAAM,iBAAiB,sBAAsB;EAK7C,MAAM,kBACJ,YAAY,uBAAuB,UAC/B,GAAG,QAAA,KACH;EACN,uBAAuB,UAAU;EAEjC,4BAA4B,0BAA0B;GACpD,GAAG;IACF,WAAW,CACV,GAAG,qBAA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