Debian Codegraph @

www/src/assets/js/search-index.js

raw symbols SCIP
1 import {Document, Charset} from 'flexsearch';
2
3 /**
4 * Generic search index web component wrapping FlexSearch.
5 *
6 * @example Basic usage (zero config)
7 * <search-index src="/search.json"></search-index>
8 *
9 * @example With options
10 * <search-index
11 * src="/search.json"
12 * fields="title,description"
13 * highlight="<mark>$1</mark>"
14 * preload
15 * ></search-index>
16 *
17 * @attr {string} src - URL to fetch search data from (required)
18 * @attr {string} fields - Comma-separated fields to search (default: all strings except id/url)
19 * @attr {string} highlight - Highlight template, $1 = matched text
20 * @attr {number} limit - Default result limit (default: 50)
21 * @attr {string} tokenize - strict | forward | reverse | full (default: forward)
22 * @attr {boolean} suggest - Enable fuzzy matching (default: true)
23 * @attr {boolean} preload - Load index on connect
24 */
25 class SearchIndex extends HTMLElement {
26 constructor() {
27 super();
28 this.index = null;
29 this.loadingPromise = null;
30 this.rawData = [];
31 this.schema = new Set();
32 }
33
34 static get observedAttributes() {
35 return ['src', 'highlight', 'limit', 'suggest', 'tokenize', 'fields'];
36 }
37
38 // Property accessors
39 get src() {
40 return this.getAttribute('src');
41 }
42 set src(value) {
43 if (value) this.setAttribute('src', value);
44 else this.removeAttribute('src');
45 }
46
47 get fields() {
48 const attr = this.getAttribute('fields');
49 return attr ? attr.split(',').map(f => f.trim()) : null;
50 }
51 set fields(value) {
52 if (value) this.setAttribute('fields', value.join(','));
53 else this.removeAttribute('fields');
54 }
55
56 get highlight() {
57 return this.getAttribute('highlight');
58 }
59 set highlight(value) {
60 if (value) this.setAttribute('highlight', value);
61 else this.removeAttribute('highlight');
62 }
63
64 get limit() {
65 return Number(this.getAttribute('limit')) || 50;
66 }
67 set limit(value) {
68 this.setAttribute('limit', String(value));
69 }
70
71 get suggest() {
72 return this.hasAttribute('suggest') ? this.getAttribute('suggest') !== 'false' : true;
73 }
74 set suggest(value) {
75 this.toggleAttribute('suggest', value);
76 }
77
78 get preload() {
79 return this.hasAttribute('preload');
80 }
81 set preload(value) {
82 this.toggleAttribute('preload', value);
83 }
84
85 get ready() {
86 return this.index !== null;
87 }
88
89 connectedCallback() {
90 if (this.preload) {
91 this.load().catch(err => console.error('<search-index>: preload failed', err));
92 }
93 }
94
95 attributeChangedCallback(name, oldValue, newValue) {
96 if (oldValue === newValue) return;
97
98 // Reset index if configuration changes
99 if (['src', 'tokenize', 'fields'].includes(name) && this.index) {
100 this.clear();
101 }
102 }
103
104 async load() {
105 if (this.loadingPromise) return this.loadingPromise;
106 if (this.index) return Promise.resolve();
107
108 const src = this.src;
109 if (!src) {
110 throw new Error('<search-index>: "src" attribute is required');
111 }
112
113 this.setAttribute('data-loading', '');
114 this.removeAttribute('data-error');
115
116 this.loadingPromise = (async () => {
117 try {
118 const response = await fetch(src);
119 if (!response.ok) {
120 throw new Error(`Failed to fetch: ${response.statusText}`);
121 }
122 const data = await response.json();
123 this.rawData = data.results || [];
124
125 if (this.rawData.length === 0) {
126 console.warn('<search-index>: No results in data');
127 return;
128 }
129
130 // Build schema from ALL results (not just first one)
131 this.schema = this._buildSchema(this.rawData);
132
133 // Determine searchable fields
134 const searchableFields = this._getSearchableFields();
135
136 // Create FlexSearch index
137 this.index = new Document({
138 document: {
139 id: 'id',
140 index: searchableFields,
141 store: Array.from(this.schema) // Always store everything
142 },
143 tokenize: this.getAttribute('tokenize') || 'forward',
144 charset: Charset.LatinBalance,
145 optimize: true,
146 cache: true
147 });
148
149 // Populate index
150 for (const result of this.rawData) {
151 this.index.add(result);
152 }
153
154 this.dispatchEvent(new CustomEvent('load', {
155 detail: {
156 count: this.rawData.length,
157 fields: searchableFields,
158 schema: Array.from(this.schema)
159 },
160 bubbles: true
161 }));
162 } catch (error) {
163 console.error('<search-index>:', error);
164 this.setAttribute('data-error', '');
165 this.dispatchEvent(new CustomEvent('error', {
166 detail: {error},
167 bubbles: true
168 }));
169 throw error;
170 } finally {
171 this.removeAttribute('data-loading');
172 this.loadingPromise = null;
173 }
174 })();
175
176 return this.loadingPromise;
177 }
178
179 async search(query, options = {}) {
180 await this.load();
181
182 if (!this.index) return [];
183
184 const trimmedQuery = query?.trim();
185 if (!trimmedQuery) {
186 this.removeAttribute('data-searched');
187 this.removeAttribute('data-empty');
188 return [];
189 }
190
191 this.setAttribute('data-searching', '');
192
193 const searchOptions = {
194 limit: options.limit ?? this.limit,
195 suggest: options.suggest ?? this.suggest,
196 enrich: true,
197 ...options
198 };
199
200 const searchResults = this.index.search(trimmedQuery, searchOptions);
201
202 // Build lookup map from rawData (preserves nested objects like meta)
203 const dataMap = new Map(this.rawData.map(item => [item.id, item]));
204
205 // Deduplicate results across fields
206 const seen = new Set();
207 const results = [];
208
209 for (const fieldResult of searchResults) {
210 for (const match of fieldResult.result || []) {
211 const id = typeof match === 'object' ? (match.id ?? match.doc?.id) : match;
212 if (id == null || seen.has(id)) continue;
213 seen.add(id);
214
215 const doc = dataMap.get(id);
216 if (!doc) continue;
217
218 // Highlight text fields if configured
219 const tpl = this.highlight;
220 if (tpl) {
221 results.push(this._highlight(doc, trimmedQuery, tpl));
222 } else {
223 results.push(doc);
224 }
225 }
226 }
227
228 // Supplement: add any keyword matches FlexSearch may have missed
229 // (e.g. very short queries like "ws" that FlexSearch can't tokenize)
230 const queryLower = trimmedQuery.toLowerCase();
231 for (const doc of this.rawData) {
232 if (seen.has(doc.id) || !doc.keywords) continue;
233 const kw = doc.keywords.toLowerCase().split(/,\s*/);
234 if (kw.includes(queryLower)) {
235 seen.add(doc.id);
236 const tpl = this.highlight;
237 results.push(tpl ? this._highlight(doc, trimmedQuery, tpl) : doc);
238 }
239 }
240
241 // Sort results by relevance.
242 // Priority: exact title > exact keyword > partial title match.
243 // Case-sensitive is tried first so "HX-Trigger" (header) beats
244 // "hx-trigger" (attribute). Case-insensitive is used as a fallback so
245 // "headers" still finds "Headers".
246 results.sort((a, b) => {
247 const aRaw = a.title?.replace(/<[^>]*>/g, '') || '';
248 const bRaw = b.title?.replace(/<[^>]*>/g, '') || '';
249 const aLower = aRaw.toLowerCase();
250 const bLower = bRaw.toLowerCase();
251
252 // Keywords: split comma-separated string, check if query matches any keyword
253 const aKw = (a.keywords || '').toLowerCase().split(/,\s*/);
254 const bKw = (b.keywords || '').toLowerCase().split(/,\s*/);
255 const aHasKw = aKw.includes(queryLower);
256 const bHasKw = bKw.includes(queryLower);
257
258 // 1. Case-sensitive exact title match
259 const aExact = aRaw === trimmedQuery;
260 const bExact = bRaw === trimmedQuery;
261 if (aExact !== bExact) return aExact ? -1 : 1;
262
263 // 2. Case-insensitive exact title match
264 const aExactI = aLower === queryLower;
265 const bExactI = bLower === queryLower;
266 if (aExactI !== bExactI) return aExactI ? -1 : 1;
267
268 // 3. Exact keyword match (curated aliases like "sse", "ws")
269 if (aHasKw !== bHasKw) return aHasKw ? -1 : 1;
270
271 // 4. Case-sensitive title contains
272 const aContains = aRaw.includes(trimmedQuery);
273 const bContains = bRaw.includes(trimmedQuery);
274 if (aContains !== bContains) return aContains ? -1 : 1;
275
276 // 5. Case-insensitive title contains
277 const aContainsI = aLower.includes(queryLower);
278 const bContainsI = bLower.includes(queryLower);
279 if (aContainsI !== bContainsI) return aContainsI ? -1 : 1;
280
281 return 0;
282 });
283
284 this.removeAttribute('data-searching');
285 this.setAttribute('data-searched', '');
286 this.toggleAttribute('data-empty', results.length === 0);
287
288 this.dispatchEvent(new CustomEvent('search', {
289 detail: {query: trimmedQuery, results, count: results.length},
290 bubbles: true
291 }));
292
293 return results;
294 }
295
296 _highlight(doc, query, template) {
297 const terms = query.split(/\s+/).filter(Boolean);
298 if (!terms.length) return doc;
299
300 const pattern = new RegExp(
301 `(${terms.map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})`,
302 'gi'
303 );
304 const wrap = (str) => typeof str === 'string' ? str.replace(pattern, template) : str;
305
306 const highlighted = {
307 ...doc,
308 title: wrap(doc.title),
309 description: wrap(doc.description)
310 };
311
312 // If nothing was highlighted in title or description, this was a
313 // keyword-only match (e.g. "ws" → "Web Sockets"). Show the matching
314 // keyword so the user understands why this result appeared.
315 if (highlighted.title === doc.title && highlighted.description === doc.description && doc.keywords) {
316 const queryLower = query.toLowerCase();
317 const kw = doc.keywords.split(/,\s*/);
318 const match = kw.find(k => k.toLowerCase() === queryLower);
319 if (match) {
320 const kwTag = template.replace('$1', match);
321 highlighted.description = highlighted.description
322 ? `${kwTag} · ${highlighted.description}`
323 : kwTag;
324 }
325 }
326
327 return highlighted;
328 }
329
330 clear() {
331 this.index = null;
332 this.loadingPromise = null;
333 this.rawData = [];
334 this.schema.clear();
335 this.removeAttribute('data-loading');
336 this.removeAttribute('data-searched');
337 this.removeAttribute('data-empty');
338 this.removeAttribute('data-error');
339 }
340
341 update(doc) {
342 if (!this.index) throw new Error('Index not loaded');
343 this.index.update(doc);
344 }
345
346 // this was named remove but renamed to avoid prototype pollution
347 // causing hx-preserve remove to break
348 removeDoc(id) {
349 if (!this.index) throw new Error('Index not loaded');
350 this.index.remove(id);
351 }
352
353 add(doc) {
354 if (!this.index) throw new Error('Index not loaded');
355 this.index.add(doc);
356 this.rawData.push(doc);
357 // Update schema with new fields
358 Object.keys(doc).forEach(key => this.schema.add(key));
359 }
360
361 getData() {
362 return [...this.rawData];
363 }
364
365 getSchema() {
366 return Array.from(this.schema);
367 }
368
369 // Private: Build complete schema from ALL results
370 _buildSchema(results) {
371 const schema = new Set();
372 for (const result of results) {
373 Object.keys(result).forEach(key => schema.add(key));
374 }
375 return schema;
376 }
377
378 // Private: Determine which fields should be searchable
379 _getSearchableFields() {
380 // If explicitly configured, use that
381 const explicitFields = this.fields;
382 if (explicitFields) {
383 return explicitFields;
384 }
385
386 // Default: search all string fields except id/url
387 const firstResult = this.rawData[0];
388 return Array.from(this.schema).filter(key => {
389 if (['id', 'url'].includes(key)) return false;
390 // Check if field is string in first result (performance optimization)
391 return typeof firstResult[key] === 'string';
392 });
393 }
394 }
395
396 customElements.define('search-index', SearchIndex);