{"version":3,"file":"ShareLocationDialog.mjs","names":[],"sources":["../../../../src/components/Location/ShareLocationDialog.tsx"],"sourcesContent":["import React, {\n  type ComponentType,\n  useCallback,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react';\nimport { useComponentContextIcons, useTranslationContext } from '../../context';\nimport { ContextMenuBody, ContextMenuButton, ContextMenuRoot, Prompt } from '../Dialog';\nimport {\n  Dropdown,\n  type DropdownTriggerProps,\n  useDropdownContext,\n} from '../Form/Dropdown';\nimport { useMessageComposerController } from '../MessageComposer/hooks/useMessageComposerController';\nimport { SwitchField } from '../Form/SwitchField';\nimport { useNotificationApi } from '../Notifications';\nimport type { Coords } from 'stream-chat';\nimport { Button } from '../Button';\nimport clsx from 'clsx';\n\nconst MIN_LIVE_LOCATION_SHARE_DURATION = 60 * 1000; // 1 minute\n\n// Time the browser gets to produce a position. A first fix (e.g. a cold GPS start)\n// can take several seconds.\nconst GEOLOCATION_TIMEOUT_MS = 10 * 1000;\n\nconst DEFAULT_SHARE_LOCATION_DURATIONS = [\n  15 * 60 * 1000, // 15 minutes\n  60 * 60 * 1000, // 1 hour\n  8 * 60 * 60 * 1000, // 8 hours\n];\n\nexport type ShareGeolocationMapProps = Partial<Coords> & {\n  loadingLocation: boolean;\n  restartLocationWatching: () => void;\n  geolocationPositionError?: GeolocationPositionError;\n};\n\nexport type ShareLocationDialogProps = {\n  close: () => void;\n  shareDurations?: number[];\n  GeolocationMap?: ComponentType<ShareGeolocationMapProps>;\n  DurationDropdownItems?: ComponentType<DurationDropdownItemsProps>;\n};\n\nconst DefaultGeolocationMap = () => null;\n\nconst LiveLocationDurationTrigger = ({\n  children,\n  onClick,\n  referenceRef,\n  ...props\n}: DropdownTriggerProps) => (\n  <Button\n    {...props}\n    className='str-chat__live-location-sharing-duration-selector__button'\n    onClick={onClick}\n    ref={referenceRef as React.Ref<HTMLButtonElement>}\n    type='button'\n  >\n    {children}\n  </Button>\n);\n\nexport const ShareLocationDialog = ({\n  close,\n  GeolocationMap = DefaultGeolocationMap,\n  shareDurations = DEFAULT_SHARE_LOCATION_DURATIONS,\n}: ShareLocationDialogProps) => {\n  const { IconChevronDown } = useComponentContextIcons();\n  const { addNotification } = useNotificationApi();\n  const { t } = useTranslationContext();\n  const messageComposer = useMessageComposerController();\n  const [durations, setDurations] = useState<number[]>([]);\n  const [selectedDuration, setSelectedDuration] = useState<number | undefined>(undefined);\n  const [geolocationPosition, setGeolocationPosition] =\n    useState<GeolocationPosition | null>(null);\n  const [loadingLocation, setLoadingLocation] = useState<boolean>(false);\n  const [geolocationPositionError, setGeolocationPositionError] = useState<\n    GeolocationPositionError | undefined\n  >(undefined);\n\n  const validShareDurations = useMemo(\n    () => shareDurations.filter((d) => d >= MIN_LIVE_LOCATION_SHARE_DURATION),\n    [shareDurations],\n  );\n\n  const selectedDurationLabel = useMemo(\n    () =>\n      durations.length > 0\n        ? t('duration.shareLocation', {\n            milliseconds: selectedDuration ?? durations[0],\n          })\n        : undefined,\n    [durations, selectedDuration, t],\n  );\n\n  const durationTriggerProps = useMemo(\n    () => ({\n      children: selectedDurationLabel ? (\n        <>\n          <span>{selectedDurationLabel}</span>\n          <IconChevronDown />\n        </>\n      ) : null,\n    }),\n    [IconChevronDown, selectedDurationLabel],\n  );\n\n  const getPosition = useCallback(\n    (): Promise<GeolocationPosition> =>\n      new Promise((resolve, reject) => {\n        navigator.geolocation.getCurrentPosition(\n          (position) => {\n            resolve(position);\n          },\n          (positionError) => {\n            console.warn(positionError);\n            reject(positionError);\n          },\n          { timeout: GEOLOCATION_TIMEOUT_MS },\n        );\n      }),\n    [],\n  );\n\n  // The dialog runs at most one position watch: its id is kept here so that a restart\n  // and unmount can clear it.\n  const watchIdRef = useRef<number | undefined>(undefined);\n  // Bumped whenever a watch stops. A callback the browser queued before clearWatch still\n  // runs, and its watch's generation no longer matches, so it leaves the state alone.\n  const watchGenerationRef = useRef(0);\n\n  const stopPositionWatching = useCallback(() => {\n    watchGenerationRef.current += 1;\n    if (watchIdRef.current === undefined) return;\n    navigator.geolocation.clearWatch(watchIdRef.current);\n    watchIdRef.current = undefined;\n  }, []);\n\n  const startPositionWatching = useCallback(() => {\n    stopPositionWatching();\n    setLoadingLocation(true);\n    const watchGeneration = watchGenerationRef.current;\n    const isStoppedWatch = () => watchGeneration !== watchGenerationRef.current;\n    let watchHasPosition = false;\n    watchIdRef.current = navigator.geolocation.watchPosition(\n      (position) => {\n        if (isStoppedWatch()) return;\n        watchHasPosition = true;\n        setGeolocationPosition(position);\n        setLoadingLocation(false);\n        setGeolocationPositionError(undefined);\n      },\n      (error) => {\n        if (isStoppedWatch()) return;\n        // Some browsers (e.g. Firefox) report TIMEOUT whenever a stationary device\n        // produces no new position in time. The last position stays valid then.\n        const isTimeoutAfterPosition = watchHasPosition && error.code === error.TIMEOUT;\n        if (isTimeoutAfterPosition) return;\n        setGeolocationPosition(null);\n        setLoadingLocation(false);\n        setGeolocationPositionError(error);\n      },\n      { timeout: GEOLOCATION_TIMEOUT_MS },\n    );\n  }, [stopPositionWatching]);\n\n  useEffect(() => {\n    startPositionWatching();\n    return stopPositionWatching;\n  }, [startPositionWatching, stopPositionWatching]);\n\n  const liveLocationSwitchEnabled = durations.length > 0;\n  return (\n    <Prompt.Root\n      className='str-chat__share-location-dialog'\n      data-testid='share-location-dialog'\n    >\n      <Prompt.Header\n        close={close}\n        description={t(\n          'location.shareLocationDialog.description',\n          'Select your current location and optionally enable live location sharing',\n        )}\n        title={t('location.shareLocationDialog.shareLocation.title', 'Share Location')}\n      />\n      <Prompt.Body>\n        <GeolocationMap\n          geolocationPositionError={geolocationPositionError}\n          latitude={geolocationPosition?.coords.latitude}\n          loadingLocation={loadingLocation}\n          longitude={geolocationPosition?.coords.longitude}\n          restartLocationWatching={startPositionWatching}\n        />\n        {validShareDurations.length > 0 && (\n          <div\n            className={clsx('str-chat__live-location-activation', {\n              'str-chat__live-location-activation--expanded': liveLocationSwitchEnabled,\n            })}\n          >\n            <SwitchField\n              checked={liveLocationSwitchEnabled}\n              data-testid='share-location-dialog-live-location-switch'\n              disabled={!geolocationPosition}\n              onChange={(e) => {\n                e.stopPropagation();\n                if (liveLocationSwitchEnabled) {\n                  setDurations([]);\n                  setSelectedDuration(undefined);\n                } else {\n                  setDurations(validShareDurations);\n                  setSelectedDuration(validShareDurations[0]);\n                }\n              }}\n              title={t(\n                'location.shareLocationDialog.shareLiveLocation.title',\n                'Share live location for',\n              )}\n            />\n            {liveLocationSwitchEnabled && selectedDurationLabel && (\n              <div className='str-chat__live-location-sharing-duration-selector'>\n                <Dropdown\n                  placement='bottom-start'\n                  TriggerComponent={LiveLocationDurationTrigger}\n                  triggerProps={durationTriggerProps}\n                >\n                  <DurationDropdownItems\n                    durations={durations}\n                    selectDuration={setSelectedDuration}\n                    selectedDuration={selectedDuration}\n                  />\n                </Dropdown>\n              </div>\n            )}\n          </div>\n        )}\n      </Prompt.Body>\n      <Prompt.Footer>\n        <Prompt.FooterControls>\n          <Prompt.FooterControlsButtonSecondary\n            className='str-chat__prompt__footer__controls-button--cancel'\n            onClick={() => {\n              messageComposer.locationComposer.initState();\n              close();\n            }}\n          >\n            {t('common.cancel.label', 'Cancel')}\n          </Prompt.FooterControlsButtonSecondary>\n          <Prompt.FooterControlsButtonSecondary\n            className='str-chat__prompt__footer__controls-button--submit'\n            disabled={!geolocationPosition}\n            onClick={async () => {\n              let coords = geolocationPosition && {\n                latitude: geolocationPosition.coords.latitude,\n                longitude: geolocationPosition.coords.longitude,\n              };\n              if (!coords) {\n                coords = (await getPosition()).coords;\n              }\n              messageComposer.locationComposer.setData({\n                ...coords,\n                durationMs: selectedDuration,\n              });\n              close();\n            }}\n            type='submit'\n          >\n            {t('location.shareLocationDialog.attach.text', 'Attach')}\n          </Prompt.FooterControlsButtonSecondary>\n          <Prompt.FooterControlsButtonPrimary\n            className='str-chat__prompt__footer__controls-button--submit'\n            disabled={!geolocationPosition}\n            onClick={async () => {\n              let coords = geolocationPosition && {\n                latitude: geolocationPosition.coords.latitude,\n                longitude: geolocationPosition.coords.longitude,\n              };\n              if (!coords) {\n                try {\n                  coords = (await getPosition()).coords;\n                } catch (e) {\n                  addNotification({\n                    emitter: 'ShareLocationDialog',\n                    error: e instanceof Error ? e : undefined,\n                    message: t(\n                      'notification.locationGetFailed',\n                      'Failed to retrieve location',\n                    ),\n                    severity: 'error',\n                    type: 'browser:location:get:failed',\n                  });\n                  return;\n                }\n              }\n\n              messageComposer.locationComposer.setData({\n                ...coords,\n                durationMs: selectedDuration,\n              });\n              try {\n                await messageComposer.sendLocation();\n              } catch (err) {\n                addNotification({\n                  emitter: 'ShareLocationDialog',\n                  error: err instanceof Error ? err : undefined,\n                  message: t(\n                    'notification.locationShareFailed',\n                    'Failed to share location',\n                  ),\n                  severity: 'error',\n                  type: 'api:location:share:failed',\n                });\n                return;\n              }\n              close();\n            }}\n            type='submit'\n          >\n            {t('location.shareLocationDialog.share.text', 'Share')}\n          </Prompt.FooterControlsButtonPrimary>\n        </Prompt.FooterControls>\n      </Prompt.Footer>\n    </Prompt.Root>\n  );\n};\n\nexport type DurationDropdownItemsProps = {\n  durations: number[];\n  selectedDuration?: number;\n  selectDuration: (duration: number) => void;\n};\nconst DurationDropdownItems = ({\n  durations,\n  selectDuration,\n  selectedDuration,\n}: DurationDropdownItemsProps) => {\n  const { t } = useTranslationContext();\n  const { close } = useDropdownContext();\n  return (\n    <ContextMenuRoot>\n      <ContextMenuBody>\n        {durations.map((duration) => (\n          <ContextMenuButton\n            aria-checked={selectedDuration === duration}\n            className='str-chat__live-location-sharing-duration-option'\n            key={`duration-${duration}`}\n            onClick={() => {\n              selectDuration(duration);\n              close();\n            }}\n            role='menuitemradio'\n          >\n            {t('duration.shareLocation', { milliseconds: duration })}\n          </ContextMenuButton>\n        ))}\n      </ContextMenuBody>\n    </ContextMenuRoot>\n  );\n};\n"],"mappings":";;;;;;;;;;;;;AAsBA,IAAM,mCAAmC,KAAK;AAI9C,IAAM,yBAAyB,KAAK;AAEpC,IAAM,mCAA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