forked from meilisearch/documentation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.js
More file actions
630 lines (537 loc) · 23.4 KB
/
search.js
File metadata and controls
630 lines (537 loc) · 23.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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
const MEILISEARCH_HOST = 'https://ms-909f535664f8-173.lon.meilisearch.io'
const MEILISEARCH_API_KEY = '776dc6a11c118bd1640c3a9ff9679f920bc384238534fc4861fcde0152e7fd68'; // Public search-only API key
const MEILISEARCH_INDEX = 'mintlify-production';
function initializeMeilisearchIntegration() {
// Add a check at the start of the function to prevent multiple initializations
if (document.getElementById('meilisearch-bar-container')) {
return;
}
// Modify the responsive visibility handler
const handleResponsiveVisibility = () => {
// Check for both possible IDs
const searchBarContainer = document.getElementById('meilisearch-bar-container');
const originalSearchButton = document.getElementById('search-bar-entry');
const originalMobileSearchButton = document.getElementById('search-bar-entry-mobile');
if (!searchBarContainer) return;
const isMobileView = window.innerWidth < 1024;
if (isMobileView) {
// Hide our search bar
searchBarContainer.style.display = 'none';
if (originalSearchButton) {
originalSearchButton.style.display = 'none';
}
// Show Mintlify's search buttons
if (originalMobileSearchButton) {
originalMobileSearchButton.style.display = 'flex';
}
} else {
// Show our search bar
searchBarContainer.style.display = 'block';
// Hide Mintlify's search buttons
if (originalSearchButton) {
originalSearchButton.style.display = 'none';
}
if (originalMobileSearchButton) {
originalMobileSearchButton.style.display = 'none';
}
}
};
// ========= Step 1: Create and inject the visible search bar in the header =========
const initSearchBar = () => {
// When finding the original search button, also look for mobile version icon
const originalSearchButton = document.getElementById('search-bar-entry');
const originalMobileSearchButton = document.getElementById('search-bar-entry-mobile');
// Find the header where we'll add our search input
const header = document.querySelector('header');
if (!header) { //header not found, cannot add search bar
return;
}
// Log header properties to help with debugging
// console.log('Header found, dimensions:', {
// width: header.offsetWidth,
// height: header.offsetHeight,
// position: window.getComputedStyle(header).position
// });
// Try to find a proper container within the header for the search
let headerContainer = null;
// Option 1: Look for navigation in the header
const navElement = header.querySelector('nav');
if (navElement) {
headerContainer = navElement;
}
// Option 2: Look for a flex container in the header
else {
const potentialContainers = Array.from(header.children).filter(el => {
const style = window.getComputedStyle(el);
return style.display === 'flex' || style.display === 'inline-flex';
});
if (potentialContainers.length > 0) {
// Use the widest container
headerContainer = potentialContainers.reduce((prev, current) => {
return (prev.offsetWidth > current.offsetWidth) ? prev : current;
});
} else {
// Use the header itself as a last resort
headerContainer = header;
}
}
// If we found the original search button, use its positioning and parent
if (originalSearchButton) {
// Get the parent element of the search button
const searchParent = originalSearchButton.parentElement;
if (searchParent) {
headerContainer = searchParent;
}
}
// Create our search input container
const searchBarContainer = document.createElement('div');
searchBarContainer.id = 'meilisearch-bar-container';
searchBarContainer.className = 'meilisearch-bar-container';
// Create the search input that looks like Meilisearch's
const searchBar = document.createElement('div');
searchBar.id = 'meilisearch-search-bar';
searchBar.className = 'meilisearch-search-bar';
searchBar.role = 'button';
searchBar.tabIndex = 0;
// Add the search icon and placeholder text
searchBar.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 10px;">
<circle cx="11" cy="11" r="8"></circle>
<path d="m21 21-4.3-4.3"></path>
</svg>
<span class="meilisearch-search-bar__text">Search…</span>
<span class="meilisearch-search-bar__shortcut">⌘K</span>
`;
// Append the search bar to the container
searchBarContainer.appendChild(searchBar);
// Check if the header container is a flex container
const containerStyle = window.getComputedStyle(headerContainer);
const isFlexContainer = containerStyle.display === 'flex' || containerStyle.display === 'inline-flex';
// If the header isn't a flex container, we need to make it one for proper centering
if (!isFlexContainer) {
// Create a wrapper to center the search bar
const flexWrapper = document.createElement('div');
flexWrapper.className = 'meilisearch-flexwrapper';
flexWrapper.appendChild(searchBarContainer);
headerContainer.appendChild(flexWrapper);
} else {
// Insert the search container into the flex container
// Find the right position - ideally in the middle
const childCount = headerContainer.children.length;
if (childCount > 2) {
// If there are more than 2 children, insert it in the middle
const middleIndex = Math.floor(childCount / 2);
const referenceNode = headerContainer.children[middleIndex];
headerContainer.insertBefore(searchBarContainer, referenceNode);
} else {
// Otherwise just append it
headerContainer.appendChild(searchBarContainer);
// If this is a flex container, we need to adjust styles for centering
searchBarContainer.style.flex = '1';
searchBarContainer.style.margin = '0 auto';
}
}
// ========= Step 2: Create the modal search overlay =========
const modalOverlay = document.createElement('div');
modalOverlay.id = 'meilisearch-modal-overlay';
modalOverlay.className = 'meilisearch-modal-overlay';
// Create the search modal container
const searchModal = document.createElement('div');
searchModal.id = 'meilisearch-modal';
searchModal.className = 'meilisearch-modal';
// Create the search input container
const searchInputContainer = document.createElement('div');
searchInputContainer.className = 'meilisearch-modal__input-container'
// Create the search input
const searchInput = document.createElement('input');
searchInput.id = 'meilisearch-search-input';
searchInput.className = 'meilisearch-modal__input';
searchInput.type = 'text';
searchInput.placeholder = 'Search…';
// Create the ESC key indicator
const escIndicator = document.createElement('span');
escIndicator.textContent = 'ESC';
escIndicator.className = 'meilisearch-modal__escape';
// Create the search icon
const searchIcon = document.createElement('div');
searchIcon.className = 'meilisearch-modal__icon';
searchIcon.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 10px;">
<circle cx="11" cy="11" r="8"></circle>
<path d="m21 21-4.3-4.3"></path>
</svg>
`;
// Add elements to the search input container
searchInputContainer.appendChild(searchIcon);
searchInputContainer.appendChild(searchInput);
searchInputContainer.appendChild(escIndicator);
// Create the results container
const resultsContainer = document.createElement('div');
resultsContainer.id = 'meilisearch-results';
resultsContainer.className = 'meilisearch-modal__results';
resultsContainer.style.cssText = `
`;
// Create the faceted filter container
const filterContainer = document.createElement('div');
filterContainer.id = 'meilisearch-filter-container';
filterContainer.className = 'meilisearch-filter-container';
filterContainer.style.display = 'none';
// Create filter title
const filterTitle = document.createElement('div');
filterTitle.className = 'meilisearch-filter-title';
filterTitle.textContent = 'Narrow down by section';
// Create filter tags container
const filterTagsContainer = document.createElement('div');
filterTagsContainer.className = 'meilisearch-filter-tags';
// Create filter tags for each section
const sections = ['learn', 'guides', 'reference'];
const filterTags = {};
sections.forEach(section => {
const tag = document.createElement('button');
tag.className = 'meilisearch-filter-tag';
tag.textContent = section;
tag.dataset.section = section;
tag.addEventListener('click', () => {
tag.classList.toggle('active');
// Get current active filters
const activeFilters = Array.from(filterContainer.querySelectorAll('.meilisearch-filter-tag.active'))
.map(tag => tag.dataset.section);
// Show filter container if there are active filters
filterContainer.style.display = activeFilters.length > 0 ? 'block' : 'none';
// Trigger search with current filters if there's a search query
if (searchInput.value.trim().length >= 2) {
const inputEvent = new Event('input', { bubbles: true });
searchInput.dispatchEvent(inputEvent);
}
});
filterTagsContainer.appendChild(tag);
filterTags[section] = tag;
});
// Add filter elements to container
filterContainer.appendChild(filterTitle);
filterContainer.appendChild(filterTagsContainer);
// Append everything to the modal
searchModal.appendChild(searchInputContainer);
searchModal.appendChild(filterContainer);
searchModal.appendChild(resultsContainer);
// Add the modal to the overlay
modalOverlay.appendChild(searchModal);
// Add the overlay to the body
document.body.appendChild(modalOverlay);
// ========= Step 3: Set up event listeners =========
// Function to open the search modal
const openSearchModal = () => {
// Always place the modal at the top, regardless of scroll position
modalOverlay.style.display = 'flex';
// Focus the input
setTimeout(() => {
searchInput.focus();
}, 10);
};
// Function to close the search modal
const closeSearchModal = () => {
modalOverlay.style.display = 'none';
searchInput.value = '';
resultsContainer.innerHTML = '';
};
// Function to handle clicks on Mintlify search buttons
const handleMintlifySearchClick = (e) => {
e.preventDefault();
e.stopPropagation();
openSearchModal();
};
// Open modal when clicking the search bar
searchBar.addEventListener('click', openSearchModal);
// Add click handlers to Mintlify search buttons
if (originalSearchButton) {
originalSearchButton.addEventListener('click', handleMintlifySearchClick);
}
if (originalMobileSearchButton) {
originalMobileSearchButton.addEventListener('click', handleMintlifySearchClick);
}
// Add handlers for any search buttons that might be added later
const searchButtonObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.addedNodes.length) {
mutation.addedNodes.forEach((node) => {
if (node.id === 'search-bar-entry' || node.id === 'search-bar-entry-mobile') {
node.addEventListener('click', handleMintlifySearchClick);
}
});
}
});
});
searchButtonObserver.observe(document.body, { childList: true, subtree: true });
// Close modal when clicking outside the search modal
modalOverlay.addEventListener('click', (e) => {
if (e.target === modalOverlay) {
closeSearchModal();
}
});
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
// Open with Cmd+K / Ctrl+K
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
openSearchModal();
return false;
}
// Close with Escape
if (e.key === 'Escape' && modalOverlay.style.display === 'flex') {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
closeSearchModal();
return false;
}
}, true);
// ========= Step 4: Set up Meilisearch for searching =========
// Load Meilisearch client
if (!window.meilisearch) {
const meilisearchScript = document.createElement('script');
meilisearchScript.src = 'https://cdn.jsdelivr.net/npm/meilisearch@latest/dist/bundles/meilisearch.umd.js';
meilisearchScript.onload = () => {
// The UMD bundle exposes MeiliSearch directly, no need to access .default
window.meilisearch = window.MeiliSearch;
setupMeilisearchHandlers(searchInput, resultsContainer);
};
document.head.appendChild(meilisearchScript);
} else {
setupMeilisearchHandlers(searchInput, resultsContainer);
}
// Make sure we call handleResponsiveVisibility immediately after creating the search bar
handleResponsiveVisibility();
// Add a debounced resize listener to prevent too many calls
let resizeTimeout;
window.addEventListener('resize', () => {
if (resizeTimeout) {
clearTimeout(resizeTimeout);
}
resizeTimeout = setTimeout(handleResponsiveVisibility, 100);
});
};
// Set up the search functionality
const setupMeilisearchHandlers = (searchInput, resultsContainer) => {
try {
const client = new window.meilisearch({
host: MEILISEARCH_HOST,
apiKey: MEILISEARCH_API_KEY
});
const index = client.index(MEILISEARCH_INDEX);
// Function to get active filters
const getActiveFilters = () => {
const filterContainer = document.getElementById('meilisearch-filter-container');
if (!filterContainer) return [];
const activeTags = filterContainer.querySelectorAll('.meilisearch-filter-tag.active');
return Array.from(activeTags).map(tag => tag.dataset.section);
};
// Function to perform search with filters
const performSearch = (query, activeFilters = []) => {
// Show loading indicator
const indicatorEl = document.createElement('div');
indicatorEl.className = 'meilisearch-modal__indicator';
indicatorEl.innerHTML = 'Searching…';
resultsContainer.appendChild(indicatorEl);
// Build base search options
const baseSearchOptions = {
attributesToHighlight: ['hierarchy_lvl1', 'hierarchy_lvl2', 'hierarchy_lvl3', 'hierarchy_lvl4', 'hierarchy_lvl5', 'content'],
attributesToCrop: ['content'],
cropLength: 100,
hybrid: {
semanticRatio: 0.5,
embedder: "default"
}
};
// Create federated multi-search queries
const multiSearchQueries = [
{
indexUid: MEILISEARCH_INDEX,
q: query,
// Lower weight for error code results
filter: activeFilters.length > 0
? `(${activeFilters.map(section => `section = "${section}"`).join(' OR ')}) AND (hierarchy_lvl0 = "Errors" OR hierarchy_lvl1 = "Error codes")`
: `hierarchy_lvl0 = "Errors" OR hierarchy_lvl1 = "Error codes"`,
federationOptions: {
weight: 0.7
},
...baseSearchOptions
},
{
indexUid: MEILISEARCH_INDEX,
q: query,
// Higher weight for non-error code results
filter: activeFilters.length > 0
? `(${activeFilters.map(section => `section = "${section}"`).join(' OR ')}) AND NOT (hierarchy_lvl0 = "Errors" OR hierarchy_lvl1 = "Error codes")`
: `NOT (hierarchy_lvl0 = "Errors" OR hierarchy_lvl1 = "Error codes")`,
federationOptions: {
weight: 1.0
},
...baseSearchOptions
}
];
// Perform federated multi-search
const multiSearchRequest = {
federation: {
limit: 25
},
queries: multiSearchQueries
};
client.multiSearch(multiSearchRequest)
.then(response => {
resultsContainer.innerHTML = '';
const filterContainer = document.getElementById('meilisearch-filter-container');
// Handle federated multi-search response
const allHits = response.hits || [];
if (allHits.length === 0) {
if (filterContainer) filterContainer.style.display = 'none';
const noResultsEl = document.createElement('div');
noResultsEl.className = 'meilisearch-modal__indicator';
noResultsEl.innerHTML = 'No results found';
resultsContainer.appendChild(noResultsEl);
return;
}
// Show filter container when there are results
if (filterContainer) filterContainer.style.display = 'block';
// Group results by category if available
const grouped = {};
allHits.forEach(hit => {
const category = hit.hierarchy_lvl0 || 'General';
if (!grouped[category]) {
grouped[category] = [];
}
grouped[category].push(hit);
});
// Create result items
Object.keys(grouped).forEach(category => {
const results = grouped[category];
// Only add category header if there are multiple categories
if (Object.keys(grouped).length > 1) {
const categoryHeader = document.createElement('div');
categoryHeader.className = 'meilisearch-modal__category-header';
categoryHeader.textContent = category;
resultsContainer.appendChild(categoryHeader);
}
results.forEach(hit => {
const resultItem = document.createElement('a');
resultItem.href = hit.url || `/${hit.path}`;
resultItem.className = 'meilisearch-modal__result';
// Format content nicely
// Build title from hierarchy levels
const hierarchy_lvl1 = hit._formatted?.hierarchy_lvl1
? hit._formatted.hierarchy_lvl1.replace(/<em>/g, '<em class="meilisearch-modal__category-em">')
: '';
const hierarchy_lvl2 = hit._formatted?.hierarchy_lvl2
? hit._formatted.hierarchy_lvl2.replace(/<em>/g, '<em class="meilisearch-modal__category-em">')
: '';
const hierarchy_lvl3 = hit._formatted?.hierarchy_lvl3
? hit._formatted.hierarchy_lvl3.replace(/<em>/g, '<em class="meilisearch-modal__category-em">')
: '';
const hierarchy_lvl4 = hit._formatted?.hierarchy_lvl4
? hit._formatted.hierarchy_lvl4.replace(/<em>/g, '<em class="meilisearch-modal__category-em">')
: '';
const hierarchy_lvl5 = hit._formatted?.hierarchy_lvl5
? hit._formatted.hierarchy_lvl5.replace(/<em>/g, '<em class="meilisearch-modal__category-em">')
: '';
const content = hit._formatted?.content
? hit._formatted.content.replace(/<em>/g, '<em class="meilisearch-modal__category-em">')
: '';
let title = '';
if (hierarchy_lvl1) {
title = hierarchy_lvl1;
if (hierarchy_lvl2) {
title += ' > ' + hierarchy_lvl2;
if (hierarchy_lvl3) {
title += ' > ' + hierarchy_lvl3;
if (hierarchy_lvl4) {
title += ' > ' + hierarchy_lvl4;
if (hierarchy_lvl5) {
title += ' > ' + hierarchy_lvl5;
}
}
}
}
}
resultItem.innerHTML = `
<div class="meilisearch-modal__result-heading">${title}</div>
${content ? `<div class="meilisearch-modal__result-content">${content}</div>` : ''}
`;
// Make clicking the result close the modal
resultItem.addEventListener('click', () => {
document.getElementById('meilisearch-modal-overlay').style.display = 'none';
});
resultsContainer.appendChild(resultItem);
});
});
})
.catch(error => {
console.error('Meilisearch error:', error);
const errorEl = document.createElement('div');
errorEl.className = 'meilisearch-modal__error';
errorEl.innerHTML = 'Search error. Please try again.';
resultsContainer.appendChild(errorEl);
});
};
// Add search event listener
let debounceTimer;
searchInput.addEventListener('input', (e) => {
clearTimeout(debounceTimer);
const query = e.target.value.trim();
const activeFilters = getActiveFilters();
if (query.length < 2) {
resultsContainer.innerHTML = '';
const filterContainer = document.getElementById('meilisearch-filter-container');
// Show filter container if there are active filters, even when search is empty
if (filterContainer) {
filterContainer.style.display = activeFilters.length > 0 ? 'block' : 'none';
}
return;
}
debounceTimer = setTimeout(() => {
performSearch(query, activeFilters);
}, 300);
});
} catch (error) {
console.error('Error setting up Meilisearch handlers:', error);
}
};
// Initialize the search bar
initSearchBar();
// Update the MutationObserver logic
const observer = new MutationObserver(mutations => {
if (observer.processing) return;
observer.processing = true;
mutations.forEach(mutation => {
if (mutation.type === 'childList') {
const header = document.querySelector('header');
if (mutation.target === header || header?.contains(mutation.target)) {
if (window.innerWidth >= 1024) {
// Check for both possible IDs
const searchBar = document.getElementById('meilisearch-search-bar') ||
document.getElementById('search-bar-entry');
const searchBarContainer = document.getElementById('meilisearch-bar-container') ||
document.getElementById('search-bar-entry');
if (!searchBar && !searchBarContainer) { //searchbar missing in desktop view, reinitialize
initSearchBar();
}
}
}
}
});
observer.processing = false;
});
// Update observer configuration to be more specific
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: false,
characterData: false
});
}
// Initialization
if (document.readyState === 'complete' || document.readyState === 'interactive') { //document ready, initialize
initializeMeilisearchIntegration();
} else { //waiting for DOMContentLoaded, initialize
document.addEventListener('DOMContentLoaded', initializeMeilisearchIntegration);
}