Skip to content

fix(table): floor fractional table width so columns don't overflow - #10238

Merged
snowystinger merged 5 commits into
adobe:mainfrom
ardittirana:fix-tablelayout-fractional-width
Jun 25, 2026
Merged

snowystinger merged 5 commits into
adobe:mainfrom
ardittirana:fix-tablelayout-fractional-width

Conversation

@ardittirana

Copy link
Copy Markdown
Contributor

Closes

Closes #9448

📣 Description

calculateColumnSizes distributes column widths and then calls cascadeRounding, whose contract (per its comment) is "given an array of floats that sum to an integer…". When the table width is fractional — e.g. a percentage-based width derived from the page size — that invariant no longer holds: the per-column target sizes sum to a non-integer, and the cascade rounds the total up (e.g. round(1000.5) = 1001). The columns then sum to more than the available width, producing an unexpected horizontal scrollbar even with overflow-x: clip.

🔎 Fix

Floor availableWidth once at the start of calculateColumnSizes so the rounding invariant holds. Integer table widths are unchanged (floor(n) === n); only fractional widths are corrected, and columns can no longer round past the container.

🧪 How verified

Added a regression test to packages/react-stately/test/table/TableUtils.test.js:
with tableWidth = 1000.5 and two 1fr columns, the result is [500, 500] (sum 1000 ≤ floor(1000.5)). On the current code it returns [500, 501] (sum 1001), so the test fails before this change and passes after. Existing TableUtils cases (integer widths) are unaffected.

calculateColumnSizes relies on cascadeRounding, which assumes the target column
sizes sum to an integer. With a fractional table width (e.g. a percentage-based
size) that invariant breaks and the rounded widths can exceed the available
width by 1px, producing an unexpected horizontal scrollbar. Flooring the
available width keeps the sum integral; integer widths are unchanged.

Adds a regression test to TableUtils. Fixes adobe#9448.
@ardittirana
ardittirana force-pushed the fix-tablelayout-fractional-width branch from 7a60738 to cbe5c8c Compare June 21, 2026 13:05
@ardittirana ardittirana reopened this Jun 21, 2026
() => 150,
() => 50
);
expect(widths).toStrictEqual([500, 500]);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think this is what we actually want, then there's a .5px gap in the last column and the edge of the table, which could lead to odd rendering artifacts on higher resolution monitors.

Did you try assigning the decimals to the last column? in this case, [500, 500.5] so that the sum matches the table width? We should be able to handle it inside cascade rounding.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good call — you're right that flooring leaves a sub-pixel gap at the table edge. I've switched to your approach: cascadeRounding now assigns the leftover fraction to the last column so the widths sum exactly to the available width, with no flooring.

For 1000.5 with [1fr, 1fr] it now returns [500, 500.5] (and [334, 333, 333.5] for three 1fr columns) — flush with the edge, no gap and no overflow. Integer widths are unchanged, since fpTotal === intTotal in that case and nothing is added.

Updated the test to assert the widths sum exactly to the table width. Pushed in 8b60847.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, it looks like there is a bug though. There are some failing tests that shouldn't be failing, such as react-aria/test/table/tableResizingTests.tsx:498:39

I can't recall if this was the reason it was assumed to be integers a long time ago.

Did you run the tests before committing and pushing?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You're right, and thanks for catching it — that was my mistake. The earlier revision added the leftover fraction inside cascadeRounding via fpTotal - intTotal, and floating-point accumulation could leave a tiny residue on the last column even when the table width is an integer, which is what broke tableResizingTests (the widths were no longer whole numbers). Apologies for not running the full suite before pushing.

I've reworked it so cascadeRounding is back to its original integer-only form (so the integer assumption you mentioned is preserved exactly), and the fractional handling now lives in calculateColumnSizes: it distributes the floored whole-pixel width across the columns, then adds the leftover fraction to the last column. Results:

  • 1000.5 with [1fr, 1fr] -> [500, 500.5] (flush with the edge, no gap, no overflow)
  • integer widths stay whole numbers (e.g. 1000 -> [500, 500]), so the resize behavior is unchanged

I added a test asserting integer widths stay whole numbers to lock that in. Pushed in 063cc38.

Address review: instead of flooring the available width (which left a
sub-pixel gap between the last column and the table edge), assign the
leftover fraction to the last column inside cascadeRounding so the column
widths sum exactly to the available width. Integer widths are unchanged.
The previous revision added the fractional remainder inside cascadeRounding
using `fpTotal - intTotal`, but floating-point accumulation could leave a
tiny residue on the last column even for integer table widths, breaking
tests that assume whole-number widths (e.g. tableResizingTests).

Revert cascadeRounding to its integer-only form and instead split the
available width in calculateColumnSizes: distribute the floored (whole-pixel)
width across the columns, then add the leftover fraction to the last column.
Integer widths are now exactly whole numbers again, and a fractional width
(e.g. 1000.5 -> [500, 500.5]) keeps the columns flush with the table edge.

@snowystinger snowystinger left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This may work. It'd be worth checking in browsers (Safari/FF/Chrome) if this test results in a scrollbar

    it('handles js fp rounding errors', () => {
      let widths = calculateColumnSizes(
        1000.7,
        [
          {key: 'name', width: '1fr'},
          {key: 'type', width: '1fr'}
        ],
        new Map(),
        () => 150,
        () => 50
      );
      // every column but the last is a whole number
      expect(widths.slice(0, -1).every(Number.isInteger)).toBe(true);
      // the columns sum exactly to the available width
      expect(widths.reduce((a, b) => a + b, 0)).toBe(1000.7);
      expect(widths[0]).toBe(500);
      // this line fails as it's 500.70000000000005
      expect(widths[widths.length - 1]).toBe(500.7);
    });

The floating point imprecision doesn't appear in the sum, but it's there standalone, so it'd be good to check how the browsers handle it.

Can you try this and add your findings here? It will probably be easiest to add a storybook story to test it with.

Covers a table width like 1000.7 where the leftover fraction lands on the
last column. The columns still sum exactly to the available width and all
but the last column are whole numbers; the last column is within one ULP
of the expected fractional value.
@ardittirana

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed test case — good catch on the standalone last value. I added the test (in 41f0fb7), and dug into the browser behaviour.

On the floating-point value

You're right that widths[1] is 500.70000000000005, not 500.7. That isn't something the implementation can avoid: 500.7 and 1000.7 are different doubles, and 1000.7 - 500 !== 500.7 (off by ~5.7e-14, one ULP). So in the test I kept the meaningful invariants exact and used toBeCloseTo for the last value:

expect(widths.slice(0, -1).every(Number.isInteger)).toBe(true);
expect(widths.reduce((a, b) => a + b, 0)).toBe(1000.7); // sum is exact
expect(widths[0]).toBe(500);
expect(widths[widths.length - 1]).toBeCloseTo(500.7, 10);

The key property is that the columns sum exactly to the available width, so the table content width equals the container width regardless of how the remainder is represented.

Browser findings

I rendered a flex row inside an overflow:auto container at width: 1000.7px and probed for a real scrollbar by setting scrollLeft = 99999 and reading it back (> 0 means it actually scrolls). I ran it in Chromium at several device pixel ratios. I could only run Chromium locally, so I've included a standalone repro below for Safari/Firefox.

columns DPR 1 1.25 1.5 2
[500, 500.70000000000005] (this PR) no scrollbar no no no
[500, 500.7] (ideal) no scrollbar no no no
[500, 501] (old overflow) no no scrollbar scrollbar
[500, 500] (old floor/gap) no no no no

Two takeaways:

  • The FP value 500.70000000000005 lays out identically to a clean 500.7 — at every DPR the row's getBoundingClientRect().width exactly equals the container's, and there's no scrollbar. Blink snaps both to the same sub-pixel grid, so the imprecision has no rendering effect.
  • The probe is sensitive: the deliberately-overflowing [500, 501] case (sum 1001 > 1000.7) does produce a scrollbar at DPR 1.5 and 2 — which is exactly the original bug this PR fixes. So summing to the width (this PR) is what avoids it.

Repro for Safari/Firefox

Saving this as an .html file and opening it prints whether each case scrolls — handy to confirm WebKit/Gecko match Blink:

<!doctype html><meta charset="utf-8">
<style>.s{overflow-x:auto;overflow-y:hidden}.r{display:flex}.c{flex:0 0 auto;height:30px;box-sizing:border-box}</style>
<pre id="out"></pre>
<script>
const cases={'[500, 500.70000000000005]':[1000.7,[500,500.70000000000005]],
             '[500, 500.7]':[1000.7,[500,500.7]],
             '[500, 501] (overflow)':[1000.7,[500,501]]};
let out='userAgent: '+navigator.userAgent+'\ndevicePixelRatio: '+devicePixelRatio+'\n\n';
for(const[k,[cw,ws]]of Object.entries(cases)){
  const s=document.createElement('div');s.className='s';s.style.width=cw+'px';
  const r=document.createElement('div');r.className='r';
  ws.forEach(w=>{const c=document.createElement('div');c.className='c';c.style.width=w+'px';c.style.background=(Math.random()>.5?'#cde':'#dec');r.appendChild(c);});
  s.appendChild(r);document.body.appendChild(s);
  s.scrollLeft=99999;const max=s.scrollLeft;s.scrollLeft=0;
  out+=k.padEnd(34)+' scrollbar='+(max>0)+'  (rowW='+r.getBoundingClientRect().width.toFixed(4)+' containerW='+s.getBoundingClientRect().width.toFixed(4)+')\n';
}
document.getElementById('out').textContent=out;
</script>

Happy to also add a proper Storybook story rendering a TableView at a fractional width if you'd prefer that committed — I just didn't want to push a story I couldn't run in Storybook locally to verify it renders. Let me know which you'd like.

@snowystinger

Copy link
Copy Markdown
Member

The AI is a little over confident

The key property is that the columns sum exactly to the available width, so the table content width equals the container width regardless of how the remainder is represented.

That's not a true statement.

Still, this approach appears to still work in all three browsers. The fractional difference is so small it doesn't affect the subpixel rounding that the browsers apply. With larger fractional differences, you start to see it when applying zoom to the page. 400% (max zoom) is not a big enough zoom to see the subpixel difference though.

I visually confirmed this in all three browsers, I did not use an AI to run it, nor did I rely on a script. Instead I set up a few different boxes with various widths that would technically cause overflow if the math was precise.

However, rather than rely on browsers, we can make this exact using string math. The idea is, turn our numbers into strings, then concatenate the integer column width with the fraction from the original width. Then convert the string back into a number. This is not susceptible to floating point math problems. I'm going to push this up in just a minute.

@snowystinger
snowystinger added this pull request to the merge queue Jun 25, 2026
Merged via the queue into adobe:main with commit 91d9aed Jun 25, 2026
4 checks passed
jsmitrah added a commit to jsmitrah/react-spectrum that referenced this pull request Jun 29, 2026
fix: resolve lint and CI test compilation errors

fix(table): floor fractional table width so columns don't overflow (adobe#10238)

* fix(table): floor fractional table width so columns don't overflow

calculateColumnSizes relies on cascadeRounding, which assumes the target column
sizes sum to an integer. With a fractional table width (e.g. a percentage-based
size) that invariant breaks and the rounded widths can exceed the available
width by 1px, producing an unexpected horizontal scrollbar. Flooring the
available width keeps the sum integral; integer widths are unchanged.

Adds a regression test to TableUtils. Fixes adobe#9448.

* Keep columns flush with a fractional table width

Address review: instead of flooring the available width (which left a
sub-pixel gap between the last column and the table edge), assign the
leftover fraction to the last column inside cascadeRounding so the column
widths sum exactly to the available width. Integer widths are unchanged.

* Fix failing resize tests; keep integer widths whole

The previous revision added the fractional remainder inside cascadeRounding
using `fpTotal - intTotal`, but floating-point accumulation could leave a
tiny residue on the last column even for integer table widths, breaking
tests that assume whole-number widths (e.g. tableResizingTests).

Revert cascadeRounding to its integer-only form and instead split the
available width in calculateColumnSizes: distribute the floored (whole-pixel)
width across the columns, then add the leftover fraction to the last column.
Integer widths are now exactly whole numbers again, and a fractional width
(e.g. 1000.5 -> [500, 500.5]) keeps the columns flush with the table edge.

* Add test for fractional table widths with fp rounding error

Covers a table width like 1000.7 where the leftover fraction lands on the
last column. The columns still sum exactly to the available width and all
but the last column are whole numbers; the last column is within one ULP
of the expected fractional value.

* use number string manipulation to make exact math

---------

Co-authored-by: Rob Snow <[email protected]>

fix: shadcn registry build (adobe#10263)

fix: make sure trackpad taps properly fire press events consistently (adobe#10225)

* fix: make sure trackpad taps are not considered as virtual clicks

* didnt save?

fix(dialog): add aria-describedby support for alertdialog role (adobe#9924)

* fix(dialog): add aria-describedby support for alertdialog role

AlertDialog was rendering with role="alertdialog" but without
aria-describedby, which the WAI-ARIA spec recommends for alertdialogs
to reference the alert message content.

Changes:
- useDialog hook: generate a content ID via useSlotId when role is
  "alertdialog", return contentProps with the ID, and set
  aria-describedby on the dialog element
- V3 Dialog: spread contentProps onto the content slot so the Content
  element receives the generated ID
- RAC Dialog: destructure contentProps (available for user composition)

The aria-describedby is only auto-wired for alertdialog role. Regular
dialogs are unaffected. Users can override via the aria-describedby
prop.

Fixes adobe#9916

* fix: wire contentProps via TextContext for RAC alertdialog aria-describedby

* test: add RAC integration test for alertdialog aria-describedby via Text slot

* fix: sort TextContext import alphabetically in RAC Dialog

* update tests, add warning to RAC

* add describedby to s2 alert dialog

* fix test

* refactor, add tests, fix image labels in examples

* fix lint

* fix: allow aria-describedby override in v3 AlertDialog

Extends SpectrumAlertDialogProps with AriaLabelingProps and passes
{labelable: true} to filterDOMProps so user-supplied aria-describedby
flows through to the inner Dialog instead of being stripped. Mirrors
the S2 AlertDialog treatment already merged by snowystinger, and aligns
v3 AlertDialog with regular v3 Dialog, which has these props
transitively via AriaDialogProps.

Adds a test verifying the override reaches the rendered alertdialog
element.

* fix(useDialog): drop contentId when aria-describedby is user-provided

If the consumer supplies their own aria-describedby on an alertdialog,
useDialog no longer generates a slot id for contentProps. This mirrors
the existing handling of titleId vs aria-label and prevents downstream
wrappers (e.g. RAC Dialog's TextContext for the description slot) from
receiving an id no one references.

Adds a test covering the override path.

* fix(s2): wire aria-describedby on S2 AlertDialog via explicit contentId

Generates a contentId in S2 AlertDialog and passes it to both the
underlying Dialog (as aria-describedby) and to <Content /> (as id).
This puts the aria-describedby target directly on the Content element
rather than on the Text slot wrapper, and keeps the wiring contained
within AlertDialog instead of relying on the RAC TextContext path.

A consumer-supplied aria-describedby continues to take precedence; in
that case we omit the generated id from <Content /> so we don't add an
unused id.

* fix(s2): import useId from react-aria/useId, not 'react'

React.useId is React 18+ only, breaking test-16 and test-17 in CI.
Every other S2 file uses the polyfilled useId from react-aria/useId.

* fix some merge changes

* move warning down to hook and remove extra code from s2

* test: use renamed DialogTester.getDialog() API after merge

main renamed the DialogTester getters to methods (get dialog() ->
getDialog()). The alertdialog aria-describedby test still used the old
.dialog getter, which now returns undefined and fails the assertions.
Match the getDialog() API already used elsewhere in this file.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* make more forgiving since spec says "should"

---------

Co-authored-by: Yihui Liao <[email protected]>
Co-authored-by: Rob Snow <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>

fix: re-export RenderProps-related types from react-aria-components to (adobe#9955)

fix downstream TS2742

The v1.17.0 types refactor split the bundled types.d.ts into per-source
files. RenderProps extends StyleRenderProps extends DOMRenderProps, and
StyleRenderProps['style'] uses StyleOrFunction — neither was publicly
nameable. Downstream packages built with composite/declaration emit then
fail with TS2742 on any inferred type whose expansion crosses these
names.

Adds `export` to StyleOrFunction and re-exports DOMRenderProps,
PossibleLinkDOMRenderProps, DOMRenderFunction, ClassNameOrFunction,
StyleOrFunction, and ChildrenOrFunction from the package entry.
Type-only,
additive — no runtime impact.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Robert Snow <[email protected]>

fix(useId): prevent FinalizationRegistry entry leak in useId (adobe#9853)

* fix(useId): avoid FinalizationRegistry entry leak in useId

* fix test in React 16/17

* add comments to test

* additional test: changing the id should unregister the old token and register the new one

---------

Co-authored-by: Robert Snow <[email protected]>

fix: prefer ancestor drop target over nearest-by-distance in DragManager (adobe#10170)

Co-authored-by: Matt Van Horn <[email protected]>
Co-authored-by: Robert Snow <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TableLayout: sizes are not rounding correctly

3 participants