| 1 |
import {Document, Charset} from 'flexsearch'; |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 131 |
this.schema = this._buildSchema(this.rawData); |
| 132 |
|
| 133 |
|
| 134 |
const searchableFields = this._getSearchableFields(); |
| 135 |
|
| 136 |
|
| 137 |
this.index = new Document({ |
| 138 |
document: { |
| 139 |
id: 'id', |
| 140 |
index: searchableFields, |
| 141 |
store: Array.from(this.schema) |
| 142 |
}, |
| 143 |
tokenize: this.getAttribute('tokenize') || 'forward', |
| 144 |
charset: Charset.LatinBalance, |
| 145 |
optimize: true, |
| 146 |
cache: true |
| 147 |
}); |
| 148 |
|
| 149 |
|
| 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 |
|
| 203 |
const dataMap = new Map(this.rawData.map(item => [item.id, item])); |
| 204 |
|
| 205 |
|
| 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 |
|
| 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 |
|
| 229 |
|
| 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 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 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 |
|
| 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 |
|
| 259 |
const aExact = aRaw === trimmedQuery; |
| 260 |
const bExact = bRaw === trimmedQuery; |
| 261 |
if (aExact !== bExact) return aExact ? -1 : 1; |
| 262 |
|
| 263 |
|
| 264 |
const aExactI = aLower === queryLower; |
| 265 |
const bExactI = bLower === queryLower; |
| 266 |
if (aExactI !== bExactI) return aExactI ? -1 : 1; |
| 267 |
|
| 268 |
|
| 269 |
if (aHasKw !== bHasKw) return aHasKw ? -1 : 1; |
| 270 |
|
| 271 |
|
| 272 |
const aContains = aRaw.includes(trimmedQuery); |
| 273 |
const bContains = bRaw.includes(trimmedQuery); |
| 274 |
if (aContains !== bContains) return aContains ? -1 : 1; |
| 275 |
|
| 276 |
|
| 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 |
|
| 313 |
ng |
| 314 |
|
| 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 |
|
| 347 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 379 |
_getSearchableFields() { |
| 380 |
|
| 381 |
const explicitFields = this.fields; |
| 382 |
if (explicitFields) { |
| 383 |
return explicitFields; |
| 384 |
} |
| 385 |
|
| 386 |
|
| 387 |
const firstResult = this.rawData[0]; |
| 388 |
return Array.from(this.schema).filter(key => { |
| 389 |
if (['id', 'url'].includes(key)) return false; |
| 390 |
|
| 391 |
return typeof firstResult[key] === 'string'; |
| 392 |
}); |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
customElements.define('search-index', SearchIndex); |