Skip to content

[material-ui] Per-palette interaction state generators (enhanceColorStates) - #49048

Draft
siriwatknp wants to merge 3 commits into
mui:masterfrom
siriwatknp:exp/color-bg-state
Draft

[material-ui] Per-palette interaction state generators (enhanceColorStates)#49048
siriwatknp wants to merge 3 commits into
mui:masterfrom
siriwatknp:exp/color-bg-state

Conversation

@siriwatknp

@siriwatknp siriwatknp commented Aug 28, 2026

Copy link
Copy Markdown
Member

Draft / RFC prototype. Opening for design feedback on the API shape, not for merge. Two families are converted as proof; the rest are listed below.

Problem

Material UI produces interaction colors one fixed way and offers no level at which a design system can change it.

  1. The production rules are hard-coded per component and mutually inconsistent. Four mechanisms coexist today: a palette[color].dark shift (Button contained, Chip, Fab, PaginationItem, ButtonGroup); an alpha(…, action.hoverOpacity) tint (13 components reference hoverOpacity); a flat action.hover color (7 components use it as a state background); and no state color at all in Tab, AccordionSummary, BottomNavigationAction, StepButton, OutlinedInput and FilledInput. Several components mix two or three. There is no pressed state anywhere.

  2. The global surface is too small to redirect any of it. All a theme can say globally is palette.action.* and palette[color].light / .dark. That surface is flat (one hover color for the whole app, so a primary row and an error row hover identically), absolute (an rgba constant and a fixed "darker" direction, neither of which can move away from the page background), and partial (Button reads none of action.hover, so the one global lever misses the most-used component).

  3. So every correction lands inside a component, per variant, per scheme, through styleOverrides.

The clearest evidence the mechanism is missing is that the library itself has nowhere to put one. This string is hand-written, character for character, 14 times across 7 components (Chip ×3; Autocomplete, ToggleButton, MenuItem, PaginationItem, ListItemButton ×2 each; TableRow ×1):

`${(theme.vars || theme).palette.action.selectedOpacity} + ${(theme.vars || theme).palette.action.hoverOpacity}`

Composing "selected" with "hover" is a rule. With no place to store a rule, it gets copied.

Proposal

One flat config: an entry per palette colour, each naming the generator that produces its states.

import { createTheme, enhanceColorStates, colorMix, relativeColor } from '@mui/material/styles';

const theme = enhanceColorStates(createTheme({ /* plain palette */ }), {
  default: colorMix({ overlayStep: '5%' }),   // the colour-independent ghost ramp
  primary: colorMix({ step: '4.4%' }),
  error:   colorMix({ step: '3.7%' }),
  warning: relativeColor({ lightness: 0.072, chroma: 0.014, hue: 4.15 }),
});

It runs each generator once and attaches theme.states, a sibling of theme.palette holding
ready-to-use style objects keyed by state name:

theme.states.primary.hover          // { backgroundColor, borderColor }
theme.states.default.selectedHover  // { backgroundColor }
theme.states.default.disabled       // { opacity: 0.5, boxShadow: 'none' }

There are no defaults, and that is the point

A colour that is not listed keeps today's styles. So zero-diff is provable per colour, not merely
per theme, and Material UI never picks a magnitude, a ramp direction, or a CSS backend for a colour it
knows nothing about.

That is a measured decision, not a stylistic one. Fitting all 71 solid default → hover → pressed
triads in a production design system's export:

  • the magnitude differs per colour by up to 6.3× (amber tint 1.70%, primary 4.58%, accent 10.75%
    in light) and again per scheme (error 3.66% light vs 6.54% dark);
  • chroma usually increases along the ramp (median ΔC +0.007), which a mix toward a neutral pole
    cannot do at any percentage;
  • hue holds within 0.4°/level for every chromatic family except amber, at 4.15° — it loses chroma
    steeply as lightness drops and reads brown without the correction.

Any single house default would therefore be wrong for someone.

Two generators, and why the backend is named per colour

colorMix({ step, overlayStep, target, levels }) — emits color-mix(in oklab, …). Within
browserslist targets today. in oklab, not oklch: with a neutral target the two are identical,
but a tinted target makes oklch rotate hue — a red button drifts purple. target lets a tinted
surface ramp toward its own anchor instead of the page pole, which takes a tinted amber surface from
Δ12/Δ25 to Δ1/Δ2.

relativeColor({ lightness, chroma, hue, levels }) — emits
oklch(from <color> calc(l + …) calc(c + …) calc(h + …)). The only backend that can raise chroma or
rotate hue. Needs Chrome 119 / Firefox 128, above the current floor.

Naming the backend at the call site is deliberate: the browser requirement is readable in the theme
rather than buried in documentation, and it is confined to the colours that need it. Measured across
the same 71 triads — colorMix leaves 38% of tokens visibly off, relativeColor 13%, and
relativeColor with hue and a per-colour active level free, 3%, with nothing in the "clearly
different" bucket.

Why derive at all, and why toward a pole

palette[color].dark encodes an absolute direction. "Darker on hover" is right on a light ground
and wrong on a dark one, which is why dark mode needs state colours hand-authored a second time.
Material UI already ships the pole that fixes this: palette.common.onBackground (#000 light /
#fff dark), already consumed by the input and ButtonGroup borders, and settable — which matters,
because a third colour mode in that same export uses a pale blue rather than white.

Per-scheme magnitudes

Every generator option is a plain CSS string, so a value that must differ per scheme is passed as a
variable reference and resolved by the existing colour-scheme emitter — palette.states carries it,
no new namespace, no library change. The library never invents a variable name; it cannot know the
theme's cssVarPrefix.

Component contract

Components gate; they never consume.

...(theme.states?.default ? null : { /* its fixed state colors */ })
...(theme.states?.[color] ? null : { /* its per-color state colors */ })

It gates the colors, not the block, so behavior like a touch reset or text-decoration: none keeps applying.

Each declaration is gated on the entry that would replace it. Because colours are configured
independently, a theme may have states.primary and no states.default. Button's contained fill and
outlined border come from states[color]; its text and outlined tints come from states.default.
Gating them together dropped a value nothing put back — verified in the browser: with primary
configured and default omitted, the fill derives while the text button correctly falls back to its
legacy alpha(main, hoverOpacity) hover. A private shared layer (sharedStateComponents.ts, sibling of sharedDensityComponents.ts) then applies the values at each family's own selectors, as function overrides.

Selectors belong to the component, never to the data. Which selector a state maps to — and whether hover is media-gated — already differs per family, so encoding it in the theme would force every family into one family's assumptions. Keying by name makes both access patterns first-class:

'&:hover': base.hover                                  // apply whole
'--variant-containedBg': state.hover.backgroundColor   // read one property

Hover is emitted inside @media (hover: hover) by the layer, so nothing downstream needs a @media (hover: none) reset; :active stays ungated so a tap still gives press feedback.

Backward compatibility

  • Zero-diff by construction. No enhanceColorStates → no theme.states → every gate takes its legacy branch → identical output.
  • createTheme is not modified (verified by an empty diff). The enhancer is the seam, exactly as it is for density.
  • light / dark remain authored tokens and keep being read by everything that reads them today.
  • palette gains no color keys, so code iterating palette colors is unaffected.
  • Adoption is incremental per component family.

Results

  • Fidelity vs. the reference tokens (worst 8-bit channel error; perceptual threshold ≈ 5–8): light Δ0 / Δ0 / Δ0 at step: 4.6%; dark Δ0 / Δ1 / Δ3 at 4.4%.
  • active exists — contained Button reads three distinct rest/hover/active values.
  • Compound works — a selected MenuItem deepens 5% → 10% on hover with nothing authored.
  • Duplication: one generator replaces the 14 hand-copied composition rules. Raw declaration count is roughly a wash (~9 per color either way), so the honest claim is derivation plus an active state at equal cost — not a size win.

Scope here, and what follows

Converted: Button (unpacks into its private --variant-* properties) and MenuItem (applies straight at its own selectors) — deliberately the two different shapes.

Next, ordered by the mechanism each component uses rather than popularity: Autocomplete, TableRow, ListItemButton, ListItem, PaginationItem (direct painters — the layer only spreads, and they remove 7 of the 14 rule copies), then Chip, ToggleButton, ButtonGroup, IconButton, Fab (border ramp), then the inputs, then the SwitchBase controls.

Open questions

  1. Should hover stay media-gated by default, or become a lever?
  2. Naming: enhanceColorStates / colorMix / relativeColor / theme.states. The generator names
    deliberately echo the CSS features they emit, so the browser requirement is inferable.
  3. A theme wanting uniform behaviour across six palette colours writes six entries. That is the cost
    of having no defaults; a '*' key would be a default in disguise. Confirming the trade.
  4. Because the layer targets Button's private --variant-* properties, a rename would fail silently — this needs a CI test asserting those names still appear in the component's output. It is intended to land with the VRT pass once the conversion set is final. Reworking Button's indirection is not proposed; it correctly decomposes 3 variants × N colors into 3 + N rules.

Try it

docs/pages/experiments/color-gap.tsx/experiments/color-gap/ — a tokens-only theme (zero styleOverrides) with a baseline toggle and swatches read straight from theme.states.

…lors

Today the library produces interaction colors four different ways
(palette[color].dark shift, alpha(hoverOpacity) tint, flat action.hover, or
nothing at all), offers no theme-level lever to redirect them, and has no
pressed state. The compound rule `selectedOpacity + hoverOpacity` is hand-copied
14 times across 7 components because there is nowhere to store it.

enhanceColorStates(theme, config) runs a generator once and attaches
theme.states: ready-to-use style objects keyed by state name, derived per
palette color with color-mix toward palette.common.onBackground so one
expression is correct in every scheme. Levers are a pole, two magnitudes,
per-state levels and a disabled model.

Components gate only; sharedStateComponents applies the values at each family's
own selectors. Button and MenuItem converted. createTheme is untouched — a theme
that never calls the enhancer emits identical CSS.
Tokens-only theme (zero styleOverrides) plus enhanceColorStates, light and dark.
Swatches read rest/hover/active straight out of theme.states; a toggle compares
against the baseline theme.
@siriwatknp siriwatknp added type: new feature Expand the scope of the product to solve a new problem. customization: theme Higher level theming customizability. package: material-ui Specific to Material UI. labels Aug 28, 2026
@code-infra-dashboard

code-infra-dashboard Bot commented Aug 28, 2026

Copy link
Copy Markdown

Deploy preview

https://deploy-preview-49048--material-ui.netlify.app/
QR code for https://deploy-preview-49048--material-ui.netlify.app/

Bundle size

Bundle Parsed size Gzip size
@mui/material 🔺+3.24KB(+0.61%) 🔺+1.08KB(+0.70%)
@mui/lab 0B(0.00%) 0B(0.00%)
@mui/private-theming 0B(0.00%) 0B(0.00%)
@mui/system 0B(0.00%) 0B(0.00%)
@mui/utils 0B(0.00%) 0B(0.00%)

Details of bundle changes


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

Replaces the single derived-by-default model with one entry per palette colour,
each naming its own generator:

  enhanceColorStates(theme, {
    default: colorMix({ overlayStep: '5%' }),
    primary: colorMix({ step: '4.4%' }),
    warning: relativeColor({ lightness: 0.072, chroma: 0.014, hue: 4.15 }),
  })

Material UI no longer picks a magnitude, a ramp direction or a CSS backend.
Measured against a real design system, the right values differ per colour AND
per scheme, so any house default is wrong for someone. A colour that is not
listed keeps today's styles, which makes zero-diff provable per colour instead
of per theme.

Two generators ship. colorMix() is within browserslist targets. relativeColor()
uses relative colour syntax (Chrome 119 / Firefox 128, above the floor) and is
the only one that can raise chroma or rotate hue — needed for amber, the one
hue family measured to rotate along its ramp. Naming the backend per colour puts
that browser requirement at the call site instead of in a footnote.

Button's gate is split accordingly: the fill and border are gated on
states[color], the text/outlined tints on states.default, because the two are
now configured independently. Gating them together dropped a value nothing put
back, leaving text buttons with no hover.
@siriwatknp siriwatknp changed the title [material-ui] Derive interaction state colors from the palette (enhanceColorStates) [material-ui] Per-palette interaction state generators (enhanceColorStates) Aug 30, 2026
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. package: material-ui Specific to Material UI. type: new feature Expand the scope of the product to solve a new problem.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant