ant-design / cssinjs

https://ant-design.github.io/cssinjs
MIT License
237 stars 59 forks source link

feat: Components level cssinjs #1

Closed zombieJ closed 2 years ago

zombieJ commented 2 years ago

πŸ”₯ Summary

To reduce v4 less style migration cost. We want to provide a light-way cssinjs resolution. Which keep the origin style structure as less and resolve micro-app style conflict.

🀿 Motivation

As research of emotion.js, its strong cssinjs resolution. To enable light-way migration purpose, we use stylis @emotion/hash @emotion/unitless and mix them with component specific library.

🎰 Preview

https://cssinjs-git-cssinjs-ant-design.vercel.app/

🐚 Usage

Follow the docs/examples/components/theme.tsx. Here is the simple example:

Generate Design Token

Use @ant-design/cssinjs to create a customize design token:

export interface DesignToken {
  primaryColor: string;
}

And define the derivative token:

export interface DerivativeToken extends DesignToken {
  primaryColorDisabled: string;
}

Define the algorithm:

import { TinyColor } from '@ctrl/tinycolor';

function derivative(designToken: DesignToken): DerivativeToken {
  return {
    ...designToken,
    primaryColorDisabled: new TinyColor(designToken.primaryColor)
      .setAlpha(0.5)
      .toString(),
  };
}

Now you can get the merged token with default token and customize token:

import { Theme } from '@ant-design/cssinjs';

const theme = new Theme(derivative);
const defaultDesignToken: DesignToken = {
  primaryColor: '#1890ff',
};

// Get merged token
const [token] = useCacheToken(theme, [defaultDesignToken, someCustomizeToken]);

Use Token in Component

Generate style by token:

import { CSSInterpolation } from '@ant-design/cssinjs';

const genSpinStyle = (
  prefixCls: string,
  token: DerivativeToken,
): CSSInterpolation => ({
    [`.${prefixCls}`]: { // Different with other cssinjs solution. We need pass `prefixCls` here.
      backgroundColor: token.primaryColor,
  },
});

Use in component:

import { useStyleRegister } from '@ant-design/cssinjs';

const Spin = ({ prefixCls = 'ant-spin', className, ...restProps }: SpinProps) => {
  // Simple code. It should use context in real world
  const [token] = useCacheToken(theme, [defaultDesignToken, someCustomizeToken]);

  // Register global style
  useStyleRegister({ theme, token, path: [prefixCls] }, () => [
    genSpinStyle(prefixCls, token),
  ]);

  return (
    <div className={classNames(prefixCls, hashId, className)} {...restProps} />
  );
};
vercel[bot] commented 2 years ago

This pull request is being automatically deployed with Vercel (learn more).
To see the status of your deployment, click below or on the icon next to each commit.

πŸ” Inspect: https://vercel.com/ant-design/cssinjs/Ht4fg5WF44rJaAN28vcRbYUCCc5M
βœ… Preview: https://cssinjs-git-cssinjs-ant-design.vercel.app

zombieJ commented 2 years ago

ζ–‡ζ‘£εŽθ‘₯

zqran commented 1 year ago

🎰 Preview

https://cssinjs-git-cssinjs-ant-design.vercel.app/

link 404