Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SearchField.tsx

92 lines3.0 KB

1import { useState, type RefObject } from "react";
2import { Pressable, TextInput, type TextInputInstance, View } from "react-native";
3​
4import { SymbolView } from "./AppSymbol";
5import { useAndroidControlSizing } from "./useAndroidControlSizing";
6​
7export interface SearchFieldProps {
8 readonly autoFocus?: boolean;
9 readonly inputRef: RefObject<TextInputInstance | null>;
10 readonly accessibilityLabel: string;
11 readonly clearAccessibilityLabel: string;
12 readonly placeholder: string;
13 readonly value: string;
14 readonly onChangeText: (value: string) => void;
16​
17export function SearchField({
18 inputRef,
19 autoFocus = true,
20 accessibilityLabel,
21 clearAccessibilityLabel,
22 placeholder,
23 value,
24 onChangeText,
25}: SearchFieldProps) {
26 const { scale, mediumIconSize } = useAndroidControlSizing();
27 // The owner's query can reach this field several commits after a keystroke. Show the native
28 // text locally and skip `value`s this field sent itself, so a late one cannot rewrite the field.
29 const [field, setField] = useState({ text: value, value, sent: [] as string[] });
30 if (field.value !== value) {
31 const echo = field.sent.indexOf(value);
32 setField(
33 echo === -1
34 ? { text: value, value, sent: [] }
35 : { text: field.text, value, sent: field.sent.slice(echo + 1) },
36 );
37 }
38 const changeText = (text: string) => {
39 setField((current) => ({ ...current, text, sent: [...current.sent, text] }));
40 onChangeText(text);
41 };
42 return (
43 <View
44 className="min-w-0 flex-1 flex-row items-center rounded-full border border-input-border bg-input"
45 style={{
46 minHeight: Math.max(48, 42 * scale),
47 gap: 7 * scale,
48 paddingHorizontal: 10.5 * scale,
49 }}
50 >
51 <SymbolView
52 name="magnifyingglass"
53 size={mediumIconSize}
54 tintColorClassName="accent-foreground-muted"
55 />
56 <TextInput
57 ref={inputRef}
58 accessibilityLabel={accessibilityLabel}
59 autoFocus={autoFocus}
60 autoCapitalize="none"
61 autoCorrect={false}
62 returnKeyType="search"
63 placeholder={placeholder}
64 placeholderTextColorClassName="accent-placeholder"
65 selectionColorClassName="accent-focus/32"
66 cursorColorClassName="accent-focus"
67 selectionHandleColorClassName="accent-focus"
68 className="min-w-0 flex-1 font-sans text-base text-foreground"
69 style={{ minHeight: Math.max(48, 42 * scale), paddingVertical: 7 * scale }}
70 value={field.text}
71 onChangeText={changeText}
72 />
73 {field.text.length > 0 ? (
74 <Pressable
75 accessibilityLabel={clearAccessibilityLabel}
76 accessibilityRole="button"
77 hitSlop={10}
78 onPress={() => {
79 changeText("");
80 inputRef.current?.focus();
81 }}
82 >
83 <SymbolView
84 name="xmark.circle.fill"
85 size={mediumIconSize}
86 tintColorClassName="accent-foreground-muted"
87 />
88 </Pressable>
89 ) : null}
90 </View>
91 );