{"version":3,"file":"OptionFieldSet.mjs","names":[],"sources":["../../../../../src/components/Poll/PollCreationDialog/OptionFieldSet.tsx"],"sourcesContent":["import clsx from 'clsx';\nimport React, { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { TextInput } from '../../Form/TextInput';\nimport { useTranslationContext } from '../../../context';\nimport { useMessageComposerController } from '../../MessageComposer/hooks/useMessageComposerController';\nimport { useStateStore } from '../../../store';\nimport { POLL_COMPOSER_VALIDATION_CODE } from 'stream-chat';\nimport type {\n  PollComposerOption,\n  PollComposerState,\n  PollComposerValidationCode,\n} from 'stream-chat';\nimport { useComponentContextIcons } from '../../../context';\nimport { Button, type ButtonProps } from '../../Button';\nimport { TextInputFieldSet } from '../../Form/TextInputFieldSet';\nimport { VisuallyHidden } from '../../VisuallyHidden';\nimport { useStableId } from '../../UtilityComponents/useStableId';\nimport {\n  useAriaLiveAnnouncer,\n  useInteractionAnnouncements,\n  useSettledAnnouncement,\n} from '../../Accessibility';\nimport { PollOptionReorderHandle } from './PollOptionReorderHandle';\n\nconst pollComposerStateSelector = (state: PollComposerState) => ({\n  errors: state.errors.options,\n  options: state.data.options,\n});\n\n/**\n * Option inputs of the poll creation dialog, with reorder and removal. Announcements are delivered\n * through the modal `AriaLiveOutlet`, because screen readers ignore live regions outside the active\n * `aria-modal` container.\n */\nexport const OptionFieldSet = () => {\n  const { pollComposer } = useMessageComposerController();\n  const { errors, options } = useStateStore(\n    pollComposer.state,\n    pollComposerStateSelector,\n  );\n  const { t } = useTranslationContext();\n  const announce = useAriaLiveAnnouncer();\n  const { announceInteraction } = useInteractionAnnouncements();\n  const optionInputRefs = useRef<Array<HTMLInputElement | null>>([]);\n  const handleRefs = useRef<Array<HTMLButtonElement | null>>([]);\n  const pendingFocusIndexRef = useRef<number | null>(null);\n  const [activeOptionId, setActiveOptionId] = useState<string | null>(null);\n\n  const knownValidationErrors = useMemo<\n    Partial<Record<PollComposerValidationCode, string>>\n  >(\n    () => ({\n      [POLL_COMPOSER_VALIDATION_CODE.optionDuplicate]: t(\n        'poll.suggestPollOption.optionAlreadyExists.label',\n        'Option already exists',\n      ),\n      [POLL_COMPOSER_VALIDATION_CODE.optionEmpty]: t(\n        'poll.optionFieldSet.optionEmpty.label',\n        'Option is empty',\n      ),\n    }),\n    [t],\n  );\n\n  const labelForOption = useCallback(\n    (option: PollComposerOption, position: number) =>\n      option.text.trim() ||\n      t('poll.optionFieldSet.option.ariaLabel', 'Option {{ position }}', { position }),\n    [t],\n  );\n\n  const registerHandleRef = useCallback(\n    (index: number, element: HTMLButtonElement | null) => {\n      handleRefs.current[index] = element;\n    },\n    [],\n  );\n\n  const onSetNewOrder = useCallback(\n    (newOrder: number[]) => {\n      const prevOptions = pollComposer.options;\n      pollComposer.updateFields({\n        data: { options: newOrder.map((index) => prevOptions[index]) },\n      });\n    },\n    [pollComposer],\n  );\n\n  const clearOption = useCallback(\n    (removedOptionId: string) => {\n      const nextOptions = [...pollComposer.options];\n      if (!nextOptions.length) return;\n\n      const removedOptionIndex = pollComposer.options.findIndex(\n        (option) => option.id === removedOptionId,\n      );\n\n      if (removedOptionIndex === -1) return;\n      const [removedOption] = nextOptions.splice(removedOptionIndex, 1);\n\n      pollComposer.updateFields({ data: { options: nextOptions } });\n\n      // Polite, so it queues behind the focus move to the next field instead of interrupting it.\n      announceInteraction('poll.optionRemoved', {\n        option: labelForOption(removedOption, removedOptionIndex + 1),\n      });\n\n      if (activeOptionId === removedOptionId) {\n        setActiveOptionId(null);\n      }\n\n      if (!nextOptions.length) return;\n      const nextFocusedOptionIndex = Math.min(removedOptionIndex, nextOptions.length - 1);\n      requestAnimationFrame(() => {\n        optionInputRefs.current[nextFocusedOptionIndex]?.focus();\n      });\n    },\n    [activeOptionId, announceInteraction, labelForOption, pollComposer],\n  );\n\n  const handleActivate = useCallback(\n    (optionId: string) => {\n      const idx = pollComposer.options.findIndex((option) => option.id === optionId);\n      if (idx === -1) return;\n      const option = pollComposer.options[idx];\n      setActiveOptionId(optionId);\n      announceInteraction('poll.optionPickedUp', {\n        option: labelForOption(option, idx + 1),\n      });\n    },\n    [announceInteraction, labelForOption, pollComposer],\n  );\n\n  const handleDeselect = useCallback(() => {\n    if (!activeOptionId) return;\n    const idx = pollComposer.options.findIndex((option) => option.id === activeOptionId);\n    const option = idx === -1 ? null : pollComposer.options[idx];\n\n    setActiveOptionId(null);\n\n    if (!option) return;\n\n    announceInteraction('poll.optionDropped', {\n      option: labelForOption(option, idx + 1),\n      position: idx + 1,\n    });\n  }, [activeOptionId, announceInteraction, labelForOption, pollComposer]);\n\n  const handleMove = useCallback(\n    (direction: -1 | 1) => {\n      if (!activeOptionId) return;\n      const currentIndex = pollComposer.options.findIndex(\n        (option) => option.id === activeOptionId,\n      );\n      if (currentIndex === -1) return;\n      const targetIndex = currentIndex + direction;\n      if (targetIndex < 0 || targetIndex >= pollComposer.options.length) return;\n\n      const nextOptions = [...pollComposer.options];\n      const [moved] = nextOptions.splice(currentIndex, 1);\n      nextOptions.splice(targetIndex, 0, moved);\n      pollComposer.updateFields({ data: { options: nextOptions } });\n\n      pendingFocusIndexRef.current = targetIndex;\n      // No announcement: the layout effect below focuses the new handle, and its aria-label\n      // already carries the option text and position.\n    },\n    [activeOptionId, pollComposer],\n  );\n\n  useLayoutEffect(() => {\n    if (pendingFocusIndexRef.current === null) return;\n    const idx = pendingFocusIndexRef.current;\n    pendingFocusIndexRef.current = null;\n    handleRefs.current[idx]?.focus();\n  }, [options]);\n\n  const draggable = options.length > 1;\n\n  // The reorder handle and remove button exist only with 2+ options. Each input's\n  // `aria-describedby` points at hidden text saying so, but VoiceOver does not reliably speak\n  // descriptions, so a polite cue is also announced once. It waits for `options` to go idle: the\n  // screen reader re-reads the focused field when the list mutates, which supersedes live messages.\n  const optionsHintId = useStableId();\n\n  useSettledAnnouncement(announce, {\n    active: draggable,\n    message: t(\n      'poll.optionFieldSet.optionsCanNowReordered.ariaLabel',\n      'Options can now be reordered and removed.',\n    ),\n    settleKey: options,\n  });\n\n  return (\n    <>\n      <TextInputFieldSet\n        draggable={draggable}\n        label={t('poll.optionFieldSet.options.label', 'Options')}\n        onSetNewOrder={onSetNewOrder}\n      >\n        {options.map((option, i) => {\n          const error = errors?.[option.id];\n          return (\n            <div\n              className={clsx('str-chat__form__input-field', {\n                'str-chat__form__input-field--draggable': draggable,\n                'str-chat__form__input-field--has-error': error,\n              })}\n              key={`option-row-${i}`}\n            >\n              <TextInput\n                aria-describedby={draggable ? optionsHintId : undefined}\n                className='str-chat__form__input-field__value'\n                error={!!error}\n                fieldMessagePlacement='inside'\n                id={option.id}\n                leading={\n                  draggable ? (\n                    <PollOptionReorderHandle\n                      index={i}\n                      isActive={option.id === activeOptionId}\n                      onActivate={handleActivate}\n                      onDeselect={handleDeselect}\n                      onMove={handleMove}\n                      option={option}\n                      registerRef={registerHandleRef}\n                      totalOptionCount={options.length}\n                    />\n                  ) : undefined\n                }\n                message={\n                  error ? (\n                    <span data-testid='poll-option-input-field-error'>\n                      {knownValidationErrors[error.code] ?? error.message}\n                    </span>\n                  ) : undefined\n                }\n                onBlur={() => {\n                  pollComposer.handleFieldBlur('options');\n                }}\n                onChange={(e) => {\n                  pollComposer.updateFields({\n                    data: { options: { index: i, text: e.target.value } },\n                  });\n                }}\n                onKeyUp={(event) => {\n                  const isFocusedLastOptionField = i === options.length - 1;\n                  if (event.key === 'Enter' && !isFocusedLastOptionField) {\n                    optionInputRefs.current[i + 1]?.focus();\n                  }\n                }}\n                placeholder={t(\n                  'poll.optionFieldSet.addOption.placeholder',\n                  'Add an Option',\n                )}\n                ref={(element) => {\n                  optionInputRefs.current[i] = element;\n                }}\n                trailing={\n                  draggable ? (\n                    <RemoveOptionButton\n                      // Named after its option so screen reader users can tell the rows apart.\n                      aria-label={t(\n                        'poll.optionFieldSet.removeOption.ariaLabel',\n                        'Remove option: {{ option }}',\n                        {\n                          option: labelForOption(option, i + 1),\n                        },\n                      )}\n                      onClick={() => clearOption(option.id)}\n                    />\n                  ) : undefined\n                }\n                type='text'\n                value={option.text}\n              />\n            </div>\n          );\n        })}\n      </TextInputFieldSet>\n      {draggable && (\n        <VisuallyHidden id={optionsHintId}>\n          {t(\n            'poll.optionFieldSet.optionCanReorderedRemoved.ariaLabel',\n            'This option can be reordered and removed.',\n          )}\n        </VisuallyHidden>\n      )}\n    </>\n  );\n};\n\nconst RemoveOptionButton = ({ className, ...props }: ButtonProps) => {\n  const { IconMinusCircle } = useComponentContextIcons();\n\n  return (\n    <Button\n      appearance='ghost'\n      circular\n      className={clsx('str-chat__form__remove-option-button', className)}\n      size='xs'\n      variant='secondary'\n      {...props}\n    >\n      <IconMinusCircle />\n    </Button>\n  );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwBA,IAAM,6BAA6B,WAA8B;CAC/D,QAAQ,MAAM,OAAO;CACrB,SAAS,MAAM,KAAK;AACtB;;;;;;AAOA,IAAa,uBAAuB;CAClC,MAAM,EAAE,iBAAiB,6BAA6B;CACtD,MAAM,EAAE,QAAQ,YAAY,cAC1B,aAAa,OACb,yBACF;CACA,MAAM,EAAE,MAAM,sBAAsB;CACpC,MAAM,WAAW,qBAAqB;CACtC,MAAM,EAAE,wBAAwB,4BAA4B;CAC5D,MAAM,kBAAkB,OAAuC,CAAC,CAAC;CACjE,MAAM,aAAa,OAAwC,CAAC,CAAC;CAC7D,MAAM,uBAAuB,OAAsB,IAAI;CACvD,MAAM,CAAC,gBAAgB,qBAAqB,SAAwB,IAAI;CAExE,MAAM,wBAAwB,eAGrB;GACJ,8BAA8B,kBAAkB,EAC/C,oDACA,uBACF;GACC,8BAA8B,cAAc,EAC3C,yCACA,iBACF;CACF,IACA,CAAC,CAAC,CACJ;CAEA,MAAM,iBAAiB,aACpB,QAA4B,aAC3B,OAAO,KAAK,KAAK,KACjB,EAAE,wCAAwC,yBAAyB,EAAE,SAAS,CAAC,GACjF,CAAC,CAAC,CACJ;CAEA,MAAM,oBAAoB,aACvB,OAAe,YAAsC;EACpD,WAAW,QAAQ,SAAS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