Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

12.4 KB
Raw Blame
import { useEffect, useMemo, useRef, useState } from 'react'
import {
  ActivityIndicator,
  FlatList,
  InteractionManager,
  Pressable,
  Text,
  TextInput,
  View
} from 'react-native'
import type { RpcClient } from '../transport/rpc-client'
import type { SmartWorkspaceSourceRow as SourceRow } from '../../../src/shared/new-workspace/smart-workspace-source-results'
import type { JiraSite, JiraSiteSelection } from '../../../src/shared/jira/jira-types'
import { isBlockingJiraUrlIntent } from '../../../src/shared/new-workspace/smart-workspace-source-results'
import {
  MR_STATE_FILTER_OPTIONS,
  resolveAvailableSmartModes,
  resolveDefaultSmartMode,
  SMART_MODE_OPTIONS,
  type SmartModeAvailabilityInput,
  type SmartModeOption
} from '../tasks/mobile-smart-source-modes'
import type { MrStateFilter, SmartNameMode } from '../tasks/mobile-composer-source-types'
import {
  lookupGitHubItemByOwnerRepo,
  type PasteRepoCandidate
} from '../tasks/smart-source-paste-intent'
import { useSmartWorkspaceSource } from '../tasks/use-smart-workspace-source'
import type { MobileComposerSource } from '../tasks/use-mobile-composer-source'
import { colors } from '../theme/mobile-theme'
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
import { useMobileTranslation } from '../i18n/use-mobile-translation'
import { BottomDrawer } from './BottomDrawer'
import { smartWorkspaceSourceDrawerStyles as styles } from './smart-workspace-source-drawer-styles'
import { TextField } from './composer-input/TextField'
import { SmartSourceModeIcon } from './SmartSourceModeIcon'
import { SmartWorkspaceSourceRow } from './SmartWorkspaceSourceRow'

// Delay focus like MobileSearchField: native autoFocus may not raise keyboard during drawer animation.
const SOURCE_INPUT_FOCUS_DELAY_MS = 120

type Props = {
  visible: boolean
  client: RpcClient | null
  composer: MobileComposerSource
  availability: SmartModeAvailabilityInput
  repoId: string | null
  repos: readonly PasteRepoCandidate[]
  linearWorkspaceId?: string | null
  jiraSiteId?: JiraSiteSelection | null
  jiraSites?: readonly JiraSite[]
  sshReady: boolean
  onRepoChange: (repoId: string) => void
  onClose: () => void
}

const NO_JIRA_SITES: readonly JiraSite[] = []

export function SmartWorkspaceSourceDrawer({
  visible,
  client,
  composer,
  availability,
  repoId,
  repos,
  linearWorkspaceId,
  jiraSiteId,
  jiraSites = NO_JIRA_SITES,
  sshReady,
  onRepoChange,
  onClose
}: Props) {
  useMobileColorScheme()
  const t = useMobileTranslation()
  const availableModes = useMemo(() => resolveAvailableSmartModes(availability), [availability])
  const [mode, setMode] = useState<SmartNameMode>(() => resolveDefaultSmartMode(availability))
  const [mrStateFilter, setMrStateFilter] = useState<MrStateFilter>('opened')
  const inputRef = useRef<TextInput>(null)
  // Read latest availability without reactive dependency so recreated object reseeds only on open.
  const availabilityRef = useRef(availability)
  availabilityRef.current = availability

  useEffect(() => {
    if (visible) {
      setMode(resolveDefaultSmartMode(availabilityRef.current))
    }
  }, [visible])

  // Focus after opening interactions settle; docked field shares composer.name with form.
  useEffect(() => {
    if (!visible) {
      return
    }
    let timeout: ReturnType<typeof setTimeout> | undefined
    const task = InteractionManager.runAfterInteractions(() => {
      timeout = setTimeout(() => {
        inputRef.current?.focus()
      }, SOURCE_INPUT_FOCUS_DELAY_MS)
    })
    return () => {
      task.cancel()
      if (timeout) {
        clearTimeout(timeout)
      }
    }
  }, [visible])

  const effectiveMode = availableModes.includes(mode) ? mode : (availableModes[0] ?? 'text')

  // Keep pasted Jira URLs reachable in Smart mode without repo connection; resolving one issue does not touch repo.
  const jiraUrlIntent =
    availability.jiraAvailable && isBlockingJiraUrlIntent(effectiveMode, composer.name)
  // Only Linear/Jira search works without repo; other provider/branch searches need connected repo-backed target.
  const searchEnabled =
    visible && (effectiveMode === 'linear' || effectiveMode === 'jira' || jiraUrlIntent || sshReady)

  const {
    rows,
    loading,
    error,
    needsGitHubRemote,
    emptyHint,
    crossRepoPrompt,
    dismissCrossRepoPrompt
  } = useSmartWorkspaceSource({
    client,
    enabled: searchEnabled,
    mode: effectiveMode,
    query: composer.name,
    repoId,
    githubAvailable: availability.githubAvailable,
    gitlabAvailable: availability.gitlabAvailable,
    linearAvailable: availability.linearAvailable,
    jiraAvailable: availability.jiraAvailable,
    mrStateFilter,
    linearWorkspaceId,
    jiraSiteId,
    jiraSites,
    repos
  })

  function handleSelectRow(row: SourceRow): void {
    switch (row.kind) {
      case 'use-name':
        composer.setName(row.name)
        break
      case 'create-branch':
        composer.handleSmartCreateBranch(row.name)
        break
      case 'github':
        composer.handleSmartGitHubItemSelect(row.item)
        break
      case 'gitlab':
        composer.handleSmartGitLabItemSelect(row.item)
        break
      case 'branch':
        composer.handleSmartBranchSelect(row.refName, row.localBranchName)
        break
      case 'linear':
        composer.handleSmartLinearIssueSelect(row.issue)
        break
      case 'jira':
        composer.handleSmartJiraIssueSelect(row.issue)
        break
    }
    onClose()
  }

  async function handleAcceptCrossRepo(): Promise<void> {
    if (!client || !crossRepoPrompt) {
      return
    }
    const { link, matchingRepo } = crossRepoPrompt
    try {
      const item = await lookupGitHubItemByOwnerRepo(
        client,
        matchingRepo.id,
        link.slug,
        link.number,
        link.type
      )
      if (item) {
        onRepoChange(matchingRepo.id)
        composer.handleSmartGitHubItemSelect(item)
        onClose()
      }
    } catch {
      dismissCrossRepoPrompt()
    }
  }

  const showEmpty =
    !loading && !error && !needsGitHubRemote && effectiveMode !== 'text' && rows.length === 0

  const modeTabs = SMART_MODE_OPTIONS.filter((option: SmartModeOption) =>
    availableModes.includes(option.id)
  )

  return (
    <BottomDrawer
      visible={visible}
      onClose={onClose}
      dragContentToDismiss={false}
      contentScrollable={false}
      fillAvailable
      // Layer above pinned create form so dismiss reveals outer sheet at original height.
      zIndex={1100}
    >
      {/* Fill column ends at keyboard top; non-flex dock stays beside flex results so FlatList cannot clip input. */}
      <View style={styles.root}>
        <View style={styles.header}>
          <Text style={styles.title}>
            {t('components.smartWorkspaceSourceDrawer.title', "Name or 'Create From'")}
          </Text>
          <Pressable onPress={onClose} hitSlop={8}>
            <Text style={styles.done}>{t('common.done', 'Done')}</Text>
          </Pressable>
        </View>

        <View style={styles.results}>
          {crossRepoPrompt ? (
            <View style={styles.crossRepo}>
              <Text style={styles.crossRepoText}>
                {t(
                  'components.smartWorkspaceSourceDrawer.crossRepoMessage',
                  'This item lives in {{owner}}/{{repo}}.',
                  {
                    owner: crossRepoPrompt.link.slug.owner,
                    repo: crossRepoPrompt.link.slug.repo
                  }
                )}
              </Text>
              <View style={styles.crossRepoActions}>
                <Pressable style={styles.crossRepoDismiss} onPress={dismissCrossRepoPrompt}>
                  <Text style={styles.crossRepoDismissText}>{t('common.cancel', 'Cancel')}</Text>
                </Pressable>
                <Pressable
                  style={styles.crossRepoSwitch}
                  onPress={() => void handleAcceptCrossRepo()}
                >
                  <Text style={styles.crossRepoSwitchText}>
                    {t(
                      'components.smartWorkspaceSourceDrawer.switchRepo',
                      'Switch to {{repoName}}',
                      {
                        repoName: crossRepoPrompt.matchingRepo.displayName
                      }
                    )}
                  </Text>
                </Pressable>
              </View>
            </View>
          ) : null}

          {!sshReady &&
          effectiveMode !== 'text' &&
          effectiveMode !== 'linear' &&
          effectiveMode !== 'jira' &&
          !jiraUrlIntent ? (
            <Text style={styles.notice}>
              {t(
                'components.smartWorkspaceSourceDrawer.connectRepository',
                'Connect the repository to search sources.'
              )}
            </Text>
          ) : needsGitHubRemote ? (
            <Text style={styles.notice}>
              {t(
                'components.smartWorkspaceSourceDrawer.gitHubRemoteRequired',
                'This SSH repo needs a GitHub remote to list issues and PRs.'
              )}
            </Text>
          ) : error ? (
            <Text style={styles.errorNotice}>{error}</Text>
          ) : null}

          <FlatList
            data={rows}
            keyExtractor={(row) => row.value}
            style={styles.list}
            contentContainerStyle={styles.listContent}
            keyboardShouldPersistTaps="handled"
            keyboardDismissMode="none"
            nestedScrollEnabled
            ListFooterComponent={
              loading ? (
                <View style={styles.loading}>
                  <ActivityIndicator size="small" color={colors.textSecondary} />
                </View>
              ) : showEmpty ? (
                <Text style={styles.empty}>
                  {emptyHint ||
                    t('components.smartWorkspaceSourceDrawer.noResults', 'No results found.')}
                </Text>
              ) : rows.length === 0 && effectiveMode === 'text' ? (
                <Text style={styles.empty}>
                  {t(
                    'components.smartWorkspaceSourceDrawer.typeWorkspaceName',
                    'Type a workspace name in the field below.'
                  )}
                </Text>
              ) : null
            }
            renderItem={({ item }) => (
              <SmartWorkspaceSourceRow row={item} onPress={() => handleSelectRow(item)} />
            )}
          />
        </View>

        <View style={styles.dock}>
          {effectiveMode === 'gitlab' ? (
            <View style={styles.chipRow}>
              {MR_STATE_FILTER_OPTIONS.map((option) => {
                const selected = option.id === mrStateFilter
                return (
                  <Pressable
                    key={option.id}
                    style={[styles.chip, selected && styles.chipSelected]}
                    onPress={() => setMrStateFilter(option.id)}
                  >
                    <Text style={[styles.chipText, selected && styles.chipTextSelected]}>
                      {option.label}
                    </Text>
                  </Pressable>
                )
              })}
            </View>
          ) : null}

          <View style={styles.tabRow}>
            {modeTabs.map((option) => {
              const selected = option.id === effectiveMode
              const tint = selected ? colors.textPrimary : colors.textSecondary
              return (
                <Pressable
                  key={option.id}
                  style={[styles.tab, selected && styles.tabSelected]}
                  onPress={() => setMode(option.id)}
                >
                  <SmartSourceModeIcon icon={option.icon} color={tint} />
                  <Text style={[styles.tabText, selected && styles.tabTextSelected]}>
                    {option.label}
                  </Text>
                </Pressable>
              )
            })}
          </View>

          <TextField
            inputRef={inputRef}
            value={composer.name}
            onChangeText={composer.setName}
            placeholder={t(
              'components.smartWorkspaceSourceDrawer.searchPlaceholder',
              'Type a name or search a source'
            )}
            autoCapitalize="none"
            autoCorrect={false}
            // Still request native auto-focus; the delayed ref focus is the reliable path.
            autoFocus
            returnKeyType="done"
            onSubmitEditing={onClose}
            blurOnSubmit={false}
          />
        </View>
      </View>
    </BottomDrawer>
  )
}