()
| 9 | |
| 10 | const PAGE_SIZE = 6 |
| 11 | export const CodeExamples = () => { |
| 12 | const { productCodeExamples } = useProductLandingContext() |
| 13 | const { t } = useTranslation('product_landing') |
| 14 | const [numVisible, setNumVisible] = useState(PAGE_SIZE) |
| 15 | const [search, setSearch] = useState('') |
| 16 | const [typed, setTyped] = useState('') |
| 17 | |
| 18 | useEffect(() => { |
| 19 | setNumVisible(PAGE_SIZE) // reset the visible count (only matters after searching) |
| 20 | }, [search]) |
| 21 | |
| 22 | const isSearching = !!search |
| 23 | let searchResults: typeof productCodeExamples = [] |
| 24 | if (isSearching) { |
| 25 | // The following replace method escapes special characters in regular expression creation. |
| 26 | const matchReg = new RegExp(search.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'), 'i') |
| 27 | searchResults = productCodeExamples.filter((example) => { |
| 28 | const searchableStr = `${example.tags.join(' ')} ${example.title} ${example.description}` |
| 29 | return matchReg.test(searchableStr) |
| 30 | }) |
| 31 | } |
| 32 | |
| 33 | return ( |
| 34 | <div> |
| 35 | <form |
| 36 | data-search="hide" |
| 37 | className="pr-lg-3 mb-5 mt-3" |
| 38 | onSubmit={(event) => { |
| 39 | event.preventDefault() |
| 40 | setSearch(typed.trim()) |
| 41 | }} |
| 42 | > |
| 43 | <Text |
| 44 | className="ml-1 mr-2" |
| 45 | fontWeight="bold" |
| 46 | fontSize={2} |
| 47 | as="label" |
| 48 | htmlFor="searchCodeExamples" |
| 49 | id="searchCodeExamples" |
| 50 | > |
| 51 | Search code examples: |
| 52 | </Text> |
| 53 | <input |
| 54 | data-testid="code-examples-input" |
| 55 | className="input-lg py-2 px-3 col-12 col-lg-8 form-control" |
| 56 | placeholder={t('search_code_examples')} |
| 57 | type="search" |
| 58 | autoComplete="off" |
| 59 | aria-label={t('search_code_examples')} |
| 60 | onChange={(event) => setTyped(event.target.value)} |
| 61 | value={typed} |
| 62 | /> |
| 63 | <button data-testid="code-examples-search-btn" className="btn ml-2 py-2" type="submit"> |
| 64 | Search |
| 65 | </button> |
| 66 | </form> |
| 67 | |
| 68 | {isSearching && ( |
nothing calls this directly
no test coverage detected