Skip to content
Source
Sign inSign up
TanStack/virtual
Open History to see the last commit

index.ts

226 lines6.4 KB

1import {
2 ApplicationRef,
3 DestroyRef,
4 Injector,
5 afterRenderEffect,
6 assertInInjectionContext,
7 computed,
8 inject,
9 linkedSignal,
10 runInInjectionContext,
11 untracked,
12} from '@angular/core'
13import {
14 Virtualizer,
15 elementScroll,
16 observeElementOffset,
17 observeElementRect,
18 observeWindowOffset,
19 observeWindowRect,
20 windowScroll,
21} from '@tanstack/virtual-core'
22import { signalProxy } from './proxy'
23import type { ElementRef } from '@angular/core'
24import type { PartialKeys, VirtualizerOptions } from '@tanstack/virtual-core'
25import type { AngularVirtualizer } from './types'
26​
27export * from '@tanstack/virtual-core'
28export * from './types'
29​
30export type AngularVirtualizerOptions<
31 TScrollElement extends Element | Window,
32 TItemElement extends Element,
33> = VirtualizerOptions<TScrollElement, TItemElement> & {
34 /**
35 * Whether to flush the DOM using `ApplicationRef.tick()`
36 * @default true
37 * */
38 useApplicationRefTick?: boolean
40​
41export type AngularExtensionOptions = {
42 /**
43 * The injector to use for the virtualizer.
44 * @default inject(Injector)
45 */
46 injector?: Injector
48​
49// Flush CD after virtual-core updates so template bindings hit the DOM
50// before the next frame's scroll reconciliation reads `scrollHeight`.
51function injectScheduleDomFlushViaAppRefTick() {
52 const appRef = inject(ApplicationRef)
53 const destroyRef = inject(DestroyRef)
54 let hostDestroyed = false
55 destroyRef.onDestroy(() => {
56 hostDestroyed = true
57 })
58 let domFlushQueued = false
59​
60 return () => {
61 if (domFlushQueued) return
62 domFlushQueued = true
63 queueMicrotask(() => {
64 domFlushQueued = false
65 if (hostDestroyed) return
66 appRef.tick()
67 })
68 }
70​
71function injectVirtualizerBase<
72 TScrollElement extends Element | Window,
73 TItemElement extends Element,
74>(
75 options: () => AngularVirtualizerOptions<TScrollElement, TItemElement>,
76 extensions: AngularExtensionOptions = {},
77) {
78 let injector = extensions.injector
79 if (!injector) {
80 assertInInjectionContext(injectVirtualizerBase)
81 injector = inject(Injector)
82 }
83​
84 return runInInjectionContext(injector, () => {
85 const scheduleDomFlush = injectScheduleDomFlushViaAppRefTick()
86​
87 const resolvedOptions = computed<
88 VirtualizerOptions<TScrollElement, TItemElement>
89 >(() => {
90 const { useApplicationRefTick = true, ..._options } = options()
91 return {
92 ..._options,
93 onChange: (instance, sync) => {
94 reactiveVirtualizer.set(instance)
95 if (useApplicationRefTick) {
96 scheduleDomFlush()
97 }
98 _options.onChange?.(instance, sync)
99 },
100 }
101 })
102​
103 // Computed here is used to lazily initialize the Virtualizer instance,
104 // allowing it to be created after input/model signals are initialized.
105 // Options are untracked to maintain a single instance of the Virtualizer.
106 const lazyVirtualizer = computed(
107 () => new Virtualizer(untracked(resolvedOptions)),
108 )
109​
110 // The reference in onChange is safe since computed signals are not evaluated eagerly.
111 const reactiveVirtualizer = linkedSignal(
112 () => {
113 const virtualizer = lazyVirtualizer()
114 // If setOptions does not call onChange, it's safe to call it here
115 virtualizer.setOptions(resolvedOptions())
116 return virtualizer
117 },
118 { equal: () => false },
119 )
120​
121 afterRenderEffect((cleanup) => {
122 cleanup(lazyVirtualizer()._didMount())
123 })
124​
125 afterRenderEffect(() => {
126 reactiveVirtualizer()._willUpdate()
127 })
128​
129 return signalProxy(
130 reactiveVirtualizer,
131 // Methods that pass through: call on the instance without tracking the signal read
132 [
133 '_didMount',
134 '_willUpdate',
135 'calculateRange',
136 'getVirtualIndexes',
137 'measure',
138 'measureElement',
139 'resizeItem',
140 'scrollBy',
141 'scrollToIndex',
142 'scrollToOffset',
143 'setOptions',
144 ],
145 // Attributes that will be transformed to signals
146 [
147 'isScrolling',
148 'measurementsCache',
149 'options',
150 'range',
151 'scrollDirection',
152 'scrollElement',
153 'scrollOffset',
154 'scrollRect',
155 ],
156 // Methods that will be tracked to the virtualizer signal
157 [
158 'getOffsetForAlignment',
159 'getOffsetForIndex',
160 'getVirtualItemForOffset',
161 'indexFromElement',
162 ],
163 // Zero-arg methods exposed as computed signals
164 ['getTotalSize', 'getVirtualItems'],
165 // The rest is passed as is, and can be accessed or called before initialization
166 ) as unknown as AngularVirtualizer<TScrollElement, TItemElement>
167 })
169​
170export function injectVirtualizer<
171 TScrollElement extends Element,
172 TItemElement extends Element,
173>(
174 options: () => PartialKeys<
175 Omit<
176 AngularVirtualizerOptions<TScrollElement, TItemElement>,
177 'getScrollElement'
178 >,
179 'observeElementRect' | 'observeElementOffset' | 'scrollToFn'
180 > & {
181 scrollElement: ElementRef<TScrollElement> | TScrollElement | undefined
182 },
183): AngularVirtualizer<TScrollElement, TItemElement> {
184 return injectVirtualizerBase<TScrollElement, TItemElement>(() => {
185 const _options = options()
186 return {
187 observeElementRect: observeElementRect,
188 observeElementOffset: observeElementOffset,
189 scrollToFn: elementScroll,
190 getScrollElement: () => {
191 const elementOrRef = _options.scrollElement
192 return (
193 (isElementRef(elementOrRef)
194 ? elementOrRef.nativeElement
195 : elementOrRef) ?? null
196 )
197 },
198 ..._options,
199 }
200 })
202​
203function isElementRef<T extends Element>(
204 elementOrRef: ElementRef<T> | T | undefined,
205): elementOrRef is ElementRef<T> {
206 return elementOrRef != null && 'nativeElement' in elementOrRef
208​
209export function injectWindowVirtualizer<TItemElement extends Element>(
210 options: () => PartialKeys<
211 AngularVirtualizerOptions<Window, TItemElement>,
212 | 'getScrollElement'
213 | 'observeElementRect'
214 | 'observeElementOffset'
215 | 'scrollToFn'
216 >,
217): AngularVirtualizer<Window, TItemElement> {
218 return injectVirtualizerBase<Window, TItemElement>(() => ({
219 getScrollElement: () => (typeof document !== 'undefined' ? window : null),
220 observeElementRect: observeWindowRect,
221 observeElementOffset: observeWindowOffset,
222 scrollToFn: windowScroll,
223 initialOffset: () => (typeof document !== 'undefined' ? window.scrollY : 0),
224 ...options(),
225 }))