Skip to content

[material-ui] Derive interaction state colors from the palette (enhanceColorStates) - #49048

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

[material-ui] Derive interaction state colors from the palette (enhanceColorStates)#49048
siriwatknp wants to merge 2 commits into
mui:masterfrom
siriwatknp:exp/color-bg-state

Conversation

@siriwatknp

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 function. The palette is authored exactly as it is today — nothing is marked or wrapped.

const theme = enhanceColorStates(
  createTheme({
    colorSchemes: { light: { palette: { primary: { main: '#006DA2' } } } },
  }),
);

It runs a 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' }

Every palette entry carrying a main derives, including custom colors; text, background, action, grey, common and divider are skipped without a list to maintain.

Why derived, 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 colors hand-authored a second time. Measured against a production design system's token export (3 color modes, ~100 default → hover → pressed triads), every state is the rest color moved a fixed number of steps away from the page background — one step for hover, two for pressed.

Material UI already ships the pole that expresses this: palette.common.onBackground (#000 light / #fff dark), already consumed by the input and ButtonGroup borders, and settable — which matters, because a third mode in that same export uses a pale blue rather than white.

color-mix(in oklab, var(--mui-palette-primary-main), var(--mui-palette-common-onBackground) 4.5%)

in oklab, not oklch: with a neutral pole the two are identical, but a tinted pole makes oklch rotate hue — a red button drifts purple — while oklab desaturates and keeps color identity.

Configuration

The entire public surface is a pole, two magnitudes, per-state levels, and a disabled model:

enhanceColorStates(theme, {
  step: '4.5%',
  overlayStep: '5%',
  pole: undefined,                              // defaults to palette.common.onBackground
  levels: { hover: 1, active: 2, selected: 1 },
  disabled: { opacity: 0.5 },                   // or { color, background } to recolor
});

Per-scheme magnitudes need no second API: every field is a plain CSS string, so a theme passes a var() reference and lets the existing color-scheme emitter resolve it per scheme (palette.states carries the values).

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. 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 / theme.states.
  3. 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

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 🔺+2.6KB(+0.49%) 🔺+752B(+0.49%)
@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.

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