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 {useCallback} from 'react'
import {View} from 'react-native'
import {Sift, type UseSiftReturn} from '@bsky.app/sift' import {Sift, type UseSiftReturn} from '@bsky.app/sift'
import {atoms as a, useTheme} from '#/alf' import {atoms as a, useTheme} from '#/alf'
@@ -22,7 +21,7 @@ function renderItem(
case 'search': case 'search':
return <AutocompleteItemSearch {...item} /> return <AutocompleteItemSearch {...item} />
default: default:
return <View /> return <></>
} }
} }
@@ -33,6 +32,7 @@ export function Autocomplete({
render = renderItem, render = renderItem,
onSelect, onSelect,
onDismiss, onDismiss,
fullWidth = false,
}: { }: {
inverted?: boolean inverted?: boolean
sift: UseSiftReturn sift: UseSiftReturn
@@ -40,6 +40,12 @@ export function Autocomplete({
render?: Parameters<typeof Sift<AutocompleteItem>>[0]['render'] render?: Parameters<typeof Sift<AutocompleteItem>>[0]['render']
onSelect: (item: AutocompleteItem) => void onSelect: (item: AutocompleteItem) => void
onDismiss: () => 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() const t = useTheme()
@@ -50,6 +56,8 @@ export function Autocomplete({
useOnKeyboard('keyboardDidShow', updatePosition) useOnKeyboard('keyboardDidShow', updatePosition)
useOnKeyboard('keyboardDidHide', updatePosition) useOnKeyboard('keyboardDidHide', updatePosition)
const maxWidth = IS_WEB && !fullWidth ? {maxWidth: 300} : {}
return ( return (
<Portal> <Portal>
<Sift <Sift
@@ -58,16 +66,7 @@ export function Autocomplete({
data={data} data={data}
onSelect={onSelect} onSelect={onSelect}
onDismiss={onDismiss} onDismiss={onDismiss}
outerStyle={[ outerStyle={[a.rounded_md, a.w_full, t.atoms.shadow_lg, maxWidth]}
a.rounded_md,
a.w_full,
t.atoms.shadow_lg,
IS_WEB
? {
maxWidth: 300,
}
: {},
]}
innerStyle={[ innerStyle={[
a.overflow_hidden, a.overflow_hidden,
a.rounded_md, a.rounded_md,
@@ -75,11 +74,7 @@ export function Autocomplete({
t.atoms.border_contrast_low, t.atoms.border_contrast_low,
t.atoms.bg, t.atoms.bg,
a.w_full, a.w_full,
IS_WEB maxWidth,
? {
maxWidth: 300,
}
: {},
]} ]}
render={render} render={render}
/> />
+1
View File
@@ -45,4 +45,5 @@ export type AutocompleteItemProps = Parameters<
export type AutocompleteApi = { export type AutocompleteApi = {
query: string query: string
items: AutocompleteItem[] items: AutocompleteItem[]
isFetching: boolean
} }
@@ -118,6 +118,7 @@ export function useAutocomplete({
return { return {
query: q, query: q,
items, items,
isFetching: query.isFetching,
} }
} }
+57 -16
View File
@@ -23,7 +23,6 @@ import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback'
import {MagnifyingGlassIcon} from '#/lib/icons' import {MagnifyingGlassIcon} from '#/lib/icons'
import {type NavigationProp, type SearchParams} from '#/lib/routes/types' import {type NavigationProp, type SearchParams} from '#/lib/routes/types'
import {listenSoftReset} from '#/state/events' import {listenSoftReset} from '#/state/events'
import {useActorAutocompleteQuery} from '#/state/queries/actor-autocomplete'
import { import {
unstableCacheProfileView, unstableCacheProfileView,
useProfilesQuery, useProfilesQuery,
@@ -43,8 +42,8 @@ import {
} from '#/screens/Search/searchParams' } from '#/screens/Search/searchParams'
import {makeSearchQuery} from '#/screens/Search/utils' import {makeSearchQuery} from '#/screens/Search/utils'
import {atoms as a, tokens, useBreakpoints, useTheme, web} from '#/alf' import {atoms as a, tokens, useBreakpoints, useTheme, web} from '#/alf'
import {useAutocomplete} from '#/components/Autocomplete'
import {Button, ButtonIcon} from '#/components/Button' import {Button, ButtonIcon} from '#/components/Button'
import {SearchInput} from '#/components/forms/SearchInput'
import {ArrowLeft_Stroke2_Corner0_Rounded as ArrowLeftIcon} from '#/components/icons/Arrow' import {ArrowLeft_Stroke2_Corner0_Rounded as ArrowLeftIcon} from '#/components/icons/Arrow'
import {ArrowShareRight_Stroke2_Corner2_Rounded as ShareIcon} from '#/components/icons/ArrowShareRight' import {ArrowShareRight_Stroke2_Corner2_Rounded as ShareIcon} from '#/components/icons/ArrowShareRight'
import * as Layout from '#/components/Layout' import * as Layout from '#/components/Layout'
@@ -57,6 +56,7 @@ import type * as bsky from '#/types/bsky'
import {AdvancedSearchDialog} from './components/AdvancedSearchDialog' import {AdvancedSearchDialog} from './components/AdvancedSearchDialog'
import {AutocompleteResults} from './components/AutocompleteResults' import {AutocompleteResults} from './components/AutocompleteResults'
import {DetectedLanguagesAdmonition} from './components/DetectedLanguagesAdmonition' import {DetectedLanguagesAdmonition} from './components/DetectedLanguagesAdmonition'
import {SearchAutocompleteInput} from './components/SearchAutocompleteInput'
import {SearchHistory} from './components/SearchHistory' import {SearchHistory} from './components/SearchHistory'
import {SearchLanguageDropdown} from './components/SearchLanguageDropdown' import {SearchLanguageDropdown} from './components/SearchLanguageDropdown'
import {Explore} from './Explore' import {Explore} from './Explore'
@@ -125,8 +125,16 @@ export function SearchScreenShell({
setSearchText(text) setSearchText(text)
}, []) }, [])
const {data: autocompleteData, isFetching: isAutocompleteFetching} = const {items: autocompleteItems, isFetching: isAutocompleteFetching} =
useActorAutocompleteQuery(searchText, true) 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) const [showAutocomplete, setShowAutocomplete] = useState(false)
@@ -388,6 +396,38 @@ export function SearchScreenShell({
[updateProfileHistory, queryClient], [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(() => { const onSoftReset = useCallback(() => {
if (IS_WEB) { if (IS_WEB) {
/* /*
@@ -495,13 +535,11 @@ export function SearchScreenShell({
{isExplore ? <Trans>Explore</Trans> : <Trans>Search</Trans>} {isExplore ? <Trans>Explore</Trans> : <Trans>Search</Trans>}
</Layout.Header.TitleText> </Layout.Header.TitleText>
</Layout.Header.Content> </Layout.Header.Content>
{showFilters ? ( {showFilters && !advancedSearchV2Enabled ? (
advancedSearchV2Enabled ? null : ( <SearchLanguageDropdown
<SearchLanguageDropdown value={filters.lang ?? ''}
value={filters.lang ?? ''} onChange={onChangeLang}
onChange={onChangeLang} />
/>
)
) : ( ) : (
<Layout.Header.Slot /> <Layout.Header.Slot />
)} )}
@@ -528,7 +566,7 @@ export function SearchScreenShell({
size="large" size="large"
variant="ghost" variant="ghost"
color="secondary" color="secondary"
shape="rectangular" shape="round"
style={[a.px_sm]} style={[a.px_sm]}
onPress={onPressCancelSearch} onPress={onPressCancelSearch}
hitSlop={HITSLOP_10}> hitSlop={HITSLOP_10}>
@@ -536,7 +574,7 @@ export function SearchScreenShell({
</Button> </Button>
)} )}
<View style={[a.flex_1]}> <View style={[a.flex_1]}>
<SearchInput <SearchAutocompleteInput
testID="searchScreenInput" testID="searchScreenInput"
ref={textInput} ref={textInput}
value={searchText} value={searchText}
@@ -547,6 +585,9 @@ export function SearchScreenShell({
placeholder={inputPlaceholder ?? l`Search`} placeholder={inputPlaceholder ?? l`Search`}
hitSlop={{...HITSLOP_20, top: 0}} hitSlop={{...HITSLOP_20, top: 0}}
hotkey={true} hotkey={true}
fixedParams={Boolean(fixedParams)}
onSelectProfile={onSelectProfile}
onSelectSearch={onSelectSearch}
/> />
</View> </View>
</View> </View>
@@ -589,10 +630,10 @@ export function SearchScreenShell({
display: showAutocomplete && !fixedParams ? 'flex' : 'none', display: showAutocomplete && !fixedParams ? 'flex' : 'none',
flex: 1, flex: 1,
}}> }}>
{searchText.length > 0 ? ( {searchText.length > 0 && IS_NATIVE ? (
<AutocompleteResults <AutocompleteResults
isAutocompleteFetching={isAutocompleteFetching} items={autocompleteItems}
autocompleteData={autocompleteData} isFetching={isAutocompleteFetching}
searchText={searchText} searchText={searchText}
onSubmit={onSubmit('autocomplete')} onSubmit={onSubmit('autocomplete')}
onResultPress={onAutocompleteResultPress} onResultPress={onAutocompleteResultPress}
@@ -1,49 +1,44 @@
import {memo} from 'react' import {memo} from 'react'
import { import {TouchableOpacity, View, type ViewStyle} from 'react-native'
ActivityIndicator, import {useLingui} from '@lingui/react/macro'
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 {usePalette} from '#/lib/hooks/usePalette'
import {useModerationOpts} from '#/state/preferences/moderation-opts' 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 {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 * 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 {useAnalytics} from '#/analytics'
import {IS_NATIVE} from '#/env' import {IS_NATIVE} from '#/env'
import type * as bsky from '#/types/bsky'
let AutocompleteResults = ({ let AutocompleteResults = ({
isAutocompleteFetching, items,
autocompleteData, isFetching,
searchText, searchText,
onSubmit, onSubmit,
onResultPress, onResultPress,
onProfileClick, onProfileClick,
}: { }: {
isAutocompleteFetching: boolean items: AutocompleteItem[]
autocompleteData: AppBskyActorDefs.ProfileViewBasic[] | undefined isFetching: boolean
searchText: string searchText: string
onSubmit: () => void onSubmit: () => void
onResultPress: () => void onResultPress: () => void
onProfileClick: (profile: AppBskyActorDefs.ProfileViewBasic) => void onProfileClick: (profile: bsky.profile.AnyProfileView) => void
}): React.ReactNode => { }): React.ReactNode => {
const ax = useAnalytics() const ax = useAnalytics()
const {_} = useLingui() const {t: l} = useLingui()
const moderationOpts = useModerationOpts() const moderationOpts = useModerationOpts()
return ( return (
<> <>
{(isAutocompleteFetching && !autocompleteData?.length) || {(isFetching && !items.length) || !moderationOpts ? (
!moderationOpts ? (
<Layout.Content> <Layout.Content>
<View style={[a.py_xl]}> <View style={[a.py_xl, a.align_center]}>
<ActivityIndicator /> <Loader size="xl" />
</View> </View>
</Layout.Content> </Layout.Content>
) : ( ) : (
@@ -51,7 +46,7 @@ let AutocompleteResults = ({
keyboardShouldPersistTaps="handled" keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"> keyboardDismissMode="on-drag">
<SearchLinkCard <SearchLinkCard
label={_(msg`Search for "${searchText}"`)} label={l`Search for ${searchText}`}
onPress={native(onSubmit)} onPress={native(onSubmit)}
to={ to={
IS_NATIVE IS_NATIVE
@@ -60,21 +55,24 @@ let AutocompleteResults = ({
} }
style={a.border_b} style={a.border_b}
/> />
{autocompleteData?.map((item, index) => ( {items.map((item, index) => {
<SearchProfileCard if (item.type !== 'profile') return null
key={item.did} return (
profile={item} <SearchProfileCard
moderationOpts={moderationOpts} key={item.key}
onPress={() => { profile={item.profile}
ax.metric('search:autocomplete:press', { moderationOpts={moderationOpts}
profileDid: item.did, onPress={() => {
position: index, ax.metric('search:autocomplete:press', {
}) profileDid: item.profile.did,
onProfileClick(item) position: index,
onResultPress() })
}} onProfileClick(item.profile)
/> onResultPress()
))} }}
/>
)
})}
<View style={{height: 200}} /> <View style={{height: 200}} />
</Layout.Content> </Layout.Content>
)} )}
@@ -95,12 +93,12 @@ let SearchLinkCard = ({
onPress?: () => void onPress?: () => void
style?: ViewStyle style?: ViewStyle
}): React.ReactNode => { }): React.ReactNode => {
const pal = usePalette('default') const t = useTheme()
const inner = ( const inner = (
<View <View
style={[pal.border, {paddingVertical: 16, paddingHorizontal: 12}, style]}> style={[a.flex_1, a.py_lg, a.px_md, t.atoms.border_contrast_low, style]}>
<Text type="md" style={[pal.text]}> <Text emoji style={[a.text_md, t.atoms.text]}>
{label} {label}
</Text> </Text>
</View> </View>
@@ -117,18 +115,13 @@ let SearchLinkCard = ({
) )
} }
return ( if (to) {
<Link href={to} asAnchor anchorNoUnderline> return (
<View <Link label={label} to={to}>
style={[ {inner}
pal.border, </Link>
{paddingVertical: 16, paddingHorizontal: 12}, )
style, }
]}>
<Text type="md" style={[pal.text]}> return inner
{label}
</Text>
</View>
</Link>
)
} }
@@ -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 {useCallback} from 'react'
import {View} from 'react-native' 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 {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react' import {useLingui} from '@lingui/react'
import {useQueryClient} from '@tanstack/react-query' 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 {atoms as a, useTheme} from '#/alf'
import {Link} from '#/components/Link' import {Link} from '#/components/Link'
import * as ProfileCard from '#/components/ProfileCard' import * as ProfileCard from '#/components/ProfileCard'
import type * as bsky from '#/types/bsky'
export function SearchProfileCard({ export function SearchProfileCard({
profile, profile,
moderationOpts, moderationOpts,
onPress: onPressInner, onPress: onPressInner,
}: { }: {
profile: AppBskyActorDefs.ProfileViewBasic profile: bsky.profile.AnyProfileView
moderationOpts: ModerationOpts moderationOpts: ModerationOpts
onPress?: () => void onPress?: () => void
}) { }) {