Skip to content

[theme] Add unstable_enhanceDensity - #48749

Merged
siriwatknp merged 292 commits into
mui:masterfrom
siriwatknp:exp/density-button-prototype
Nov 23, 2026
Merged

siriwatknp merged 292 commits into
mui:masterfrom
siriwatknp:exp/density-button-prototype

Conversation

@siriwatknp

@siriwatknp siriwatknp commented Jul 1, 2026 •

Copy link
Copy Markdown
Member

closes #48746

Summary

This PR adds unstable_enhanceDensity, an opt-in theme enhancer that sizes Material UI components from one shared scale. Same-size controls render on the same box, and changing the scale resizes the whole set.

import { createTheme, unstable_enhanceDensity as enhanceDensity } from '@mui/material/styles';

const theme = enhanceDensity(createTheme());

// any value can be overridden, in px
const roomy = enhanceDensity(createTheme(), { touchTarget: 40, iconSize: 20 });

The scale has two parts:

  • Seven spacing steps, xxSmall to xxLarge (4, 8, 12, 16, 24, 32 and 48px by default). Components use them for padding, margin and gap.
  • Two sizes: touchTarget (32px by default) is the height of a medium control, and iconSize (16px by default) is the size of a medium icon. Small controls are touchTarget - xxSmall and large controls are touchTarget + small.

What the enhanced theme gives you:

  • theme.spacing() resolves the step names next to numbers and raw CSS: theme.spacing('small') is '12px', and theme.spacing('-xSmall') is '-8px'. The sx spacing props accept them too: <Box sx={{ p: 'small', gap: 'xSmall' }} />.
  • theme.touchTarget and theme.iconSize hold the resolved lengths. theme.unstable_densityScale holds every value as a px number, for code that computes sizes in JavaScript.
  • With cssVariables: true, the theme writes --mui-spacing-<step>, --mui-touchTarget and --mui-iconSize, and components read those variables. Setting --mui-touchTarget on an element resizes the controls inside it.
  • Your own styleOverrides keep winning. Pass them to createTheme before you enhance the theme, and the enhancer appends the density styles in front of them.

Themes that don't call enhanceDensity render exactly as before.

The types are opt-in, so projects that don't use the enhancer keep their own Theme augmentations and spacing types. To type theme.touchTarget, theme.iconSize and the step names in theme.spacing(), import the augmentation once:

import type {} from '@mui/material/themeDensityAugmentation';

For reviewers

Where the code is

  • enhanceDensity is the entry point. It calls applyDensity to set up the scale, then writes the density styles for 66 components.
  • applyDensity wraps theme.spacing so it resolves step names, sets theme.touchTarget, theme.iconSize and theme.unstable_densityScale, and adds the CSS variables to generateStyleSheets. It also wraps generateSpacing and generateThemeVars, because CssVarsProvider rebuilds both on mount.
  • addStyleOverride stores each slot as [density, user], so the user's override renders after the density style.

Design decisions

  • The steps are absolute px. small is 12px whatever spacing is set to. Numbers passed to theme.spacing() still use the theme's spacing unit, so existing layouts don't move.
  • The steps are spacing only. Heights come from touchTarget and iconSize, so changing touchTarget moves every control box at once while padding and gaps stay on the steps.
  • User overrides win where they win on master. When a density value has to reach a child slot, the enhancer writes a private CSS variable on the parent and a plain declaration on the slot that reads it, instead of a nested selector that would outrank the user's slot override. The contract tests render each case with and without the enhancer and compare.
  • Breakpoints and pointer type. Where master changes a size at a breakpoint or on a coarse pointer, the density value is restated inside the same media query, so the enhanced size holds on every screen.

Accepted tradeoffs

  • One call per theme. Calling enhanceDensity on a theme that is already enhanced returns it unchanged and logs an error in development.
  • Nested CSS variables themes. A nested ThemeProvider with the same cssVarPrefix skips its style sheet, as it does on master, so the inner theme's scale doesn't apply. Override the variables on a wrapper element, or use a different cssVarPrefix. The docs say so.
  • FormControlLabel spacing moves to gap. FormGroup spaces its labels with gap, and the label drops its own margin. Labels outside a FormGroup get no spacing. The docs say so.
  • One text size for every Button size. Button and ToggleButton use typography.button for all sizes. On master, small is 13px and large is 15px. The docs say so.
  • scroll="body" Dialog keeps master's width cap. The breakpoint is a media query, which can't read --_dialogMargin, so the cap stays at calc(100% - 64px). Narrow screens show 32px gutters instead of 24px, and the paper never grows past its maxWidth.
  • Tooltip gap fits the default arrow. The enhancer sizes the gap for the 10px arrow, and a larger custom arrow keeps that gap. A gap that followed the arrow size would need a variable on the tooltip, which would stop a user's arrow font-size from resizing the arrow.
  • Same inline padding for every Button variant. An outlined Button is 2px wider than a contained one with the same label, because the padding doesn't subtract the border.

Changes outside the enhancer

These keep master's output identical and only expose a value the enhancer needs to change:

  • Tooltip reads its gap from --_spacing, with master's values as the defaults. The touch variant now sets --_spacing: 24px instead of repeating the four placement rules.
  • Dialog reads its margin from --_dialogMargin (32px by default), and the calc(100% - 64px) sizes use twice that variable.
  • spacing in @mui/system: a spacing function can list the names it resolves in a keys property. sx resolves those names and passes every other string through as raw CSS, as before. createSpacing adds a SpacingKeyOverrides interface so the names show up in autocompletion. Grid resolves the names for rowSpacing and columnSpacing the same way.
  • @mui/material/themeDensityAugmentation is the opt-in type entry. The module augmentation fixtures cover a project with and without it.

Tests

  • densityContract.test.tsx runs in Chromium. It measures rendered boxes at two scales (dense and default), and checks that user overrides, sx, modularCssLayers and coarse pointers behave as on master. The expected values are computed from the scale, not copied from the enhancer.
  • densityScale.test.ts and enhanceDensity.test.ts cover the spacing wrapper, the CSS variables, scale overrides with every spacing option form, and step names in the sx spacing props.
  • densityAnnotationParity.test.tsx checks that the docs annotations match the values the components render.
  • The @mui/system tests cover named steps in sx, Grid and CSS Grid, and raw strings passing through unchanged.

@siriwatknp siriwatknp added the RFC Request For Comments. label Jul 1, 2026
@siriwatknp
siriwatknp force-pushed the exp/density-button-prototype branch from 59837ad to 5389da7 Compare July 1, 2026 03:54
@siriwatknp siriwatknp changed the title [prototype] CSS-var density adapter (enhanceDensity) + experiment page [prototype] CSS-var density adapter (enhanceDensity) — Button + experiment page Jul 1, 2026
@code-infra-dashboard

code-infra-dashboard Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Deploy preview

Bundle size

Bundle Parsed size Gzip size
@mui/material 🔺+31.7KB(+5.88%) 🔺+6.94KB(+4.43%)
@mui/lab 0B(0.00%) 0B(0.00%)
@mui/private-theming 0B(0.00%) 0B(0.00%)
@mui/system 🔺+339B(+0.49%) 🔺+115B(+0.47%)
@mui/utils 0B(0.00%) 0B(0.00%)

Details of bundle changes

Performance

No regressions in 32 benchmarks · ran 2m 24s · details


Check out the code infra dashboard for more information about this PR.

@siriwatknp siriwatknp changed the title [prototype] CSS-var density adapter (enhanceDensity) — Button + experiment page [WIP][prototype] CSS-var density adapter (enhanceDensity) — Button + experiment page Jul 1, 2026
@siriwatknp siriwatknp changed the title [WIP][prototype] CSS-var density adapter (enhanceDensity) — Button + experiment page [WIP][prototype] CSS-var density adapter (enhanceDensity) Jul 1, 2026
@siriwatknp siriwatknp changed the title [WIP][prototype] CSS-var density adapter (enhanceDensity) [WIP][prototype] density system Jul 1, 2026
@siriwatknp
siriwatknp force-pushed the exp/density-button-prototype branch from 4549eae to 6ce32e1 Compare August 12, 2026 07:37
@siriwatknp
siriwatknp force-pushed the exp/density-button-prototype branch from 97b009b to c9bc7e8 Compare August 27, 2026 03:09
@siriwatknp
siriwatknp force-pushed the exp/density-button-prototype branch from c9bc7e8 to c371ca2 Compare August 27, 2026 04:06
Replaces mockup text that tracked real products too closely with
original content. Structure, styles and component choices unchanged.
Stack gaps move from sx to the spacing prop; settings rows drop the
explicit gap/minHeight.
Text labels replace the density glyphs, ordered least to most dense.
A Checkbox renders an input inside an element that already carries
role=menuitemcheckbox and aria-checked, duplicating the state and
nesting an interactive control. The indicator is now a plain glyph.
Removes the menu option, its state and theme wiring, and the SvgIcon
glyph set it existed to apply. The data file now has a single export,
so it default-exports to match its filename.
No JSX left in it since the custom icons layer went.
The Button spinner size, the Tooltip arrow size, the outlined border width, the shrunk-label lift bounds and threshold, and the collapsed breadcrumb selector are now named constants. The emitted styles are unchanged.
stepValue becomes toAbsolutePx, which says the steps are px and never the spacing unit. In @mui/system, keyedTransformers becomes transformersByTheme, and the condition for routing step names around the base transformer moves into an isSeparateKeyedScale type guard, which also drops a non-null assertion.
The annotation overlay z-index and the Dialog and Autocomplete stage heights in the enhance-density demos are now named constants. Values are unchanged.
The wrapped field in the density contract test sat in a plain block div, so the input root lined up on a text line whose baseline depends on font metrics. With CI fonts, Firefox placed it 1px off the direct layout. The wrapper now uses display: contents, so it still keeps the input out of direct FormControl children without changing the layout.
addStyleOverride(enhanced.components, 'MuiOutlinedInput', 'input', {
paddingBlock: 'var(--_outlinedInputPadBlock)',
paddingLeft: spacing('small'),
[notSelectInput]: { paddingRight: spacing('small') },

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think this nested rule wins over the endAdornment and multiline resets below. Emotion puts nested selectors after the class's own declarations, so the :where(:not(.MuiSelect-select, …)) rule comes last at the same specificity. It came in with d395818.

From what I tested, an input with an end adornment and a multiline textarea now get padding-right: 12px (medium density) instead of 0.
The root already gives the space before the adornment, so a long value is cut 20px before the icon instead of 8px, and multiline text wraps 12px earlier.
MuiFilledInput has the same rule on line 480.

To reproduce:

const theme = enhanceDensity(createTheme());

<ThemeProvider theme={theme}>
  <TextField
    defaultValue="A long value that runs into the end adornment of this field"
    slotProps={{
      input: {
        endAdornment: (
          <InputAdornment position="end">
            <ErrorOutlined />
          </InputAdornment>
        ),
      },
    }}
  />
  <TextField multiline defaultValue="A long value that wraps" />
</ThemeProvider>

Inspect the <input> and the <textarea>: padding-right is 12px, expected 0. variant="filled" is the same.

Could be something like this, in both MuiOutlinedInput and MuiFilledInput:

{
  props: { multiline: true },
  style: { paddingBlock: 0, paddingLeft: 0, [notSelectInput]: { paddingRight: 0 } },
},
// …
{
  props: ({ ownerState }) => !!ownerState.endAdornment,
  style: { [notSelectInput]: { paddingRight: 0 } },
},

Tested locally: the adorned input and the textarea go back to 0, plain inputs keep 12px, and Select keeps its own 28px.

…ight padding

d395818 moved the input paddingRight into a nested :where(:not(select)) rule. Emotion emits nested rules after the block's own declarations, so it beat the plain paddingRight: 0 resets for end adornments and multiline at the same specificity. Inputs with an end adornment and multiline textareas got 12px of right padding instead of 0.

The two resets now sit under the same guard, so the variant rules come after the base rule again. A contract test covers outlined and filled inputs at each density.
d395818 excluded every native select from the 1lh input height so that a multiple native select keeps its height: auto. NativeSelect only sets height: auto when multiple, so single native selects lost the density height and rendered 1px off the TextField box at every density. The height guard now excludes .MuiNativeSelect-multiple instead of every native select; the padding guard still excludes them all for the caret. A contract test checks that a native select has the TextField box.
The touch-target line-height on Breadcrumbs items now skips links that
are a ButtonBase, so a Button or IconButton item keeps its own size
instead of being stretched to the touch target.
The outlined label lifted only when touchTarget was below a fixed 32.5px,
so a larger touch target dropped it back onto Autocomplete chips. It now
lifts when the value or the chips start closer than the label's letters
reach below the border, which follows the font size and scaling.

The Autocomplete sets the chip offset as a private variable that the
label reads, so a label sx or theme override keeps winning.
The outlined and filled Autocomplete indicators sat a fixed 9px from the
field edge. They now sit half of xSmall from it (2px, 4px and 6px for
the high, medium and low presets), and the input keeps its right
padding in step so the text still clears them.
Master removed the legacy demo renderer, so the page's demo entries
broke the docs build. Each demo now lives in its own demos/ folder with
client and index files, and the page references it with a component
entry. The JavaScript twins are removed, as master no longer generates
them.
- Return an already enhanced theme unchanged from enhanceDensity and log an error in development.
- Build the medium contract density from literal values with a compact type ramp, so the expected values no longer come from the enhancer's own defaults. Tests that compare against master use enhanceDensity(createTheme()).
- Document the nested CSS variables limitation, the one-call rule, the FormGroup gap and the Button text size.
- Replace 11 copies of max(wcagTargetSize, smallBox) with one constant, renamed smallTargetBox because Checkbox, Radio, Switch and ListItemButton use it too. The emitted styles are unchanged.
- Say in the density recipes docs that low and high also change the type ramp.
@siriwatknp siriwatknp added needs cherry-pick The PR should be cherry-picked to master after merge. v9.x labels Nov 22, 2026
Body-scrolling dialogs: Dialog still shrinks the paper by a literal 64px,
so a density `large` step above 32px pushed the paper past the viewport
on narrow screens. The enhancer now adds its own shrink rule for each
`maxWidth`: below `cap + max(2 * large, 64px)` the paper is capped at
`min(cap, 100% - 2 * --_dialogMargin)`. The rule stays inside a media
query, so it wins against user overrides the same way master's rule
does. Dialog.js is unchanged, so themes without the enhancer render as
before.

Dense ListItem: it kept the regular `xSmall` block padding. It now uses
the same padding and min height as a dense ListItemButton, so both rows
are the same height at every scale.
`edge` pulled IconButton, Checkbox and Radio by `touchTarget / 4`, and
small Checkbox and Radio by `smallTargetBox / 8`. That puts the icon on
the content edge only when the icon is half the box. With custom scales
the icon landed 1-3px past or inside the edge, small IconButton was 2px
past at the default scale, and small Checkbox and Radio were 4.5-7.5px
inside at every scale.

Each size now pulls by `(icon - box) / 2`, the gap between the icon and
the box it sits in. IconButton uses `iconSize` at every size, since a
default child icon does not follow the button size. Checkbox and Radio
use `iconSize` in `touchTarget` and `iconSmall` in `smallTargetBox`,
the same pairs their label margins already use. Large IconButton gets
its own rule.
Revert the density shrink rule for body-scrolling dialogs added in
d9f9535. It took about 25 lines and only matters when the `large`
step is above 32px, which neither the default scale nor any docs recipe
uses. The docs now say that a `large` step above 32px makes a Dialog
with `scroll="body"` wider than the screen on narrow viewports.

The dense ListItem fix from the same commit stays.
@siriwatknp
siriwatknp enabled auto-merge (squash) November 23, 2026 02:01
@siriwatknp
siriwatknp merged commit 9879540 into mui:master Nov 23, 2026
23 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

Cherry-pick PRs will be created targeting branches: v9.x

siriwatknp added a commit to siriwatknp/material-ui-x that referenced this pull request Nov 24, 2026
Material UI 9.6.0 ships unstable_enhanceDensity, so the branch drops the
pkg.pr.new pin of mui/material-ui#48749 and uses the release.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

customization: theme Higher level theming customizability. needs cherry-pick The PR should be cherry-picked to master after merge. package: material-ui Specific to Material UI. type: new feature Expand the scope of the product to solve a new problem. v9.x

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] enhanceDensity — normalize components into a consistent scale

6 participants