Update search input with useAutocomplete (#11023)

This commit is contained in:
DS Boyce
2026-06-30 10:34:17 -07:00
committed by GitHub
parent 6607118729
commit 298c83bcba
9 changed files with 285 additions and 91 deletions
@@ -1,49 +1,44 @@
import {memo} from 'react'
import {
ActivityIndicator,
TouchableOpacity,
View,
type ViewStyle,
} from 'react-native'
import {type AppBskyActorDefs} from '@atproto/api'
import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react'
import {TouchableOpacity, View, type ViewStyle} from 'react-native'
import {useLingui} from '@lingui/react/macro'
import {usePalette} from '#/lib/hooks/usePalette'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {Link} from '#/view/com/util/Link'
import {Text} from '#/view/com/util/text/Text'
import {SearchProfileCard} from '#/screens/Search/components/SearchProfileCard'
import {atoms as a, native} from '#/alf'
import {atoms as a, native, useTheme} from '#/alf'
import {type AutocompleteItem} from '#/components/Autocomplete'
import * as Layout from '#/components/Layout'
import {Link} from '#/components/Link'
import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography'
import {useAnalytics} from '#/analytics'
import {IS_NATIVE} from '#/env'
import type * as bsky from '#/types/bsky'
let AutocompleteResults = ({
isAutocompleteFetching,
autocompleteData,
items,
isFetching,
searchText,
onSubmit,
onResultPress,
onProfileClick,
}: {
isAutocompleteFetching: boolean
autocompleteData: AppBskyActorDefs.ProfileViewBasic[] | undefined
items: AutocompleteItem[]
isFetching: boolean
searchText: string
onSubmit: () => void
onResultPress: () => void
onProfileClick: (profile: AppBskyActorDefs.ProfileViewBasic) => void
onProfileClick: (profile: bsky.profile.AnyProfileView) => void
}): React.ReactNode => {
const ax = useAnalytics()
const {_} = useLingui()
const {t: l} = useLingui()
const moderationOpts = useModerationOpts()
return (
<>
{(isAutocompleteFetching && !autocompleteData?.length) ||
!moderationOpts ? (
{(isFetching && !items.length) || !moderationOpts ? (
<Layout.Content>
<View style={[a.py_xl]}>
<ActivityIndicator />
<View style={[a.py_xl, a.align_center]}>
<Loader size="xl" />
</View>
</Layout.Content>
) : (
@@ -51,7 +46,7 @@ let AutocompleteResults = ({
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag">
<SearchLinkCard
label={_(msg`Search for "${searchText}"`)}
label={l`Search for “${searchText}”`}
onPress={native(onSubmit)}
to={
IS_NATIVE
@@ -60,21 +55,24 @@ let AutocompleteResults = ({
}
style={a.border_b}
/>
{autocompleteData?.map((item, index) => (
<SearchProfileCard
key={item.did}
profile={item}
moderationOpts={moderationOpts}
onPress={() => {
ax.metric('search:autocomplete:press', {
profileDid: item.did,
position: index,
})
onProfileClick(item)
onResultPress()
}}
/>
))}
{items.map((item, index) => {
if (item.type !== 'profile') return null
return (
<SearchProfileCard
key={item.key}
profile={item.profile}
moderationOpts={moderationOpts}
onPress={() => {
ax.metric('search:autocomplete:press', {
profileDid: item.profile.did,
position: index,
})
onProfileClick(item.profile)
onResultPress()
}}
/>
)
})}
<View style={{height: 200}} />
</Layout.Content>
)}
@@ -95,12 +93,12 @@ let SearchLinkCard = ({
onPress?: () => void
style?: ViewStyle
}): React.ReactNode => {
const pal = usePalette('default')
const t = useTheme()
const inner = (
<View
style={[pal.border, {paddingVertical: 16, paddingHorizontal: 12}, style]}>
<Text type="md" style={[pal.text]}>
style={[a.flex_1, a.py_lg, a.px_md, t.atoms.border_contrast_low, style]}>
<Text emoji style={[a.text_md, t.atoms.text]}>
{label}
</Text>
</View>
@@ -117,18 +115,13 @@ let SearchLinkCard = ({
)
}
return (
<Link href={to} asAnchor anchorNoUnderline>
<View
style={[
pal.border,
{paddingVertical: 16, paddingHorizontal: 12},
style,
]}>
<Text type="md" style={[pal.text]}>
{label}
</Text>
</View>
</Link>
)
if (to) {
return (
<Link label={label} to={to}>
{inner}
</Link>
)
}
return inner
}
@@ -0,0 +1,17 @@
import {SearchInput} from '#/components/forms/SearchInput'
import {type SearchAutocompleteInputProps} from './shared'
/**
* Native: renders the search input as-is. Typed results are shown inline in the
* full-page list (see Shell.tsx), so there is no anchored dropdown here. See
* index.tsx for the web (floating Sift dropdown) variant.
*/
export function SearchAutocompleteInput({
// web-only props are ignored on native
fixedParams: _fixedParams,
onSelectProfile: _onSelectProfile,
onSelectSearch: _onSelectSearch,
...rest
}: SearchAutocompleteInputProps) {
return <SearchInput {...rest} />
}
@@ -0,0 +1,122 @@
import {useRef, useState} from 'react'
import {type TextInput, View} from 'react-native'
import {useSift} from '@bsky.app/sift'
import {mergeRefs} from '#/lib/merge-refs'
import {atoms as a} from '#/alf'
import {
Autocomplete,
type AutocompleteItem,
useAutocomplete,
} from '#/components/Autocomplete'
import {SearchInput} from '#/components/forms/SearchInput'
import {type SearchAutocompleteInputProps} from './shared'
/**
* Web: typed results float in a Sift dropdown anchored to the search input
* (matching the desktop nav-bar search). Search history continues to render
* full-page underneath the input in Shell.tsx, so it is not shown here. See
* index.native.tsx for the native (inline list) variant.
*/
export function SearchAutocompleteInput({
fixedParams,
onSelectProfile,
onSelectSearch,
value = '',
onFocus,
onBlur,
onChangeText,
ref,
...rest
}: SearchAutocompleteInputProps) {
const [focused, setFocused] = useState(false)
/*
* Sift dismisses on Escape without blurring the input, so `focused` stays
* true. Track that dismissal separately (reset on type or refocus) rather
* than clearing `focused`, otherwise the dropdown wouldn't reopen on the next
* keystroke while the input is still focused.
*/
const [dismissed, setDismissed] = useState(false)
const inputRef = useRef<TextInput>(null)
const sift = useSift({
offset: a.p_sm.padding,
placement: 'bottom',
})
const active = focused && !dismissed
const {items} = useAutocomplete({
type: 'profile',
// The dropdown only shows while active, so don't fetch otherwise. This
// avoids a typeahead request on mount when arriving with text already
// present (e.g. /search?q=foo).
query: active ? value : '',
showSearchFallback: true,
})
const showDropdown =
active && !fixedParams && value.length > 0 && items.length > 0
function onSelect(item: AutocompleteItem) {
if (item.type === 'profile') {
const position = items.filter(i => i.type === 'profile').indexOf(item)
onSelectProfile?.(item.profile, position)
} else if (item.type === 'search') {
onSelectSearch?.(item.value)
}
inputRef.current?.blur()
}
/*
* setAnchor goes on the full-width wrapper View so the dropdown matches the
* input's container width; the input ref (targetProps.ref) lands on the inner
* TextInput for Sift's positioning math, and the remaining combobox a11y
* props are spread onto the input.
*/
const {setAnchor} = sift.refs
const {ref: inputAnchorRef, ...comboboxProps} = sift.targetProps
return (
<View
collapsable={false}
ref={setAnchor}
/*
* Focusing the input reveals the Cancel button alongside it (see
* Shell.tsx), which shrinks the anchor after Sift's initial measurement
* and leaves the dropdown too wide until the next re-measure. Recompute on
* layout (react-native-web backs onLayout with a ResizeObserver) so the
* width tracks the anchor through that reflow and window resizes.
*/
onLayout={() => void sift.updatePosition()}>
<SearchInput
{...rest}
{...comboboxProps}
ref={mergeRefs([ref, inputAnchorRef, inputRef])}
value={value}
onChangeText={text => {
setDismissed(false)
onChangeText?.(text)
}}
onFocus={e => {
setDismissed(false)
setFocused(true)
onFocus?.(e)
}}
onBlur={e => {
setFocused(false)
onBlur?.(e)
}}
/>
{showDropdown && (
<Autocomplete
sift={sift}
data={items}
onSelect={onSelect}
onDismiss={() => setDismissed(true)}
fullWidth
/>
)}
</View>
)
}
@@ -0,0 +1,23 @@
import {type SearchInput} from '#/components/forms/SearchInput'
import type * as bsky from '#/types/bsky'
type SearchInputProps = React.ComponentProps<typeof SearchInput>
export type SearchAutocompleteInputProps = SearchInputProps & {
/**
* When the search has fixed params (e.g. ProfileSearch), the web dropdown is
* suppressed.
*/
fixedParams?: boolean
/**
* Web only. Called when a profile result in the dropdown is selected.
*/
onSelectProfile?: (
profile: bsky.profile.AnyProfileView,
position: number,
) => void
/**
* Web only. Called when the "Search for X" row in the dropdown is selected.
*/
onSelectSearch?: (value: string) => void
}
@@ -1,6 +1,6 @@
import {useCallback} from 'react'
import {View} from 'react-native'
import {type AppBskyActorDefs, type ModerationOpts} from '@atproto/api'
import {type ModerationOpts} from '@atproto/api'
import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react'
import {useQueryClient} from '@tanstack/react-query'
@@ -10,13 +10,14 @@ import {unstableCacheProfileView} from '#/state/queries/unstable-profile-cache'
import {atoms as a, useTheme} from '#/alf'
import {Link} from '#/components/Link'
import * as ProfileCard from '#/components/ProfileCard'
import type * as bsky from '#/types/bsky'
export function SearchProfileCard({
profile,
moderationOpts,
onPress: onPressInner,
}: {
profile: AppBskyActorDefs.ProfileViewBasic
profile: bsky.profile.AnyProfileView
moderationOpts: ModerationOpts
onPress?: () => void
}) {