{"version":3,"file":"AttachmentActions.mjs","names":[],"sources":["../../../../src/components/Attachment/AttachmentActions.tsx"],"sourcesContent":["import React, { useEffect, useMemo, useRef } from 'react';\nimport type { Action, Attachment } from 'stream-chat';\n\nimport { useTranslationContext } from '../../context';\n\nimport { useFocusReturn, useInteractionAnnouncements } from '../Accessibility';\nimport { getGiphyDescriptiveTitle } from './giphyAccessibility';\nimport type { ActionHandlerReturnType } from '../Message/hooks/useActionHandler';\nimport { Button } from '../Button';\nimport { VisuallyHidden } from '../VisuallyHidden';\nimport { useStableId } from '../UtilityComponents/useStableId';\nimport clsx from 'clsx';\nimport { asDynamicKey } from '../../i18n/utils';\n\nexport type AttachmentActionsProps = Attachment & {\n  /** Actions to render as buttons. */\n  actions: Action[];\n  /** Prefix of each action button's React key (`${id}-${action.value}`). */\n  id: string;\n  /** Text rendered before the action buttons. */\n  text: string;\n  /** Called with the action's name and value and the click event. */\n  actionHandler?: ActionHandlerReturnType;\n  /** `value` of the action button to focus on initial render. */\n  defaultFocusedActionValue?: string;\n};\n\nexport type AttachmentActionsDefaultFocusByType = Partial<\n  Record<NonNullable<Attachment['type']>, string>\n>;\n\nexport const defaultAttachmentActionsDefaultFocus: AttachmentActionsDefaultFocusByType = {\n  giphy: 'send',\n};\n\nconst UnMemoizedAttachmentActions = (props: AttachmentActionsProps) => {\n  const {\n    actionHandler,\n    actions,\n    defaultFocusedActionValue,\n    giphy,\n    id,\n    image_url: imageUrl,\n    text,\n    thumb_url: thumbUrl,\n    title,\n    type,\n  } = props;\n  const { t } = useTranslationContext();\n  const { announceInteraction } = useInteractionAnnouncements();\n  const { reserve: reserveFocusReturn, restore: restoreFocusReturn } = useFocusReturn();\n  const buttonRefs = useRef<Array<HTMLButtonElement | null>>([]);\n\n  const isGiphy = type === 'giphy';\n  // The giphy preview auto-focuses its primary action, so its description is attached to that\n  // control with `aria-describedby`: a live-region announcement would be preempted by the focus\n  // change and never heard.\n  const giphyDescriptionId = useStableId();\n\n  // Human-readable, non-URL title of the giphy, usually absent. Included in the shuffle\n  // announcement.\n  const descriptiveTitle = isGiphy ? getGiphyDescriptiveTitle(title) : undefined;\n  // Identifies the GIF: its URL changes on every shuffle. A giphy attachment usually has no\n  // `image_url`, so `giphy.original.url` and `thumb_url` come first.\n  const giphyImageIdentity = isGiphy\n    ? (giphy?.original?.url ?? thumbUrl ?? imageUrl ?? null)\n    : null;\n  const previousGiphyImageRef = useRef<string | null>(null);\n  const giphyImageInitializedRef = useRef(false);\n\n  const handleActionClick = (\n    event: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n    name?: string,\n    value?: string,\n  ) => {\n    actionHandler?.(name, value, event);\n\n    // Giphy send/cancel: restore focus first, then announce on the next frame. The screen reader\n    // speaks the focus change immediately, and a live-region message in the same tick races with it\n    // and can be dropped. The frame is not cancelled on unmount: the preview unmounts on send, but\n    // the announcer lives at the Chat root.\n    if (isGiphy && (value === 'send' || value === 'cancel')) {\n      restoreFocusReturn();\n      const interaction = value === 'send' ? 'giphy.sent' : 'giphy.canceled';\n      requestAnimationFrame(() => announceInteraction(interaction));\n    }\n  };\n\n  const knownActionText = useMemo<Record<string, string>>(\n    () => ({\n      Cancel: t('common.cancel.label', 'Cancel'),\n      Send: t('common.send.label', 'Send'),\n      Shuffle: t('attachment.actions.shuffle.label', 'Shuffle'),\n    }),\n    [t],\n  );\n\n  const focusIndex = useMemo(() => {\n    if (!defaultFocusedActionValue) return null;\n    const index = actions.findIndex(\n      (action) => action.value === defaultFocusedActionValue,\n    );\n    return index >= 0 ? index : null;\n  }, [actions, defaultFocusedActionValue]);\n\n  useEffect(() => {\n    if (focusIndex === null) return;\n    const button = buttonRefs.current[focusIndex];\n    if (button && document.activeElement !== button) {\n      // Remember where focus is (e.g. the composer) before taking it, so a terminal action can\n      // return it with `restoreFocusReturn()`.\n      reserveFocusReturn();\n      button.focus();\n    }\n  }, [focusIndex, reserveFocusReturn]);\n\n  // Shuffle swaps the GIF in place and focus stays on the Shuffle button, so the change is\n  // announced via the live region. The initial mount is skipped: the focused control's\n  // description already conveys the preview.\n  useEffect(() => {\n    if (!isGiphy) return;\n    if (!giphyImageInitializedRef.current) {\n      giphyImageInitializedRef.current = true;\n      previousGiphyImageRef.current = giphyImageIdentity;\n      return;\n    }\n    if (giphyImageIdentity === previousGiphyImageRef.current) return;\n    previousGiphyImageRef.current = giphyImageIdentity;\n    // Giphy payloads rarely have a title, so this usually announces just \"Giphy image changed\".\n    announceInteraction('giphy.shuffled', { title: descriptiveTitle });\n  }, [announceInteraction, descriptiveTitle, giphyImageIdentity, isGiphy]);\n\n  const groupProps = isGiphy\n    ? {\n        'aria-label': t('attachment.actions.giphyActions.ariaLabel', 'Giphy actions'),\n        role: 'group' as const,\n      }\n    : {};\n\n  return (\n    <div className='str-chat__message-attachment-actions'>\n      <div className='str-chat__message-attachment-actions-form' {...groupProps}>\n        <span>{text}</span>\n        {actions.map((action, index) => {\n          const label = action.text\n            ? (knownActionText[action.text] ?? t(asDynamicKey(action.text)))\n            : null;\n\n          return (\n            <Button\n              appearance='ghost'\n              // Only the auto-focused action carries the preview description, so it is spoken with\n              // the focus announcement.\n              aria-describedby={\n                isGiphy && action.value === defaultFocusedActionValue\n                  ? giphyDescriptionId\n                  : undefined\n              }\n              // Gives giphy buttons a self-contained accessible name so surrounding list or\n              // group context does not swallow the action label.\n              aria-label={isGiphy ? (label ?? undefined) : undefined}\n              className={clsx(\n                `str-chat__message-attachment-actions-button str-chat__message-attachment-actions-button--${action.style}`,\n              )}\n              data-testid={`${action.name}`}\n              data-value={action.value}\n              key={`${id}-${action.value}`}\n              onClick={(event) => handleActionClick(event, action.name, action.value)}\n              ref={(element) => {\n                buttonRefs.current[index] = element;\n              }}\n              variant='secondary'\n            >\n              {label}\n            </Button>\n          );\n        })}\n        {isGiphy && (\n          <VisuallyHidden id={giphyDescriptionId}>\n            {t(\n              'attachment.actions.giphyPreviewOnlyVisible.ariaLabel',\n              'Giphy preview, only visible to you. Use the Send, Shuffle, or Cancel actions.',\n            )}\n          </VisuallyHidden>\n        )}\n      </div>\n    </div>\n  );\n};\n\n/** Renders the actions that can be taken on an attachment. */\nexport const AttachmentActions = React.memo(\n  UnMemoizedAttachmentActions,\n) as typeof UnMemoizedAttachmentActions;\n"],"mappings":";;;;;;;;;;;;AA+BA,IAAa,uCAA4E,EACvF,OAAO,OACT;AAEA,IAAM,+BAA+B,UAAkC;CACrE,MAAM,EACJ,eACA,SACA,2BACA,OACA,IACA,WAAW,UACX,MACA,WAAW,UACX,OACA,SACE;CACJ,MAAM,EAAE,MAAM,sBAAsB;CACpC,MAAM,EAAE,wBAAwB,4BAA4B;CAC5D,MAAM,EAAE,SAAS,oBAAoB,SAAS,uBAAuB,eAAe;CACpF,MAAM,aAAa,OAAwC,CAAC,CAAC;CAE7D,MAAM,UAAU,SAAS;CAIzB,MAAM,qBAAqB,YAAY;CAIvC,MAAM,mBAAmB,UAAU,yBAAyB,KAAK,IAAI,KAAA;CAGrE,MAAM,qBAAqB,UACtB,OAAO,UAAU,OAAO,YAAY,YAAY,OACjD;CACJ,MAAM,wBAAwB,OAAsB,IAAI;CACxD,MAAM,2BAA2B,OAAO,KAAK;CAE7C,MAAM,qBACJ,OACA,MACA,UACG;EACH,gBAAgB,MAAM,OAAO,KAAK;EAMlC,IAAI,YAAY,UAAU,UAAU,UAAU,WAAW;GACvD,mBAAmB;GACnB,MAAM,cAAc,UAAU,SAAS,eAAe;GACtD,4BAA4B,oBAAoB,WAAW,CAAC;EAC9D;CACF;CAEA,MAAM,kBAAkB,eACf;EACL,QAAQ,EAAE,uBAAuB,QAAQ;EACzC,MAAM,EAAE,qBAAqB,MAAM;EACnC,SAAS,EAAE,oCAAoC,SAAS;CAC1D,IACA,CAAC,CAAC,CACJ;CAEA,MAAM,aAAa,cAAc;EAC/B,IAAI,CAAC,2BAA2B,OAAO;EACvC,MAAM,QAAQ,QAAQ,WACnB,WAAW,OAAO,UAAU,yBAC/B;EACA,OAAO,SAAS,IAAI,QAAQ;CAC9B,GA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