Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-angular-virtual-ng0600.md
Original file line number Diff line number Diff line change
@@ -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()`.
4 changes: 4 additions & 0 deletions packages/angular-virtual/e2e/app/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'
>
|
<a routerLink="/stale-index" routerLinkActive="active">Stale index</a>
|
<a routerLink="/computed-count" routerLinkActive="active"
>Computed count</a
>
</nav>

<router-outlet />
Expand Down
5 changes: 5 additions & 0 deletions packages/angular-virtual/e2e/app/src/app/app.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
{
Expand All @@ -26,4 +27,8 @@ export const routes: Routes = [
path: 'stale-index',
component: StaleIndexComponent,
},
{
path: 'computed-count',
component: ComputedCountComponent,
},
]
133 changes: 133 additions & 0 deletions packages/angular-virtual/e2e/app/src/app/computed-count.component.ts
Original file line number Diff line number Diff line change
@@ -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: `
<div>
<button data-testid="set-0" type="button" (click)="setCount(0)">
Set 0
</button>
<button data-testid="set-20" type="button" (click)="setCount(20)">
Set 20
</button>
<button data-testid="set-35" type="button" (click)="setCount(35)">
Set 35
</button>
<button data-testid="set-5" type="button" (click)="setCount(5)">
Set 5
</button>
<button
data-testid="toggle-tall"
type="button"
(click)="toggleFirstItemHeight()"
>
Toggle tall first item
</button>
<button
data-testid="measure-burst"
type="button"
(click)="measureAllVisible()"
>
Measure burst
</button>

<div data-testid="item-count">{{ count() }}</div>
<div data-testid="last-index">{{ lastVirtualIndex() }}</div>
<div data-testid="effect-total">{{ effectTotalSize() }}</div>
<div data-testid="total-size">{{ virtualizer.getTotalSize() }}</div>

<div
#scrollElement
data-testid="scroll-container"
style="height: 200px; overflow: auto;"
>
<div
style="position: relative; width: 100%;"
[style.height.px]="virtualizer.getTotalSize()"
>
@for (row of virtualizer.getVirtualItems(); track row.index) {
<div
#virtualItem
[attr.data-testid]="'row-' + row.index"
[attr.data-index]="row.index"
style="position: absolute; top: 0; left: 0; width: 100%; box-sizing: border-box;"
[style.height.px]="
row.index === 0 && tallFirstItem()
? 90
: (row.index === 1 || row.index === 2) && tallExtraRows()
? 70
: 40
"
[style.transform]="'translateY(' + row.start + 'px)'"
>
Row {{ row.index }}
</div>
}
</div>
</div>
</div>
`,
})
export class ComputedCountComponent {
scrollElement = viewChild<ElementRef<HTMLDivElement>>('scrollElement')
virtualItems = viewChildren<ElementRef<HTMLDivElement>>('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)
}
}
55 changes: 55 additions & 0 deletions packages/angular-virtual/e2e/app/test/computed-count.spec.ts
Original file line number Diff line number Diff line change
@@ -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<string> = []
const consoleErrors: Array<string> = []

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([])
})
80 changes: 75 additions & 5 deletions packages/angular-virtual/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
ApplicationRef,
DestroyRef,
Injector,
NgZone,
afterRenderEffect,
assertInInjectionContext,
computed,
Expand Down Expand Up @@ -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(() => {
Expand All @@ -63,7 +65,9 @@ function injectScheduleDomFlushViaAppRefTick() {
queueMicrotask(() => {
domFlushQueued = false
if (hostDestroyed) return
appRef.tick()
ngZone.run(() => {
appRef.tick()
})
})
}
}
Expand All @@ -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 = <T>(fn: () => T): T => {
computedReadDepth++
try {
return fn()
} finally {
computedReadDepth--
}
}

const scheduleMeasureWarm = (
instance: Virtualizer<TScrollElement, TItemElement>,
) => {
if (pendingMeasureWarm) return
pendingMeasureWarm = true
queueMicrotask(() => {
pendingMeasureWarm = false
if (hostDestroyed || isNotifying) return
isNotifying = true
try {
instance.getTotalSize()
} finally {
isNotifying = false
}
})
}

const resolvedOptions = computed<
VirtualizerOptions<TScrollElement, TItemElement>
Expand All @@ -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)
Expand All @@ -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 },
Expand Down Expand Up @@ -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<TScrollElement, TItemElement>
})
Expand Down
Loading