forked from denoland/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.client.ts
More file actions
567 lines (493 loc) · 17.4 KB
/
search.client.ts
File metadata and controls
567 lines (493 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// Orama Search Client
// This handles the client-side search functionality for the Deno docs
import type { Hit, OramaCloud, SearchResult } from "jsr:@orama/core@1.2.4";
interface OramaDocument {
title: string;
content: string;
url?: string;
path?: string;
category?: string;
section?: string;
kind?: string;
command?: string;
}
// Configuration - Replace these with your actual Orama Cloud credentials
const ORAMA_CONFIG = {
projectId: "c9394670-656a-4f78-a551-c2603ee119e7",
apiKey: "c1_E4q2kmwSiWpPYzeIzP38VyHmekjnZUJL3yB7Kprr8$YF-u_cXBSn3u0-AvX",
};
class OramaSearch {
private client: OramaCloud | null = null;
private searchInput: HTMLInputElement | null = null;
private searchResults: HTMLElement | null = null;
private searchLoading: HTMLElement | null = null;
private ariaLiveRegion: HTMLElement | null = null;
private searchTimeout: number | null = null;
private isResultsOpen = false;
private selectedIndex = -1; // Track selected result for keyboard navigation
constructor() {
this.init();
}
async init() {
// Wait for DOM to be ready
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => this.setupElements());
} else {
this.setupElements();
}
// Initialize Orama client
await this.initOramaClient();
}
setupElements() {
this.searchInput = document.getElementById(
"orama-search-input",
) as HTMLInputElement;
this.searchResults = document.getElementById(
"orama-search-results-content",
); // Target the scrollable container
this.searchLoading = document.getElementById("orama-search-loading");
this.ariaLiveRegion = document.getElementById("orama-results-announcer");
if (!this.searchInput) {
console.warn("Orama search input not found");
return;
}
// Bind event listeners
this.searchInput.addEventListener("input", this.handleInput.bind(this));
this.searchInput.addEventListener("focus", this.handleFocus.bind(this));
this.searchInput.addEventListener("keydown", this.handleKeyDown.bind(this));
this.searchResults?.addEventListener("keyup", (event) => {
if (event.key === "Escape") this.handleEscape();
});
document.addEventListener("keydown", (event) => {
if ((event.metaKey || event.ctrlKey) && event.key === "k") {
event.preventDefault();
this.searchInput?.focus();
}
});
const searchKey = document.getElementById("search-key");
let isMac = false;
const uaPlatform =
(navigator as Navigator & { userAgentData?: { platform?: string } })
.userAgentData?.platform;
if (
(uaPlatform && uaPlatform.toUpperCase().startsWith("MAC")) ||
navigator.userAgent.indexOf("Mac OS X") != -1 ||
navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i)
) {
isMac = true;
}
if (searchKey) {
if (isMac) {
searchKey.textContent = "⌘K";
} else {
searchKey.textContent = "Ctrl+K";
}
}
// Close search results when clicking outside
document.addEventListener("mousedown", this.handleClickOutside.bind(this));
}
async initOramaClient() {
try {
if (
ORAMA_CONFIG.projectId === "YOUR_ORAMA_PROJECT_ID_HERE" ||
ORAMA_CONFIG.apiKey === "YOUR_ORAMA_API_KEY_HERE"
) {
console.warn(
"Orama search not configured. Please add your project ID and API key to search.client.ts",
);
this.showNotConfiguredMessage();
return;
}
const { OramaCloud } = await import("jsr:@orama/core@1.2.4");
this.client = new OramaCloud({
projectId: ORAMA_CONFIG.projectId,
apiKey: ORAMA_CONFIG.apiKey,
});
console.log("Orama search client initialized successfully");
} catch (error) {
console.error("Failed to initialize Orama client:", error);
this.showErrorMessage("Failed to initialize search");
}
}
handleInput(event: Event) {
const value = (event.target as HTMLInputElement).value;
if (this.searchTimeout) {
clearTimeout(this.searchTimeout);
}
if (!value.trim()) {
this.hideResults();
return;
}
// Reset selection when user types
this.selectedIndex = -1;
// Debounce search by 300ms
this.searchTimeout = setTimeout(() => {
this.performSearch(value);
}, 300);
}
handleFocus() {
if (this.searchInput?.value.trim() && this.searchResults?.children.length) {
this.showResults();
}
}
handleEscape() {
this.hideResults();
if (this.searchInput) {
this.searchInput.value = ""; // Clears input when escape is triggered from within the list rather than on the input
this.searchInput.focus();
}
this.selectedIndex = -1;
}
handleKeyDown(event: KeyboardEvent) {
if (!this.isResultsOpen) {
return;
}
const resultsLinks = this.searchResults?.querySelectorAll(
".search-result-link",
);
const totalResults = resultsLinks?.length || 0;
switch (event.key) {
case "Escape":
this.handleEscape();
break;
case "ArrowDown":
event.preventDefault();
this.selectedIndex = Math.min(this.selectedIndex + 1, totalResults - 1);
this.updateSelection();
break;
case "ArrowUp":
event.preventDefault();
this.selectedIndex = Math.max(this.selectedIndex - 1, -1);
this.updateSelection();
break;
case "Enter":
event.preventDefault();
if (this.selectedIndex >= 0 && resultsLinks) {
const selectedLink =
resultsLinks[this.selectedIndex] as HTMLAnchorElement;
if (selectedLink) {
this.hideResults();
// Navigate to the selected result
globalThis.location.href = selectedLink.href;
}
}
break;
}
}
updateSelection() {
const resultsLinks = this.searchResults?.querySelectorAll(
".search-result-link",
);
if (!resultsLinks) return;
// Remove previous selection
resultsLinks.forEach((link, index) => {
link.classList.remove("bg-blue-50", "dark:bg-blue-900/20");
if (index === this.selectedIndex) {
link.classList.add("bg-blue-50", "dark:bg-blue-900/20");
// Scroll the selected item into view
link.scrollIntoView({ block: "nearest", behavior: "smooth" });
}
});
}
handleClickOutside(event: MouseEvent) {
const target = event.target as Element;
// Don't hide results if clicking on a search result link
if (target.closest(".search-result-link")) {
return;
}
// Check if click is outside the search container
const searchContainer = document.getElementById("orama-search-results");
if (
!this.searchInput?.parentElement?.contains(target) &&
!searchContainer?.contains(target)
) {
this.hideResults();
}
}
async performSearch(term: string) {
if (!this.client) {
this.showNotConfiguredMessage();
return;
}
this.showLoading(true);
try {
const results = await this.client.search({
term,
mode: "fulltext",
limit: 8,
threshold: 1,
properties: ["title", "content", "description"],
datasources: ["b03275f5-6d98-499e-9fe5-5d704221006e"],
boost: {
title: 12,
content: 4,
description: 2,
},
});
this.renderResults(
results as unknown as SearchResult<OramaDocument>,
term,
);
this.showResults();
} catch (error) {
console.error("Search error:", error);
this.showErrorMessage("Search failed. Please try again.");
} finally {
this.showLoading(false);
}
}
renderResults(results: SearchResult<OramaDocument>, searchTerm: string) {
if (!this.searchResults) return;
if (results.hits.length === 0) {
this.searchResults.innerHTML = `
<div class="p-4 border-b border-foreground-tertiary bg-background-secondary">
<h3 class="text-sm font-semibold text-foreground-primary">Search Results</h3>
</div>
<div class="p-8 text-center">
<div class="w-16 h-16 mx-auto mb-4 text-foreground-tertiary">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" class="w-full h-full">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
</svg>
</div>
<p class="text-sm font-medium text-foreground-primary mb-1">No results found</p>
<p class="text-xs text-foreground-secondary">Try different keywords or check your spelling</p>
</div>
`;
return;
}
// Filter out results that don't have valid URLs or paths
const validResults = results.hits.filter((hit) => {
// First check basic requirements
if (!hit.document) return false;
// Check if it has valid URL/path or can be constructed
const hasValidUrl = hit.document.url || hit.document.path ||
hit.document.title || hit.id;
if (!hasValidUrl) return false;
// Filter out navigation/menu content
if (this.isNavigationContent(hit)) {
return false;
}
return true;
})
// Sort by Orama's relevance score
.sort((a, b) => {
const scoreA = a.score || 0;
const scoreB = b.score || 0;
return scoreB - scoreA; // Higher score first
});
const resultsHtml = `
<div class="p-4 border-b border-foreground-tertiary bg-background-secondary">
<div class="flex items-center justify-between">
<h2 class="text-sm font-semibold text-foreground-primary" id="search-results__heading">Search Results</h2>
<span class="text-xs text-foreground-secondary">${validResults.length} result${
validResults.length !== 1 ? "s" : ""
}</span>
</div>
</div>
<ul aria-labelledby="search-results__heading">
${
validResults.map((hit) => `
<li>
<a
href="${
this.escapeHtml(hit.document.url || hit.document.path || "#")
}"
class="flex flex-col px-4 py-3 hover:bg-foreground-quaternary transition-colors duration-150 border-b border-foreground-quaternary last:border-b-0 search-result-link group"
>
<div class="font-bold text-foreground-primary text-sm mb-2 group-hover:text-primary transition-colors">
${
this.highlightMatch(
this.escapeHtml(this.cleanTitle(hit.document.title)),
searchTerm,
)
}
</div>
<div class="pl-3 border-l border-foreground-quaternary text-sm text-foreground-secondary leading-relaxed mb-2 line-clamp-3">
${
this.highlightMatch(
this.escapeHtml(hit.document.content.slice(0, 200)) + "...",
searchTerm,
)
}
</div>
<div class="flex items-center text-xs text-gray-500 dark:color-gray-600">
<svg class="w-3 h-3 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path>
</svg>
${this.escapeHtml(hit.document.url || hit.document.path || "")}
</div>
</a>
</li>
`).join("")
}
</ul>
`;
this.searchResults.innerHTML = resultsHtml;
// Reset selection for new results
this.selectedIndex = -1;
if (this.ariaLiveRegion) {
this.ariaLiveRegion.textContent =
`${validResults.length} results found for "${searchTerm}"`;
}
}
showNotConfiguredMessage() {
if (!this.searchResults) return;
this.searchResults.innerHTML = `
<div class="p-4 border-b border-foreground-tertiary bg-background-secondary">
<h3 class="text-sm font-semibold text-foreground-primary">Search</h3>
</div>
<div class="p-8 text-center">
<div class="w-16 h-16 mx-auto mb-4 text-foreground-tertiary">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" class="w-full h-full">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
</svg>
</div>
<p class="text-sm font-medium text-foreground-primary mb-1">Search not configured</p>
<p class="text-xs text-foreground-secondary">Please add your Orama credentials</p>
</div>
`;
this.showResults();
}
showErrorMessage(message: string) {
if (!this.searchResults) return;
this.searchResults.innerHTML = `
<div class="p-4 border-b border-foreground-tertiary bg-background-secondary">
<h3 class="text-sm font-semibold text-foreground-primary">Search Error</h3>
</div>
<div class="p-8 text-center">
<div class="w-16 h-16 mx-auto mb-4 text-red-500">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" class="w-full h-full">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
</div>
<p class="text-sm font-medium text-foreground-primary mb-1">${
this.escapeHtml(message)
}</p>
<p class="text-xs text-foreground-secondary">Please try again or contact support</p>
</div>
`;
this.showResults();
}
showResults() {
const resultsContainer = document.getElementById("orama-search-results");
if (resultsContainer) {
resultsContainer.classList.remove("hidden");
this.isResultsOpen = true;
}
}
hideResults() {
const resultsContainer = document.getElementById("orama-search-results");
if (resultsContainer) {
resultsContainer.classList.add("hidden");
this.isResultsOpen = false;
this.selectedIndex = -1; // Reset selection when hiding
}
}
showLoading(show: boolean) {
if (this.searchLoading) {
if (show) {
this.searchLoading.classList.remove("hidden");
} else {
this.searchLoading.classList.add("hidden");
}
}
}
highlightMatch(text: string, term: string): string {
if (!term.trim()) return text;
const regex = new RegExp(
`(${term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`,
"gi",
);
return text.replace(
regex,
'<mark class="bg-runtime px-[1px] py-0.5 rounded text-black font-bold">$1</mark>',
);
}
escapeHtml(text: string): string {
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
// Helper method to clean titles by removing unwanted text
cleanTitle(title: string): string {
if (!title) return title;
// Remove "jump to heading" patterns with any combination of spaces, dashes, and/or hashes
let cleaned = title
.replace(/[\s#-]*jump to heading[\s#-]*/gi, "")
.trim();
// Remove any trailing or leading hashes
cleaned = cleaned.replace(/^#+|#+$/g, "");
// If the title became empty, return the original
if (!cleaned || cleaned.trim() === "") {
return title;
}
return cleaned;
}
// Helper method to detect navigation/menu content
isNavigationContent(hit: Hit<OramaDocument>): boolean {
if (!hit.document) return false;
const title = hit.document.title?.toLowerCase() || "";
const content = hit.document.content?.toLowerCase() || "";
const section = hit.document.section?.toLowerCase() || "";
const category = hit.document.category?.toLowerCase() || "";
// Navigation indicators in titles
const navTitlePatterns = [
/^(home|menu|navigation|nav|sidebar|header|footer)$/,
/^(getting started|quick start|overview)$/,
/^(table of contents|toc)$/,
/^(breadcrumb|breadcrumbs)$/,
];
// Navigation indicators in content
const navContentPatterns = [
/^(home|menu|navigation|nav|sidebar|header|footer|skip to|jump to)$/,
/^\s*(getting started|quick start|overview|table of contents|toc|breadcrumb)\s*$/,
/^\s*\|\s*$/, // Just pipe characters (common in nav separators)
/^(previous|next|back|continue)$/,
];
// Check for very short content that's likely navigation
if (
content.length < 50 && (
navContentPatterns.some((pattern) => pattern.test(content)) ||
navTitlePatterns.some((pattern) => pattern.test(title))
)
) {
return true;
}
// Check if section/category indicates navigation
const navSections = [
"navigation",
"nav",
"menu",
"sidebar",
"header",
"footer",
"breadcrumb",
];
if (navSections.includes(section) || navSections.includes(category)) {
return true;
}
// Check for content that's mostly just links/navigation words
const navWords = [
"home",
"about",
"docs",
"api",
"guide",
"tutorial",
"reference",
"examples",
];
const words = content.split(/\s+/).filter((w) => w.length > 2);
if (words.length <= 5 && words.every((word) => navWords.includes(word))) {
return true;
}
return false;
}
}
// Initialize search when the script loads
const oramaSearch = new OramaSearch();
// Make it globally available for onclick handlers
declare global {
var oramaSearch: OramaSearch;
}
globalThis.oramaSearch = oramaSearch;