Skip to content

feat: add observeItemSizes, fix unchanged-box re-measure churn - #27

Merged
Eliav2 merged 2 commits into
mainfrom
fix/resize-observer-churn-and-item-observation
Aug 8, 2026
Merged

Eliav2 merged 2 commits into
mainfrom
fix/resize-observer-churn-and-item-observation

Conversation

@Eliav2

@Eliav2 Eliav2 commented Aug 8, 2026 •

Copy link
Copy Markdown
Owner

Two changes to what re-triggers measurement. Bumps to 0.5.0 (new public prop).

fix: useResizeObserver re-measured on an unchanged box

Consumers key off the returned object's identity, so storing a fresh object per notification made every notification look like a resize. Notifications reporting the same box do happen: an observer delivers one when it starts observing, and hiding or revealing an element can produce one without its box moving. Each cost a full re-measure downstream.

feat: observeItemSizes, off by default

Measurement re-runs on every render (item sizes compared against the sizes the current count was chosen for) and on container resize. Both need a trigger, so a size change React is not involved in is missed: a web font swapping in, an image loading, a CSS transition, a drag handle.

It usually hides. Items that grow enough to wrap make the container taller, and its own observer notices, so the list looks like it is tracking the items when it is really tracking itself. It stays missed when the container's box cannot change (a fixed-height bar), or when items shrink, since shrinking never wraps.

observeItemSizes closes that with a ResizeObserver over the children, extracted as useChildrenResizeObserver (internal, not exported). Off by default: most lists never need it.

Two load-bearing details, both settled by measurement in Chrome

Border box, not content box. A child's padding or border changing fires a border-box observer and not a content-box one, while getBoundingClientRect moves either way:

child change content-box fires border-box fires signature moves
padding no yes yes
border no yes yes
text yes yes yes

Left on the default box, the observer would stay silent for exactly the changes the check looks for.

A pass waits for one quiet animation frame rather than running per notification. Dragging a single child, 100 items, 3s:

fps dropped frames passes during drag correction after release
option off 120 0/200 0 never (stale)
per notification 88 29/200 ~199 live
quiet frame 121 0/200 0 ~2 frames

The wait is a frame count, not a duration, so there is no interval to tune: a size still moving notifies every frame, so one quiet frame separates moving from stopped. Two chained frames because in Chrome a frame's ResizeObserver callbacks run after its rAF callbacks. That order is not specified (WICG/resize-observer#37 has been open on it since 2017), so the comparison is written to hold under either order, and tests drive both.

Consequence worth knowing: the list is deliberately stale while sizes are moving and corrects when they stop. That is what keeps it free.

The item path is flushed like the container path when flushImmediately is set, so the corrected count lands in the frame about to be painted rather than a beat later.

Storybook

Behaviour/ResizableChildren puts a native resize handle on every item and on the container, with a live observeItemSizes toggle and a per-frame readout. Dragging the container exercises the path that needs no opt-in; dragging an item exercises the one that does. Same gesture, and only one is covered by default.

Also imports the Tailwind stylesheet in .storybook/preview.ts. It was never imported, so every class in every story was inert. This changes how the other stories look.

Testing

45 tests. Mutation tested by reverting each decision one at a time; ten of eleven are caught by a failing test:

reverted caught by
identity-churn guard 3 tests
default flipped to on is off by default
hook never wired up 4 tests
per-commit check 3 tests
enabled ignored in the hook 3 tests
border-box to content-box observes them on their border box
quiet-frame wait 5 tests
counter captured after requesting the frame 4 tests
pending wait not cancelled on stop drops a pending callback
unobserve stale children stops observing children that leave
two frames to one frame nothing

Two known gaps, both recorded in comments rather than papered over:

  • one frame vs two is not covered. The jsdom harness delivers a notification the moment a test asks, where a browser delivers it at a fixed point in the frame, so a one-frame wait passes every test. Covering it means teaching the harness to deliver at the frame's observer point, which every other test's timing depends on not doing. The second frame rests on the Chrome measurement.
  • the flushSync on the item path is not covered either: everything in the suite runs inside act(), which flushes batching regardless. It rests on consistency with the container path and on what flushImmediately documents.

Two tests assert the off path, so "off means off" is pinned rather than assumed: children are not observed at all, and an item-driven change stays unnoticed.

No regression in the browser: #21 holds one row through every badge stage, #23's four lists are unchanged through popover open and close.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added optional observeItemSizes support to detect changes in child dimensions and update overflow layouts after sizes stabilize.
    • Added interactive Storybook examples for resizing list items and containers.
  • Bug Fixes

    • Prevented unnecessary updates when container dimensions remain unchanged.
    • Improved handling of rapidly changing and detached items.
  • Documentation

    • Documented measurement triggers, child-size observation, and update batching behavior.
  • Chores

    • Updated the package version to 0.5.0.

Two changes to what re-triggers measurement.

fix(useResizeObserver): skip the update when the reported box is unchanged

Consumers key off the returned object's identity, so storing a fresh object per
notification made every notification look like a resize. Notifications that
report the same box do happen: an observer delivers one when it starts
observing, and hiding or revealing an element can produce one without its box
moving. Each of those cost a full re-measure downstream.

feat(overflow): observeItemSizes, off by default

Measurement re-runs on every render (comparing item sizes against the sizes the
current count was chosen for) and on container resize. Both need a trigger, so a
size change React is not involved in is missed: a web font swapping in, an image
loading, a CSS transition, a drag handle. It usually hides, because items that
grow enough to wrap make the container taller and its own observer notices. It
stays missed when the container's box cannot change, or when items shrink, since
shrinking never wraps.

observeItemSizes closes that with a ResizeObserver over the children, extracted
as useChildrenResizeObserver (internal). Off by default: most lists never need
it, and it is one observer per list.

Two details in that hook are load-bearing, both settled by measurement in Chrome:

- Children are observed on their border box. A child's padding or border
  changing fires a border-box observer and not a content-box one, while
  getBoundingClientRect moves either way, so the default box would stay silent
  for exactly the changes the check looks for.

- A pass waits for one animation frame with no further notification, rather than
  running per notification. Dragging a single child with 100 items dropped 29 of
  200 frames and took the page from 120fps to 88 when firing per notification;
  with the wait, frame times match leaving the option off. The wait is a frame
  count and not a duration, so there is no interval to tune. Two chained frames,
  because in Chrome a frame's ResizeObserver callbacks run after its rAF
  callbacks; the comparison is written to hold under either order, since the
  order is not specified (WICG/resize-observer#37).

The item path is flushed like the container path when flushImmediately is set,
so the corrected count lands in the frame about to be painted instead of a beat
later.

Storybook: Behaviour/ResizableChildren puts a native resize handle on every item
and on the container, with a live toggle, so both paths are reachable by hand.
Also imports the Tailwind stylesheet in .storybook/preview.ts, which was never
imported, leaving every class in every story inert.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@codesandbox

codesandbox Bot commented Aug 8, 2026

Copy link
Copy Markdown

Review or Edit in CodeSandbox

Open the branch in Web Editor • VS Code • Insiders

Open Preview

@netlify

netlify Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for react-responsive-overflow-list ready!

Name Link
🔨 Latest commit c1a8e3a
🔍 Latest deploy log https://app.netlify.com/projects/react-responsive-overflow-list/deploys/6a77af94c0334900080b3e18
😎 Deploy Preview https://deploy-preview-27--react-responsive-overflow-list.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Eliav2, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 25 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 7bc131db-d574-4752-8c37-e903aef3eb11

📥 Commits

Reviewing files that changed from the base of the PR and between 1cf46d9 and c1a8e3a.

📒 Files selected for processing (3)
  • demo/src/examples/ObserveItemSizesExample.tsx
  • demo/src/routes/docs/api.tsx
  • demo/src/routes/docs/examples.tsx
📝 Walkthrough

Walkthrough

Changes

OverflowList child-size observation

Layer / File(s) Summary
Public option and documentation
README.md, src/components/OverflowList.tsx, src/hooks/useOverflowList.ts, package.json
observeItemSizes is available on both APIs and defaults to disabled. The documentation describes child-size and container-size measurement triggers.
Child observation and settling
src/hooks/useChildrenResizeObserver.ts, src/hooks/useResizeObserver.ts, tests/dom/children-resize-observer.test.tsx, tests/dom/layout-harness.ts
Direct children are observed with border-box measurements. Notifications settle after quiet animation frames, unchanged dimensions are ignored, and cleanup removes observers and pending callbacks.
Remeasurement integration
src/hooks/useOverflowList.ts, tests/dom/overflow-list.test.tsx
Child-size changes invoke content-signature validation. Updates use synchronous flushing when configured and normal scheduling otherwise. Tests cover defaults, detached items, delayed changes, and notification coalescing.
Interactive resize demonstrations
demo/.storybook/preview.ts, demo/src/stories/ResizableChildren.stories.tsx
Storybook loads the demo styles and provides configurable stories for resizing children and containers, including pinned heights, multiple rows, and 100-item lists.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ResizeObserver
  participant useChildrenResizeObserver
  participant useOverflowList
  participant OverflowList
  ResizeObserver->>useChildrenResizeObserver: report child border-box change
  useChildrenResizeObserver->>useChildrenResizeObserver: wait for two quiet animation frames
  useChildrenResizeObserver->>useOverflowList: invoke settled callback
  useOverflowList->>OverflowList: apply synchronous or scheduled remeasurement
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 69.23% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the two primary changes: adding observeItemSizes and fixing unnecessary re-measurement churn.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/resize-observer-churn-and-item-observation

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
demo/src/stories/ResizableChildren.stories.tsx (1)

76-105: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Reduce the per-frame layout reads in the readout loop.

tick runs on every animation frame for the life of the story. For each child it calls getComputedStyle once and getBoundingClientRect up to three times. At the 100-item story that is about 100 style resolutions and 300 rect reads per frame, each one forcing synchronous layout.

The HundredItemsPinnedHeight story states that it exists to show dropped frames while dragging. The readout loop adds its own per-frame layout cost, so it competes with the behavior the story measures.

Two changes keep the readout accurate and cut most of the cost:

  • Read each child rect once per tick and reuse it.
  • Replace the getComputedStyle position check with a rect-based check, since a positioned child is already excluded by the getClientRects() test in the layouts used here.
♻️ Proposed refactor to read each rect once per tick
-        const children = Array.from(list.children) as HTMLElement[];
-        const laidOut = children.filter(
-          (child) => child.getClientRects().length > 0 && getComputedStyle(child).position === "static",
-        );
-        const rows = new Set(laidOut.map((child) => Math.round(child.getBoundingClientRect().top)));
-        const listBox = list.getBoundingClientRect();
-        const widths = laidOut.map((child) => Math.round(child.getBoundingClientRect().width));
-        const used = widths.reduce((total, width) => total + width, 0);
-        const lastRight = laidOut.length
-          ? Math.round(laidOut[laidOut.length - 1].getBoundingClientRect().right - listBox.left)
-          : 0;
+        const children = Array.from(list.children) as HTMLElement[];
+        const laidOut = children
+          .filter((child) => child.getClientRects().length > 0 && getComputedStyle(child).position === "static")
+          .map((child) => ({ child, rect: child.getBoundingClientRect() }));
+        const rows = new Set(laidOut.map(({ rect }) => Math.round(rect.top)));
+        const listBox = list.getBoundingClientRect();
+        const widths = laidOut.map(({ rect }) => Math.round(rect.width));
+        const used = widths.reduce((total, width) => total + width, 0);
+        const lastRight = laidOut.length ? Math.round(laidOut[laidOut.length - 1].rect.right - listBox.left) : 0;

The readout.textContent lines then read from laidOut[i].child and laidOut[i].rect.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@demo/src/stories/ResizableChildren.stories.tsx` around lines 76 - 105, Update
the per-frame `tick` readout loop to measure each child’s bounding rect once and
reuse it for visibility, row, width, and right-edge calculations. Remove the
per-child `getComputedStyle` position check and retain only the rect-based
visibility check, storing each qualifying child with its rect so the
`readout.textContent` formatting uses those cached values without additional
layout reads.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@demo/src/stories/ResizableChildren.stories.tsx`:
- Around line 176-183: Wire the ResizableChildren story documentation into
Storybook: in demo/src/stories/ResizableChildren.stories.tsx lines 176-183, add
the autodocs tag to meta unless demo/.storybook/main.ts enables autodocs
globally; in lines 5-30, move the intro documentation block from above LABELS to
directly above meta so it becomes the component description.

---

Nitpick comments:
In `@demo/src/stories/ResizableChildren.stories.tsx`:
- Around line 76-105: Update the per-frame `tick` readout loop to measure each
child’s bounding rect once and reuse it for visibility, row, width, and
right-edge calculations. Remove the per-child `getComputedStyle` position check
and retain only the rect-based visibility check, storing each qualifying child
with its rect so the `readout.textContent` formatting uses those cached values
without additional layout reads.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f8b197ae-5089-4415-ab75-ac1cfc6ea757

📥 Commits

Reviewing files that changed from the base of the PR and between 1e5859c and 1cf46d9.

📒 Files selected for processing (11)
  • README.md
  • demo/.storybook/preview.ts
  • demo/src/stories/ResizableChildren.stories.tsx
  • package.json
  • src/components/OverflowList.tsx
  • src/hooks/useChildrenResizeObserver.ts
  • src/hooks/useOverflowList.ts
  • src/hooks/useResizeObserver.ts
  • tests/dom/children-resize-observer.test.tsx
  • tests/dom/layout-harness.ts
  • tests/dom/overflow-list.test.tsx

The Storybook story covered this but the demo app did not, so the prop was
undocumented everywhere a user actually lands: the examples page and the API
reference table.

The example gives every item a native resize handle and gives the box around
them one too, so both invalidation paths are reachable by hand. Dragging the box
re-measures with nothing opted in, because that is the container's own size.
Dragging an item only changes a child, which is the case the prop exists for. The
readout is written straight into the DOM from an animation frame rather than held
in state, since a render is itself enough to re-measure and would hide the very
thing the example demonstrates.

Reset restores the starting width rather than clearing the inline one. Dragging
writes widths React does not own, so it will not undo them; clearing them
outright would also drop React's own value and let the box grow to fill the page.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@Eliav2
Eliav2 merged commit 1cf6a29 into main Aug 8, 2026
6 checks passed
@Eliav2
Eliav2 deleted the fix/resize-observer-churn-and-item-observation branch August 8, 2026 22:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant