Skip to content

Commit 8a7ba33

Browse files
committed
feat: highlight matched letters
1 parent 6f07df3 commit 8a7ba33

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

src/components/search/SearchBox.tsx

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,16 +202,36 @@ const ValuePopupList = styled.div`
202202
overflow-y: auto;
203203
`;
204204

205+
const MatchHighlight = styled.span`
206+
background: color-mix(in srgb, var(--highlight) 25%, transparent);
207+
border-radius: 2px;
208+
`;
209+
210+
function HighlightMatch({ text, query }: { text: string; query: string }) {
211+
if (!query) return <>{text}</>;
212+
const idx = text.toLowerCase().indexOf(query.toLowerCase());
213+
if (idx === -1) return <>{text}</>;
214+
return (
215+
<>
216+
{text.slice(0, idx)}
217+
<MatchHighlight>{text.slice(idx, idx + query.length)}</MatchHighlight>
218+
{text.slice(idx + query.length)}
219+
</>
220+
);
221+
}
222+
205223
function ValueSuggestPopup({
206224
header,
207225
values,
208226
activeIndex,
209227
onSelect,
228+
query,
210229
}: {
211230
header: string;
212231
values: string[];
213232
activeIndex: number;
214233
onSelect: (value: string) => void;
234+
query: string;
215235
}) {
216236
return (
217237
<TagPopup role="listbox" aria-label={header}>
@@ -229,7 +249,7 @@ function ValueSuggestPopup({
229249
onSelect(v);
230250
}}
231251
>
232-
<TagItemName>{v}</TagItemName>
252+
<TagItemName><HighlightMatch text={v} query={query} /></TagItemName>
233253
</TagItem>
234254
))}
235255
</ValuePopupList>
@@ -444,6 +464,7 @@ export function SearchBox({
444464
values={secondLevelValues}
445465
activeIndex={activeIndex}
446466
onSelect={handleValueSelect}
467+
query={secondLevel.value}
447468
/>
448469
)}
449470
</SearchBoxWrapper>

0 commit comments

Comments
 (0)