diff --git a/.changeset/fix-angular-virtual-ng0600.md b/.changeset/fix-angular-virtual-ng0600.md new file mode 100644 index 000000000..1fe1acd0b --- /dev/null +++ b/.changeset/fix-angular-virtual-ng0600.md @@ -0,0 +1,5 @@ +--- +'@tanstack/angular-virtual': patch +--- + +Prevent `NG0600` (`Writing to signals is not allowed in a computed`) when measurement-affecting options or dynamic item sizes change while Angular `computed()` / `effect()` readers access `getVirtualItems()` or `getTotalSize()`. diff --git a/packages/angular-virtual/e2e/app/src/app/app.component.ts b/packages/angular-virtual/e2e/app/src/app/app.component.ts index 00b89cf0e..8d0602695 100644 --- a/packages/angular-virtual/e2e/app/src/app/app.component.ts +++ b/packages/angular-virtual/e2e/app/src/app/app.component.ts @@ -17,6 +17,10 @@ import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router' > | Stale index + | + Computed count diff --git a/packages/angular-virtual/e2e/app/src/app/app.routes.ts b/packages/angular-virtual/e2e/app/src/app/app.routes.ts index b82c9497f..4230bf40d 100644 --- a/packages/angular-virtual/e2e/app/src/app/app.routes.ts +++ b/packages/angular-virtual/e2e/app/src/app/app.routes.ts @@ -3,6 +3,7 @@ import { MeasureElementComponent } from './measure-element.component' import { SmoothScrollComponent } from './smooth-scroll.component' import { ScrollComponent } from './scroll.component' import { StaleIndexComponent } from './stale-index.component' +import { ComputedCountComponent } from './computed-count.component' export const routes: Routes = [ { @@ -26,4 +27,8 @@ export const routes: Routes = [ path: 'stale-index', component: StaleIndexComponent, }, + { + path: 'computed-count', + component: ComputedCountComponent, + }, ] diff --git a/packages/angular-virtual/e2e/app/src/app/computed-count.component.ts b/packages/angular-virtual/e2e/app/src/app/computed-count.component.ts new file mode 100644 index 000000000..c4aae7216 --- /dev/null +++ b/packages/angular-virtual/e2e/app/src/app/computed-count.component.ts @@ -0,0 +1,133 @@ +import { + ChangeDetectionStrategy, + Component, + ElementRef, + computed, + effect, + signal, + viewChild, + viewChildren, +} from '@angular/core' +import { injectVirtualizer } from '@tanstack/angular-virtual' + +@Component({ + standalone: true, + selector: 'app-computed-count', + changeDetection: ChangeDetectionStrategy.OnPush, + template: ` +
+ + + + + + + +
{{ count() }}
+
{{ lastVirtualIndex() }}
+
{{ effectTotalSize() }}
+
{{ virtualizer.getTotalSize() }}
+ +
+
+ @for (row of virtualizer.getVirtualItems(); track row.index) { +
+ Row {{ row.index }} +
+ } +
+
+
+ `, +}) +export class ComputedCountComponent { + scrollElement = viewChild>('scrollElement') + virtualItems = viewChildren>('virtualItem') + + count = signal(0) + tallFirstItem = signal(false) + tallExtraRows = signal(false) + effectTotalSize = signal(0) + + virtualizer = injectVirtualizer(() => ({ + scrollElement: this.scrollElement(), + count: this.count(), + estimateSize: () => 40, + overscan: 2, + })) + + // Regression target for #1096: reading getVirtualItems() inside computed() + lastVirtualIndex = computed(() => { + const items = this.virtualizer.getVirtualItems() + return items.at(-1)?.index ?? -1 + }) + + // Regression target for #1096: reading getVirtualItems() & getTotalSize() inside effect() + #syncEffect = effect(() => { + this.virtualizer.getVirtualItems() + this.effectTotalSize.set(this.virtualizer.getTotalSize()) + }) + + setCount(nextCount: number) { + this.count.set(nextCount) + } + + toggleFirstItemHeight() { + this.tallFirstItem.update((v) => !v) + queueMicrotask(() => { + const first = this.virtualItems()[0]?.nativeElement + if (first) { + this.virtualizer.measureElement(first) + } + }) + } + + measureAllVisible() { + this.tallExtraRows.set(true) + setTimeout(() => { + this.virtualItems().forEach((el) => { + this.virtualizer.measureElement(el.nativeElement) + }) + }, 0) + } +} diff --git a/packages/angular-virtual/e2e/app/test/computed-count.spec.ts b/packages/angular-virtual/e2e/app/test/computed-count.spec.ts new file mode 100644 index 000000000..3c3bbe05d --- /dev/null +++ b/packages/angular-virtual/e2e/app/test/computed-count.spec.ts @@ -0,0 +1,55 @@ +import { expect, test } from '@playwright/test' + +test('updating count and measured size with computed/effect readers does not throw NG0600', async ({ + page, +}) => { + const pageErrors: Array = [] + const consoleErrors: Array = [] + + page.on('pageerror', (err) => { + pageErrors.push(err.message) + }) + page.on('console', (msg) => { + if (msg.type() === 'error') { + consoleErrors.push(msg.text()) + } + }) + + await page.goto('/computed-count') + + await expect(page.locator('[data-testid="item-count"]')).toHaveText('0') + await expect(page.locator('[data-testid="last-index"]')).toHaveText('-1') + await expect(page.locator('[data-testid="total-size"]')).toHaveText('0') + + await page.click('[data-testid="set-20"]') + await expect(page.locator('[data-testid="item-count"]')).toHaveText('20') + await expect(page.locator('[data-testid="total-size"]')).toHaveText('800') + await expect(page.locator('[data-testid="effect-total"]')).toHaveText('800') + await expect(page.locator('[data-testid="row-0"]')).toBeVisible() + + await page.click('[data-testid="set-35"]') + await expect(page.locator('[data-testid="item-count"]')).toHaveText('35') + await expect(page.locator('[data-testid="total-size"]')).toHaveText('1400') + await expect(page.locator('[data-testid="effect-total"]')).toHaveText('1400') + + await page.click('[data-testid="toggle-tall"]') + await expect(page.locator('[data-testid="total-size"]')).toHaveText('1450') + await expect(page.locator('[data-testid="effect-total"]')).toHaveText('1450') + + await page.click('[data-testid="set-5"]') + await expect(page.locator('[data-testid="item-count"]')).toHaveText('5') + await expect(page.locator('[data-testid="total-size"]')).toHaveText('250') + await expect(page.locator('[data-testid="effect-total"]')).toHaveText('250') + await expect(page.locator('[data-testid="last-index"]')).toHaveText('4') + + await page.click('[data-testid="measure-burst"]') + await expect(page.locator('[data-testid="total-size"]')).toHaveText('310') + await expect(page.locator('[data-testid="effect-total"]')).toHaveText('310') + + await page.click('[data-testid="set-0"]') + await expect(page.locator('[data-testid="total-size"]')).toHaveText('0') + await expect(page.locator('[data-testid="last-index"]')).toHaveText('-1') + + expect(pageErrors).toEqual([]) + expect(consoleErrors).toEqual([]) +}) diff --git a/packages/angular-virtual/src/index.ts b/packages/angular-virtual/src/index.ts index 81a1f983e..52dfe2412 100644 --- a/packages/angular-virtual/src/index.ts +++ b/packages/angular-virtual/src/index.ts @@ -2,6 +2,7 @@ import { ApplicationRef, DestroyRef, Injector, + NgZone, afterRenderEffect, assertInInjectionContext, computed, @@ -50,6 +51,7 @@ export type AngularExtensionOptions = { // before the next frame's scroll reconciliation reads `scrollHeight`. function injectScheduleDomFlushViaAppRefTick() { const appRef = inject(ApplicationRef) + const ngZone = inject(NgZone) const destroyRef = inject(DestroyRef) let hostDestroyed = false destroyRef.onDestroy(() => { @@ -63,7 +65,9 @@ function injectScheduleDomFlushViaAppRefTick() { queueMicrotask(() => { domFlushQueued = false if (hostDestroyed) return - appRef.tick() + ngZone.run(() => { + appRef.tick() + }) }) } } @@ -82,7 +86,44 @@ function injectVirtualizerBase< } return runInInjectionContext(injector, () => { + const destroyRef = inject(DestroyRef) const scheduleDomFlush = injectScheduleDomFlushViaAppRefTick() + let hostDestroyed = false + destroyRef.onDestroy(() => { + hostDestroyed = true + }) + + let computedReadDepth = 0 + let isSyncingOptions = false + let isNotifying = false + let pendingMeasureWarm = false + let pendingSignalSync = false + + const withComputedRead = (fn: () => T): T => { + computedReadDepth++ + try { + return fn() + } finally { + computedReadDepth-- + } + } + + const scheduleMeasureWarm = ( + instance: Virtualizer, + ) => { + if (pendingMeasureWarm) return + pendingMeasureWarm = true + queueMicrotask(() => { + pendingMeasureWarm = false + if (hostDestroyed || isNotifying) return + isNotifying = true + try { + instance.getTotalSize() + } finally { + isNotifying = false + } + }) + } const resolvedOptions = computed< VirtualizerOptions @@ -91,8 +132,28 @@ function injectVirtualizerBase< return { ..._options, onChange: (instance, sync) => { - reactiveVirtualizer.set(instance) - if (useApplicationRefTick) { + let deferredSignalWrite = false + if (!isSyncingOptions) { + scheduleMeasureWarm(instance) + if (computedReadDepth > 0) { + deferredSignalWrite = true + if (!pendingSignalSync) { + pendingSignalSync = true + queueMicrotask(() => { + pendingSignalSync = false + if (!hostDestroyed) { + reactiveVirtualizer.set(instance) + if (useApplicationRefTick) { + scheduleDomFlush() + } + } + }) + } + } else { + reactiveVirtualizer.set(instance) + } + } + if (useApplicationRefTick && !deferredSignalWrite) { scheduleDomFlush() } _options.onChange?.(instance, sync) @@ -111,8 +172,16 @@ function injectVirtualizerBase< const reactiveVirtualizer = linkedSignal( () => { const virtualizer = lazyVirtualizer() - // If setOptions does not call onChange, it's safe to call it here - virtualizer.setOptions(resolvedOptions()) + isSyncingOptions = true + try { + // If setOptions does not call onChange, it's safe to call it here + virtualizer.setOptions(resolvedOptions()) + // Warm lazy measurements outside computed/effect reads so PR #1085's + // getMeasurements -> notify() does not write signals inside computed(). + virtualizer.getTotalSize() + } finally { + isSyncingOptions = false + } return virtualizer }, { equal: () => false }, @@ -163,6 +232,7 @@ function injectVirtualizerBase< ], // Zero-arg methods exposed as computed signals ['getTotalSize', 'getVirtualItems'], + withComputedRead, // The rest is passed as is, and can be accessed or called before initialization ) as unknown as AngularVirtualizer }) diff --git a/packages/angular-virtual/src/proxy.ts b/packages/angular-virtual/src/proxy.ts index 0a9749d45..9ecb01fef 100644 --- a/packages/angular-virtual/src/proxy.ts +++ b/packages/angular-virtual/src/proxy.ts @@ -29,6 +29,7 @@ export function signalProxy< attributesToTransformToSignals: Array, methodsToTrack: Array, methodsToTransformToSignals: Array, + onComputedRead?: (fn: () => T) => T, ): SignalProxy< TInput, TMethodsToPassThrough, @@ -61,16 +62,21 @@ export function signalProxy< property as TMethodsToTransformToSignals, ) ) { - return (target[property] = computed(() => - (inputSignal()[property as keyof TInput] as () => unknown)(), - )) + return (target[property] = computed(() => { + const run = () => + (inputSignal()[property as keyof TInput] as () => unknown)() + return onComputedRead ? onComputedRead(run) : run() + })) } // Methods that need to be tracked, track instance changes and call the method if (methodsToTrack.includes(property as TMethodsToTrack)) { return (target[property] = ( ...args: Parameters - ) => inputSignal()[property as keyof TInput](...args)) + ) => { + const run = () => inputSignal()[property as keyof TInput](...args) + return onComputedRead ? onComputedRead(run) : run() + }) } // Other values that are tracked as signals @@ -79,9 +85,10 @@ export function signalProxy< property as TAttributesToTransformToSignals, ) ) { - return (target[property] = computed( - () => inputSignal()[property as keyof TInput], - )) + return (target[property] = computed(() => { + const run = () => inputSignal()[property as keyof TInput] + return onComputedRead ? onComputedRead(run) : run() + })) } // All other fields. Any field that is not handled above will fail if the signal includes