web/src/components/things/Search.svelte

260 lines · 7293 bytes

  1<script lang="ts">
  2  import { onMount } from 'svelte';
  3  import Fuse from 'fuse.js';
  4  import { fetchCategories, slugify } from '@utils/fetch-data';
  5  import { formatLink } from '@utils/parse-markdown';
  6  import { prepareSearchItems, searchOptions } from '@utils/do-searchy-searchy';
  7  import type { SearchItem } from '@utils/do-searchy-searchy';
  8
  9  interface Props {
 10    previousSearch?: string | undefined;
 11  }
 12  const { previousSearch = undefined }: Props = $props();
 13
 14  let fuse: Fuse<SearchItem> | null = $state(null);
 15  let searchQuery = $state('');
 16
 17  // Initialize Fuse.js
 18  onMount(async () => {
 19    const items = prepareSearchItems(await fetchCategories());
 20    fuse = new Fuse(items, searchOptions);
 21  });
 22
 23  const makeResultLink = (cat?: string, sec?: string, itm?: string) => {
 24    if (!cat) return '/';
 25    if (!sec) return `/${slugify(cat)}/`;
 26    if (!itm) return `/${slugify(cat)}/${slugify(sec)}/`;
 27    return `/${slugify(cat)}/${slugify(sec)}/${slugify(itm)}/`;
 28  };
 29
 30  const makeResultText = (cat?: string, sec?: string, itm?: string) => {
 31    if (itm) return itm;
 32    if (sec) return sec;
 33    if (cat) return cat;
 34    return '';
 35  };
 36
 37  const makeLogoSrc = (logo?: string, url?: string) => {
 38    if (!logo && !url) return '/broken-image.png';
 39    return logo || `https://icon.horse/icon/${formatLink(url || '')}`;
 40  };
 41
 42  const makeTitle = (typ?: string, desc?: string) => {
 43    if (desc && typ === 'Service') {
 44      return `${desc.slice(0, 60)}...`;
 45    }
 46    return '';
 47  };
 48
 49  let activeIndex = $state(-1);
 50
 51  const results: SearchItem[] = $derived(
 52    searchQuery && fuse
 53      ? fuse
 54          .search(searchQuery)
 55          .map((r) => r.item)
 56          .slice(0, 25)
 57      : [],
 58  );
 59
 60  function handleKeyDown(event: KeyboardEvent) {
 61    if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
 62      event.preventDefault();
 63      const step = event.key === 'ArrowDown' ? 1 : -1;
 64      activeIndex = (activeIndex + step + results.length) % results.length;
 65      return;
 66    }
 67    if (event.key === 'Enter') {
 68      event.preventDefault();
 69      const active = results[activeIndex];
 70      window.location.href = active
 71        ? makeResultLink(active.category, active.sectionName, active.name)
 72        : `/search/${encodeURIComponent(searchQuery)}/`;
 73    }
 74    if (event.key === 'Escape') {
 75      searchQuery = '';
 76      activeIndex = -1;
 77    }
 78  }
 79
 80  $effect(() => {
 81    searchQuery;
 82    activeIndex = -1;
 83  });
 84</script>
 85
 86<div class="search-wrap">
 87  <label for="search">
 88    What are you looking for?
 89    {#if searchQuery.length > 0}
 90      <span class="enter-hint">Press enter to view all results</span>
 91    {/if}
 92  </label>
 93  <input
 94    id="search"
 95    placeholder={previousSearch || 'Start typing...'}
 96    autocomplete="off"
 97    role="combobox"
 98    aria-expanded={results.length > 0}
 99    aria-controls="search-results"
100    aria-autocomplete="list"
101    aria-activedescendant={activeIndex >= 0
102      ? `search-result-${activeIndex}`
103      : undefined}
104    bind:value={searchQuery}
105    onkeydown={handleKeyDown}
106  />
107
108  {#if searchQuery.length > 0}
109    <div class="suggestions">
110      <ul id="search-results" role="listbox" aria-label="Search results">
111        {#each results as result, i (result.name + result.category + result.sectionName)}
112          <li
113            class="result-row"
114            class:active={i === activeIndex}
115            id={`search-result-${i}`}
116            role="option"
117            aria-selected={i === activeIndex}
118          >
119            <a
120              href={makeResultLink(
121                result.category,
122                result.sectionName,
123                result.name,
124              )}
125              title={makeTitle(result.type, result.description)}
126            >
127              <span class="name">
128                {#if result.type === 'Service'}
129                  <img
130                    src={makeLogoSrc(result.logo, result.url)}
131                    alt={result.name}
132                    width="20"
133                    height="20"
134                    loading="lazy"
135                  />
136                {/if}
137
138                {makeResultText(
139                  result.category,
140                  result.sectionName,
141                  result.name,
142                )}
143
144                {#if result.itemCount}
145                  <i>({result.itemCount})</i>
146                {/if}
147              </span>
148              <span class="path">
149                {result.category ? `${result.category}` : ''}
150                {result.sectionName ? `➔ ${result.sectionName}` : ''}
151                {result.name ? `➔ ${result.name}` : ''}
152              </span>
153            </a>
154          </li>
155        {/each}
156      </ul>
157    </div>
158  {/if}
159</div>
160
161<style lang="scss">
162  .search-wrap {
163    display: flex;
164    flex-direction: column;
165    position: relative;
166    max-width: 900px;
167    margin: 0 auto;
168    width: 100%;
169    label {
170      margin: var(--space-sm) 0;
171      display: flex;
172      justify-content: space-between;
173      align-items: center;
174      flex-wrap: wrap;
175      .enter-hint {
176        font-size: var(--text-sm);
177        opacity: var(--opacity-soft);
178      }
179    }
180
181    input {
182      padding: var(--space-sm) var(--space-md);
183      font-size: var(--text-2xl);
184      border: var(--border-heavy);
185      box-shadow: var(--shadow-sm);
186      z-index: 4;
187      background: var(--background-form);
188      color: var(--foreground);
189      &:focus {
190        outline: none;
191        border-color: var(--accent);
192        box-shadow: 3px 3px 0 var(--accent);
193      }
194    }
195
196    .suggestions {
197      ul {
198        position: absolute;
199        background: var(--background-form);
200        z-index: 3;
201        width: 100%;
202
203        list-style: none;
204        padding: 0;
205        margin: 0;
206        border: var(--border-heavy);
207        border-radius: 0 0 var(--curve-lg) var(--curve-lg);
208        box-shadow: var(--shadow-sm);
209        transform: translateY(-0.5rem);
210        max-height: 500px;
211        overflow-y: auto;
212        li.result-row {
213          padding: var(--space-sm) var(--space-md);
214          margin: var(--space-sm) 0;
215          a {
216            color: var(--foreground);
217            text-decoration: none;
218            display: flex;
219            justify-content: space-between;
220            flex-wrap: wrap;
221            .name {
222              display: flex;
223              align-items: center;
224              gap: var(--space-sm);
225              i {
226                color: var(--accent-text);
227                font-weight: bold;
228                font-style: normal;
229              }
230              img {
231                border-radius: var(--curve-md);
232                width: 1.25rem;
233                height: 1.25rem;
234                object-fit: contain;
235                font-size: 10px;
236                color: var(--accent-text);
237                overflow: hidden;
238                background: var(--accent-translucent);
239                padding: 1px;
240              }
241            }
242            .path {
243              font-size: var(--text-sm);
244              opacity: var(--opacity-soft);
245            }
246          }
247          &:hover,
248          &.active {
249            background: var(--accent);
250            a,
251            .name i,
252            .path {
253              color: var(--accent-fg);
254            }
255          }
256        }
257      }
258    }
259  }
260</style>