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/batch-register-measure.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"js.foresight": patch
---

Measure newly registered elements in one batch after the registering task instead of inside `register()`. Registering thousands of elements while a framework inserts them (Vue function refs) no longer forces a layout per element. `getBounds()` and `isIntersectingWithViewport` now get their first values right after the registering task
2 changes: 2 additions & 0 deletions packages/docs/docs/_partials/_registration-options.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,8 @@ Subscribes to geometry changes for this element. The listener is called every ti

Returns the current immutable `ElementBounds` snapshot for this element: its measured `originalRect` and the hitSlop-expanded `expandedRect` used for interaction detection.

Elements are measured right after the task that registered them, in one batch, so `getBounds()` returns empty rects (and `isIntersectingWithViewport` is `false`) if read synchronously after `register()`. Use `subscribeToBounds` or `subscribe` to get the first measurement.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

subscribe (the state channel) won't fire for an element that is offscreen at first measurement: isIntersectingWithViewport stays false, so updateElementState early-returns and no state subscriber is notified. Only subscribeToBounds reliably delivers the first measurement. Suggest narrowing this to subscribeToBounds (or noting the caveat).


---

### State Fields
Expand Down
12 changes: 5 additions & 7 deletions packages/js.foresight/src/helpers/createInitialState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ import type {
ForesightRegisterOptionsWithoutElement,
HitSlop,
} from "../types/types"
import { getExpandedRect, normalizeHitSlop } from "./rectAndHitSlop"
import { initialViewportState } from "./initialViewportState"
import { normalizeHitSlop } from "./rectAndHitSlop"
import { canBeActive } from "./canBeActive"

export const createDefaultManagerSettings = (): ForesightManagerSettings => {
Expand Down Expand Up @@ -104,15 +103,12 @@ export const createElementInternal = (
enabled: isEnabled,
} = resolveElementOptions(options, defaultHitSlop)

const initialRect = element.getBoundingClientRect()

const state: ForesightElementState = {
...createBaseElementState(isLimitedConnection),
id,
name,
meta,
hitSlop,
isIntersectingWithViewport: initialViewportState(initialRect),
isRegistered: true,
isActive: canBeActive({ isEnabled, isLimitedConnection, isParked: false }),
isEnabled,
Expand All @@ -121,9 +117,11 @@ export const createElementInternal = (

return {
state,
// Empty until the manager measures it after the registering task, so a
// batch of registrations costs one layout instead of one per element.
bounds: {
originalRect: initialRect,
expandedRect: getExpandedRect(initialRect, hitSlop),
originalRect: new DOMRectReadOnly(),
expandedRect: { top: 0, left: 0, right: 0, bottom: 0 },
},
element,
callback,
Expand Down
25 changes: 21 additions & 4 deletions packages/js.foresight/src/managers/ForesightManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -878,12 +878,12 @@ describe("ForesightManager", () => {
describe("Bounds channel (getBounds / subscribeToBounds)", () => {
it("notifies only bounds subscribers on a rect-only update", async () => {
const { element, result } = setup()
await settle()
const stateListener = vi.fn()
const boundsListener = vi.fn()
result.subscribe(stateListener)
result.subscribeToBounds(boundsListener)
const snapshotBefore = result.getSnapshot()
await settle()

reportPosition(element, rectAt(300, 300))

Expand All @@ -895,6 +895,7 @@ describe("ForesightManager", () => {

it("notifies only state subscribers on a logical change", async () => {
const { element, result } = setup()
await settle()
const stateListener = vi.fn()
const boundsListener = vi.fn()
result.subscribe(stateListener)
Expand All @@ -911,17 +912,33 @@ describe("ForesightManager", () => {

it("does not notify when the rect is unchanged", async () => {
const { element, result } = setup()
await settle()
const boundsListener = vi.fn()
result.subscribeToBounds(boundsListener)
const boundsBefore = result.getBounds()
await settle()

reportPosition(element, rectAt())

expect(boundsListener).not.toHaveBeenCalled()
expect(result.getBounds()).toBe(boundsBefore)
})

it("defers measuring until after the registering task", async () => {
const manager = ForesightManager.initialize()
const elements = [createElement(), createElement()]
const reads = elements.map(element => vi.spyOn(element, "getBoundingClientRect"))
const results = elements.map(element => manager.register({ element, callback: vi.fn() }))

expect(reads.every(read => read.mock.calls.length === 0)).toBe(true)
expect(results[0].getSnapshot().isIntersectingWithViewport).toBe(false)

await Promise.resolve()

expect(reads.every(read => read.mock.calls.length === 1)).toBe(true)
expect(results[0].getSnapshot().isIntersectingWithViewport).toBe(true)
expect(results[0].getBounds().originalRect.top).toBe(100)
})

it("updates bounds before state on a hitSlop change", () => {
const { manager, element, result } = setup({ hitSlop: 10 })
const order: string[] = []
Expand All @@ -940,9 +957,9 @@ describe("ForesightManager", () => {

it("supports manager-level bounds subscriptions and clears them on unregister", async () => {
const { manager, element } = setup()
await settle()
const boundsListener = vi.fn()
manager.subscribeToElementBounds(element, boundsListener)
await settle()

reportPosition(element, rectAt(300, 300))
expect(boundsListener).toHaveBeenCalledTimes(1)
Expand All @@ -957,9 +974,9 @@ describe("ForesightManager", () => {
it("binds results of re-registrations to the same bounds", async () => {
const { manager, element, result: first } = setup()
const second = manager.register({ element, callback: vi.fn() })
await settle()
const boundsListener = vi.fn()
first.subscribeToBounds(boundsListener)
await settle()

reportPosition(element, rectAt(300, 300))

Expand Down
38 changes: 34 additions & 4 deletions packages/js.foresight/src/managers/ForesightManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from "../helpers/createInitialState"
import { applyDataAttributes, removeDataAttributes } from "../helpers/dataAttributes"
import { isScannable } from "../helpers/isScannable"
import { initialViewportState } from "../helpers/initialViewportState"
import { canBeActive } from "../helpers/canBeActive"
import { ForesightEventEmitter } from "../core/ForesightEventEmitter"
import type { ForesightModuleDependencies } from "../core/BaseForesightModule"
Expand Down Expand Up @@ -62,10 +63,12 @@ export class ForesightManager {
/**
* Precomputed subset of {@link elementEntries} that the mouse trajectory scan
* iterates every pointer move (see {@link isScannable}). Kept in sync by
* {@link updateElementState} plus register/unregister, so the hot loop skips
* {@link updateElementState} plus unregister, so the hot loop skips
* the full registry and its per-element flag checks.
*/
private scannableElements: Set<ForesightElementInternal> = new Set()
/** Registered this task and not yet measured, see {@link measureNewElements}. */
private unmeasuredElements: Set<ForesightElementInternal> = new Set()
/** Public read-only view exposing only external state, derived from {@link elementEntries}. */
public readonly registeredElements: ReadonlyMap<ForesightElement, ForesightElementState> =
new DerivedMapView(this.elementEntries, (entry: ForesightElementInternal) => entry.state)
Expand Down Expand Up @@ -270,11 +273,12 @@ export class ForesightManager {
)

this.elementEntries.set(options.element, entry)

if (isScannable(entry.state)) {
this.scannableElements.add(entry)
if (this.unmeasuredElements.size === 0) {
queueMicrotask(this.measureNewElements)
}

this.unmeasuredElements.add(entry)

if (this._globalSettings.setDataAttributes) {
applyDataAttributes(entry.element, entry.state)
}
Expand All @@ -295,6 +299,32 @@ export class ForesightManager {
return this.buildRegisterResult(entry)
}

/**
* Measures every element registered in the current task at once. Measuring
* inside register() forces a layout per element when a framework inserts and
* registers elements in turn (Vue function refs), which is quadratic. All
* reads happen before any write so the batch costs a single layout.
*/
private measureNewElements = (): void => {
const measured = Array.from(this.unmeasuredElements, entry => ({
entry,
rect: entry.element.getBoundingClientRect(),
}))
this.unmeasuredElements.clear()

for (const { entry, rect } of measured) {
if (this.elementEntries.get(entry.element) !== entry) {
continue
}

this.updateElementBounds(entry, {
originalRect: rect,
expandedRect: getExpandedRect(rect, entry.state.hitSlop),
})
this.updateElementState(entry, { isIntersectingWithViewport: initialViewportState(rect) })
}
}

private buildRegisterResult(entry: ForesightElementInternal): ForesightRegisterResult {
return {
...entry.state,
Expand Down
Loading