ant-design/cssinjs

repository·master·Indexed 43 days ago

https://github.com/ant-design/cssinjs

A component-level CSS-in-JS solution used in Ant Design, acting as a subset of Emotion with a specialized design token logic wrapper. Version 2.1.2 provides tools for style injection via StyleProvider, theme creation with createTheme, and SSR style extraction using extractStyle. It includes transformers for px2rem and logical properties, as well as hooks like useCacheToken and useStyleRegister for managing design tokens and CSS variables.

Tokens
8.1K
Snippets
30
Records
42
Agent score
52%

What's inside ant-design/cssinjs

  1. Transform CSS using StyleProvider transformers

    master

    You can transform CSSObjects before they are injected into the document by passing an array of transformers to the transformers prop of StyleProvider.

    Available Transformers

    legacyLogicalPropertiesTransformer

    Converts logical properties to legacy properties for better compatibility (e.g., converting marginBlockStart to marginTop). It supports:

    • inset
    • margin
    • padding
    • border

    px2remTransformer

    Converts pixel (px) units to rem units.

    import {
      legacyLogicalPropertiesTransformer,
      StyleProvider,
    } from '@ant-design/cssinjs';
    
    export default () => (
      <StyleProvider transformers={[legacyLogicalPropertiesTransformer]}>
        <MyApp />
      </StyleProvider>
    );
  2. Configure CSS Layers with LayerConfig

    master

    You can wrap your styles in CSS @layer using the layer option in useStyleRegister. This allows you to manage CSS specificity and ensure certain styles (like base or reset styles) are applied in a predictable order relative to component styles.

    export interface LayerConfig {
      name: string;
      dependencies?: string[];
    }

    When dependencies are provided, the library will inject @layer name, dependency1, dependency2; to establish the layer hierarchy.

    const layerConfig = {
      name: 'components',
      dependencies: ['reset', 'base'],
    };
  3. Use CSS Variables with @ant-design/cssinjs

    master

    The @ant-design/cssinjs library supports using CSS variables within its styling system. This allows for dynamic theme updates and easier integration with external CSS variable-based design systems. You can define styles that reference CSS variables (e.g., var(--my-color)) directly within the cssinjs functions.

    // Note: The actual implementation is located in ../examples/css-var.tsx
    // This demo demonstrates how to leverage CSS variables within the cssinjs workflow.
  4. Use logical properties transformer

    master

    The logicalProperties transformer allows you to convert physical CSS properties (like margin-left or padding-top) into logical properties (like margin-inline-start or padding-block-start). This is useful for supporting multi-directional layouts and internationalization (i18n) where text direction might change.

    // Example usage of logicalProperties transformer
    // Refer to ../examples/logicalProperties.tsx for implementation details
  5. Use px2rem transformer

    master

    The px2rem transformer automatically converts pixel (px) values into rem units. This is commonly used to implement responsive typography and spacing based on the root font size.

    // Example usage of px2rem transformer
    // Refer to ../examples/px2rem.tsx for implementation details
  6. Use StyleProvider to configure CSS-in-JS behavior

    master

    The StyleProvider component allows you to configure how styles are injected, cached, and transformed. It is the primary way to manage the CSS-in-JS context in your application.

    Props

    PropTypeDefaultDescription
    autoClearbooleanfalseClear inject style element when component remove.
    cacheCacheEntity-Config cssinjs cache entity. Only set when you need ssr to extract style on you own.
    hashPriority'low' | 'high''low'Use :where selector to reduce hashId css selector priority.
    containerElement | ShadowRootdocument.headTell cssinjs where to inject style in.
    ssrInlinebooleanfalseComponent will render inline <style /> for fallback in SSR. (Not recommended).
    transformersTransformer[]-Transform css before inject in document. Note: transformers do not support dynamic update.
  7. Extract styles with extractStyle

    master

    The extractStyle function extracts styles from a provided cache instance and returns them as a string. This is primarily used for SSR to collect styles generated during rendering.

    Parameters

    • cache (Cache): The cache instance containing the styles.
    • options (object | boolean, optional): Options for extracting the styles.
      • plain (boolean, optional): If true, the styles will be returned in plain format. Default is false.
      • types (string | string[], optional): The types of styles to extract. Default is ['style', 'token', 'cssVar'].

    Returns

    • string: The extracted styles as a string.
    import { extractStyle, createCache } from '@ant-design/cssinjs';
    
    // Create and populate cache
    const cache = createCache();
    // Note: In actual usage, the cache is typically populated automatically when rendering components
    
    // Extract styles
    const styles = extractStyle(cache, { plain: true, types: ['style', 'token'] });
    
    // Use the extracted styles
    const styleElement = document.createElement('style');
    styleElement.innerHTML = styles;
    document.head.appendChild(styleElement);
  8. Configure CSS variable transformation via useCacheToken

    master

    When using useCacheToken, the cssVar option controls how design tokens are converted into CSS variables. This is essential for implementing dynamic theming via CSS variables.

    OptionTypeDescription
    keystringRequired. A unique identifier for the current theme. Used to track and clean up styles.
    prefixstringA prefix applied to the generated CSS variable names.
    hashedbooleanIf true, the generated class name will include a hash.
    unitlessRecord<string, boolean>Specifies tokens that should not have units (like px or rem) appended.
    ignoreRecord<string, boolean>Specifies tokens that should be skipped during CSS variable transformation.
    preserveRecord<string, boolean>Specifies tokens that should retain their original value instead of being transformed.
    cssVar: {
      key: 'my-unique-theme-key',
      prefix: '--ant-',
      unitless: { borderRadius: true },
      ignore: { color: true },
      preserve: { fontSize: true },
      hashed: true,
    }
  9. Use useCSSVarRegister to register CSS variables

    master

    The useCSSVarRegister hook is used to transform design tokens into CSS variables and register them in the global cache. It handles the transformation of tokens (applying prefixes, unitless settings, or ignoring specific keys), generates a unique style ID, and injects the resulting CSS variable declarations into the DOM.

    Configuration Options

    When calling useCSSVarRegister, you provide a config object and a function fn that returns the original tokens.

    OptionTypeDescription
    pathstring[]A path array used to identify the style hierarchy.
    keystringThe unique key for this token set.
    prefixstring (optional)A prefix applied to the generated CSS variable names.
    unitlessRecord<string, boolean> (optional)A map specifying which token keys should have their units removed.
    ignoreRecord<string, boolean> (optional)A map specifying which token keys should be ignored during transformation.
    scopestring | string[] (optional)Defines the scope for the CSS variables.
    tokenanyThe token object, which must contain a _tokenKey property.
    hashIdstring (optional)An optional hash ID for class name generation.
    noncestring | (() => string) (optional)A CSP nonce for secure style injection.

    Return Value

    The hook returns a CSSVarCacheValue tuple containing:

    1. cssVarToken: The transformed token object containing CSS variable references.
    2. cssVarStr: The raw CSS variable string.
    3. styleId: The unique identifier for the injected style.
    4. cssVarKey: The key used for registration.
    const [cssVarToken, cssVarStr, styleId, cssVarKey] = useCSSVarRegister({
      path: ['some', 'path'],
      key: 'myTokenKey',
      prefix: 'myPrefix',
      token: { _tokenKey: 'tokenKey' },
      // ... other options
    }, () => originalTokens);
  10. Use Transformers to modify CSS

    master

    Transformers allow you to manipulate CSS objects during the styling process. The package exports several built-in transformers:

    • autoPrefixTransformer: Adds vendor prefixes to CSS properties.
    • legacyLogicalPropertiesTransformer: Converts logical properties to physical properties for older browser support.
    • px2remTransformer: Converts pixel values to rem units.