Skip to content

Send files directly between devices over the internet - no cloud storage, no size limits.

14.5 KB
Raw Blame
import { useState } from 'react'
import { Platform, Pressable, ScrollView, Share, StyleSheet, View } from 'react-native'
import * as Clipboard from 'expo-clipboard'
import {
  buildShareInvite,
  buildWebReceiveUrl,
  exceedsWebLinkLimit,
  useSubscriptionStore,
  formatFileSize,
  formatItemsCount,
  useShareViewModel,
  WEB_LINK_MAX_LABEL,
  type DeviceRenameTarget
} from '@altersend/domain'
import { Button, Input, LinkCard, LinkRow, WaitingRadar, useTheme } from '@altersend/components'
import {
  CheckIcon,
  ChevronsUpDownIcon,
  CopyIcon,
  deviceIcon,
  FolderIcon,
  QrCodeIcon,
  LinkIcon,
  ShareIcon
} from '@altersend/components/icons'
import { useTranslation } from '@altersend/locales'
import { useRouter } from 'expo-router'
import { useToast } from '@/src/components/Toast'
import { mediumTap, successTap } from '@/src/haptics'
import { ConfirmDialog, DeviceActionsSheet, DeviceRenameSheet } from '@/src/components'
import { useDeviceRename } from '@/src/pairing/useDeviceRename'
import { useDeviceRemove } from '@/src/pairing/useDeviceRemove'
import { QRSection } from './QRSection'
import { ShareQrSheet } from './ShareQrSheet'
import { ShareFilesSheet } from './ShareFilesSheet'
import { Text } from '@/src/components/ThemedText'

const TILE_GAP = 12

export function ShareView() {
  const { t } = useTranslation(['send', 'common', 'settings'])
  const { theme } = useTheme()
  const c = theme.colors
  const toast = useToast()
  const router = useRouter()
  const vm = useShareViewModel(t, {
    onPeerJoined: (peer) =>
      toast.show({
        title: peer.isKnown
          ? t('send:status.deviceConnected', { name: peer.name })
          : t('send:status.peerConnected'),
        durationMs: 2500
      }),
    onPeerPaired: (peer) =>
      toast.show({ title: t('send:status.pairedToast', { name: peer.name }), durationMs: 2500 }),
    onPeerDownloaded: successTap,
    onInviteFailed: (peer) =>
      toast.show({
        title: t('send:status.inviteFailedToast', { name: peer.name }),
        hint: t('send:status.inviteFailedHint'),
        tone: 'error',
        durationMs: 3500
      }),
    onPeerOutdated: () =>
      toast.show({ title: t('send:status.peerOutdated'), tone: 'error', durationMs: 4000 })
  })
  const [isFilesSheetOpen, setIsFilesSheetOpen] = useState(false)
  const [isQrOpen, setIsQrOpen] = useState(false)
  const [contentWidth, setContentWidth] = useState(0)
  const [actionsTarget, setActionsTarget] = useState<DeviceRenameTarget | null>(null)
  const { openRename, renameSheet } = useDeviceRename(vm.rename)
  const { confirmRemove, removeDialog } = useDeviceRemove(vm.forget)

  const copyTopic = async () => {
    if (!vm.topic) return
    try {
      await Clipboard.setStringAsync(vm.topic)
      vm.markCopied()
      toast.show({ title: t('send:connection.copiedToast') })
    } catch (error) {
      console.error(error)
    }
  }

  const pro = useSubscriptionStore((state) => state.active)
  const webLinkTooLarge = exceedsWebLinkLimit(vm.totalSize, pro)
  const tileCount = 3
  const tileWidth =
    contentWidth > 0 ? (contentWidth - TILE_GAP * (tileCount - 1)) / tileCount : undefined

  const shareLink = async () => {
    if (!vm.topic) return
    if (webLinkTooLarge) {
      router.push('/account')
      return
    }

    try {
      const link = buildWebReceiveUrl(vm.topic, process.env.EXPO_PUBLIC_WEB_URL)
      await Clipboard.setStringAsync(link)
      await Share.share({
        message: buildShareInvite(t, {
          link,
          fileCount: vm.files.length,
          textCount: vm.texts.length,
          totalSize: vm.totalSize
        })
      })
      toast.show({
        title: t('send:connection.copiedToast'),
        hint: pro ? undefined : t('send:connection.linkHint', { limit: WEB_LINK_MAX_LABEL })
      })
    } catch (error) {
      console.error(error)
    }
  }

  return (
    <>
      <ScrollView
        style={styles.container}
        contentContainerStyle={styles.content}
        onLayout={(event) => setContentWidth(event.nativeEvent.layout.width)}
      >
        {vm.phase === 'waiting' && (
          <View style={styles.statusStrip}>
            <WaitingRadar
              size={60}
              color={c.colorInfo}
              pulsing
              icon={<ShareIcon size={16} color={c.colorInfo} />}
            />
            <View style={styles.statusText}>
              <Text style={[styles.statusTitle, { color: c.colorTextPrimary }]}>
                {t('send:status.waitingForJoin')}
              </Text>
              {Platform.OS === 'ios' && (
                <Text style={[styles.statusCaption, { color: c.colorTextMuted }]} numberOfLines={1}>
                  {t('send:hints.stayInApp')}
                </Text>
              )}
            </View>
          </View>
        )}

        {vm.hasDevices ? (
          <View style={styles.tiles}>
            <View style={[styles.tile, { width: tileWidth }]}>
              <Button
                stack
                size='sm'
                variant='secondary'
                width='full'
                icon={vm.isCopied ? <CheckIcon size={18} /> : <CopyIcon size={18} />}
                onClick={() => void copyTopic()}
              >
                {vm.isCopied ? t('common:actions.copied') : t('send:connection.copyCode')}
              </Button>
            </View>
            <View style={[styles.tile, { width: tileWidth }]}>
              <Button
                stack
                size='sm'
                variant='secondary'
                width='full'
                disabled={!vm.topic}
                icon={<LinkIcon size={18} />}
                onClick={() => void shareLink()}
              >
                {t('send:connection.shareLink')}
              </Button>
            </View>
            <View style={[styles.tile, { width: tileWidth }]}>
              <Button
                stack
                size='sm'
                variant='secondary'
                width='full'
                icon={<QrCodeIcon size={18} />}
                onClick={() => setIsQrOpen(true)}
              >
                {t('send:connection.qrCode')}
              </Button>
            </View>
          </View>
        ) : (
          <View style={styles.invitePanel}>
            <QRSection
              topic={vm.topic}
              showWaitingState={false}
              size={200}
              style={styles.qrPanelSection}
            />
            <View style={styles.keyRow}>
              <View style={styles.keyInput}>
                <Input
                  aria-label={t('send:connection.copyLabel')}
                  placeholder={t('send:connection.placeholder')}
                  readOnly
                  trailing={
                    <Button
                      variant={vm.isCopied ? 'success' : 'ghost'}
                      size='sm'
                      iconOnly
                      aria-label={t('send:connection.copyLabel')}
                      disabled={!vm.topic}
                      onClick={() => void copyTopic()}
                      icon={vm.isCopied ? <CheckIcon size={16} /> : <CopyIcon size={16} />}
                    />
                  }
                  value={vm.topic}
                />
              </View>
              <View style={styles.keyAction}>
                <Button
                  variant='secondary'
                  width='full'
                  iconOnly
                  aria-label={t('send:connection.shareLink')}
                  disabled={!vm.topic}
                  icon={<LinkIcon size={18} />}
                  onClick={() => void shareLink()}
                />
              </View>
            </View>
          </View>
        )}

        {(vm.files.length > 0 || vm.texts.length > 0) && (
          <View style={styles.filesWrap}>
            <LinkCard>
              <LinkRow
                icon={<FolderIcon size={20} color={c.colorTextSecondary} />}
                label={formatItemsCount(vm.files.length, vm.texts.length, t)}
                subtitle={vm.totalSize > 0 ? formatFileSize(vm.totalSize) : undefined}
                onPress={() => setIsFilesSheetOpen(true)}
                trailing={<ChevronsUpDownIcon size={18} color={c.colorTextMuted} />}
                isLast
              />
            </LinkCard>
          </View>
        )}

        {vm.hasDevices && (
          <>
            <View style={styles.sectionHeader}>
              <Text style={[styles.sectionLabel, { color: c.colorTextMuted }]}>
                {t('send:peer.devices')}
              </Text>
              {vm.connectedCount > 0 && (
                <Text style={[styles.sectionCount, { color: c.colorTextMuted }]}>
                  {t('send:peer.connectedCount', { count: vm.connectedCount })}
                </Text>
              )}
            </View>
            <View style={styles.section}>
              <LinkCard>
                {vm.devices.map((row, index) => {
                  const isLast = index === vm.devices.length - 1
                  const openActions = () => {
                    mediumTap()
                    setActionsTarget({ peerKey: row.peerKey, name: row.name })
                  }
                  if (row.kind === 'connected') {
                    const Icon = row.deviceType ? deviceIcon(row.deviceType) : null
                    return (
                      <Pressable key={row.peerKey} onLongPress={openActions}>
                        <LinkRow
                          icon={
                            Icon ? (
                              <Icon size={18} color={c.colorTextSecondary} />
                            ) : (
                              <Text style={[styles.initials, { color: c.colorInfo }]}>
                                {row.name.slice(0, 2).toUpperCase()}
                              </Text>
                            )
                          }
                          iconBackground={Icon ? c.colorSurfacePrimary : c.colorInfoSubtle}
                          label={row.name}
                          subtitle={row.subtitle}
                          subtitleTone={row.subtitleTone}
                          status={row.status}
                          progressPercent={row.progressPercent}
                          trailing={
                            row.action === 'pair' ? (
                              <Button
                                onClick={() => vm.pair(row.peerKey)}
                                size='sm'
                                variant='secondary'
                                pill
                              >
                                {t('send:peer.pair')}
                              </Button>
                            ) : row.action === 'pair-requested' ? (
                              <Button size='sm' variant='secondary' pill loading>
                                {t('send:peer.requested')}
                              </Button>
                            ) : null
                          }
                          isLast={isLast}
                        />
                      </Pressable>
                    )
                  }
                  const PeerIcon = deviceIcon(row.deviceType)
                  const isActive = row.action === 'inviting' || row.action === 'invite-sent'
                  const label =
                    row.action === 'inviting'
                      ? t('send:peer.inviting')
                      : row.action === 'invite-sent'
                        ? t('send:peer.sent')
                        : t('send:peer.invite')
                  return (
                    <Pressable key={row.peerKey} onLongPress={openActions}>
                      <LinkRow
                        icon={<PeerIcon size={18} color={c.colorTextSecondary} />}
                        label={row.name}
                        subtitle={row.subtitle}
                        subtitleTone={row.subtitleTone}
                        onPress={() => void vm.invite(row.peerKey)}
                        trailing={
                          <Button
                            disabled={isActive}
                            loading={isActive}
                            onClick={() => void vm.invite(row.peerKey)}
                            size='sm'
                            variant='primary'
                            pill
                          >
                            {label}
                          </Button>
                        }
                        isLast={isLast}
                      />
                    </Pressable>
                  )
                })}
              </LinkCard>
            </View>
          </>
        )}
      </ScrollView>

      <ShareQrSheet open={isQrOpen} topic={vm.topic} onClose={() => setIsQrOpen(false)} />

      <DeviceActionsSheet
        open={actionsTarget !== null}
        onClose={() => setActionsTarget(null)}
        onRemove={() => {
          const target = actionsTarget
          setActionsTarget(null)
          if (target) confirmRemove(target)
        }}
        onRename={() => {
          const target = actionsTarget
          setActionsTarget(null)
          if (target) openRename(target)
        }}
      />

      <ConfirmDialog {...removeDialog} />

      <DeviceRenameSheet {...renameSheet} />

      <ShareFilesSheet
        open={isFilesSheetOpen}
        files={vm.files}
        texts={vm.texts}
        totalSize={vm.totalSize}
        onClose={() => setIsFilesSheetOpen(false)}
      />
    </>
  )
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  content: { paddingTop: 0, paddingBottom: 16 },
  statusStrip: { flexDirection: 'row', alignItems: 'center', gap: 12, marginBottom: 24 },
  statusText: { flex: 1, minWidth: 0 },
  statusTitle: { fontSize: 16, fontWeight: '700' },
  statusCaption: { fontSize: 12.5, lineHeight: 17, marginTop: 2 },
  sectionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 4,
    marginBottom: 8
  },
  sectionLabel: { fontSize: 13, fontWeight: '500' },
  sectionCount: { fontSize: 11.5, fontWeight: '500' },
  section: { marginBottom: 16 },
  filesWrap: { marginBottom: 24 },
  tiles: {
    flexDirection: 'row',
    alignItems: 'stretch',
    width: '100%',
    gap: TILE_GAP,
    marginBottom: 24
  },
  tile: { flexGrow: 1, flexShrink: 1, minWidth: 0 },
  invitePanel: {
    marginBottom: 20
  },
  keyRow: { marginTop: 20, width: '100%', flexDirection: 'row', alignItems: 'center', gap: 8 },
  keyInput: { flex: 1, minWidth: 0 },
  keyAction: { width: 48, height: 48, flexDirection: 'row' },
  qrPanelSection: { paddingTop: 0 },
  initials: { fontSize: 14, fontWeight: '700', letterSpacing: 0.5 }
})