UNPKG

@atlaskit/primitives

Version:

Primitives are token-backed low-level building blocks.

76 lines (69 loc) 2.86 kB
// eslint-disable-next-line @atlaskit/ui-styling-standard/use-compiled -- Ignored via go/DSP-18766 import { css as cssEmotion } from '@emotion/react'; import { tokensMap } from './tokens-map'; import { uniqueSymbol } from './unique-symbol'; const isSafeEnvToThrow = () => typeof process === 'object' && typeof process.env === 'object' && process.env.NODE_ENV !== 'production'; const reNestedSelectors = /(\.|\s|&+|\*\>|#|\[.*\])/; const safeSelectors = /^@media .*$|^::?.*$|^@supports .*$/; const transformStyles = styleObj => { if (!styleObj || typeof styleObj !== 'object') { return styleObj; } // If styles are defined as a CSSObject[], recursively call on each element until we reach CSSObject if (Array.isArray(styleObj)) { return styleObj.map(transformStyles); } // Modifies styleObj in place. Be careful. Object.entries(styleObj).forEach(([key, value]) => { // If key is a pseudo class or a pseudo element, then value should be an object. // So, call transformStyles on the value if (typeof value === 'object' && safeSelectors.test(key)) { styleObj[key] = transformStyles(value); return; } if (isSafeEnvToThrow()) { // We don't support `.class`, `[data-testid]`, `> *`, `#some-id` if (reNestedSelectors.test(key)) { throw new Error(`Styles not supported for key '${key}'.`); } } // We have now dealt with all the special cases, so, // check whether what remains is a style property // that can be transformed. if (!(key in tokensMap)) { return; } const tokenValue = tokensMap[key][value]; styleObj[key] = tokenValue !== null && tokenValue !== void 0 ? tokenValue : value; }); return styleObj; }; const baseXcss = style => { const transformedStyles = transformStyles(style); return { // eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values, @atlaskit/ui-styling-standard/no-imported-style-values -- Ignored via go/DSP-18766 [uniqueSymbol]: cssEmotion(transformedStyles) }; }; // Media queries should not contain nested media queries // Allow only a specific subset of chained selectors to maintain workable TypeScript performance // Pseudos should not contain nested pseudos, or media queries /** * ### xcss * * `xcss` is a safer, tokens-first approach to CSS-in-JS. It allows token-backed values for * CSS application. * * ```tsx * const styles = xcss({ * padding: 'space.100' * }) * ``` * * @deprecated Use `@atlaskit/css` with `@atlaskit/primitives/compiled` instead. * {@link https://hello.atlassian.net/wiki/spaces/DST/pages/4992259434/Guidance+Migrating+to+atlaskit+css+from+xcss Internal documentation for migration; no external access} */ // eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports export function xcss(style) { return baseXcss(style); }