Files
orca/mobile/src/components/SmartWorkspaceSourceDrawer.tsx
T
Neil 176943e8fe refactor(mobile-tasks): group modules by concrete feature owners (#41410)
* refactor(mobile-tasks): group modules by concrete feature owners

* refactor(mobile-tasks): consolidate concrete owner imports

* refactor(mobile-tasks): point recording loaders at concrete owners
2026-11-11 22:40:18 -08:00

392 lines
13 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from 'react'
import {
ActivityIndicator,
FlatList,
Pressable,
Text,
View,
type TextInputInstance
} from 'react-native'
import type { RpcClient } from '../transport/rpc/rpc-client-contract'
import type { JiraSite, JiraSiteSelection } from '../../../src/shared/jira/jira-types'
import {
isBlockingJiraUrlIntent,
type SmartWorkspaceSourceRow as SourceRow,
type SmartNameMode
} from '../../../src/shared/new-workspace/smart-workspace-source-results'
import {
MR_STATE_FILTER_OPTIONS,
resolveAvailableSmartModes,
resolveDefaultSmartMode,
SMART_MODE_OPTIONS,
type SmartModeAvailabilityInput,
type SmartModeOption
} from '../new-workspace/source-selection/mobile-smart-source-modes'
import type { MrStateFilter } from '../new-workspace/source-selection/mobile-composer-source-types'
import {
lookupGitHubItemByOwnerRepo,
type PasteRepoCandidate
} from '../new-workspace/source-selection/smart-source-paste-intent'
import { useSmartWorkspaceSource } from '../new-workspace/source-selection/use-smart-workspace-source'
import type { MobileComposerSource } from '../new-workspace/source-selection/use-mobile-composer-source'
import { colors, pressedStyle } from '../theme/mobile-theme'
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
import { useMobileTranslation } from '../i18n/use-mobile-translation'
import { BottomDrawer } from './bottom-drawer/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'
import { SheetHeader } from './nav-bar/SheetHeader'
import { runAfterInteractions } from '../platform/after-interactions'
// 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<TextInputInstance>(null)
// Reseed only on open so a recreated availability object cannot reset the picked mode.
const [wasVisible, setWasVisible] = useState(visible)
if (wasVisible !== visible) {
setWasVisible(visible)
if (visible) {
setMode(resolveDefaultSmartMode(availability))
}
}
// Focus after opening interactions settle; docked field shares composer.name with form.
useEffect(() => {
if (!visible) {
return
}
let timeout: ReturnType<typeof setTimeout> | undefined
const task = 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}>
<SheetHeader
title={
availability.textOnly
? t('components.smartWorkspaceSourceDrawer.workspaceName', 'Workspace name')
: t('components.smartWorkspaceSourceDrawer.startFrom', 'Start from')
}
trailing={{ label: t('common.done', 'Done'), onPress: onClose }}
/>
</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={({ pressed }) => [styles.crossRepoDismiss, pressed && pressedStyle]}
onPress={dismissCrossRepoPrompt}
>
<Text style={styles.crossRepoDismissText}>{t('common.cancel', 'Cancel')}</Text>
</Pressable>
<Pressable
style={({ pressed }) => [styles.crossRepoSwitch, pressed && pressedStyle]}
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, rows.length === 0 && styles.listEmpty]}
contentContainerStyle={styles.listContent}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="none"
nestedScrollEnabled
ItemSeparatorComponent={SourceRowSeparator}
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>
) : undefined
}
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={({ pressed }) => [
styles.chip,
selected && styles.chipSelected,
pressed && pressedStyle
]}
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={({ pressed }) => [
styles.tab,
selected && styles.tabSelected,
pressed && pressedStyle
]}
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>
)
}
function SourceRowSeparator() {
useMobileColorScheme()
return <View style={styles.separator} />
}