From 8f60307124b0cbf3572665c71750ca78761bc340 Mon Sep 17 00:00:00 2001 From: Adrian Santana Berg Date: Tue, 26 Sep 2023 16:26:31 +0200 Subject: [PATCH] refactor: refactor search highlighting --- src/components/search/index.tsx | 94 +++++++++++++++---------- src/components/search/search.module.css | 2 + 2 files changed, 57 insertions(+), 39 deletions(-) diff --git a/src/components/search/index.tsx b/src/components/search/index.tsx index c6302f83..2e3db4d0 100644 --- a/src/components/search/index.tsx +++ b/src/components/search/index.tsx @@ -2,7 +2,6 @@ import Downshift from 'downshift'; import { useState } from 'react'; import { useAutocomplete } from '@atb/page-modules/departures/client'; import style from './search.module.css'; -import { debounce, split } from 'lodash'; import { MonoIcon } from '@atb/assets/mono-icon'; import VenueIcon from '@atb/components/venue-icon'; import { andIf } from '@atb/utils/css'; @@ -16,17 +15,11 @@ type SearchProps = { export default function Search({ label, onChange, - initialQuery = '', + initialQuery = 'No', }: SearchProps) { const [query, setQuery] = useState(initialQuery); const { data } = useAutocomplete(query); - const highlight = (name: string, inputValue: string | null) => { - if (!inputValue) return [name]; - - return split(name, new RegExp(`(${inputValue})`, 'gi')); - }; - return ( )} ); } + +function highlightSearchText(input: string | null, name: string) { + if (!input) return [{ part: name, highlight: false }]; + + let startIndex = name.toLowerCase().indexOf(input.toLowerCase()); + + if (startIndex !== -1) { + let endIndex = startIndex + input.length; + return [ + { + part: name.substring(0, startIndex), + highlight: false, + }, + { + part: name.substring(startIndex, endIndex), + highlight: true, + }, + { + part: name.substring(endIndex), + highlight: false, + }, + ]; + } else { + return [{ part: name, highlight: false }]; + } +} diff --git a/src/components/search/search.module.css b/src/components/search/search.module.css index aebf61df..d67491ef 100644 --- a/src/components/search/search.module.css +++ b/src/components/search/search.module.css @@ -75,6 +75,8 @@ } .itemIcon { + display: flex; + align-items: center; padding: var(--spacings-small); padding-right: var(--spacings-xLarge); }