Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[material-ui][joy-ui] Generate typography tokens #41703

Merged
merged 8 commits into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 0 additions & 20 deletions packages/mui-joy/src/styles/CssVarsProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,6 @@ describe('[Joy] CssVarsProvider', () => {
});

describe('shouldSkipGeneratingVar', () => {
it('skip typography', () => {
expect(shouldSkipGeneratingVar(['typography'])).to.equal(true);
});

it('skip variants', () => {
expect(shouldSkipGeneratingVar(['variants'])).to.equal(true);
});
Expand Down Expand Up @@ -564,22 +560,6 @@ describe('[Joy] CssVarsProvider', () => {
expect(container.firstChild?.textContent).not.to.equal('variants');
});

it('should not contain `typography` in theme.vars', () => {
function Consumer() {
const theme = useTheme();
// @ts-expect-error
return <div>{theme.vars.typography ? 'typography' : ''}</div>;
}

const { container } = render(
<CssVarsProvider>
<Consumer />
</CssVarsProvider>,
);

expect(container.firstChild?.textContent).not.to.equal('typography');
});

it('should contain only `focus.thickness` in theme.vars', () => {
function Consumer() {
const theme = useTheme();
Expand Down
19 changes: 19 additions & 0 deletions packages/mui-joy/src/styles/extendTheme.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,25 @@ describe('extendTheme', () => {
});
});

describe('typography', () => {
it('produce typography token by default', () => {
const theme = extendTheme();
expect(Object.keys(theme.vars.typography)).to.deep.equal([
'h1',
'h2',
'h3',
'h4',
'title-lg',
'title-md',
'title-sm',
'body-lg',
'body-md',
'body-sm',
'body-xs',
]);
});
});

describe('theme.unstable_sx', () => {
const { render } = createRenderer();

Expand Down
3 changes: 3 additions & 0 deletions packages/mui-joy/src/styles/extendTheme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
SxConfig,
} from '@mui/system';
import { unstable_applyStyles as applyStyles } from '@mui/system/createTheme';
import { prepareTypographyVars } from '@mui/system/cssVars';
import { createUnarySpacing } from '@mui/system/spacing';
import defaultSxConfig from './sxConfig';
import colors from '../colors';
Expand Down Expand Up @@ -604,6 +605,7 @@ export default function extendTheme(themeOptions?: CssVarsThemeOptions): Theme {
cssVarPrefix,
getCssVar,
spacing: getSpacingVal(spacing),
typography: prepareTypographyVars(mergedScales.typography),
} as unknown as Theme & { attribute: string; colorSchemeSelector: string }; // Need type casting due to module augmentation inside the repo

/**
Expand Down Expand Up @@ -675,6 +677,7 @@ export default function extendTheme(themeOptions?: CssVarsThemeOptions): Theme {
return createSpacing(spacing, createUnarySpacing(this));
};
theme.spacing = theme.generateSpacing();
theme.typography = mergedScales.typography as any; // cast to `any` to avoid internal module augmentation in the repo.
Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Member Author

Choose a reason for hiding this comment

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

Let me clarify, it is redefined to preserve the same behavior as the developers passed the typography in.

In line 608, the typography is configured by prepareTypographyVars so that the generated token is in the format of font: ….

prepareTypographyVars({ h1: { fontFamily: , fontSize: , lineHeight: , fontWeight:  }})
// { h1: "…valid CSS `font` value", …other typography }

At the end, before the theme is return, the original typography object is redefined back so that this behavior remains the same:

styled('div')({ theme }) => ({
  …theme.typography.h1,
})

Copy link
Member

Choose a reason for hiding this comment

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

So, line 608 adds the theme.vars.typography... values?

Copy link
Member Author

Choose a reason for hiding this comment

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

Not really, line 608 builds up the typography structure so that prepareCssVars at line 667 generates the vars.typography based on that structure.

Copy link
Member

Choose a reason for hiding this comment

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

Thanks for the explanation!

theme.unstable_sxConfig = {
...defaultSxConfig,
...themeOptions?.unstable_sxConfig,
Expand Down
2 changes: 1 addition & 1 deletion packages/mui-joy/src/styles/shouldSkipGeneratingVar.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export default function shouldSkipGeneratingVar(keys: string[]) {
return (
!!keys[0].match(/^(typography|variants|breakpoints)$/) ||
!!keys[0].match(/^(variants|breakpoints)$/) ||
!!keys[0].match(/sxConfig$/) || // ends with sxConfig
(keys[0] === 'palette' && !!keys[1]?.match(/^(mode)$/)) ||
(keys[0] === 'focus' && keys[1] !== 'thickness')
Expand Down
5 changes: 4 additions & 1 deletion packages/mui-joy/src/styles/types/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
SxConfig,
ApplyStyles,
} from '@mui/system';
import { ExtractTypographyTokens } from '@mui/system/cssVars';
import { DefaultColorScheme, ExtendedColorScheme } from './colorScheme';
import { ColorSystem } from './colorSystem';
import { Focus } from './focus';
Expand Down Expand Up @@ -82,7 +83,9 @@ export type ThemeScalesOptions = MergeDefault<
interface ColorSystemVars extends Omit<ColorSystem, 'palette'> {
palette: Omit<ColorSystem['palette'], 'mode'>;
}
export interface ThemeVars extends ThemeScales, ColorSystemVars {}
export interface ThemeVars extends ThemeScales, ColorSystemVars {
typography: ExtractTypographyTokens<TypographySystem>;
}

export interface ThemeCssVarOverrides {}

Expand Down
16 changes: 0 additions & 16 deletions packages/mui-material/src/styles/CssVarsProvider.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -305,22 +305,6 @@ describe('[Material UI] CssVarsProvider', () => {
expect(container.firstChild?.textContent).not.to.equal('variants');
});

it('should not contain `typography` in theme.vars', () => {
function Consumer() {
const theme = useTheme();
// @ts-expect-error
return <div>{theme.vars.typography ? 'typography' : ''}</div>;
}

const { container } = render(
<CssVarsProvider>
<Consumer />
</CssVarsProvider>,
);

expect(container.firstChild?.textContent).not.to.equal('typography');
});

it('should not contain `focus` in theme.vars', () => {
function Consumer() {
const theme = useTheme();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { OverridableStringUnion } from '@mui/types';
import { SxConfig, SxProps, CSSObject, ApplyStyles } from '@mui/system';
import { ExtractTypographyTokens } from '@mui/system/cssVars';
import { ThemeOptions, Theme } from './createTheme';
import { Palette, PaletteOptions } from './createPalette';
import { Shadows } from './shadows';
Expand Down Expand Up @@ -336,6 +337,7 @@ export interface ThemeVars {
shape: Theme['shape'];
spacing: string;
zIndex: ZIndex;
typography: ExtractTypographyTokens<Theme['typography']>;
}

type Split<T, K extends keyof T = keyof T> = K extends string | number
Expand Down
4 changes: 3 additions & 1 deletion packages/mui-material/src/styles/experimental_extendTheme.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import deepmerge from '@mui/utils/deepmerge';
import { unstable_createGetCssVar as systemCreateGetCssVar, createSpacing } from '@mui/system';
import { createUnarySpacing } from '@mui/system/spacing';
import { prepareCssVars } from '@mui/system/cssVars';
import { prepareCssVars, prepareTypographyVars } from '@mui/system/cssVars';
import styleFunctionSx, {
unstable_defaultSxConfig as defaultSxConfig,
} from '@mui/system/styleFunctionSx';
Expand Down Expand Up @@ -139,6 +139,7 @@ export default function extendTheme(options = {}, ...args) {
overlays: colorSchemesInput.dark?.overlays || defaultDarkOverlays,
},
},
typography: prepareTypographyVars(muiTheme.typography),
spacing: getSpacingVal(input.spacing),
};

Expand Down Expand Up @@ -436,6 +437,7 @@ export default function extendTheme(options = {}, ...args) {
theme.getColorSchemeSelector = (colorScheme) => `[${theme.attribute}="${colorScheme}"] &`;
theme.spacing = theme.generateSpacing();
theme.shouldSkipGeneratingVar = shouldSkipGeneratingVar;
theme.typography = muiTheme.typography;
theme.unstable_sxConfig = {
...defaultSxConfig,
...input?.unstable_sxConfig,
Expand Down
22 changes: 22 additions & 0 deletions packages/mui-material/src/styles/experimental_extendTheme.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,28 @@ describe('experimental_extendTheme', () => {
});
});

describe('typography', () => {
it('produce typography token by default', () => {
const theme = extendTheme();
expect(Object.keys(theme.vars.typography)).to.deep.equal([
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'subtitle1',
'subtitle2',
'body1',
'body2',
'button',
'caption',
'overline',
'inherit',
]);
});
});

it('shallow merges multiple arguments', () => {
const theme = extendTheme({ foo: 'I am foo' }, { bar: 'I am bar' });
expect(theme.foo).to.equal('I am foo');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export default function shouldSkipGeneratingVar(keys: string[]) {
return (
!!keys[0].match(/(cssVarPrefix|typography|mixins|breakpoints|direction|transitions)/) ||
!!keys[0].match(/(cssVarPrefix|mixins|breakpoints|direction|transitions)/) ||
!!keys[0].match(/sxConfig$/) || // ends with sxConfig
(keys[0] === 'palette' && !!keys[1]?.match(/(mode|contrastThreshold|tonalOffset)/))
);
Expand Down
2 changes: 2 additions & 0 deletions packages/mui-system/src/cssVars/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ export type {

export { default as getInitColorSchemeScript } from './getInitColorSchemeScript';
export { default as prepareCssVars } from './prepareCssVars';
export { default as prepareTypographyVars } from './prepareTypographyVars';
export type { ExtractTypographyTokens } from './prepareTypographyVars';
export { default as createCssVarsTheme } from './createCssVarsTheme';
25 changes: 25 additions & 0 deletions packages/mui-system/src/cssVars/prepareTypographyVars.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { expect } from 'chai';
import { createTheme } from '@mui/material/styles';
import prepareTypographyTokens from './prepareTypographyVars';

describe('prepareTypographyVars', () => {
it('should prepare typography vars', () => {
const theme = createTheme();
expect(prepareTypographyTokens(theme.typography)).to.deep.equal({
body1: '400 1rem/1.5 "Roboto", "Helvetica", "Arial", sans-serif',
body2: '400 0.875rem/1.43 "Roboto", "Helvetica", "Arial", sans-serif',
button: '500 0.875rem/1.75 "Roboto", "Helvetica", "Arial", sans-serif',
caption: '400 0.75rem/1.66 "Roboto", "Helvetica", "Arial", sans-serif',
h1: '300 6rem/1.167 "Roboto", "Helvetica", "Arial", sans-serif',
h2: '300 3.75rem/1.2 "Roboto", "Helvetica", "Arial", sans-serif',
h3: '400 3rem/1.167 "Roboto", "Helvetica", "Arial", sans-serif',
h4: '400 2.125rem/1.235 "Roboto", "Helvetica", "Arial", sans-serif',
h5: '400 1.5rem/1.334 "Roboto", "Helvetica", "Arial", sans-serif',
h6: '500 1.25rem/1.6 "Roboto", "Helvetica", "Arial", sans-serif',
inherit: 'inherit inherit/inherit inherit',
overline: '400 0.75rem/2.66 "Roboto", "Helvetica", "Arial", sans-serif',
subtitle1: '400 1rem/1.75 "Roboto", "Helvetica", "Arial", sans-serif',
subtitle2: '500 0.875rem/1.57 "Roboto", "Helvetica", "Arial", sans-serif',
});
});
});
18 changes: 18 additions & 0 deletions packages/mui-system/src/cssVars/prepareTypographyVars.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
type RecordPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? never : T[K] extends Record<string, any> ? K : never;
}[keyof T];

export type ExtractTypographyTokens<T> = { [K in RecordPropertyNames<T>]: string };

export default function prepareTypographyTokens<T extends Record<string, any>>(typography: T) {
const vars: Record<string, string | number> = {};
const entries = Object.entries(typography);
entries.forEach((entry) => {
const [key, value] = entry;
if (typeof value === 'object') {
vars[key] =
`${value.fontStyle ? `${value.fontStyle} ` : ''}${value.fontVariant ? `${value.fontVariant} ` : ''}${value.fontWeight ? `${value.fontWeight} ` : ''}${value.fontStretch ? `${value.fontStretch} ` : ''}${value.fontSize || ''}${value.lineHeight ? `/${value.lineHeight} ` : ''}${value.fontFamily || ''}`;
}
});
return vars as ExtractTypographyTokens<T>;
}