@tanstack/query-devtools 5.105.3 → 5.106.1

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.
Files changed (50) hide show
  1. package/build/Devtools-75tXP6g3.cjs +1269 -0
  2. package/build/Devtools-DJ2H9xNC.js +1270 -0
  3. package/build/Devtools-DJ2H9xNC.js.map +1 -0
  4. package/build/{Devtools-DICxXjAp.js → Devtools-rtsOXx72.js} +6164 -3805
  5. package/build/{Devtools-2V_Pd-w1.cjs → Devtools-v4_2Fgnd.cjs} +6152 -3787
  6. package/build/DevtoolsComponent-BhxzD0Z_.cjs +2 -0
  7. package/build/{DevtoolsComponent-BAslf3AU.cjs → DevtoolsComponent-D-GGWO6D.cjs} +11 -5
  8. package/build/{DevtoolsComponent-CLOdqERu.js → DevtoolsComponent-DjX8H_OS.js} +11 -5
  9. package/build/DevtoolsComponent-Y_UD6BDS.js +3 -0
  10. package/build/DevtoolsComponent-Y_UD6BDS.js.map +1 -0
  11. package/build/{DevtoolsPanelComponent-BZiLbaMl.js → DevtoolsPanelComponent-BryTHuft.js} +18 -12
  12. package/build/{DevtoolsPanelComponent-BIzP-MqF.cjs → DevtoolsPanelComponent-BtyHS22R.cjs} +18 -12
  13. package/build/DevtoolsPanelComponent-azgDvAlF.js +3 -0
  14. package/build/DevtoolsPanelComponent-azgDvAlF.js.map +1 -0
  15. package/build/DevtoolsPanelComponent-ecGfyOWI.cjs +2 -0
  16. package/build/dev.cjs +4 -3
  17. package/build/dev.js +4 -3
  18. package/build/index.cjs +2 -1
  19. package/build/index.d.cts +1 -0
  20. package/build/index.d.cts.map +1 -1
  21. package/build/index.d.ts +1 -0
  22. package/build/index.d.ts.map +1 -1
  23. package/build/index.js +2 -1
  24. package/build/index.js.map +1 -1
  25. package/build/{utils-CiEaQT28.cjs → utils-CzP8C7c0.cjs} +170 -51
  26. package/build/{utils-CsIEjnKb.js → utils-D7iZi04l.js} +147 -52
  27. package/build/utils-DC2pN79q.js +3 -0
  28. package/build/utils-DC2pN79q.js.map +1 -0
  29. package/build/utils-DJl-N7L2.cjs +2 -0
  30. package/package.json +4 -3
  31. package/src/Devtools.tsx +82 -165
  32. package/src/DevtoolsComponent.tsx +7 -4
  33. package/src/DevtoolsPanelComponent.tsx +11 -8
  34. package/src/Explorer.tsx +349 -28
  35. package/src/VirtualList.tsx +105 -0
  36. package/src/explorerSearch.ts +159 -0
  37. package/src/nativeObjectType.ts +70 -0
  38. package/src/utils.tsx +74 -34
  39. package/build/Devtools-CD2ZvU1I.js +0 -1238
  40. package/build/Devtools-CD2ZvU1I.js.map +0 -1
  41. package/build/Devtools-DDcV5oIp.cjs +0 -1237
  42. package/build/DevtoolsComponent-D1MmpObN.js +0 -2
  43. package/build/DevtoolsComponent-D1MmpObN.js.map +0 -1
  44. package/build/DevtoolsComponent-zpIDe7Wu.cjs +0 -1
  45. package/build/DevtoolsPanelComponent-CRFy_L77.js +0 -2
  46. package/build/DevtoolsPanelComponent-CRFy_L77.js.map +0 -1
  47. package/build/DevtoolsPanelComponent-DJuL4CDS.cjs +0 -1
  48. package/build/utils-CpoIvKO8.cjs +0 -1
  49. package/build/utils-LNrmpo6y.js +0 -2
  50. package/build/utils-LNrmpo6y.js.map +0 -1
package/src/Explorer.tsx CHANGED
@@ -5,9 +5,13 @@ import {
5
5
  Match,
6
6
  Show,
7
7
  Switch,
8
+ createEffect,
8
9
  createMemo,
9
10
  createSignal,
10
11
  createUniqueId,
12
+ on,
13
+ onCleanup,
14
+ onMount,
11
15
  } from 'solid-js'
12
16
  import { Key } from '@solid-primitives/keyed'
13
17
  import * as goober from 'goober'
@@ -15,6 +19,7 @@ import { tokens } from './theme'
15
19
  import {
16
20
  deleteNestedDataByPath,
17
21
  displayValue,
22
+ isPlainObject,
18
23
  updateNestedDataByPath,
19
24
  } from './utils'
20
25
  import {
@@ -27,6 +32,9 @@ import {
27
32
  Trash,
28
33
  } from './icons'
29
34
  import { useQueryDevtoolsContext, useTheme } from './contexts'
35
+ import { primitiveText, searchEntries, searchExplorer } from './explorerSearch'
36
+ import { getNativeObjectType } from './nativeObjectType'
37
+ import type { ExplorerSearch } from './explorerSearch'
30
38
  import type { Query } from '@tanstack/query-core'
31
39
 
32
40
  /**
@@ -263,6 +271,175 @@ type ExplorerProps = {
263
271
  activeQuery?: Query
264
272
  itemsDeletable?: boolean
265
273
  onEdit?: () => void
274
+ search?: ExplorerSearch
275
+ highlight?: Highlight
276
+ }
277
+
278
+ /**
279
+ * Adds nested data search without changing the explorer's manual expansion.
280
+ * @param props - Data explorer options and the selected query or mutation identity.
281
+ * @returns The search controls and the original data tree.
282
+ */
283
+ export function SearchableExplorer(
284
+ props: ExplorerProps & { searchKey?: unknown },
285
+ ) {
286
+ const theme = useTheme()
287
+ const css = useQueryDevtoolsContext().shadowDOMTarget
288
+ ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
289
+ : goober.css
290
+ const styles = createMemo(() =>
291
+ theme() === 'dark' ? darkStyles(css) : lightStyles(css),
292
+ )
293
+ const [term, setTerm] = createSignal('')
294
+ const [debouncedTerm, setDebouncedTerm] = createSignal('')
295
+ const clear = () => {
296
+ setTerm('')
297
+ setDebouncedTerm('')
298
+ }
299
+ const searchKey = createMemo(() => props.searchKey)
300
+ createEffect(on(searchKey, clear))
301
+ createEffect(() => {
302
+ const next = term().toLowerCase()
303
+ if (!next) {
304
+ setDebouncedTerm('')
305
+ return
306
+ }
307
+ const timeout = setTimeout(() => setDebouncedTerm(next), 150)
308
+ onCleanup(() => clearTimeout(timeout))
309
+ })
310
+ const search = createMemo<ExplorerSearch | undefined>(() => {
311
+ const activeTerm = debouncedTerm()
312
+ return activeTerm
313
+ ? { term: activeTerm, match: searchExplorer(props.value, activeTerm) }
314
+ : undefined
315
+ })
316
+ const highlightName = `tsqd-data-search-${createUniqueId()}`
317
+ const [nativeHighlight, setNativeHighlight] = createSignal<Highlight>()
318
+ let root!: HTMLDivElement
319
+ onMount(() => {
320
+ const view = root.ownerDocument.defaultView!
321
+ const registry = view.CSS.highlights
322
+ createEffect(
323
+ on(search, () => {
324
+ const highlight = new view.Highlight()
325
+ registry.set(highlightName, highlight)
326
+ setNativeHighlight(highlight)
327
+ onCleanup(() => {
328
+ registry.delete(highlightName)
329
+ highlight.clear()
330
+ })
331
+ }),
332
+ )
333
+ })
334
+ const nativeHighlightStyle = createMemo(
335
+ () => css`
336
+ & ::highlight(${highlightName}) {
337
+ color: ${
338
+ theme() === 'dark' ? tokens.colors.gray[100] : tokens.colors.gray[900]
339
+ };
340
+ background-color: ${
341
+ theme() === 'dark'
342
+ ? tokens.colors.yellow[900]
343
+ : tokens.colors.yellow[200]
344
+ };
345
+ }
346
+ `,
347
+ )
348
+ return (
349
+ <div ref={root} class={nativeHighlightStyle()}>
350
+ <div class={styles().search}>
351
+ <input
352
+ type="search"
353
+ aria-label="Search data"
354
+ placeholder="Search data"
355
+ class={styles().searchInput}
356
+ value={term()}
357
+ onInput={(event) => setTerm(event.currentTarget.value)}
358
+ onKeyDown={(event) => {
359
+ if (event.key === 'Escape') {
360
+ event.stopPropagation()
361
+ clear()
362
+ }
363
+ }}
364
+ />
365
+ <Show when={term()}>
366
+ <button
367
+ type="button"
368
+ class={styles().clearSearch}
369
+ onClick={clear}
370
+ aria-label="Clear search"
371
+ >
372
+ Clear
373
+ </button>
374
+ </Show>
375
+ </div>
376
+ <div role="status" aria-live="polite">
377
+ {search() && !search()!.match.hasMatch ? 'No matches' : ''}
378
+ </div>
379
+ <Explorer {...props} search={search()} highlight={nativeHighlight()} />
380
+ </div>
381
+ )
382
+ }
383
+
384
+ const MAX_HIGHLIGHT_RANGES = 1000
385
+
386
+ /**
387
+ * Marks literal, case-insensitive matches in a label or primitive value.
388
+ * @param props - The text, normalized search term, and shared highlight instance.
389
+ * @returns Text with matching substrings marked.
390
+ */
391
+ function HighlightedText(props: {
392
+ text: string
393
+ term?: string
394
+ highlight?: Highlight
395
+ }) {
396
+ const matches = createMemo(() => {
397
+ const term = props.term
398
+ if (!term) return []
399
+ const lower = props.text.toLowerCase()
400
+ let originalStart = 0
401
+ let originalEnd = 0
402
+ let lowercaseEnd = 0
403
+ const originalPosition = (index: number) => {
404
+ while (lowercaseEnd <= index) {
405
+ const character = String.fromCodePoint(
406
+ props.text.codePointAt(originalEnd)!,
407
+ )
408
+ originalStart = originalEnd
409
+ originalEnd += character.length
410
+ lowercaseEnd += character.toLowerCase().length
411
+ }
412
+ return { start: originalStart, end: originalEnd }
413
+ }
414
+ const ranges: Array<{ start: number; end: number }> = []
415
+ let index = lower.indexOf(term)
416
+ while (index !== -1 && ranges.length < MAX_HIGHLIGHT_RANGES) {
417
+ const from = originalPosition(index).start
418
+ const to = originalPosition(index + term.length - 1).end
419
+ ranges.push({ start: from, end: to })
420
+ index = lower.indexOf(term, index + term.length)
421
+ }
422
+ return ranges
423
+ })
424
+ const text = document.createTextNode('')
425
+ createEffect(() => {
426
+ text.data = props.text
427
+ const highlight = props.highlight
428
+ if (!highlight) return
429
+ const ranges: Array<Range> = []
430
+ for (const match of matches()) {
431
+ if (highlight.size >= MAX_HIGHLIGHT_RANGES) break
432
+ const range = text.ownerDocument.createRange()
433
+ range.setStart(text, match.start)
434
+ range.setEnd(text, match.end)
435
+ highlight.add(range)
436
+ ranges.push(range)
437
+ }
438
+ onCleanup(() => {
439
+ for (const range of ranges) highlight.delete(range)
440
+ })
441
+ })
442
+ return text
266
443
  }
267
444
 
268
445
  /**
@@ -294,34 +471,66 @@ export default function Explorer(props: ExplorerProps) {
294
471
  const [expanded, setExpanded] = createSignal(
295
472
  (props.defaultExpanded || []).includes(props.label),
296
473
  )
297
- const toggleExpanded = () => setExpanded((old) => !old)
474
+ const hasSearchMatchingChild = () =>
475
+ !!props.search &&
476
+ [...props.search.match.children.values()].some((child) => child.hasMatch)
477
+ const isExpanded = () => expanded() || hasSearchMatchingChild()
478
+ const toggleExpanded = () => {
479
+ if (!hasSearchMatchingChild()) setExpanded((old) => !old)
480
+ }
298
481
  const [expandedPages, setExpandedPages] = createSignal<Array<number>>([])
482
+ const nativeObjectType = createMemo(() => getNativeObjectType(props.value))
483
+ const childrenEditable = createMemo(
484
+ () =>
485
+ props.editable &&
486
+ (Array.isArray(props.value) ||
487
+ nativeObjectType() === 'Map' ||
488
+ nativeObjectType() === 'Set' ||
489
+ isPlainObject(props.value)),
490
+ )
299
491
 
300
492
  const subEntries = createMemo(() => {
493
+ if (props.search) {
494
+ return props.search.match.kind === 'branch'
495
+ ? (searchEntries(props.value) ?? [])
496
+ : []
497
+ }
301
498
  if (Array.isArray(props.value)) {
302
499
  return props.value.map((d, i) => ({
303
500
  label: i.toString(),
501
+ key: i.toString(),
304
502
  value: d,
305
503
  }))
504
+ } else if (nativeObjectType() === 'Map') {
505
+ return Array.from(
506
+ Map.prototype.entries.call(props.value),
507
+ ([key, val]) => ({
508
+ label: primitiveText(key) ?? '[Object key]',
509
+ key,
510
+ value: val,
511
+ }),
512
+ )
513
+ } else if (nativeObjectType() === 'Set') {
514
+ return Array.from(Set.prototype.values.call(props.value), (val, i) => ({
515
+ label: i.toString(),
516
+ key: i.toString(),
517
+ value: val,
518
+ }))
306
519
  } else if (
307
520
  props.value !== null &&
308
521
  typeof props.value === 'object' &&
309
522
  isIterable(props.value) &&
310
523
  typeof props.value[Symbol.iterator] === 'function'
311
524
  ) {
312
- if (props.value instanceof Map) {
313
- return Array.from(props.value, ([key, val]) => ({
314
- label: key,
315
- value: val,
316
- }))
317
- }
318
525
  return Array.from(props.value, (val, i) => ({
319
526
  label: i.toString(),
527
+ key: i.toString(),
320
528
  value: val,
321
529
  }))
322
530
  } else if (typeof props.value === 'object' && props.value !== null) {
323
531
  return Object.entries(props.value).map(([key, val]) => ({
324
532
  label: key,
533
+ key,
325
534
  value: val,
326
535
  }))
327
536
  }
@@ -329,6 +538,12 @@ export default function Explorer(props: ExplorerProps) {
329
538
  })
330
539
 
331
540
  const type = createMemo<string>(() => {
541
+ if (props.search) {
542
+ if (Array.isArray(props.value)) return 'array'
543
+ if (nativeObjectType() === 'Map' || nativeObjectType() === 'Set')
544
+ return 'Iterable'
545
+ return props.value === null ? 'object' : typeof props.value
546
+ }
332
547
  if (Array.isArray(props.value)) {
333
548
  return 'array'
334
549
  } else if (
@@ -346,6 +561,63 @@ export default function Explorer(props: ExplorerProps) {
346
561
 
347
562
  const subEntryPages = createMemo(() => chunkArray(subEntries(), 100))
348
563
 
564
+ const pageHasMatch = (index: number) =>
565
+ !!(
566
+ props.search &&
567
+ subEntryPages()[index]?.some(
568
+ (entry) => props.search?.match.children.get(entry.key)?.hasMatch,
569
+ )
570
+ )
571
+ const matchingPage = createMemo(() =>
572
+ subEntryPages().findIndex((_, index) => pageHasMatch(index)),
573
+ )
574
+ const isPageExpanded = (index: number) =>
575
+ expandedPages().includes(index) || matchingPage() === index
576
+ const childSearch = (key: unknown): ExplorerSearch | undefined => {
577
+ const search = props.search
578
+ const match = search?.match.children.get(key)
579
+ return search && match ? { term: search.term, match } : undefined
580
+ }
581
+ const label = () => (
582
+ <HighlightedText
583
+ text={props.label}
584
+ term={props.search?.match.label ? props.search.term : undefined}
585
+ highlight={props.highlight}
586
+ />
587
+ )
588
+ const valueText = () => {
589
+ if (!props.search) return displayValue(props.value)
590
+ switch (props.search.match.kind) {
591
+ case 'circular':
592
+ return '[Circular]'
593
+ case 'accessor':
594
+ return '[Getter]'
595
+ case 'opaque':
596
+ return '[Object]'
597
+ case 'branch':
598
+ return Array.isArray(props.value)
599
+ ? '[]'
600
+ : nativeObjectType() === 'Map'
601
+ ? 'Map(0)'
602
+ : nativeObjectType() === 'Set'
603
+ ? 'Set(0)'
604
+ : '{}'
605
+ case 'value':
606
+ return primitiveText(props.value)
607
+ }
608
+ }
609
+ const renderedValue = () => (
610
+ <>
611
+ {props.search && typeof props.value === 'string' ? '"' : ''}
612
+ <HighlightedText
613
+ text={valueText() ?? ''}
614
+ term={props.search?.match.value ? props.search.term : undefined}
615
+ highlight={props.highlight}
616
+ />
617
+ {props.search && typeof props.value === 'string' ? '"' : ''}
618
+ </>
619
+ )
620
+
349
621
  const currentDataPath = props.dataPath ?? []
350
622
 
351
623
  const inputId = createUniqueId()
@@ -357,9 +629,9 @@ export default function Explorer(props: ExplorerProps) {
357
629
  <button
358
630
  class={styles().expanderButton}
359
631
  onClick={() => toggleExpanded()}
360
- aria-expanded={expanded() ? 'true' : 'false'}
632
+ aria-expanded={isExpanded() ? 'true' : 'false'}
361
633
  >
362
- <Expander expanded={expanded()} /> <span>{props.label}</span>{' '}
634
+ <Expander expanded={isExpanded()} /> <span>{label()}</span>{' '}
363
635
  <span class={styles().info}>
364
636
  {String(type()).toLowerCase() === 'iterable' ? '(Iterable) ' : ''}
365
637
  {subEntries().length} {subEntries().length > 1 ? `items` : `item`}
@@ -387,7 +659,13 @@ export default function Explorer(props: ExplorerProps) {
387
659
  />
388
660
  </Show>
389
661
 
390
- <Show when={!!props.onEdit && !serialize(props.value).meta}>
662
+ <Show
663
+ when={
664
+ !!props.onEdit &&
665
+ !props.search &&
666
+ !serialize(props.value).meta
667
+ }
668
+ >
391
669
  <button
392
670
  class={styles().actionButton}
393
671
  title={'Bulk Edit Data'}
@@ -402,18 +680,20 @@ export default function Explorer(props: ExplorerProps) {
402
680
  </div>
403
681
  </Show>
404
682
  </div>
405
- <Show when={expanded()}>
683
+ <Show when={isExpanded()}>
406
684
  <Show when={subEntryPages().length === 1}>
407
685
  <div class={styles().subEntry}>
408
- <Key each={subEntries()} by={(item) => item.label}>
686
+ <Key each={subEntries()} by={(item) => item.key}>
409
687
  {(entry) => {
410
688
  return (
411
689
  <Explorer
412
690
  defaultExpanded={props.defaultExpanded}
413
691
  label={entry().label}
692
+ search={childSearch(entry().key)}
693
+ highlight={props.highlight}
414
694
  value={entry().value}
415
- editable={props.editable}
416
- dataPath={[...currentDataPath, entry().label]}
695
+ editable={childrenEditable()}
696
+ dataPath={[...currentDataPath, entry().key]}
417
697
  activeQuery={props.activeQuery}
418
698
  itemsDeletable={
419
699
  type() === 'array' ||
@@ -433,29 +713,41 @@ export default function Explorer(props: ExplorerProps) {
433
713
  <div>
434
714
  <div class={styles().entry}>
435
715
  <button
436
- onClick={() =>
716
+ onClick={() => {
717
+ if (matchingPage() === index) return
437
718
  setExpandedPages((old) =>
438
719
  old.includes(index)
439
720
  ? old.filter((d) => d !== index)
440
721
  : [...old, index],
441
722
  )
723
+ }}
724
+ class={cx(
725
+ styles().expanderButton,
726
+ pageHasMatch(index) && styles().highlight,
727
+ )}
728
+ aria-expanded={isPageExpanded(index)}
729
+ aria-description={
730
+ pageHasMatch(index)
731
+ ? 'Contains search matches'
732
+ : undefined
442
733
  }
443
- class={styles().expanderButton}
444
734
  >
445
- <Expander expanded={expandedPages().includes(index)} />{' '}
446
- [{index * 100}...
735
+ <Expander expanded={isPageExpanded(index)} /> [
736
+ {index * 100}...
447
737
  {index * 100 + 100 - 1}]
448
738
  </button>
449
- <Show when={expandedPages().includes(index)}>
739
+ <Show when={isPageExpanded(index)}>
450
740
  <div class={styles().subEntry}>
451
- <Key each={entries()} by={(entry) => entry.label}>
741
+ <Key each={entries()} by={(entry) => entry.key}>
452
742
  {(entry) => (
453
743
  <Explorer
454
744
  defaultExpanded={props.defaultExpanded}
455
745
  label={entry().label}
746
+ search={childSearch(entry().key)}
747
+ highlight={props.highlight}
456
748
  value={entry().value}
457
- editable={props.editable}
458
- dataPath={[...currentDataPath, entry().label]}
749
+ editable={childrenEditable()}
750
+ dataPath={[...currentDataPath, entry().key]}
459
751
  activeQuery={props.activeQuery}
460
752
  />
461
753
  )}
@@ -473,7 +765,7 @@ export default function Explorer(props: ExplorerProps) {
473
765
  <Show when={subEntryPages().length === 0}>
474
766
  <div class={styles().row}>
475
767
  <label for={inputId} class={styles().label}>
476
- {props.label}:
768
+ {label()}:
477
769
  </label>
478
770
  <Show
479
771
  when={
@@ -483,9 +775,7 @@ export default function Explorer(props: ExplorerProps) {
483
775
  type() === 'number' ||
484
776
  type() === 'boolean')
485
777
  }
486
- fallback={
487
- <span class={styles().value}>{displayValue(props.value)}</span>
488
- }
778
+ fallback={<span class={styles().value}>{renderedValue()}</span>}
489
779
  >
490
780
  <Show
491
781
  when={
@@ -497,7 +787,12 @@ export default function Explorer(props: ExplorerProps) {
497
787
  <input
498
788
  id={inputId}
499
789
  type={type() === 'number' ? 'number' : 'text'}
500
- class={cx(styles().value, styles().editableInput)}
790
+ class={cx(
791
+ styles().value,
792
+ styles().editableInput,
793
+ props.search?.match.value && styles().highlight,
794
+ )}
795
+ data-search-match={props.search?.match.value || undefined}
501
796
  value={props.value as string | number}
502
797
  onChange={(changeEvent) => {
503
798
  const oldData = props.activeQuery!.state.data
@@ -528,7 +823,7 @@ export default function Explorer(props: ExplorerProps) {
528
823
  dataPath={currentDataPath}
529
824
  value={props.value as boolean}
530
825
  />
531
- {displayValue(props.value)}
826
+ {renderedValue()}
532
827
  </span>
533
828
  </Show>
534
829
  </Show>
@@ -558,6 +853,32 @@ const stylesFactory = (
558
853
  const { colors, font, size, border } = tokens
559
854
  const t = (light: string, dark: string) => (theme === 'light' ? light : dark)
560
855
  return {
856
+ search: css`
857
+ display: flex;
858
+ gap: ${size[2]};
859
+ margin-bottom: ${size[2]};
860
+ `,
861
+ searchInput: css`
862
+ min-width: 0;
863
+ flex: 1;
864
+ padding: ${size[1]} ${size[2]};
865
+ color: inherit;
866
+ background: ${t(colors.gray[100], colors.darkGray[600])};
867
+ border: 1px solid ${t(colors.gray[300], colors.darkGray[400])};
868
+ border-radius: ${border.radius.xs};
869
+ `,
870
+ clearSearch: css`
871
+ color: inherit;
872
+ background: transparent;
873
+ border: none;
874
+ cursor: pointer;
875
+ `,
876
+ highlight: css`
877
+ && {
878
+ color: ${t(colors.gray[900], colors.gray[100])};
879
+ background-color: ${t(colors.yellow[200], colors.yellow[900])};
880
+ }
881
+ `,
561
882
  entry: css`
562
883
  & * {
563
884
  font-size: ${font.size.xs};
@@ -0,0 +1,105 @@
1
+ import { createEffect, createMemo, on, onCleanup } from 'solid-js'
2
+ import { Key } from '@solid-primitives/keyed'
3
+ import { createVirtualizer } from '@tanstack/solid-virtual'
4
+ import type { VirtualItem } from '@tanstack/solid-virtual'
5
+ import type { Accessor, JSX } from 'solid-js'
6
+
7
+ type VirtualListProps<T> = {
8
+ each: ReadonlyArray<T>
9
+ getKey: (item: T) => VirtualItem['key']
10
+ class: string
11
+ contentClass: string
12
+ children: (item: Accessor<T>) => JSX.Element
13
+ }
14
+
15
+ type VisibleRow<T> = {
16
+ item: T
17
+ key: VirtualItem['key']
18
+ index: number
19
+ start: number
20
+ }
21
+
22
+ /**
23
+ * Renders measured rows for the visible portion of an ordered list.
24
+ * @param props - The items, stable keys, classes, and row content.
25
+ * @returns The scroll viewport and its visible rows.
26
+ */
27
+ export function VirtualList<T>(props: VirtualListProps<T>): JSX.Element {
28
+ let scrollElement!: HTMLDivElement
29
+ const keyForIndex = createMemo(() => {
30
+ const keys = props.each.map(props.getKey)
31
+ return (index: number) => keys[index] ?? index
32
+ })
33
+ const virtualizer = createVirtualizer<HTMLDivElement, HTMLDivElement>({
34
+ get count() {
35
+ return props.each.length
36
+ },
37
+ getScrollElement: () => scrollElement,
38
+ get getItemKey() {
39
+ return keyForIndex()
40
+ },
41
+ estimateSize: () => 28,
42
+ overscan: 5,
43
+ useAnimationFrameWithResizeObserver: true,
44
+ })
45
+ const rows = createMemo(() => {
46
+ const items = props.each
47
+ const visible: Array<VisibleRow<T>> = []
48
+ for (const entry of virtualizer.getVirtualItems()) {
49
+ const item = items[entry.index]
50
+ if (item !== undefined) {
51
+ visible.push({
52
+ item,
53
+ key: props.getKey(item),
54
+ index: entry.index,
55
+ start: entry.start,
56
+ })
57
+ }
58
+ }
59
+ return visible
60
+ })
61
+
62
+ return (
63
+ <div ref={scrollElement} class={props.class}>
64
+ <div
65
+ class={props.contentClass}
66
+ style={{
67
+ position: 'relative',
68
+ width: '100%',
69
+ height: `${virtualizer.getTotalSize()}px`,
70
+ }}
71
+ >
72
+ <Key each={rows()} by={(row) => row.key}>
73
+ {(row) => {
74
+ let element!: HTMLDivElement
75
+ createEffect(
76
+ on(
77
+ () => row().index,
78
+ (index) => {
79
+ element.setAttribute('data-index', String(index))
80
+ virtualizer.measureElement(element)
81
+ },
82
+ ),
83
+ )
84
+ onCleanup(() => virtualizer.measureElement(null))
85
+ return (
86
+ <div
87
+ ref={element}
88
+ data-index={row().index}
89
+ style={{
90
+ position: 'absolute',
91
+ top: 0,
92
+ left: 0,
93
+ width: '100%',
94
+ transform: `translateY(${row().start}px)`,
95
+ }}
96
+ >
97
+ {props.children(() => row().item)}
98
+ </div>
99
+ )
100
+ }}
101
+ </Key>
102
+ </div>
103
+ </div>
104
+ )
105
+ }