Repository navigation
[theme] Add unstable_enhanceDensity - #48749
Conversation
59837ad to
5389da7
Compare
Deploy previewBundle size
PerformanceNo regressions in 32 benchmarks · ran 2m 24s · details Check out the code infra dashboard for more information about this PR. |
4549eae to
6ce32e1
Compare
97b009b to
c9bc7e8
Compare
c9bc7e8 to
c371ca2
Compare
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') }, |
There was a problem hiding this comment.
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.
…to exp/density-button-prototype
- 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.
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.
|
Cherry-pick PRs will be created targeting branches: v9.x |
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.
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.The scale has two parts:
xxSmalltoxxLarge(4, 8, 12, 16, 24, 32 and 48px by default). Components use them for padding, margin and gap.touchTarget(32px by default) is the height of a medium control, andiconSize(16px by default) is the size of a medium icon. Small controls aretouchTarget - xxSmalland large controls aretouchTarget + small.What the enhanced theme gives you:
theme.spacing()resolves the step names next to numbers and raw CSS:theme.spacing('small')is'12px', andtheme.spacing('-xSmall')is'-8px'. Thesxspacing props accept them too:<Box sx={{ p: 'small', gap: 'xSmall' }} />.theme.touchTargetandtheme.iconSizehold the resolved lengths.theme.unstable_densityScaleholds every value as a px number, for code that computes sizes in JavaScript.cssVariables: true, the theme writes--mui-spacing-<step>,--mui-touchTargetand--mui-iconSize, and components read those variables. Setting--mui-touchTargeton an element resizes the controls inside it.styleOverrideskeep winning. Pass them tocreateThemebefore you enhance the theme, and the enhancer appends the density styles in front of them.Themes that don't call
enhanceDensityrender exactly as before.The types are opt-in, so projects that don't use the enhancer keep their own
Themeaugmentations and spacing types. To typetheme.touchTarget,theme.iconSizeand the step names intheme.spacing(), import the augmentation once:For reviewers
Where the code is
enhanceDensityis the entry point. It callsapplyDensityto set up the scale, then writes the density styles for 66 components.applyDensitywrapstheme.spacingso it resolves step names, setstheme.touchTarget,theme.iconSizeandtheme.unstable_densityScale, and adds the CSS variables togenerateStyleSheets. It also wrapsgenerateSpacingandgenerateThemeVars, becauseCssVarsProviderrebuilds both on mount.addStyleOverridestores each slot as[density, user], so the user's override renders after the density style.Design decisions
smallis 12px whateverspacingis set to. Numbers passed totheme.spacing()still use the theme's spacing unit, so existing layouts don't move.touchTargetandiconSize, so changingtouchTargetmoves every control box at once while padding and gaps stay on the steps.Accepted tradeoffs
enhanceDensityon a theme that is already enhanced returns it unchanged and logs an error in development.ThemeProviderwith the samecssVarPrefixskips 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 differentcssVarPrefix. The docs say so.gap. FormGroup spaces its labels withgap, and the label drops its own margin. Labels outside a FormGroup get no spacing. The docs say so.typography.buttonfor 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 atcalc(100% - 64px). Narrow screens show 32px gutters instead of 24px, and the paper never grows past itsmaxWidth.font-sizefrom resizing the arrow.Changes outside the enhancer
These keep master's output identical and only expose a value the enhancer needs to change:
Tooltipreads its gap from--_spacing, with master's values as the defaults. The touch variant now sets--_spacing: 24pxinstead of repeating the four placement rules.Dialogreads its margin from--_dialogMargin(32px by default), and thecalc(100% - 64px)sizes use twice that variable.spacingin@mui/system: a spacing function can list the names it resolves in akeysproperty.sxresolves those names and passes every other string through as raw CSS, as before.createSpacingadds aSpacingKeyOverridesinterface so the names show up in autocompletion.Gridresolves the names forrowSpacingandcolumnSpacingthe same way.@mui/material/themeDensityAugmentationis the opt-in type entry. The module augmentation fixtures cover a project with and without it.Tests
densityContract.test.tsxruns in Chromium. It measures rendered boxes at two scales (dense and default), and checks that user overrides,sx,modularCssLayersand coarse pointers behave as on master. The expected values are computed from the scale, not copied from the enhancer.densityScale.test.tsandenhanceDensity.test.tscover the spacing wrapper, the CSS variables, scale overrides with everyspacingoption form, and step names in thesxspacing props.densityAnnotationParity.test.tsxchecks that the docs annotations match the values the components render.@mui/systemtests cover named steps insx,Gridand CSS Grid, and raw strings passing through unchanged.