import { useEffect, useState } from 'react' import { ArrowRightIcon, SearchIcon } from '@primer/octicons-react' import { Text } from '@primer/react' import { useProductLandingContext } from 'components/context/ProductLandingContext' import { useTranslation } from 'components/hooks/useTranslation' import { CodeExampleCard } from 'components/landing/CodeExampleCard' import { Link } from 'components/Link' const PAGE_SIZE = 6 export const CodeExamples = () => { const { productCodeExamples } = useProductLandingContext() const { t } = useTranslation('product_landing') const [numVisible, setNumVisible] = useState(PAGE_SIZE) const [search, setSearch] = useState('') const [typed, setTyped] = useState('') useEffect(() => { setNumVisible(PAGE_SIZE) // reset the visible count (only matters after searching) }, [search]) const isSearching = !!search let searchResults: typeof productCodeExamples = [] if (isSearching) { // The following replace method escapes special characters in regular expression creation. const matchReg = new RegExp(search.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'), 'i') searchResults = productCodeExamples.filter((example) => { const searchableStr = `${example.tags.join(' ')} ${example.title} ${example.description}` return matchReg.test(searchableStr) }) } return (
{ event.preventDefault() setSearch(typed.trim()) }} > Search code examples: setTyped(event.target.value)} value={typed} />
{isSearching && (

{t('search_results_for')}: {search}

{t('matches_displayed')}: {searchResults.length}

)} {numVisible < productCodeExamples.length && !isSearching && ( )} {isSearching && searchResults.length === 0 && (
{' '}

{t('sorry')} {search}

{t('no_example')}
{t('try_another')}

{t('learn')}
)}
) }