about summary refs log tree commit diff
path: root/src/components/forms/SearchInput.tsx
blob: 618a0040efd8a200ce9c86d6f979c08fcd70410a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import React from 'react'
import {type TextInput, View} from 'react-native'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'

import {HITSLOP_10} from '#/lib/constants'
import {isNative} from '#/platform/detection'
import {atoms as a, useTheme} from '#/alf'
import {Button, ButtonIcon} from '#/components/Button'
import * as TextField from '#/components/forms/TextField'
import {MagnifyingGlass2_Stroke2_Corner0_Rounded as MagnifyingGlassIcon} from '#/components/icons/MagnifyingGlass2'
import {TimesLarge_Stroke2_Corner0_Rounded as X} from '#/components/icons/Times'

type SearchInputProps = Omit<TextField.InputProps, 'label'> & {
  label?: TextField.InputProps['label']
  /**
   * Called when the user presses the (X) button
   */
  onClearText?: () => void
}

export const SearchInput = React.forwardRef<TextInput, SearchInputProps>(
  function SearchInput({value, label, onClearText, ...rest}, ref) {
    const t = useTheme()
    const {_} = useLingui()
    const showClear = value && value.length > 0

    return (
      <View style={[a.w_full, a.relative]}>
        <TextField.Root>
          <TextField.Icon icon={MagnifyingGlassIcon} />
          <TextField.Input
            inputRef={ref}
            label={label || _(msg`Search`)}
            value={value}
            placeholder={_(msg`Search`)}
            returnKeyType="search"
            keyboardAppearance={t.scheme}
            selectTextOnFocus={isNative}
            autoFocus={false}
            accessibilityRole="search"
            autoCorrect={false}
            autoComplete="off"
            autoCapitalize="none"
            style={[
              showClear
                ? {
                    paddingRight: 24,
                  }
                : {},
            ]}
            {...rest}
          />
        </TextField.Root>

        {showClear && (
          <View
            style={[
              a.absolute,
              a.z_20,
              a.my_auto,
              a.inset_0,
              a.justify_center,
              a.pr_sm,
              {left: 'auto'},
            ]}>
            <Button
              testID="searchTextInputClearBtn"
              onPress={onClearText}
              label={_(msg`Clear search query`)}
              hitSlop={HITSLOP_10}
              size="tiny"
              shape="round"
              variant="ghost"
              color="secondary">
              <ButtonIcon icon={X} size="xs" />
            </Button>
          </View>
        )}
      </View>
    )
  },
)