xonecas.io
6615
Yc

yoctoselect / files

yoctoselect / src / filter.ts

921 bytes
1import type { SelectItem } from "./types.ts";
2
3export interface NormalizedItem {
4  label: string;
5  value: string;
6  filterText: string;
7}
8
9export function normalizeItems(items: SelectItem[]): NormalizedItem[] {
10  return items.map((item) => {
11    if (typeof item === "string") {
12      return { label: item, value: item, filterText: item };
13    }
14    return {
15      label: item.label,
16      value: item.value,
17      filterText: item.filterText ?? item.label,
18    };
19  });
20}
21
22export function prefixFilter(
23  items: NormalizedItem[],
24  query: string,
25): NormalizedItem[] {
26  if (!query) return items;
27  const q = query.toLowerCase();
28  return items.filter((item) => {
29    const text = item.filterText.toLowerCase();
30    if (text.startsWith(q)) return true;
31    // Also match if any word in filterText starts with the query
32    const words = text.split(/[\s/]+/);
33    return words.some((word) => word.startsWith(q));
34  });
35}