@atlaskit/tokens
Version:
Design tokens are the single source of truth to name and store design decisions.
62 lines (61 loc) • 2.77 kB
JavaScript
import { fg } from '@atlaskit/platform-feature-flags';
import { COLOR_MODE_ATTRIBUTE, CONTRAST_MODE_ATTRIBUTE, CUSTOM_THEME_ATTRIBUTE, THEME_DATA_ATTRIBUTE } from './constants';
import { themeStateDefaults } from './theme-config';
import { themeObjectToString } from './theme-object-to-string';
import { hash } from './utils/hash';
import { isValidBrandHex } from './utils/is-valid-brand-hex';
const defaultColorMode = 'light';
const defaultContrastMode = 'no-preference';
/**
* Server-side rendering utility. Generates the valid HTML attributes for a given theme.
* Note: this utility does not handle automatic theme switching.
*
* @param {Object<string, string>} themeOptions - Theme options object
* @param {string} themeState.colorMode Determines which color theme is applied. If set to `auto`, the theme applied will be determined by the OS setting.
* @param {string} themeState.dark The color theme to be applied when the color mode resolves to 'dark'.
* @param {string} themeState.light The color theme to be applied when the color mode resolves to 'light'.
* @param {string} themeState.motion The motion theme to be applied.
* @param {string} themeState.spacing The spacing theme to be applied.
* @param {string} themeState.typography The typography theme to be applied.
* @param {Object} themeState.UNSAFE_themeOptions The custom branding options to be used for custom theme generation
*
* @returns {Object} Object of HTML attributes to be applied to the document root
*/
const getThemeHtmlAttrs = ({
colorMode = themeStateDefaults['colorMode'],
dark = themeStateDefaults['dark'],
light = themeStateDefaults['light'],
contrastMode = themeStateDefaults['contrastMode'],
motion = themeStateDefaults['motion'](),
shape = themeStateDefaults['shape'](),
spacing = themeStateDefaults['spacing'],
typography = themeStateDefaults['typography'],
UNSAFE_themeOptions = themeStateDefaults['UNSAFE_themeOptions']
} = {}) => {
const themeAttribute = themeObjectToString({
dark,
light,
motion,
shape,
spacing,
typography
});
let result = {
[THEME_DATA_ATTRIBUTE]: themeAttribute,
[COLOR_MODE_ATTRIBUTE]: colorMode === 'auto' ? defaultColorMode : colorMode
};
if (fg('platform_increased-contrast-themes')) {
result = {
...result,
// CLEANUP: Move this to the initial `result` assignment above
[CONTRAST_MODE_ATTRIBUTE]: contrastMode === 'auto' ? defaultContrastMode : contrastMode
};
}
if (UNSAFE_themeOptions && isValidBrandHex(UNSAFE_themeOptions.brandColor)) {
const optionString = JSON.stringify(UNSAFE_themeOptions);
const uniqueId = hash(optionString);
result[CUSTOM_THEME_ATTRIBUTE] = uniqueId;
}
return result;
};
export default getThemeHtmlAttrs;