UNPKG

@atlassian/aui

Version:

Atlassian User Interface library

83 lines (68 loc) 2.96 kB
import TokenNames from '@atlaskit/tokens/token-names'; const testingThemeTargetElement = document.documentElement; const testingColorVariableName = '--aui-theme-testing-color'; const defaultTestingColor = 'color(srgb 1 0.75 0.8 / 0.6)'; const testingThemeTargetClass = 'aui-theme-testing'; const testingThemeSelector = `html.${testingThemeTargetClass}[data-theme*="light:"], ` + `html.${testingThemeTargetClass}[data-theme*="dark:"]`; /** * Theme that replaces all the design tokens with single color, helping to visually identify custom colors on the page * * @param solidColor any valid CSS color, will be used to replace tokens */ (function generateTestingTheme() { const initialComment = 'This theme is autogenerated using AJS.DesignTokens.generateTestingTheme().'; // If function called many times theme should be only added once const isThemeAlreadyInitialised = !document.querySelector(testingThemeSelector); if (!isThemeAlreadyInitialised) { return; } // We use overridable test color declaration to make theme configurable const colorDeclaration = `${testingColorVariableName}: ${defaultTestingColor};`; const themeCSSDeclarations = Object.values(TokenNames).map( (token) => `\t${token}: var(${testingColorVariableName});` ); const allDeclarations = [colorDeclaration, ...themeCSSDeclarations]; const themeCSS = `/* ${initialComment} */\n${testingThemeSelector} {\n${allDeclarations.join('\n')}\n}`; const themeElement = document.createElement('style'); themeElement.id = 'aui-design-tokens-testing-theme'; themeElement.innerText = themeCSS; const head = document.querySelector('head'); if (head) { head.appendChild(themeElement); } })(); /** * Overrides default testing color by setting css variable. If no color passed, will revert to default. * @param color color to use for testing */ function setTestingThemeColor(color = defaultTestingColor) { document.body.style.setProperty(testingColorVariableName, color); } function isTestingThemeEnabled() { return testingThemeTargetElement.matches(testingThemeSelector); } function enableTestingTheme() { if (!isTestingThemeEnabled()) { testingThemeTargetElement.classList.add(testingThemeTargetClass); } } function disableTestingTheme() { if (isTestingThemeEnabled()) { testingThemeTargetElement.classList.remove(testingThemeTargetClass); } } /** * Enables or disables testing theme for Design Tokens based on current state * @param targetState Optional parameter. Allows to force specific state. */ function toggleTestingTheme(targetState) { // If not passed, invert existing state if (targetState == null) { targetState = !isTestingThemeEnabled(); } targetState ? enableTestingTheme() : disableTestingTheme(); } export { setTestingThemeColor, enableTestingTheme, disableTestingTheme, toggleTestingTheme };