igniteui-astro-components 0.0.23 → 0.0.24

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "igniteui-astro-components",
3
- "version": "0.0.23",
3
+ "version": "0.0.24",
4
4
  "description": "Reusable Astro components, layouts, and integrations for Infragistics / Ignite UI documentation sites. Replaces the Starlight defaults with project-specific implementations.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -74,6 +74,7 @@
74
74
  "./plugins/remark-html-transforms": "./src/plugins/remark-html-transforms.ts",
75
75
  "./plugins/rehype-table-wrapper": "./src/plugins/rehype-table-wrapper.ts",
76
76
  "./plugins/rehype-heading-anchors": "./src/plugins/rehype-heading-anchors.ts",
77
+ "./plugins/rehype-pagefind-ignore": "./src/plugins/rehype-pagefind-ignore.ts",
77
78
  "./styles/theme.scss": "./src/styles/theme.scss",
78
79
  "./package.json": "./package.json"
79
80
  },
@@ -33,10 +33,15 @@ const resolvedSiteTitle = siteTitleProp ?? siteTitleVirtual;
33
33
  const resolvedSidebar = (sidebarItems ?? sidebarData) as SidebarEntry[];
34
34
  const sidebarCrumbs = currentSlug ? getBreadcrumb(resolvedSidebar, currentSlug) : [];
35
35
  const crumbs = sidebarCrumbs.length > 0 ? sidebarCrumbs : (pageTitle ? [pageTitle] : []);
36
+
37
+ // Expose the crumb trail as Pagefind `breadcrumb` meta (this nav is inside <main>)
38
+ // for the location line under each search result. Commas split inline meta — strip them.
39
+ const breadcrumbPath = crumbs.join(' › ');
40
+ const breadcrumbMeta = breadcrumbPath.replace(/,/g, '');
36
41
  ---
37
42
 
38
43
  {(resolvedSiteTitle || crumbs.length > 0) && (
39
- <nav class="docs-breadcrumb" aria-label="Breadcrumb">
44
+ <nav class="docs-breadcrumb" aria-label="Breadcrumb" data-pagefind-meta={breadcrumbMeta ? `breadcrumb:${breadcrumbMeta}` : undefined}>
40
45
  <ol class="docs-breadcrumb-list">
41
46
  { resolvedSiteTitle && (
42
47
  <li class="docs-breadcrumb-item docs-breadcrumb-home">
@@ -66,6 +66,9 @@ import './Search.scss';
66
66
  <div class="igd-search-content">
67
67
  <div class="igd-search-status" aria-live="polite"></div>
68
68
  <igc-list class="igd-search-results" hidden></igc-list>
69
+ <igc-button class="igd-search-more-btn" variant="flat" type="button" hidden>
70
+ Show more results
71
+ </igc-button>
69
72
  </div>
70
73
  <footer class="igd-search-footer">
71
74
  <igc-button class="search-close" variant="outlined">
@@ -103,19 +106,50 @@ import './Search.scss';
103
106
  const base = import.meta.env.BASE_URL.replace(/\/$/, '');
104
107
  const _w = window as any;
105
108
 
106
- const INPUT_DEBOUNCE_MS = 150;
107
- const MAX_RESULTS = 10;
109
+ const SEARCH_DEBOUNCE_MS = 200;
110
+ const MIN_QUERY_LEN = 2; // 1 char matches (and whole-word-highlights) everything
111
+ const PAGE_SIZE = 10; // results shown per display page
112
+ const SCAN_BATCH = 20; // raw results fetched per phrase-filter pass
108
113
 
109
- async function loadPagefind() {
110
- if (_w.__pagefind) return _w.__pagefind;
111
- try {
112
- const pf = await import(/* @vite-ignore */ `${base}/pagefind/pagefind.js`);
113
- await pf.init();
114
- _w.__pagefind = pf;
115
- return pf;
116
- } catch {
117
- return null;
118
- }
114
+ // Bumped per query; runSearch/renderNextPage bail after each await if it changed,
115
+ // so a slow query can't overwrite a newer one.
116
+ let searchSeq = 0;
117
+
118
+ // Pagination state for the active query. The phrase filter runs client-side, so
119
+ // we scan Pagefind's lazy handles (pfResults) in batches, keep the phrase matches
120
+ // (matches), and page the display over those. rawConsumed counts handles scanned,
121
+ // displayed counts matches rendered.
122
+ let activeSeq = 0;
123
+ let activeTerm = '';
124
+ let activeTokens: string[] = [];
125
+ let pfResults: any[] = [];
126
+ let rawConsumed = 0;
127
+ let matches: any[] = [];
128
+ let displayed = 0;
129
+ let loadingMore = false;
130
+
131
+ // Cache the promise so concurrent first callers share one import/options/init.
132
+ function loadPagefind(): Promise<any> {
133
+ if (_w.__pagefindPromise) return _w.__pagefindPromise;
134
+ _w.__pagefindPromise = (async () => {
135
+ try {
136
+ const pf = await import(/* @vite-ignore */ `${base}/pagefind/pagefind.js`);
137
+ // Must run before init(). Tuned so keyword-dense API pages don't bury prose.
138
+ await pf.options?.({
139
+ ranking: {
140
+ termSaturation: 1.0, // default 1.4
141
+ pageLength: 0.6, // default 0.75
142
+ termFrequency: 1.0,
143
+ termSimilarity: 1.0,
144
+ },
145
+ });
146
+ await pf.init();
147
+ return pf;
148
+ } catch {
149
+ return null;
150
+ }
151
+ })();
152
+ return _w.__pagefindPromise;
119
153
  }
120
154
 
121
155
  function escapeHtml(s: string): string {
@@ -126,10 +160,120 @@ import './Search.scss';
126
160
  .replace(/"/g, '&quot;');
127
161
  }
128
162
 
163
+ // Keep a result only if it actually contains what was typed: some highlighted
164
+ // word must start with one of the query tokens. This rejects Pagefind's prefix
165
+ // fallback — a gibberish query like "asdaasd…" matching the bare "as" on nearly
166
+ // every page — while still allowing as-you-type matches ("grid" finds "gridlines").
167
+ // No body highlights means the match was in the title/meta, which we keep.
168
+ function looksRelevant(excerpt: string, queryTokens: string[]): boolean {
169
+ if (queryTokens.length === 0) return true;
170
+ const marks = [...excerpt.matchAll(/<mark[^>]*>([\s\S]*?)<\/mark>/gi)]
171
+ .map((m) => m[1].replace(/<[^>]+>/g, '').replace(/[^a-z0-9]/gi, '').toLowerCase())
172
+ .filter(Boolean);
173
+ if (marks.length === 0) return true;
174
+ return marks.some((h) => queryTokens.some((t) => h.startsWith(t)));
175
+ }
176
+
177
+ // Pagefind highlights the whole matched word; trim each <mark> down to just the
178
+ // typed portion so only what the user typed is highlighted ("config" stays a
179
+ // prefix of <mark>config</mark>uration). Marks whose word isn't one of the typed
180
+ // tokens (e.g. a stem match) are left whole.
181
+ function trimHighlights(excerpt: string): string {
182
+ if (!activeTokens.length) return excerpt;
183
+ return excerpt.replace(/<mark[^>]*>([\s\S]*?)<\/mark>/gi, (full: string, word: string) => {
184
+ const lower = word.toLowerCase();
185
+ let keep = 0;
186
+ for (const t of activeTokens) if (t.length > keep && lower.startsWith(t)) keep = t.length;
187
+ return keep === 0 || keep >= word.length
188
+ ? full
189
+ : `<mark>${word.slice(0, keep)}</mark>${word.slice(keep)}`;
190
+ });
191
+ }
192
+
193
+ /** HTML for a single result row from its resolved Pagefind data. */
194
+ function renderResultItem(r: any): string {
195
+ const title = escapeHtml(r.meta?.title ?? r.url);
196
+ const path = r.meta?.breadcrumb ? escapeHtml(r.meta.breadcrumb) : '';
197
+ return `<igc-list-item>
198
+ <a href="${escapeHtml(r.url)}" class="igd-search-link">
199
+ <span class="igd-search-result-title">${title}</span>
200
+ ${path ? `<span class="igd-search-result-path">${path}</span>` : ''}
201
+ <span class="igd-search-result-excerpt">${trimHighlights(r.excerpt ?? '')}</span>
202
+ </a>
203
+ </igc-list-item>`;
204
+ }
205
+
206
+ // Render the empty state for the active query.
207
+ function showNoResults() {
208
+ const statusEl = document.querySelector<HTMLElement>('.igd-search-status');
209
+ const listEl = document.querySelector<any>('igc-list.igd-search-results');
210
+ const moreBtn = document.querySelector<any>('.igd-search-more-btn');
211
+ if (statusEl) statusEl.innerHTML = `<span class="igd-no-results">No results for <strong class="igd-search-query">${escapeHtml(activeTerm)}.</strong></span>`;
212
+ if (listEl) { listEl.innerHTML = ''; listEl.hidden = true; }
213
+ if (moreBtn) moreBtn.hidden = true;
214
+ }
215
+
216
+ // Scan raw Pagefind handles in batches, keeping the relevant matches, until there
217
+ // is at least one unshown display page or all raw results are scanned. Throws if
218
+ // a data() fetch rejects.
219
+ async function ensureMatches(seq: number) {
220
+ while (matches.length - displayed < PAGE_SIZE && rawConsumed < pfResults.length) {
221
+ const slice = pfResults.slice(rawConsumed, rawConsumed + SCAN_BATCH);
222
+ const data = await Promise.all(slice.map((r: any) => r.data()));
223
+ if (seq !== searchSeq) return;
224
+ rawConsumed += slice.length;
225
+ matches.push(...data.filter((r: any) => looksRelevant(r.excerpt ?? '', activeTokens)));
226
+ }
227
+ }
228
+
229
+ // Append the next page of phrase-matching results, fetching more raw batches as
230
+ // needed. seq ties the work to its query so a stale page can't render.
231
+ async function renderNextPage(seq: number, isFirst = false) {
232
+ const statusEl = document.querySelector<HTMLElement>('.igd-search-status');
233
+ const listEl = document.querySelector<any>('igc-list.igd-search-results');
234
+ const moreBtn = document.querySelector<any>('.igd-search-more-btn');
235
+ if (!statusEl || !listEl) return;
236
+
237
+ if (seq !== searchSeq || loadingMore) return;
238
+ if (displayed >= matches.length && rawConsumed >= pfResults.length) { // nothing more to show
239
+ if (isFirst) showNoResults();
240
+ return;
241
+ }
242
+
243
+ loadingMore = true;
244
+ try {
245
+ await ensureMatches(seq);
246
+ } catch {
247
+ if (seq === searchSeq) statusEl.textContent = 'Failed to load search results.';
248
+ return; // finally still clears loadingMore
249
+ } finally {
250
+ loadingMore = false;
251
+ }
252
+ if (seq !== searchSeq) return; // user typed more while data() resolved
253
+
254
+ const slice = matches.slice(displayed, displayed + PAGE_SIZE);
255
+ if (slice.length === 0) { // scanned all raw, nothing matched
256
+ if (isFirst) showNoResults();
257
+ if (moreBtn) moreBtn.hidden = true;
258
+ return;
259
+ }
260
+ displayed += slice.length;
261
+ listEl.insertAdjacentHTML('beforeend', slice.map(renderResultItem).join(''));
262
+ listEl.hidden = false;
263
+
264
+ const total = pfResults.length;
265
+ const more = displayed < matches.length || rawConsumed < pfResults.length;
266
+ statusEl.textContent = more
267
+ ? `Showing ${displayed} of ${total} results`
268
+ : `${displayed} result${displayed === 1 ? '' : 's'}`;
269
+ if (moreBtn) moreBtn.hidden = !more;
270
+ }
271
+
129
272
  async function runSearch(query: string) {
130
273
  const statusEl = document.querySelector<HTMLElement>('.igd-search-status');
131
274
  const listEl = document.querySelector<any>('igc-list.igd-search-results');
132
275
  const clearBtn = document.querySelector<any>('.igd-search-clear');
276
+ const moreBtn = document.querySelector<any>('.igd-search-more-btn');
133
277
  const input = document.querySelector<any>('igc-input.igd-search-input');
134
278
 
135
279
  if (!statusEl || !listEl) return;
@@ -137,44 +281,73 @@ import './Search.scss';
137
281
  if (clearBtn) clearBtn.hidden = !query;
138
282
  input?.requestUpdate?.();
139
283
 
140
- if (!query.trim()) {
284
+ const term = query.trim();
285
+ if (!term) {
286
+ searchSeq++; // invalidate any in-flight search so a late result can't repopulate
141
287
  statusEl.textContent = '';
142
288
  listEl.innerHTML = '';
143
289
  listEl.hidden = true;
290
+ if (moreBtn) moreBtn.hidden = true;
144
291
  return;
145
292
  }
146
293
 
294
+ if (term.length < MIN_QUERY_LEN) {
295
+ searchSeq++; // cancel any in-flight search
296
+ statusEl.textContent = `Type at least ${MIN_QUERY_LEN} characters to search.`;
297
+ listEl.innerHTML = '';
298
+ listEl.hidden = true;
299
+ if (moreBtn) moreBtn.hidden = true;
300
+ return;
301
+ }
302
+
303
+ const seq = ++searchSeq;
147
304
  statusEl.textContent = 'Searching…';
148
305
 
149
306
  const pf = await loadPagefind();
307
+ if (seq !== searchSeq) return; // superseded while loading the index
150
308
  if (!pf) {
151
309
  statusEl.textContent = 'Search index not available — run a production build first.';
152
310
  return;
153
311
  }
154
312
 
155
- const search = await pf.search(query.trim());
156
- const results = await Promise.all(
157
- search.results.slice(0, MAX_RESULTS).map((r: any) => r.data()),
158
- );
313
+ pf.preload?.(term); // warm the index chunks during the debounce window
159
314
 
160
- if (results.length === 0) {
161
- statusEl.innerHTML = `<span class="igd-no-results">No results for <strong class="igd-search-query">${escapeHtml(query)}.</strong></span>`;
162
- listEl.innerHTML = '';
163
- listEl.hidden = true;
164
- return;
165
- }
315
+ // debouncedSearch returns null when superseded; search() is a fallback for old bundles.
316
+ const search = typeof pf.debouncedSearch === 'function'
317
+ ? await pf.debouncedSearch(term, undefined, SEARCH_DEBOUNCE_MS)
318
+ : await pf.search(term);
319
+ if (search === null) return;
320
+ if (seq !== searchSeq) return;
166
321
 
167
- const total = search.results.length;
168
- statusEl.textContent = total > MAX_RESULTS
169
- ? `Showing ${MAX_RESULTS} of ${total} results`
170
- : `${total} result${total === 1 ? '' : 's'}`;
171
- listEl.innerHTML = results.map((r: any) => `<igc-list-item>
172
- <a href="${escapeHtml(r.url)}" class="igd-search-link">
173
- <span class="igd-search-result-title">${escapeHtml(r.meta?.title ?? r.url)}</span>
174
- <span class="igd-search-result-excerpt">${r.excerpt ?? ''}</span>
175
- </a>
176
- </igc-list-item>`).join('');
177
- listEl.hidden = false;
322
+ // New result set — reset pagination and render the first page.
323
+ activeSeq = seq;
324
+ activeTerm = term;
325
+ pfResults = search.results;
326
+ activeTokens = term.toLowerCase().match(/[a-z0-9]+/g) ?? [];
327
+ rawConsumed = 0;
328
+ matches = [];
329
+ displayed = 0;
330
+ listEl.innerHTML = '';
331
+
332
+ await renderNextPage(seq, true);
333
+ }
334
+
335
+ // Infinite scroll. Bound to both candidates since either may be the real
336
+ // scroll container; the one that doesn't scroll never fires. Bind-once flag.
337
+ function attachInfiniteScroll() {
338
+ const NEAR_BOTTOM_PX = 200;
339
+ const onScroll = (e: Event) => {
340
+ const el = e.currentTarget as HTMLElement;
341
+ if (el.scrollTop + el.clientHeight >= el.scrollHeight - NEAR_BOTTOM_PX) {
342
+ renderNextPage(activeSeq);
343
+ }
344
+ };
345
+ ['.igd-search-content', 'igc-list.igd-search-results'].forEach((sel) => {
346
+ const el = document.querySelector<any>(sel);
347
+ if (!el || el.__infiniteBound) return;
348
+ el.__infiniteBound = true;
349
+ el.addEventListener('scroll', onScroll, { passive: true });
350
+ });
178
351
  }
179
352
 
180
353
  async function openSearch() {
@@ -185,6 +358,7 @@ import './Search.scss';
185
358
  document.body.toggleAttribute('data-search-modal-open', true);
186
359
  await dialog.show();
187
360
  loadPagefind();
361
+ attachInfiniteScroll();
188
362
  requestAnimationFrame(() => {
189
363
  document.querySelector<any>('igc-input.igd-search-input')?.focus();
190
364
  });
@@ -237,12 +411,11 @@ import './Search.scss';
237
411
  updateSearchHint();
238
412
  });
239
413
 
240
- let debounceTimer: ReturnType<typeof setTimeout> | null = null;
241
414
  document.addEventListener('igcInput', (e: Event) => {
242
415
  if (!(e.target as Element).closest('igc-input.igd-search-input')) return;
243
- if (debounceTimer !== null) clearTimeout(debounceTimer);
244
416
  const val = (document.querySelector<any>('igc-input.igd-search-input')?.value as string) ?? '';
245
- debounceTimer = setTimeout(() => runSearch(val), INPUT_DEBOUNCE_MS);
417
+ // Debouncing + supersession are handled inside runSearch via debouncedSearch.
418
+ runSearch(val);
246
419
  });
247
420
 
248
421
  document.addEventListener('click', (e: Event) => {
@@ -255,6 +428,8 @@ import './Search.scss';
255
428
  runSearch('');
256
429
  } else if (target.closest('.search-close')) {
257
430
  document.querySelector<any>('igc-dialog.igd-search-dialog')?.hide();
431
+ } else if (target.closest('.igd-search-more-btn')) {
432
+ renderNextPage(activeSeq);
258
433
  } else if (target.closest('.igd-search-shell') && target.closest('a[href]')) {
259
434
  document.querySelector<any>('igc-dialog.igd-search-dialog')?.hide();
260
435
  }
@@ -12,6 +12,10 @@
12
12
  mark {
13
13
  background: transparent;
14
14
  color: var(--igd-accent);
15
+ // No padding/margin: a global `mark` rule adds horizontal padding that
16
+ // shows as a gap once we split a word into <mark>prefix</mark>rest.
17
+ padding: 0;
18
+ margin: 0;
15
19
  }
16
20
  }
17
21
 
@@ -66,6 +66,8 @@ export { rehypeTableWrapper } from './plugins/rehype-table-wrapper';
66
66
  import { rehypeTableWrapper } from './plugins/rehype-table-wrapper';
67
67
  import { rehypeHeadingAnchors } from './plugins/rehype-heading-anchors';
68
68
  export { rehypeHeadingAnchors } from './plugins/rehype-heading-anchors';
69
+ import { rehypePagefindIgnore } from './plugins/rehype-pagefind-ignore';
70
+ export { rehypePagefindIgnore } from './plugins/rehype-pagefind-ignore';
69
71
  import { remarkMdLinks } from './plugins/remark-md-links';
70
72
  import { remarkHtmlTransforms } from './plugins/remark-html-transforms';
71
73
 
@@ -669,6 +671,7 @@ export function createDocsSite(options: CreateDocsSiteOptions = {} as CreateDocs
669
671
  rehypeCodeView,
670
672
  rehypeTableWrapper,
671
673
  rehypeHeadingAnchors,
674
+ rehypePagefindIgnore,
672
675
  ...((astroExtra as any).markdown?.rehypePlugins ?? []),
673
676
  ],
674
677
  },
@@ -0,0 +1,40 @@
1
+ import { visit } from 'unist-util-visit';
2
+
3
+ /**
4
+ * Marks code with `data-pagefind-ignore` so Pagefind doesn't index it.
5
+ *
6
+ * Code is full of one-letter tokens (generics `T`, escapes `\t`) that Pagefind
7
+ * matches via weak prefix fallback — a search for "twitter" hits the `t` in
8
+ * `keyof T` across unrelated pages. Excluding `<pre>` (and single-char inline
9
+ * `<code>`) removes that noise; real inline `<code>` like `dataSource` stays.
10
+ */
11
+
12
+ // Concatenate all descendant text of a HAST node.
13
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
+ function textContent(node: any): string {
15
+ if (node.type === 'text') return node.value ?? '';
16
+ if (!node.children) return '';
17
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
+ return node.children.map((c: any) => textContent(c)).join('');
19
+ }
20
+
21
+ export function rehypePagefindIgnore() {
22
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
23
+ return (tree: any) => {
24
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
+ visit(tree, 'element', (node: any) => {
26
+ const ignore = () => {
27
+ node.properties = { ...node.properties, 'data-pagefind-ignore': 'all' };
28
+ };
29
+
30
+ // Fenced code blocks (covers their inner <code> via subtree ignore).
31
+ if (node.tagName === 'pre') return ignore();
32
+
33
+ // Inline code that reduces to a single alphanumeric token.
34
+ if (node.tagName === 'code') {
35
+ const token = textContent(node).replace(/[^a-z0-9]/gi, '');
36
+ if (token.length <= 1) ignore();
37
+ }
38
+ });
39
+ };
40
+ }
@@ -132,6 +132,20 @@
132
132
  }
133
133
  }
134
134
 
135
+ // Breadcrumb location line under the result title.
136
+ .igd-search-result-path {
137
+ @include type-style('caption') {
138
+ margin: 0;
139
+ }
140
+
141
+ color: light-dark(var(--ig-gray-500), var(--ig-gray-400));
142
+
143
+ mark {
144
+ background: transparent;
145
+ color: var(--igd-accent);
146
+ }
147
+ }
148
+
135
149
  .igd-search-kind {
136
150
  @include type-style('caption') {
137
151
  margin-block: 0;
@@ -200,12 +214,11 @@
200
214
  --backdrop: #{color($color: gray, $variant: 800, $opacity: .6)};
201
215
 
202
216
  &::part(base) {
203
- margin: auto;
217
+ margin: rem(192px) auto auto;
204
218
  padding: 0;
205
219
  width: 90%;
206
220
  max-width: rem(672px);
207
- height: calc(100vh - #{rem(128px)});
208
- max-height: rem(768px);
221
+ max-height: min(calc(100vh - #{rem(128px)}), #{rem(768px)});
209
222
  border-radius: rem(8px);
210
223
 
211
224
  overflow: hidden;