{"version":3,"file":"useInteractionAnnouncements.mjs","names":[],"sources":["../../../../../src/components/Accessibility/hooks/useInteractionAnnouncements.ts"],"sourcesContent":["import { useMemo, useRef } from 'react';\n\nimport type { AriaLivePriority } from '../useAriaLiveAnnouncer';\nimport { useAriaLiveAnnouncer } from '../useAriaLiveAnnouncer';\nimport { useDebouncedAnnounce } from '../scheduling';\nimport { useTranslationContext } from '../../../context/TranslationContext';\n\ntype TranslateFn = ReturnType<typeof useTranslationContext>['t'];\n\n/**\n * Delivery overrides passed alongside an interaction's message params. `debounceMs` overrides the\n * interaction's default debounce for this call and enables debouncing for one that has none.\n * `delayMs` overrides the default delay of the immediate path. `debounceMs` wins when both are set,\n * and interactions without params are always immediate.\n *\n * A debounce runs on a per-call-site timer that is cancelled when the call site unmounts, which\n * suits a value that keeps changing in place. `delayMs` is scheduled in the announcer provider and\n * survives the caller unmounting, which suits a one-shot confirmation whose origin disappears.\n */\nexport type InteractionDeliveryOptions = { debounceMs?: number; delayMs?: number };\n\n/**\n * Params of each interaction announcement. Interactions without params map to `undefined`; the\n * others also accept {@link InteractionDeliveryOptions}.\n */\nexport type InteractionAnnouncementParams = {\n  /** The audio playback rate changed. `rate` is the new multiplier. */\n  'audioPlayer.playbackRateChanged': InteractionDeliveryOptions & { rate: number };\n  /** A channel was opened from the list. `name` is its display title. */\n  'channel.opened': InteractionDeliveryOptions & { name: string };\n  /** A slash command was picked from the Instant Commands menu. `command` is its name. */\n  'command.selected': InteractionDeliveryOptions & { command: string };\n  'giphy.canceled': undefined;\n  'giphy.sent': undefined;\n  'giphy.shuffled': InteractionDeliveryOptions & { title?: string };\n  'poll.dialogOpened': undefined;\n  /** A poll option was dropped at a new position during keyboard reorder. */\n  'poll.optionDropped': InteractionDeliveryOptions & {\n    option: string;\n    position: number;\n  };\n  /** A poll option was picked up to start a keyboard reorder. `option` is its text or fallback. */\n  'poll.optionPickedUp': InteractionDeliveryOptions & { option: string };\n  'poll.optionRemoved': InteractionDeliveryOptions & { option: string };\n  'poll.sent': undefined;\n  'search.cleared': undefined;\n  'search.resultCount': InteractionDeliveryOptions & {\n    /** Whether every active source is fully loaded; appends an \"all results loaded\" clause. */\n    allResultsLoaded?: boolean;\n    count: number;\n  };\n  'suggestions.count': InteractionDeliveryOptions & {\n    count: number;\n    suggestionsLabel?: string;\n  };\n  /** A thread was opened from the list. `name` is its channel's display title. */\n  'thread.opened': InteractionDeliveryOptions & { name: string };\n  'user.selected': InteractionDeliveryOptions & { user: string };\n  /** A finished voice recording was added to the composer (async multi-send, not sent yet). */\n  'voiceRecording.attached': undefined;\n  'voiceRecording.paused': undefined;\n  'voiceRecording.resumed': undefined;\n  /** A finished voice recording was sent immediately as a message. */\n  'voiceRecording.sent': undefined;\n  'voiceRecording.started': undefined;\n};\n\nexport type InteractionAnnouncementType = keyof InteractionAnnouncementParams;\n\n/**\n * One resolver per interaction. Each calls `t()` with a literal key and inline English copy,\n * because `yarn build-translations` extracts keys from the call sites and misses dynamic keys.\n * A new interaction needs an entry here and in {@link InteractionAnnouncementParams}, plus one in\n * {@link INTERACTION_PRIORITIES} if it is not `polite`.\n */\nconst INTERACTION_MESSAGES: {\n  [T in InteractionAnnouncementType]: (\n    t: TranslateFn,\n    params: InteractionAnnouncementParams[T],\n  ) => string;\n} = {\n  // Reuses the already-localized button label so the spoken text matches the control.\n  'audioPlayer.playbackRateChanged': (t, params) =>\n    t('common.playbackSpeedX.label', 'Playback speed {{ rate }}x', { rate: params.rate }),\n  // Delayed (see INTERACTION_DELAY_MS) so it lands after the screen reader announces the element\n  // that auto-focuses on channel change (the composer), which would otherwise supersede it.\n  'channel.opened': (t, params) =>\n    t(\n      'a11y.interactionAnnouncements.openedChannel.ariaLabel',\n      'Opened channel: {{ name }}',\n      { name: params.name },\n    ),\n  // Delayed like the \"opened\" confirmations: selecting a command closes the menu and focuses the\n  // composer textarea, whose name the screen reader reads first.\n  'command.selected': (t, params) =>\n    t(\n      'a11y.interactionAnnouncements.commandActivated.ariaLabel',\n      'Command activated: {{ command }}',\n      { command: params.command },\n    ),\n  'giphy.canceled': (t) =>\n    t('a11y.interactionAnnouncements.giphyCanceled.ariaLabel', 'Giphy canceled'),\n  'giphy.sent': (t) =>\n    t('a11y.interactionAnnouncements.giphySent.ariaLabel', 'Giphy sent'),\n  // Giphy payloads rarely carry a title, so it is included only when present.\n  'giphy.shuffled': (t, params) =>\n    params.title\n      ? t(\n          'a11y.interactionAnnouncements.giphyImageChanged.withTitle.ariaLabel',\n          'Giphy image changed: {{ title }}',\n          { title: params.title },\n        )\n      : t(\n          'a11y.interactionAnnouncements.giphyImageChanged.ariaLabel',\n          'Giphy image changed',\n        ),\n  // Reuses the already-localized visible description between an \"opened\" confirmation and the\n  // Enter affordance, so spoken and visible text stay consistent.\n  'poll.dialogOpened': (t) =>\n    `${t('a11y.interactionAnnouncements.pollDialogOpened.ariaLabel', 'Poll dialog opened')}. ${t(\n      'common.createQuestionAddOptions.label',\n      'Create a question, add options, and configure poll settings',\n    )}. ${t('a11y.interactionAnnouncements.pressEnterStartTyping.ariaLabel', 'Press Enter to start typing')}.`,\n  'poll.optionDropped': (t, params) =>\n    t(\n      'a11y.interactionAnnouncements.droppedPosition.ariaLabel',\n      'Dropped \"{{ option }}\" at position {{ position }}.',\n      {\n        option: params.option,\n        position: params.position,\n      },\n    ),\n  'poll.optionPickedUp': (t, params) =>\n    t(\n      'a11y.interactionAnnouncements.pickedUpUseArrow.ariaLabel',\n      'Picked up \"{{ option }}\". Use arrow keys to reorder. Press Space or Tab to drop.',\n      { option: params.option },\n    ),\n  // Polite, so it queues behind the focus move to the next option field instead of interrupting it.\n  'poll.optionRemoved': (t, params) =>\n    t(\n      'a11y.interactionAnnouncements.removedOption.ariaLabel',\n      'Removed option {{ option }}',\n      { option: params.option },\n    ),\n  'poll.sent': (t) => t('a11y.interactionAnnouncements.pollSent.ariaLabel', 'Poll sent'),\n  'search.cleared': (t) =>\n    t('a11y.interactionAnnouncements.searchCleared.ariaLabel', 'Search cleared'),\n  // An empty result set is spelled out rather than announced as \"0\". The end-of-list status is part\n  // of this announcement (reusing the footer's \"All results loaded\" text), so no second message\n  // supersedes the count.\n  'search.resultCount': (t, params) => {\n    if (params.count <= 0)\n      return t(\n        'a11y.interactionAnnouncements.noSearchResultsFound.ariaLabel',\n        'No search results found',\n      );\n    const count = t('a11y.interactionAnnouncements.searchResults.ariaLabel', {\n      count: params.count,\n      defaultValue_one: '{{ count }} search result',\n      defaultValue_other: '{{ count }} search results',\n    });\n    return params.allResultsLoaded\n      ? `${count}. ${t('common.resultsLoaded.label', 'All results loaded')}`\n      : count;\n  },\n  // Names the suggestion type by reusing the already-localized list label (e.g. \"5 Command\n  // Suggestions\"); without a label it is the bare count.\n  'suggestions.count': (t, params) =>\n    params.suggestionsLabel\n      ? t('a11y.interactionAnnouncements.suggestionsWithLabel.ariaLabel', {\n          count: params.count,\n          defaultValue_one: '{{ count }} {{ suggestionsLabel }}',\n          defaultValue_other: '{{ count }} {{ suggestionsLabel }}',\n          suggestionsLabel: params.suggestionsLabel,\n        })\n      : t('a11y.interactionAnnouncements.suggestions.ariaLabel', {\n          count: params.count,\n          defaultValue_one: '{{ count }} suggestion',\n          defaultValue_other: '{{ count }} suggestions',\n        }),\n  // Delayed like `channel.opened`: the thread composer auto-focuses on open and its focus\n  // announcement would otherwise supersede this one.\n  'thread.opened': (t, params) =>\n    t(\n      'a11y.interactionAnnouncements.openedThread.ariaLabel',\n      'Opened thread in {{ name }}',\n      { name: params.name },\n    ),\n  'user.selected': (t, params) =>\n    t(\n      'a11y.interactionAnnouncements.userSelected.ariaLabel',\n      'User selected: {{ user }}',\n      { user: params.user },\n    ),\n  // Voice recording cancellation and errors are not listed: they surface as notifications announced\n  // by `NotificationAnnouncer`, so listing them here would announce them twice.\n  'voiceRecording.attached': (t) =>\n    t(\n      'a11y.interactionAnnouncements.voiceRecordingAttached.ariaLabel',\n      'Voice recording attached',\n    ),\n  'voiceRecording.paused': (t) =>\n    t('a11y.interactionAnnouncements.recordingPaused.ariaLabel', 'Recording paused'),\n  'voiceRecording.resumed': (t) =>\n    t('a11y.interactionAnnouncements.recordingResumed.ariaLabel', 'Recording resumed'),\n  'voiceRecording.sent': (t) =>\n    t('a11y.interactionAnnouncements.voiceMessageSent.ariaLabel', 'Voice message sent'),\n  'voiceRecording.started': (t) =>\n    t('a11y.interactionAnnouncements.recordingStarted.ariaLabel', 'Recording started'),\n};\n\n/** Per-interaction aria-live priority. Interactions default to `polite`. */\nconst INTERACTION_PRIORITIES: Partial<\n  Record<InteractionAnnouncementType, AriaLivePriority>\n> = {\n  // A polite update fired around the dialog's focus announcement is dropped; assertive is spoken.\n  'poll.dialogOpened': 'assertive',\n  // Keyboard reorder feedback must be immediate, not queued behind polite messages.\n  'poll.optionDropped': 'assertive',\n  'poll.optionPickedUp': 'assertive',\n};\n\n/**\n * Per-interaction dedupe window (ms), see `AriaLiveAnnounceOptions.dedupeMs`. List an\n * interaction only when one event can fire it more than once in quick succession, e.g. an effect\n * double-invoked by React StrictMode.\n */\nconst INTERACTION_DEDUPE_MS: Partial<Record<InteractionAnnouncementType, number>> = {\n  // Widgets rendering the same asset for the same requester share one pooled player, so one rate\n  // change fires this from each of them. Consecutive rates differ in text, so a change is not lost.\n  'audioPlayer.playbackRateChanged': 300,\n  'poll.dialogOpened': 1000,\n};\n\n/**\n * Default per-interaction debounce (ms), for rapidly updating values where only the settled one\n * should be read. Discrete confirmations are not listed and announce immediately. A call can\n * override or opt in via `params.debounceMs`, see {@link InteractionDeliveryOptions}.\n *\n * `suggestions.count` follows typing, so its delay also lets the screen reader's per-keystroke\n * echo finish: a polite update landing mid-echo is queued behind it and gets buried. Echo length\n * varies with screen-reader settings and field content, so tune the value if it still collides.\n */\nconst INTERACTION_DEBOUNCE_MS: Partial<Record<InteractionAnnouncementType, number>> = {\n  // Same rationale as `suggestions.count`, but longer because search results arrive over the\n  // network in bursts.\n  'search.resultCount': 1000,\n  'suggestions.count': 500,\n};\n\n/**\n * Default per-interaction delay (ms) for the immediate path: a single deferred emit scheduled in\n * the announcer provider (see `AriaLiveAnnounceOptions.delayMs`), so it survives the caller\n * unmounting, unlike a debounce.\n *\n * Opening a channel or thread focuses the composer, and a live-region message emitted alongside the\n * screen reader's focus announcement is dropped, so the delay moves the confirmation past it.\n * Selecting the item can unmount its list row (the whole list on mobile), which would cancel a\n * per-row debounce.\n */\nconst INTERACTION_DELAY_MS: Partial<Record<InteractionAnnouncementType, number>> = {\n  'channel.opened': 1500,\n  'command.selected': 1500,\n  'thread.opened': 1500,\n};\n\n// Overloads require params for parameterized interactions and reject them for param-less ones.\ntype AnnounceInteraction = {\n  <T extends InteractionAnnouncementType>(\n    interaction: InteractionAnnouncementParams[T] extends undefined ? T : never,\n  ): void;\n  <T extends InteractionAnnouncementType>(\n    interaction: InteractionAnnouncementParams[T] extends undefined ? never : T,\n    params: InteractionAnnouncementParams[T],\n  ): void;\n};\n\nexport type UseInteractionAnnouncementsValue = {\n  /** Announces a predefined interaction; it maps to a localized message and a fixed priority. */\n  announceInteraction: AnnounceInteraction;\n  /**\n   * Cancels pending (debounced or delayed, not yet emitted) announcements: one `interaction`, or\n   * all when omitted. Call it when the source is torn down so a queued message is not spoken out\n   * of context. An announcement already emitted into the live region cannot be recalled.\n   */\n  cancelInteraction: (interaction?: InteractionAnnouncementType) => void;\n};\n\n/**\n * Typed wrapper over {@link useAriaLiveAnnouncer} for transient, user-initiated UI interactions.\n * Each interaction maps to an i18n key and a fixed priority, and is registered as one entry in\n * {@link INTERACTION_MESSAGES}.\n */\nexport const useInteractionAnnouncements = (): UseInteractionAnnouncementsValue => {\n  const announce = useAriaLiveAnnouncer();\n  const { t } = useTranslationContext();\n  // One debounce timer per interaction type; each call passes its own delay.\n  const { announce: announceDebounced, cancel: cancelDebounced } =\n    useDebouncedAnnounce(announce);\n  // Cancel function of the pending provider-delayed emit per interaction; a re-trigger within the\n  // delay supersedes it. Not cleared on unmount: delayed emits are meant to survive the caller\n  // (e.g. `channel.opened` fires after its list row is gone).\n  const pendingImmediateCancelsRef = useRef<\n    Partial<Record<InteractionAnnouncementType, () => void>>\n  >({});\n\n  return useMemo(\n    () => ({\n      announceInteraction: (\n        interaction: InteractionAnnouncementType,\n        params?: InteractionAnnouncementParams[InteractionAnnouncementType],\n      ) => {\n        const resolveMessage = INTERACTION_MESSAGES[interaction] as (\n          t: TranslateFn,\n          params: InteractionAnnouncementParams[InteractionAnnouncementType],\n        ) => string;\n\n        if (!resolveMessage) return;\n\n        const message = resolveMessage(t, params as never);\n        const priority = INTERACTION_PRIORITIES[interaction] ?? 'polite';\n\n        // A per-call `debounceMs` overrides the default and can opt an immediate interaction in.\n        const debounceMs =\n          (params as InteractionDeliveryOptions | undefined)?.debounceMs ??\n          INTERACTION_DEBOUNCE_MS[interaction];\n        if (debounceMs === undefined) {\n          // Immediate path; `delayMs` is a provider-managed deferral that survives this call site\n          // unmounting.\n          const delayMs =\n            (params as InteractionDeliveryOptions | undefined)?.delayMs ??\n            INTERACTION_DELAY_MS[interaction];\n          // A re-trigger within the delay window supersedes the pending emit, so only the latest is\n          // spoken.\n          pendingImmediateCancelsRef.current[interaction]?.();\n          pendingImmediateCancelsRef.current[interaction] = announce(message, {\n            dedupeMs: INTERACTION_DEDUPE_MS[interaction],\n            delayMs,\n            priority,\n          });\n          return;\n        }\n\n        // Rapid updates collapse into the settled value, keyed by interaction type. An unchanged\n        // message is not deduped here: whether a repeat is meaningful is up to the caller (a steady\n        // suggestion count still re-announces on each re-filter).\n        announceDebounced(interaction, message, debounceMs, priority);\n      },\n      cancelInteraction: (interaction?: InteractionAnnouncementType) => {\n        cancelDebounced(interaction);\n        const pending = pendingImmediateCancelsRef.current;\n        if (interaction) {\n          pending[interaction]?.();\n          delete pending[interaction];\n        } else {\n          Object.values(pending).forEach((cancel) => cancel?.());\n          pendingImmediateCancelsRef.current = {};\n        }\n      },\n    }),\n    [announce, announceDebounced, cancelDebounced, t],\n  );\n};\n"],"mappings":";;;;;;;;;;;AA2EA,IAAM,uBA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