igniteui-astro-components 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1056 @@
1
+ ---
2
+ /**
3
+ * SearchAdvanced
4
+ *
5
+ * Client-side search dialog that loads a JSON search index and performs
6
+ * all matching against symbol and member names — never against page body content.
7
+ *
8
+ * Result UI:
9
+ * • Configurable tabs (only non-empty categories are shown, with their count)
10
+ * • "All" tab (always present) shows up to N results per category
11
+ * • Other tabs show all matches for that category
12
+ *
13
+ * Built so it has no runtime dependency on Starlight CSS — the trigger
14
+ * button, dialog, and all styles are self-contained.
15
+ */
16
+
17
+ export interface SearchTab {
18
+ /** Unique identifier for this tab/category */
19
+ id: string;
20
+ /** Display label for the tab */
21
+ label: string;
22
+ /**
23
+ * Kind codes from the index that map to this category.
24
+ * Use `['__name__']` for the special "page names" category.
25
+ * For member kinds: 'p' = property, 'a' = accessor, 'm' = method, 'e' = event, 'c' = constructor.
26
+ */
27
+ kindCodes: string[];
28
+ }
29
+
30
+ export interface Props {
31
+ /** CSS class for the outer element */
32
+ class?: string;
33
+ /**
34
+ * URL (or path) to the search index.
35
+ *
36
+ * Supports two modes:
37
+ * - **Single file**: URL pointing to a JSON file with a `{ pages: [...] }` shape.
38
+ * - **Manifest**: URL pointing to a `manifest.json` with a `{ files: [...] }` shape.
39
+ * Each listed file is fetched relative to the manifest URL and their pages
40
+ * are merged. This supports incremental / per-version builds.
41
+ *
42
+ * Defaults to `${BASE_URL}api-search-index/manifest.json`.
43
+ */
44
+ indexUrl?: string;
45
+ /** Search input placeholder. Defaults to "Search" */
46
+ placeholder?: string;
47
+ /** Show scope selector (current package / all packages). Defaults to false */
48
+ showScope?: boolean;
49
+ /** Tab categories to show (besides the always-present "All" tab). Defaults to none (only "All") */
50
+ tabs?: SearchTab[];
51
+ /** Maximum results per category shown in the "All" tab. Defaults to 10 */
52
+ allTabLimit?: number;
53
+ }
54
+
55
+ const {
56
+ class: className,
57
+ indexUrl,
58
+ placeholder = 'Search',
59
+ showScope = false,
60
+ tabs = [],
61
+ allTabLimit = 10,
62
+ } = Astro.props;
63
+
64
+ const ctrlKey = 'Ctrl';
65
+ // Strip any origin (scheme + host) from BASE_URL so only the path prefix is
66
+ // used. When Astro builds in SSG mode the Node.js process may have
67
+ // process.env.BASE_URL set to a full URL (e.g. "http://localhost:4567") which
68
+ // leaks into import.meta.env.BASE_URL for server-side template expressions and
69
+ // causes the data attributes to embed an absolute origin that breaks previews.
70
+ const rawBase = import.meta.env.BASE_URL ?? '/';
71
+ const basePath = (() => {
72
+ try { return new URL(rawBase).pathname; } catch { return rawBase; }
73
+ })().replace(/\/?$/, '/');
74
+ const resolvedIndexUrl = indexUrl ?? `${basePath}api-search-index/manifest.json`;
75
+ ---
76
+
77
+ <api-search-advanced
78
+ class={className}
79
+ data-base={basePath}
80
+ data-index-url={resolvedIndexUrl}
81
+ data-tabs={JSON.stringify(tabs)}
82
+ data-all-tab-limit={allTabLimit}
83
+ data-show-scope={showScope ? 'true' : 'false'}
84
+ >
85
+ <button
86
+ data-open-modal
87
+ disabled
88
+ aria-label={placeholder}
89
+ aria-keyshortcuts="Control+K"
90
+ >
91
+ <svg aria-hidden="true" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg>
92
+ <span class="search-label" aria-hidden="true">{placeholder}</span>
93
+ <kbd class="search-kbd" style="display: none;">
94
+ <kbd>{ctrlKey}</kbd><kbd>K</kbd>
95
+ </kbd>
96
+ </button>
97
+
98
+ <igc-dialog aria-label={placeholder} class="ig-search-dialog" hide-default-action close-on-outside-click>
99
+ <div class="ig-search-shell">
100
+ <header class="ig-search-header">
101
+ <igc-input
102
+ type="text"
103
+ class="ig-search-input"
104
+ placeholder={placeholder}
105
+ autocomplete="off"
106
+ outlined
107
+ aria-label={placeholder}
108
+ >
109
+ {showScope ? (
110
+ <igc-select slot="prefix" class="ig-search-scope" outlined aria-label="Search scope" value="current">
111
+ <igc-select-item value="current">Current package</igc-select-item>
112
+ <igc-select-item value="all">All packages</igc-select-item>
113
+ </igc-select>
114
+ ) : (
115
+ <svg slot="prefix" aria-hidden="true" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
116
+ <circle cx="11" cy="11" r="7"></circle>
117
+ <path d="m20 20-3.5-3.5"></path>
118
+ </svg>
119
+ )}
120
+ <igc-icon-button slot="suffix" class="ig-search-clear" variant="flat" type="button" aria-label="Clear search" hidden>
121
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
122
+ <path d="M6 6 18 18 M18 6 6 18"></path>
123
+ </svg>
124
+ </igc-icon-button>
125
+ </igc-input>
126
+ </header>
127
+
128
+ <igc-tabs class="ig-search-tabs" activation="manual" hidden></igc-tabs>
129
+
130
+ <div class="ig-search-status" aria-live="polite"></div>
131
+
132
+ <igc-list class="ig-search-results"></igc-list>
133
+ </div>
134
+ </igc-dialog>
135
+ </api-search-advanced>
136
+
137
+ <script is:inline>
138
+ /* Show the platform-correct keyboard shortcut hint after hydration. */
139
+ (() => {
140
+ const el = document.querySelector('api-search-advanced');
141
+ if (!el) return;
142
+ const openBtn = el.querySelector('button[data-open-modal]');
143
+ const shortcut = openBtn?.querySelector('kbd');
144
+ if (!openBtn || !(shortcut instanceof HTMLElement)) return;
145
+ const platformKey = shortcut.querySelector('kbd');
146
+ if (platformKey && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
147
+ platformKey.textContent = '\u2318';
148
+ openBtn.setAttribute('aria-keyshortcuts', 'Meta+K');
149
+ }
150
+ shortcut.style.display = '';
151
+ })();
152
+ </script>
153
+
154
+ <script>
155
+ import {
156
+ defineComponents,
157
+ IgcInputComponent,
158
+ IgcDialogComponent,
159
+ IgcSelectComponent,
160
+ IgcSelectItemComponent,
161
+ IgcIconButtonComponent,
162
+ IgcTabsComponent,
163
+ IgcTabComponent,
164
+ IgcListComponent,
165
+ IgcListItemComponent,
166
+ IgcListHeaderComponent,
167
+ } from 'igniteui-webcomponents';
168
+
169
+ defineComponents(
170
+ IgcInputComponent,
171
+ IgcDialogComponent,
172
+ IgcSelectComponent,
173
+ IgcSelectItemComponent,
174
+ IgcIconButtonComponent,
175
+ IgcTabsComponent,
176
+ IgcTabComponent,
177
+ IgcListComponent,
178
+ IgcListItemComponent,
179
+ IgcListHeaderComponent,
180
+ );
181
+
182
+ type IndexedPage = {
183
+ u: string;
184
+ n: string;
185
+ k: string;
186
+ v: string;
187
+ p: string;
188
+ g: string;
189
+ m: Array<[string, string]>;
190
+ };
191
+
192
+ type TabConfig = {
193
+ id: string;
194
+ label: string;
195
+ kindCodes: string[];
196
+ };
197
+
198
+ type Match = {
199
+ name: string;
200
+ pageName: string;
201
+ url: string;
202
+ category: string;
203
+ matchTier: number;
204
+ qPos: number;
205
+ hasPrefix: boolean;
206
+ typeWeight: number;
207
+ kindLabel: string;
208
+ metaLabel: string;
209
+ packageLabel: string;
210
+ };
211
+
212
+ const PAGE_KIND_LABEL: Record<string, string> = {
213
+ class: 'class',
214
+ interface: 'interface',
215
+ enum: 'enum',
216
+ type: 'type',
217
+ variable: 'variable',
218
+ function: 'function',
219
+ module: 'module',
220
+ };
221
+
222
+ const PAGE_KIND_WEIGHT: Record<string, number> = {
223
+ class: 0, interface: 1, enum: 2, type: 3, function: 4, variable: 5, module: 6,
224
+ };
225
+
226
+ const KIND_CODE_TO_LABEL: Record<string, string> = {
227
+ p: 'property',
228
+ a: 'accessor',
229
+ m: 'method',
230
+ e: 'event',
231
+ c: 'constructor',
232
+ };
233
+
234
+ const INPUT_DEBOUNCE_MS = 100;
235
+
236
+ class ApiSearchAdvanced extends HTMLElement {
237
+ private dialog!: IgcDialogComponent;
238
+ private input!: IgcInputComponent;
239
+ private clearBtn!: IgcIconButtonComponent;
240
+ private scopeSelect: IgcSelectComponent | null = null;
241
+ private tabsEl!: IgcTabsComponent;
242
+ private statusEl!: HTMLElement;
243
+ private resultsEl!: HTMLElement;
244
+ private indexPromise: Promise<IndexedPage[]> | null = null;
245
+ private currentTab: string = 'all';
246
+ private currentMatches: Map<string, Match[]> = new Map();
247
+ private currentQuery: string = '';
248
+ private debounceTimer: ReturnType<typeof setTimeout> | null = null;
249
+ private basePath: string = '/';
250
+ private indexUrl: string = '';
251
+ private currentPlatform: string = '';
252
+ private currentPkg: string = '';
253
+ private currentVersion: string = '';
254
+ private scope: 'current' | 'all' = 'current';
255
+ private categories: TabConfig[] = [];
256
+ private allTabLimit: number = 10;
257
+ private showScope: boolean = false;
258
+ private kindCodeToCategory: Map<string, string> = new Map();
259
+
260
+ connectedCallback() {
261
+ this.basePath = this.dataset.base || '/';
262
+ this.indexUrl = this.dataset.indexUrl || `${this.basePath}api-search-index.json`;
263
+ this.allTabLimit = parseInt(this.dataset.allTabLimit || '10', 10) || 10;
264
+ this.showScope = this.dataset.showScope === 'true';
265
+
266
+ // Parse tab configuration
267
+ try {
268
+ const tabsData: TabConfig[] = JSON.parse(this.dataset.tabs || '[]');
269
+ this.categories = tabsData;
270
+ } catch {
271
+ this.categories = [];
272
+ }
273
+
274
+ // Build kind code → category mapping
275
+ for (const cat of this.categories) {
276
+ for (const code of cat.kindCodes) {
277
+ if (code !== '__name__') {
278
+ this.kindCodeToCategory.set(code, cat.id);
279
+ }
280
+ }
281
+ }
282
+
283
+ const openBtn = this.querySelector<HTMLButtonElement>('button[data-open-modal]')!;
284
+ this.dialog = this.querySelector<IgcDialogComponent>('igc-dialog')!;
285
+ this.input = this.querySelector<IgcInputComponent>('igc-input.ig-search-input')!;
286
+ this.clearBtn = this.querySelector<IgcIconButtonComponent>('.ig-search-clear')!;
287
+ this.scopeSelect = this.querySelector<IgcSelectComponent>('igc-select.ig-search-scope');
288
+ this.tabsEl = this.querySelector<IgcTabsComponent>('igc-tabs.ig-search-tabs')!;
289
+ this.statusEl = this.querySelector<HTMLElement>('.ig-search-status')!;
290
+ this.resultsEl = this.querySelector<HTMLElement>('.ig-search-results')!;
291
+
292
+ if (this.showScope) {
293
+ this.detectCurrentContext();
294
+ this.updateScopeOption();
295
+ }
296
+
297
+ const open = async () => {
298
+ await this.dialog.show();
299
+ document.body.toggleAttribute('data-search-modal-open', true);
300
+ this.loadIndex();
301
+ this.input.focus();
302
+ };
303
+
304
+ openBtn.addEventListener('click', open);
305
+ openBtn.disabled = false;
306
+
307
+ this.dialog.addEventListener('igcClosed', () => {
308
+ document.body.toggleAttribute('data-search-modal-open', false);
309
+ });
310
+
311
+ // Close on result-link click (navigation)
312
+ this.resultsEl.addEventListener('click', (e) => {
313
+ if ((e.target as Element).closest('a[href]')) {
314
+ this.dialog.hide();
315
+ }
316
+ });
317
+
318
+ window.addEventListener('keydown', (e) => {
319
+ if ((e.metaKey === true || e.ctrlKey === true) && e.key === 'k') {
320
+ this.dialog.open ? this.closeModal() : open();
321
+ e.preventDefault();
322
+ }
323
+ });
324
+
325
+ this.input.addEventListener('igcInput', () => this.onInput());
326
+ this.clearBtn.addEventListener('click', () => {
327
+ this.input.value = '';
328
+ this.input.focus();
329
+ this.onInput();
330
+ });
331
+
332
+ this.tabsEl.addEventListener('igcChange', (e) => {
333
+ const tab = (e as CustomEvent<IgcTabComponent>).detail;
334
+ const tabId = (tab as HTMLElement)?.dataset?.tabId || 'all';
335
+ if (tabId === this.currentTab) return;
336
+ this.currentTab = tabId;
337
+ this.renderResults();
338
+ });
339
+
340
+ if (this.scopeSelect) {
341
+ this.scopeSelect.addEventListener('igcChange', () => {
342
+ this.scope = this.scopeSelect!.value === 'all' ? 'all' : 'current';
343
+ if (this.currentQuery) this.runSearch();
344
+ });
345
+ }
346
+ }
347
+
348
+ private detectCurrentContext() {
349
+ const path = window.location.pathname;
350
+ const stripped = path.startsWith(this.basePath) ? path.slice(this.basePath.length) : path.replace(/^\/+/, '');
351
+ const segs = stripped.split('/').filter(Boolean);
352
+ const baseSegs = this.basePath.split('/').filter(Boolean);
353
+ this.currentPlatform = baseSegs[baseSegs.length - 1] || '';
354
+ this.currentPkg = segs[0] || '';
355
+ this.currentVersion = segs[1] || '';
356
+ }
357
+
358
+ private updateScopeOption() {
359
+ if (!this.scopeSelect) return;
360
+ const item = this.scopeSelect.querySelector<HTMLElement & { value: string; disabled: boolean }>('igc-select-item[value="current"]');
361
+ if (!item) return;
362
+ if (this.currentPkg && this.currentVersion) {
363
+ item.textContent = `${this.currentPkg} ${this.currentVersion}`;
364
+ } else {
365
+ item.disabled = true;
366
+ item.hidden = true;
367
+ this.scopeSelect.value = 'all';
368
+ this.scope = 'all';
369
+ }
370
+ }
371
+
372
+ private closeModal() {
373
+ this.dialog.hide();
374
+ }
375
+
376
+ private loadIndex(): Promise<IndexedPage[]> {
377
+ if (this.indexPromise) return this.indexPromise;
378
+ this.indexPromise = this.fetchIndex();
379
+ return this.indexPromise;
380
+ }
381
+
382
+ private async fetchIndex(): Promise<IndexedPage[]> {
383
+ let data: unknown;
384
+ try {
385
+ const r = await fetch(this.indexUrl);
386
+ if (!r.ok) return [];
387
+ data = await r.json();
388
+ } catch {
389
+ return [];
390
+ }
391
+
392
+ // Single-file format: { pages: [...] }
393
+ if (Array.isArray((data as any)?.pages)) {
394
+ return (data as any).pages as IndexedPage[];
395
+ }
396
+
397
+ // Manifest format: { files: ["pkg/version.json", ...] }
398
+ if (Array.isArray((data as any)?.files)) {
399
+ const baseUrl = this.indexUrl.replace(/[^/]*$/, '');
400
+ const fetches: Promise<IndexedPage[]>[] = ((data as any).files as string[]).map(async (file: string) => {
401
+ try {
402
+ const res = await fetch(`${baseUrl}${file}`);
403
+ if (!res.ok) return [];
404
+ const d = await res.json();
405
+ return Array.isArray(d?.pages) ? d.pages as IndexedPage[] : [];
406
+ } catch {
407
+ return [];
408
+ }
409
+ });
410
+ const results = await Promise.all(fetches);
411
+ return results.flat();
412
+ }
413
+
414
+ return [];
415
+ }
416
+
417
+ private onInput() {
418
+ if (this.debounceTimer !== null) clearTimeout(this.debounceTimer);
419
+ this.debounceTimer = setTimeout(() => this.runSearch(), INPUT_DEBOUNCE_MS);
420
+ }
421
+
422
+ private async runSearch() {
423
+ const raw = (this.input.value as string) ?? '';
424
+ const q = raw.trim().toLowerCase();
425
+ this.currentQuery = q;
426
+ this.clearBtn.hidden = !raw;
427
+ // igc-input uses [slot="suffix"]:not([hidden]) to show the suffix container.
428
+ // It doesn't observe attribute mutations on slotted elements, so we must
429
+ // force a re-render whenever the clear button's visibility changes.
430
+ (this.input as unknown as { requestUpdate(): void }).requestUpdate?.();
431
+
432
+ if (!q) {
433
+ this.clearResults();
434
+ return;
435
+ }
436
+
437
+ this.statusEl.textContent = 'Searching\u2026';
438
+
439
+ let pages: IndexedPage[];
440
+ try {
441
+ pages = await this.loadIndex();
442
+ } catch (err) {
443
+ this.statusEl.textContent = `Search unavailable: ${(err as Error).message}`;
444
+ return;
445
+ }
446
+
447
+ if (q !== this.currentQuery) return;
448
+
449
+ const buckets = this.classify(pages, q);
450
+ this.currentMatches = buckets;
451
+ if (this.currentTab !== 'all' && (buckets.get(this.currentTab)?.length ?? 0) === 0) {
452
+ this.currentTab = 'all';
453
+ }
454
+ this.renderTabs();
455
+ this.renderResults();
456
+ }
457
+
458
+ private clearResults() {
459
+ this.statusEl.textContent = '';
460
+ this.tabsEl.hidden = true;
461
+ this.resultsEl.innerHTML = '';
462
+ this.currentMatches = new Map();
463
+ }
464
+
465
+ private async runBrowse() {
466
+ this.statusEl.textContent = '';
467
+
468
+ let pages: IndexedPage[];
469
+ try {
470
+ pages = await this.loadIndex();
471
+ } catch (err) {
472
+ this.statusEl.textContent = `Search unavailable: ${(err as Error).message}`;
473
+ return;
474
+ }
475
+
476
+ const nameCategories = this.categories.filter(c => c.kindCodes.includes('__name__'));
477
+
478
+ let scoped: IndexedPage[];
479
+ if (this.showScope && this.scope === 'current' && this.currentPkg && this.currentVersion) {
480
+ scoped = pages.filter((p) =>
481
+ p.p === this.currentPlatform &&
482
+ p.g === this.currentPkg &&
483
+ p.v === this.currentVersion
484
+ );
485
+ } else if (this.showScope) {
486
+ const platformPages = this.currentPlatform
487
+ ? pages.filter((p) => p.p === this.currentPlatform)
488
+ : pages;
489
+ scoped = pickHighestVersionWinners(platformPages);
490
+ } else {
491
+ scoped = pickHighestVersionWinners(pages);
492
+ }
493
+
494
+ const buckets: Map<string, Match[]> = new Map();
495
+ for (const cat of this.categories) buckets.set(cat.id, []);
496
+
497
+ for (const page of scoped) {
498
+ const isPlatformPrefixed = /^(Igx|Igr|Igc|Igb)[A-Z]/.test(page.n);
499
+ const pageWeight = PAGE_KIND_WEIGHT[page.k] ?? 8;
500
+ const meta = `${page.g} / ${page.v}`;
501
+
502
+ for (const nameCat of nameCategories) {
503
+ buckets.get(nameCat.id)?.push({
504
+ name: page.n,
505
+ pageName: page.n,
506
+ url: page.u,
507
+ category: nameCat.id,
508
+ matchTier: 0,
509
+ qPos: 0,
510
+ hasPrefix: isPlatformPrefixed,
511
+ typeWeight: pageWeight,
512
+ kindLabel: PAGE_KIND_LABEL[page.k] || page.k,
513
+ metaLabel: meta,
514
+ packageLabel: meta,
515
+ });
516
+ }
517
+
518
+ for (const [memberName, kindCode] of page.m) {
519
+ const catId = this.kindCodeToCategory.get(kindCode);
520
+ if (!catId) continue;
521
+ buckets.get(catId)?.push({
522
+ name: memberName,
523
+ pageName: page.n,
524
+ url: page.u + '#' + memberName,
525
+ category: catId,
526
+ matchTier: 0,
527
+ qPos: 0,
528
+ hasPrefix: isPlatformPrefixed,
529
+ typeWeight: pageWeight,
530
+ kindLabel: KIND_CODE_TO_LABEL[kindCode] || kindCode,
531
+ metaLabel: `${page.n} / ${page.g}`,
532
+ packageLabel: meta,
533
+ });
534
+ }
535
+ }
536
+
537
+ // Sort all buckets alphabetically by name
538
+ for (const list of buckets.values()) {
539
+ list.sort((a, b) => a.name.localeCompare(b.name));
540
+ }
541
+
542
+ this.currentMatches = buckets;
543
+
544
+ if (this.currentTab !== 'all' && (buckets.get(this.currentTab)?.length ?? 0) === 0) {
545
+ this.currentTab = 'all';
546
+ }
547
+
548
+ this.renderTabs();
549
+ this.renderResults();
550
+ }
551
+
552
+ private classify(pages: IndexedPage[], q: string): Map<string, Match[]> {
553
+ const buckets: Map<string, Match[]> = new Map();
554
+ for (const cat of this.categories) {
555
+ buckets.set(cat.id, []);
556
+ }
557
+
558
+ // Determine which categories handle page names
559
+ const nameCategories = this.categories.filter(c => c.kindCodes.includes('__name__'));
560
+
561
+ let scoped: IndexedPage[];
562
+ if (this.showScope && this.scope === 'current' && this.currentPkg && this.currentVersion) {
563
+ scoped = pages.filter((p) =>
564
+ p.p === this.currentPlatform &&
565
+ p.g === this.currentPkg &&
566
+ p.v === this.currentVersion
567
+ );
568
+ } else if (this.showScope) {
569
+ const platformPages = this.currentPlatform
570
+ ? pages.filter((p) => p.p === this.currentPlatform)
571
+ : pages;
572
+ scoped = pickHighestVersionWinners(platformPages);
573
+ } else {
574
+ scoped = pickHighestVersionWinners(pages);
575
+ }
576
+
577
+ for (const page of scoped) {
578
+ const isPlatformPrefixed = /^(Igx|Igr|Igc|Igb)[A-Z]/.test(page.n);
579
+ const pageWeight = PAGE_KIND_WEIGHT[page.k] ?? 8;
580
+ const meta = `${page.g} / ${page.v}`;
581
+
582
+ // Match page names
583
+ const tier = matchTier(page.n, q);
584
+ if (tier !== null) {
585
+ for (const nameCat of nameCategories) {
586
+ if (!buckets.has(nameCat.id)) buckets.set(nameCat.id, []);
587
+ buckets.get(nameCat.id)!.push({
588
+ name: page.n,
589
+ pageName: page.n,
590
+ url: page.u,
591
+ category: nameCat.id,
592
+ matchTier: tier,
593
+ qPos: positionInName(page.n, q),
594
+ hasPrefix: isPlatformPrefixed,
595
+ typeWeight: pageWeight,
596
+ kindLabel: PAGE_KIND_LABEL[page.k] || page.k,
597
+ metaLabel: meta,
598
+ packageLabel: meta,
599
+ });
600
+ }
601
+
602
+ // If no categories defined, put everything in a default bucket
603
+ if (nameCategories.length === 0 && this.categories.length === 0) {
604
+ if (!buckets.has('__all__')) buckets.set('__all__', []);
605
+ buckets.get('__all__')!.push({
606
+ name: page.n,
607
+ pageName: page.n,
608
+ url: page.u,
609
+ category: '__all__',
610
+ matchTier: tier,
611
+ qPos: positionInName(page.n, q),
612
+ hasPrefix: isPlatformPrefixed,
613
+ typeWeight: pageWeight,
614
+ kindLabel: PAGE_KIND_LABEL[page.k] || page.k,
615
+ metaLabel: meta,
616
+ packageLabel: meta,
617
+ });
618
+ }
619
+ }
620
+
621
+ // Match members
622
+ for (const [memberName, kindCode] of page.m) {
623
+ const memberTier = matchTier(memberName, q);
624
+ if (memberTier === null) continue;
625
+
626
+ const catId = this.kindCodeToCategory.get(kindCode);
627
+ if (catId) {
628
+ if (!buckets.has(catId)) buckets.set(catId, []);
629
+ buckets.get(catId)!.push({
630
+ name: memberName,
631
+ pageName: page.n,
632
+ url: page.u + '#' + memberName,
633
+ category: catId,
634
+ matchTier: memberTier,
635
+ qPos: positionInName(memberName, q),
636
+ hasPrefix: isPlatformPrefixed,
637
+ typeWeight: pageWeight,
638
+ kindLabel: KIND_CODE_TO_LABEL[kindCode] || kindCode,
639
+ metaLabel: `${page.n} / ${page.g}`,
640
+ packageLabel: meta,
641
+ });
642
+ } else if (this.categories.length === 0) {
643
+ // No tabs configured — all results go into one bucket
644
+ if (!buckets.has('__all__')) buckets.set('__all__', []);
645
+ buckets.get('__all__')!.push({
646
+ name: memberName,
647
+ pageName: page.n,
648
+ url: page.u + '#' + memberName,
649
+ category: '__all__',
650
+ matchTier: memberTier,
651
+ qPos: positionInName(memberName, q),
652
+ hasPrefix: isPlatformPrefixed,
653
+ typeWeight: pageWeight,
654
+ kindLabel: KIND_CODE_TO_LABEL[kindCode] || kindCode,
655
+ metaLabel: `${page.n} / ${page.g}`,
656
+ packageLabel: meta,
657
+ });
658
+ }
659
+ }
660
+ }
661
+
662
+ // Sort each bucket
663
+ for (const [catId, list] of buckets.entries()) {
664
+ const isNameCat = nameCategories.some(c => c.id === catId);
665
+ if (isNameCat) {
666
+ list.sort((a, b) => {
667
+ if (a.typeWeight !== b.typeWeight) return a.typeWeight - b.typeWeight;
668
+ return a.name.localeCompare(b.name);
669
+ });
670
+ } else {
671
+ list.sort((a, b) => {
672
+ if (a.matchTier !== b.matchTier) return a.matchTier - b.matchTier;
673
+ if (a.hasPrefix !== b.hasPrefix) return a.hasPrefix ? -1 : 1;
674
+ if (a.qPos !== b.qPos) return a.qPos - b.qPos;
675
+ if (a.typeWeight !== b.typeWeight) return a.typeWeight - b.typeWeight;
676
+ return a.name.localeCompare(b.name);
677
+ });
678
+ }
679
+ }
680
+
681
+ return buckets;
682
+ }
683
+
684
+ private renderTabs() {
685
+ const totalCount = Array.from(this.currentMatches.values()).reduce((s, l) => s + l.length, 0);
686
+
687
+ // If no categories configured, don't render tabs
688
+ if (this.categories.length === 0) {
689
+ this.tabsEl.hidden = true;
690
+ return;
691
+ }
692
+
693
+ const tabsHtml: string[] = [];
694
+ tabsHtml.push(this.tabHtml('all', 'All', totalCount, this.currentTab === 'all'));
695
+ for (const cat of this.categories) {
696
+ const count = this.currentMatches.get(cat.id)?.length ?? 0;
697
+ if (count === 0) continue;
698
+ tabsHtml.push(this.tabHtml(cat.id, cat.label, count, this.currentTab === cat.id));
699
+ }
700
+ this.tabsEl.innerHTML = tabsHtml.join('');
701
+ this.tabsEl.hidden = totalCount === 0;
702
+ }
703
+
704
+ private tabHtml(id: string, label: string, count: number, selected: boolean): string {
705
+ return `<igc-tab data-tab-id="${id}" label="${escapeHtml(label)}"${selected ? ' selected' : ''}><span slot="suffix" class="ig-search-tab-count">${count}</span></igc-tab>`;
706
+ }
707
+
708
+ private renderResults() {
709
+ const totalCount = Array.from(this.currentMatches.values()).reduce((s, l) => s + l.length, 0);
710
+ if (totalCount === 0) {
711
+ this.statusEl.textContent = this.currentQuery
712
+ ? `No results for "${this.currentQuery}".`
713
+ : 'No results.';
714
+ this.resultsEl.replaceChildren();
715
+ return;
716
+ }
717
+
718
+ this.statusEl.textContent = '';
719
+
720
+ const rendered: string[] = [];
721
+
722
+ if (this.categories.length === 0) {
723
+ // No tabs — render all results in one flat list
724
+ const list = this.currentMatches.get('__all__') ?? [];
725
+ for (const m of list) rendered.push(this.matchHtml(m));
726
+ } else if (this.currentTab === 'all') {
727
+ for (const cat of this.categories) {
728
+ const list = this.currentMatches.get(cat.id) ?? [];
729
+ if (list.length === 0) continue;
730
+ rendered.push(`<igc-list-header>${escapeHtml(cat.label)}</igc-list-header>`);
731
+ const slice = list.slice(0, this.allTabLimit);
732
+ for (const m of slice) rendered.push(this.matchHtml(m));
733
+ if (list.length > slice.length) {
734
+ rendered.push(
735
+ `<igc-list-item class="ig-search-more"><button type="button" class="ig-search-more-btn" data-tab="${cat.id}">
736
+ Show all ${list.length} ${escapeHtml(cat.label.toLowerCase())}
737
+ </button></igc-list-item>`
738
+ );
739
+ }
740
+ }
741
+ } else {
742
+ const list = this.currentMatches.get(this.currentTab) ?? [];
743
+ for (const m of list) rendered.push(this.matchHtml(m));
744
+ }
745
+
746
+ this.resultsEl.innerHTML = rendered.join('');
747
+
748
+ this.resultsEl.querySelectorAll<HTMLButtonElement>('.ig-search-more-btn').forEach((btn) => {
749
+ btn.addEventListener('click', () => {
750
+ const tabId = btn.dataset.tab!;
751
+ this.currentTab = tabId;
752
+ const tabEl = this.tabsEl.querySelector<HTMLElement>(`igc-tab[data-tab-id="${tabId}"]`);
753
+ if (tabEl) this.tabsEl.select(tabEl as any);
754
+ this.renderResults();
755
+ this.resultsEl.scrollTop = 0;
756
+ });
757
+ });
758
+ }
759
+
760
+ private matchHtml(m: Match): string {
761
+ const highlightedName = highlight(m.name, this.currentQuery);
762
+ const nameCategories = this.categories.filter(c => c.kindCodes.includes('__name__'));
763
+ const isNameMatch = nameCategories.some(c => c.id === m.category);
764
+ const subtitle = isNameMatch || m.category === '__all__'
765
+ ? `<span class="ig-search-kind">${escapeHtml(m.packageLabel)}</span>`
766
+ : `<span class="ig-search-kind">${escapeHtml(m.packageLabel)}</span><span class="ig-search-meta">in ${escapeHtml(m.pageName)}</span>`;
767
+ return `<igc-list-item>
768
+ <a href="${m.url}" class="ig-search-link" slot="title">
769
+ <span class="ig-search-result-title">${highlightedName}</span>
770
+ </a>
771
+ <span slot="subtitle" class="ig-search-result-sub">${subtitle}</span>
772
+ </igc-list-item>`;
773
+ }
774
+ }
775
+
776
+ function matchTier(name: string, q: string): number | null {
777
+ const n = name.toLowerCase();
778
+ if (n === q) return 0;
779
+ if (n.startsWith(q)) return 1;
780
+ if (n.includes(q)) return 2;
781
+ return null;
782
+ }
783
+
784
+ function positionInName(name: string, q: string): number {
785
+ const i = name.toLowerCase().indexOf(q);
786
+ return i < 0 ? 99 : Math.min(i, 99);
787
+ }
788
+
789
+ function compareVersions(a: string, b: string): number {
790
+ const ap = a.replace(/[^0-9.]/g, '').split('.').map(Number);
791
+ const bp = b.replace(/[^0-9.]/g, '').split('.').map(Number);
792
+ for (let i = 0; i < Math.max(ap.length, bp.length); i++) {
793
+ const d = (ap[i] || 0) - (bp[i] || 0);
794
+ if (d !== 0) return d;
795
+ }
796
+ return 0;
797
+ }
798
+
799
+ function pickHighestVersionWinners(pages: IndexedPage[]): IndexedPage[] {
800
+ const winners = new Map<string, IndexedPage>();
801
+ for (const p of pages) {
802
+ const key = `${p.p}|${p.g}|${p.k}|${p.n}`;
803
+ const existing = winners.get(key);
804
+ if (!existing || compareVersions(p.v, existing.v) > 0) {
805
+ winners.set(key, p);
806
+ }
807
+ }
808
+ return Array.from(winners.values());
809
+ }
810
+
811
+ function highlight(text: string, q: string): string {
812
+ if (!q) return escapeHtml(text);
813
+ const i = text.toLowerCase().indexOf(q);
814
+ if (i < 0) return escapeHtml(text);
815
+ return (
816
+ escapeHtml(text.slice(0, i)) +
817
+ '<mark>' + escapeHtml(text.slice(i, i + q.length)) + '</mark>' +
818
+ escapeHtml(text.slice(i + q.length))
819
+ );
820
+ }
821
+
822
+ function escapeHtml(s: string): string {
823
+ return s
824
+ .replace(/&/g, '&amp;')
825
+ .replace(/</g, '&lt;')
826
+ .replace(/>/g, '&gt;')
827
+ .replace(/"/g, '&quot;')
828
+ .replace(/'/g, '&#39;');
829
+ }
830
+
831
+ customElements.define('api-search-advanced', ApiSearchAdvanced);
832
+ </script>
833
+
834
+ <style>
835
+ api-search-advanced { display: contents; }
836
+
837
+ /* Hide dialog content before web components hydrate (prevents FOUC) */
838
+ igc-dialog:not(:defined) { display: none; }
839
+
840
+ button[data-open-modal] {
841
+ display: flex;
842
+ align-items: center;
843
+ gap: 0.5rem;
844
+ border: 0;
845
+ background-color: transparent;
846
+ color: var(--sl-color-gray-1);
847
+ cursor: pointer;
848
+ height: 2.5rem;
849
+ font-size: var(--sl-text-xl);
850
+ }
851
+
852
+ @media (min-width: 50rem) {
853
+ button[data-open-modal] {
854
+ border: 1px solid var(--sl-color-gray-5);
855
+ border-radius: 0.5rem;
856
+ padding-inline-start: 0.75rem;
857
+ padding-inline-end: 0.5rem;
858
+ background-color: var(--sl-color-black);
859
+ color: var(--sl-color-gray-2);
860
+ font-size: var(--sl-text-sm);
861
+ width: 100%;
862
+ max-width: 22rem;
863
+ }
864
+ button[data-open-modal]:hover {
865
+ border-color: var(--sl-color-gray-2);
866
+ color: var(--sl-color-white);
867
+ }
868
+ button[data-open-modal] > :last-child {
869
+ margin-inline-start: auto;
870
+ }
871
+ }
872
+
873
+ button > kbd {
874
+ border-radius: 0.25rem;
875
+ font-size: 0.625rem;
876
+ gap: 0.25em;
877
+ padding-inline: 0.375rem;
878
+ background-color: var(--sl-color-gray-6);
879
+ }
880
+ kbd { font-family: inherit; }
881
+ </style>
882
+
883
+ <style is:global>
884
+ /* ── Dialog ──────────────────────────────────────────────────── */
885
+ igc-dialog.ig-search-dialog {
886
+ /* Inherited by ::part(base) (native <dialog>) via igc base CSS */
887
+ background-color: var(--sl-color-bg, #fff);
888
+ color: var(--sl-color-text, inherit);
889
+ border: 1px solid var(--sl-color-gray-5, #ddd);
890
+ }
891
+ igc-dialog.ig-search-dialog::part(base) {
892
+ margin: 0;
893
+ padding: 0;
894
+ width: 100%;
895
+ max-width: 100%;
896
+ height: 100vh;
897
+ max-height: 100vh;
898
+ box-shadow: 0 10px 40px rgba(0,0,0,0.25);
899
+ }
900
+ igc-dialog.ig-search-dialog::part(content) {
901
+ padding: 0;
902
+ display: flex;
903
+ flex-direction: column;
904
+ height: 100%;
905
+ }
906
+ igc-dialog.ig-search-dialog::part(backdrop) {
907
+ background-color: rgba(0,0,0,0.4);
908
+ -webkit-backdrop-filter: blur(0.25rem);
909
+ backdrop-filter: blur(0.25rem);
910
+ }
911
+ @media (min-width: 50rem) {
912
+ igc-dialog.ig-search-dialog {
913
+ border-radius: 0.5rem;
914
+ }
915
+ igc-dialog.ig-search-dialog::part(base) {
916
+ margin: auto;
917
+ width: 90%;
918
+ max-width: 42rem;
919
+ height: calc(100vh - 8rem);
920
+ max-height: 48rem;
921
+ border-radius: 0.5rem;
922
+ }
923
+ }
924
+
925
+ [data-search-modal-open] { overflow: hidden; }
926
+
927
+ /* ── Shell layout ─────────────────────────────────────────────── */
928
+ .ig-search-shell {
929
+ display: flex;
930
+ flex-direction: column;
931
+ min-height: 0;
932
+ flex: 1 1 auto;
933
+ height: 100%;
934
+ }
935
+
936
+ /* ── Header ───────────────────────────────────────────────────── */
937
+ .ig-search-header {
938
+ padding: 0.75rem 1rem 0.5rem;
939
+ border-bottom: 1px solid var(--sl-color-gray-6, #f0f0f0);
940
+ flex-shrink: 0;
941
+ }
942
+
943
+ /* ── Scope selector (igc-select in prefix slot) ────────────── */
944
+ igc-select.ig-search-scope {
945
+ flex-shrink: 0;
946
+ max-width: 14rem;
947
+ min-width: 8rem;
948
+ }
949
+ @media (max-width: 32rem) {
950
+ igc-select.ig-search-scope { max-width: 9rem; min-width: 6rem; }
951
+ }
952
+
953
+ /* ── Search input (igc-input) ─────────────────────────────────── */
954
+ igc-input.ig-search-input {
955
+ width: 100%;
956
+ }
957
+
958
+ /* Clear icon-button in suffix slot */
959
+ igc-icon-button.ig-search-clear {
960
+ color: var(--sl-color-gray-3, #888);
961
+ }
962
+ igc-icon-button.ig-search-clear:hover {
963
+ color: var(--sl-color-text, inherit);
964
+ }
965
+
966
+ /* ── Tabs (igc-tabs) ──────────────────────────────────────────── */
967
+ igc-tabs.ig-search-tabs {
968
+ flex: 0 0 auto;
969
+ overflow: hidden;
970
+ /* Only show the tab header strip; tab body panels are unused */
971
+ max-height: 2.75rem;
972
+ border-bottom: 1px solid var(--sl-color-gray-6, #f0f0f0);
973
+ }
974
+ .ig-search-tab-count {
975
+ color: var(--sl-color-gray-3, #888);
976
+ font-weight: 400;
977
+ font-size: 0.8rem;
978
+ margin-inline-start: 0.25rem;
979
+ }
980
+
981
+ /* ── Status ───────────────────────────────────────────────────── */
982
+ .ig-search-status {
983
+ padding: 0.5rem 1rem 0;
984
+ color: var(--sl-color-gray-3, #888);
985
+ font-size: 0.875rem;
986
+ min-height: 1.25rem;
987
+ flex-shrink: 0;
988
+ }
989
+ .ig-search-status:empty { padding: 0; min-height: 0; }
990
+
991
+ /* ── Results (igc-list) ───────────────────────────────────────── */
992
+ igc-list.ig-search-results {
993
+ overflow-y: auto;
994
+ flex: 1 1 auto;
995
+ min-height: 0;
996
+ padding: 0.5rem 0.5rem 1rem;
997
+ }
998
+
999
+ igc-list.ig-search-results igc-list-header {
1000
+ font-size: 0.75rem;
1001
+ font-weight: 600;
1002
+ text-transform: uppercase;
1003
+ letter-spacing: 0.05em;
1004
+ color: var(--sl-color-gray-3, #888);
1005
+ }
1006
+
1007
+ .ig-search-link {
1008
+ text-decoration: none;
1009
+ color: inherit;
1010
+ }
1011
+ .ig-search-result-title {
1012
+ font-size: 0.95rem;
1013
+ font-weight: 600;
1014
+ color: var(--sl-color-text, inherit);
1015
+ }
1016
+ .ig-search-result-title mark {
1017
+ background: var(--sl-color-accent-low, rgba(90,62,255,0.18));
1018
+ color: inherit;
1019
+ padding: 0 1px;
1020
+ border-radius: 2px;
1021
+ }
1022
+ .ig-search-result-sub {
1023
+ display: flex;
1024
+ gap: 0.5rem;
1025
+ font-size: 0.8rem;
1026
+ color: var(--sl-color-gray-3, #888);
1027
+ flex-wrap: wrap;
1028
+ }
1029
+ .ig-search-kind {
1030
+ display: inline-block;
1031
+ padding: 0 0.375rem;
1032
+ background: var(--sl-color-gray-1, rgba(0,0,0,0.04));
1033
+ border-radius: 0.25rem;
1034
+ font-size: 0.7rem;
1035
+ letter-spacing: 0.04em;
1036
+ font-weight: 500;
1037
+ }
1038
+
1039
+ .ig-search-more {
1040
+ text-align: center;
1041
+ }
1042
+ .ig-search-more-btn {
1043
+ appearance: none;
1044
+ background: transparent;
1045
+ border: 1px solid var(--sl-color-gray-5, #ddd);
1046
+ border-radius: 0.375rem;
1047
+ padding: 0.4rem 0.9rem;
1048
+ color: var(--sl-color-text, inherit);
1049
+ font-size: 0.85rem;
1050
+ cursor: pointer;
1051
+ }
1052
+ .ig-search-more-btn:hover {
1053
+ border-color: var(--sl-color-accent, #5a3eff);
1054
+ color: var(--sl-color-text-accent, inherit);
1055
+ }
1056
+ </style>