forked from algolia/docsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchBox.tsx
More file actions
96 lines (85 loc) · 2.81 KB
/
SearchBox.tsx
File metadata and controls
96 lines (85 loc) · 2.81 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
import type { AutocompleteApi, AutocompleteState } from '@algolia/autocomplete-core';
import React, { type JSX, type RefObject } from 'react';
import { MAX_QUERY_SIZE } from './constants';
import { LoadingIcon } from './icons/LoadingIcon';
import { ResetIcon } from './icons/ResetIcon';
import { SearchIcon } from './icons/SearchIcon';
import type { InternalDocSearchHit } from './types';
export type SearchBoxTranslations = Partial<{
resetButtonTitle: string;
resetButtonAriaLabel: string;
cancelButtonText: string;
cancelButtonAriaLabel: string;
searchInputLabel: string;
}>;
interface SearchBoxProps
extends AutocompleteApi<InternalDocSearchHit, React.FormEvent, React.MouseEvent, React.KeyboardEvent> {
state: AutocompleteState<InternalDocSearchHit>;
autoFocus: boolean;
inputRef: RefObject<HTMLInputElement | null>;
onClose: () => void;
isFromSelection: boolean;
translations?: SearchBoxTranslations;
}
export function SearchBox({ translations = {}, ...props }: SearchBoxProps): JSX.Element {
const {
resetButtonTitle = 'Clear the query',
resetButtonAriaLabel = 'Clear the query',
cancelButtonText = 'Cancel',
cancelButtonAriaLabel = 'Cancel',
searchInputLabel = 'Search',
} = translations;
const { onReset } = props.getFormProps({
inputElement: props.inputRef.current,
});
React.useEffect(() => {
if (props.autoFocus && props.inputRef.current) {
props.inputRef.current.focus();
}
}, [props.autoFocus, props.inputRef]);
React.useEffect(() => {
if (props.isFromSelection && props.inputRef.current) {
props.inputRef.current.select();
}
}, [props.isFromSelection, props.inputRef]);
return (
<>
<form
className="DocSearch-Form"
onSubmit={(event) => {
event.preventDefault();
}}
onReset={onReset}
>
<label className="DocSearch-MagnifierLabel" {...props.getLabelProps()}>
<SearchIcon />
<span className="DocSearch-VisuallyHiddenForAccessibility">{searchInputLabel}</span>
</label>
<div className="DocSearch-LoadingIndicator">
<LoadingIcon />
</div>
<input
className="DocSearch-Input"
ref={props.inputRef}
{...props.getInputProps({
inputElement: props.inputRef.current!,
autoFocus: props.autoFocus,
maxLength: MAX_QUERY_SIZE,
})}
/>
<button
type="reset"
title={resetButtonTitle}
className="DocSearch-Reset"
aria-label={resetButtonAriaLabel}
hidden={!props.state.query}
>
<ResetIcon />
</button>
</form>
<button className="DocSearch-Cancel" type="reset" aria-label={cancelButtonAriaLabel} onClick={props.onClose}>
{cancelButtonText}
</button>
</>
);
}