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
+12 -17
View File
@@ -1,5 +1,4 @@
import {useCallback} from 'react'
import {View} from 'react-native'
import {Sift, type UseSiftReturn} from '@bsky.app/sift'
import {atoms as a, useTheme} from '#/alf'
@@ -22,7 +21,7 @@ function renderItem(
case 'search':
return <AutocompleteItemSearch {...item} />
default:
return <View />
return <></>
}
}
@@ -33,6 +32,7 @@ export function Autocomplete({
render = renderItem,
onSelect,
onDismiss,
fullWidth = false,
}: {
inverted?: boolean
sift: UseSiftReturn
@@ -40,6 +40,12 @@ export function Autocomplete({
render?: Parameters<typeof Sift<AutocompleteItem>>[0]['render']
onSelect: (item: AutocompleteItem) => void
onDismiss: () => void
/**
* Match the anchor's width instead of the default capped width. Use for
* full-width anchors like the search bar; leave off for inline mention
* inputs.
*/
fullWidth?: boolean
}) {
const t = useTheme()
@@ -50,6 +56,8 @@ export function Autocomplete({
useOnKeyboard('keyboardDidShow', updatePosition)
useOnKeyboard('keyboardDidHide', updatePosition)
const maxWidth = IS_WEB && !fullWidth ? {maxWidth: 300} : {}
return (
<Portal>
<Sift
@@ -58,16 +66,7 @@ export function Autocomplete({
data={data}
onSelect={onSelect}
onDismiss={onDismiss}
outerStyle={[
a.rounded_md,
a.w_full,
t.atoms.shadow_lg,
IS_WEB
? {
maxWidth: 300,
}
: {},
]}
outerStyle={[a.rounded_md, a.w_full, t.atoms.shadow_lg, maxWidth]}
innerStyle={[
a.overflow_hidden,
a.rounded_md,
@@ -75,11 +74,7 @@ export function Autocomplete({
t.atoms.border_contrast_low,
t.atoms.bg,
a.w_full,
IS_WEB
? {
maxWidth: 300,
}
: {},
maxWidth,
]}
render={render}
/>
+1
View File
@@ -45,4 +45,5 @@ export type AutocompleteItemProps = Parameters<
export type AutocompleteApi = {
query: string
items: AutocompleteItem[]
isFetching: boolean
}
@@ -118,6 +118,7 @@ export function useAutocomplete({
return {
query: q,
items,
isFetching: query.isFetching,
}
}
+57 -16
View File
@@ -23,7 +23,6 @@ import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback'
import {MagnifyingGlassIcon} from '#/lib/icons'
import {type NavigationProp, type SearchParams} from '#/lib/routes/types'
import {listenSoftReset} from '#/state/events'
import {useActorAutocompleteQuery} from '#/state/queries/actor-autocomplete'
import {
unstableCacheProfileView,
useProfilesQuery,
@@ -43,8 +42,8 @@ import {
} from '#/screens/Search/searchParams'
import {makeSearchQuery} from '#/screens/Search/utils'
import {atoms as a, tokens, useBreakpoints, useTheme, web} from '#/alf'
import {useAutocomplete} from '#/components/Autocomplete'
import {Button, ButtonIcon} from '#/components/Button'
import {SearchInput} from '#/components/forms/SearchInput'
import {ArrowLeft_Stroke2_Corner0_Rounded as ArrowLeftIcon} from '#/components/icons/Arrow'
import {ArrowShareRight_Stroke2_Corner2_Rounded as ShareIcon} from '#/components/icons/ArrowShareRight'
import * as Layout from '#/components/Layout'
@@ -57,6 +56,7 @@ import type * as bsky from '#/types/bsky'
import {AdvancedSearchDialog} from './components/AdvancedSearchDialog'
import {AutocompleteResults} from './components/AutocompleteResults'
import {DetectedLanguagesAdmonition} from './components/DetectedLanguagesAdmonition'
import {SearchAutocompleteInput} from './components/SearchAutocompleteInput'
import {SearchHistory} from './components/SearchHistory'
import {SearchLanguageDropdown} from './components/SearchLanguageDropdown'
import {Explore} from './Explore'
@@ -125,8 +125,16 @@ export function SearchScreenShell({
setSearchText(text)
}, [])
const {data: autocompleteData, isFetching: isAutocompleteFetching} =
useActorAutocompleteQuery(searchText, true)
const {items: autocompleteItems, isFetching: isAutocompleteFetching} =
useAutocomplete({
type: 'profile',
/*
* On web the dropdown (SearchAutocompleteInput) owns its own autocomplete
* query; only the native inline list consumes this one, so pass an empty
* query on web to keep the hook a no-op instead of doing wasted work.
*/
query: IS_NATIVE ? searchText : '',
})
const [showAutocomplete, setShowAutocomplete] = useState(false)
@@ -388,6 +396,38 @@ export function SearchScreenShell({
[updateProfileHistory, queryClient],
)
/**
* Web only. Selecting a profile from the anchored autocomplete dropdown.
*/
const onSelectProfile = useCallback(
(profile: bsky.profile.AnyProfileView, position: number) => {
ax.metric('search:autocomplete:press', {
profileDid: profile.did,
position,
})
handleProfileClick(profile)
navigation.navigate('Profile', {name: profile.handle})
},
[ax, handleProfileClick, navigation],
)
/**
* Web only. Selecting the "Search for X" row from the anchored autocomplete
* dropdown. This runs the typed query as-is (not a suggested profile), so it
* is attributed to `typed` rather than `autocomplete`.
*/
const onSelectSearch = useCallback(
(value: string) => {
ax.metric('search:query', {
source: 'typed',
filterCount: countActiveFilters(filters),
})
updateSearchText(value)
navigateToItem(value)
},
[ax, filters, navigateToItem, updateSearchText],
)
const onSoftReset = useCallback(() => {
if (IS_WEB) {
/*
@@ -495,13 +535,11 @@ export function SearchScreenShell({
{isExplore ? <Trans>Explore</Trans> : <Trans>Search</Trans>}
</Layout.Header.TitleText>
</Layout.Header.Content>
{showFilters ? (
advancedSearchV2Enabled ? null : (
<SearchLanguageDropdown
value={filters.lang ?? ''}
onChange={onChangeLang}
/>
)
{showFilters && !advancedSearchV2Enabled ? (
<SearchLanguageDropdown
value={filters.lang ?? ''}
onChange={onChangeLang}
/>
) : (
<Layout.Header.Slot />
)}
@@ -528,7 +566,7 @@ export function SearchScreenShell({
size="large"
variant="ghost"
color="secondary"
shape="rectangular"
shape="round"
style={[a.px_sm]}
onPress={onPressCancelSearch}
hitSlop={HITSLOP_10}>
@@ -536,7 +574,7 @@ export function SearchScreenShell({
</Button>
)}
<View style={[a.flex_1]}>
<SearchInput
<SearchAutocompleteInput
testID="searchScreenInput"
ref={textInput}
value={searchText}
@@ -547,6 +585,9 @@ export function SearchScreenShell({
placeholder={inputPlaceholder ?? l`Search`}
hitSlop={{...HITSLOP_20, top: 0}}
hotkey={true}
fixedParams={Boolean(fixedParams)}
onSelectProfile={onSelectProfile}
onSelectSearch={onSelectSearch}
/>
</View>
</View>
@@ -589,10 +630,10 @@ export function SearchScreenShell({
display: showAutocomplete && !fixedParams ? 'flex' : 'none',
flex: 1,
}}>
{searchText.length > 0 ? (
{searchText.length > 0 && IS_NATIVE ? (
<AutocompleteResults
isAutocompleteFetching={isAutocompleteFetching}
autocompleteData={autocompleteData}
items={autocompleteItems}
isFetching={isAutocompleteFetching}
searchText={searchText}
onSubmit={onSubmit('autocomplete')}
onResultPress={onAutocompleteResultPress}
@@ -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
}) {