Git Product home page Git Product logo

cssinjs's Introduction

@ant-design/cssinjs

NPM version npm download dumi build status Codecov bundle size

Component level cssinjs solution used in ant.design. It's a subset of Emotion with design token logic wrapper. Please feel free to use emotion directly if you want to find a web cssinjs solution. cssinjs related dep packages:

  • stylis
  • @emotion/hash
  • @emotion/unitless

Live Demo

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

Install

npm install @ant-design/cssinjs

or

yarn add @ant-design/cssinjs
pnpm add @ant-design/cssinjs

Development

npm install
npm start

License

@ant-design/cssinjs is released under the MIT license.

API

StyleProvider

Prop Desc Type Default
autoClear Clear inject style element when component remove. boolean false
cache Config cssinjs cache entity. Only set when you need ssr to extract style on you own. CacheEntity -
hashPriority Use :where selector to reduce hashId css selector priority 'low' | 'high' 'low'
container Tell cssinjs where to inject style in. Element | ShadowRoot document.head
ssrInline Component wil render inline <style /> for fallback in SSR. Not recommend. boolean false
transformers Transform css before inject in document. Please note that transformers do not support dynamic update Transformer[] -

createCache

return CacheEntity for StyleProvider.

createTheme

Create theme object. When same algorithm provided, it will return same object.

Design Token related API

Since @ant-design/cssinjs use strong constraints for cache hit performance, we recommend to view demo basic.tsx for usage and animation.tsx for animation usage.

Transform

When you need transform CSSObject before inject style. You can use transformers to handle this:

import {
  legacyLogicalPropertiesTransformer,
  StyleProvider,
} from '@ant-design/cssinjs';

export default () => (
  <StyleProvider transformers={[legacyLogicalPropertiesTransformer]}>
    <MyApp />
  </StyleProvider>
);

Follow are the transform we provide:

legacyLogicalPropertiesTransformer

Convert logical properties to legacy properties. e.g. marginBlockStart to marginTop:

  • inset
  • margin
  • padding
  • border

px2remTransformer

Convert pixel units to rem units. px2remTransformer.options

cssinjs's People

Contributors

afc163 avatar caijf avatar chenshuai2144 avatar crazyair avatar dunqing avatar kiner-tang avatar madccc avatar wxh16144 avatar yoyo837 avatar zombiej avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

cssinjs's Issues

Overriding styles antd component on V5

I want to customize the styles of some antd components written in cssinjs.

I created a HOC component to access the theme and override some styles and call it after defining the providers

import { useToken, useStyleRegister } from 'antd/es/theme/internal'
import { prefixCls } from 'Src/constants'
import { ReactNode } from 'react'
import { CSSObject } from '@ant-design/cssinjs'
import { GlobalToken } from 'antd/es/theme/interface'



function getStyleButton(token: GlobalToken): CSSObject {
  return {
    [`.${prefixCls}-btn`]: {
      ['&-default']: {
        backgroundColor: 'transparent '
      }
    }
  }
}



export const OverloadStyle = (props: { children: ReactNode }) => {
  const [theme, token, hashId] = useToken()

  useStyleRegister(
    {
      theme,
      token,
      hashId,
      path: ['OverloadStyle']
    },
    () => [
      getStyleButton(token),
    ]
  )
  return <>{props.children}</>
}

but there was a problem with style priority
image

calling !important is not the best way

Uploading image.png…

how to make those styles which I define were below?
Or are there other more convenient ways to extend the standard styles?

https://stackoverflow.com/questions/75286685/overriding-styles-antd-component-on-v5

Uncaught RangeError: Invalid string length

The following line causes the string to become very large if there are a lot of tokens:

str += flattenToken(value);

Screenshot 2023-11-01 at 4 21 56 PM

If the string becomes too long, it would exceed the capacity of the runtime system and raise an Uncaught RangeError: Invalid string length error.

Prop `className` did not match.

Hi, I'm using nextjs@13 + antd@5.

And browser show this in devtool:

Warning: Prop `className` did not match. 

Server: "ant-menu-overflow ant-menu ant-menu-root ant-menu-horizontal ant-menu-dark css-dev-only-do-not-override-1dsa5t3" 

Client: "ant-menu-overflow ant-menu ant-menu-root ant-menu-horizontal ant-menu-dark css-dev-only-do-not-override-t98trl"

Which I think there are something wrong with this:

image

Setting hashPriority in ant design pro v6 project

Hello, i am using ant design pro v6 project with tailwind and antd5 but unfortunately there is conflict between them. I check antd homepage but they only give the solution for react project.
image
So I need help to find out where to config that one in the pro project.

Question - How to use this right?

I could not find any documentation of the usage of this interesting lib.

I have a bad code that tries to do the same (as much as I understand) that does cssinjs, but it throws some errors when there exist certain browser add-ons used. So the following is my code and I want to achieve the same behavior using the cssinjs. Please note that the token variable refers to the global token of the current theme. (Full code can be found here.)

for (let styleSheet of document?.styleSheets || []) {
    let rule: any;
    for (rule of styleSheet?.cssRules || styleSheet?.rules || []) {
        if (rule.selectorText === ".react-tel-input .country-list") {
            rule.style.boxShadow = token.boxShadow;
            rule.style.backgroundColor = token.colorBgElevated;
        }
        if (rule.selectorText === ".react-tel-input .selected-flag") {
            rule.style.borderColor = token.colorBorder;
        }
        if (rule.selectorText === ".react-tel-input .country-list .search") {
            rule.style.backgroundColor = token.colorBgElevated;
        }
        if (rule.selectorText === ".react-tel-input .country-list .country") {
            rule.style.borderRadius = token.borderRadiusOuter + "px";
        }
        if (rule.selectorText === ".react-tel-input .country-list .country-name") {
            rule.style.color = token.colorText;
        }
        if (rule.selectorText === ".react-tel-input .country-list .country .dial-code") {
            rule.style.color = token.colorTextDescription;
        }
        if (rule.selectorText === ".react-tel-input .country-list .country:hover") {
            rule.style.backgroundColor = token.colorBgTextHover;
        }
        if (rule.selectorText === ".react-tel-input .country-list .country.highlight") {
            rule.style.backgroundColor = token.colorPrimaryBg;
        }
        if (rule.selectorText === `:where(.${inputCls}).ant-input`) {
            rule.selectorText += "\n,.react-tel-input .country-list .search-box";
            rule.style.backgroundColor = token.colorBgElevated;
        }
        if (rule.selectorText === `:where(.${inputCls}).ant-input:hover`) {
            rule.selectorText += "\n,.react-tel-input .country-list .search-box:focus";
            rule.selectorText += "\n,.react-tel-input .country-list .search-box:hover";
        }
    }
}

So this part of the code tries to make the existing stylesheets of the third-party dependency use the antd theme color scheme. And the question is can the cssinjs replace this code to achieve this behavior and if so, how?

P.S. I have tried to create a custom transformer, but it does not contain the stylesheets of the third-party dependencies.

const transform = (token) => ({
    visit: (rule) => {
        // Manipulate the rule object
        return rule;
    }
})

Will appreciate any kind of help!

Missing effect style while mount/unmount due to globalEffectStyleKeys

related: ant-design/ant-design#38911

A web component could be mount/unmount for multiple times. During when the actual dom could be created/recreated many times.

In such case, due to the cache mechanism: useStyleRegister.tsx#L386, some styles(particularly keyframes) are not able to be injected into the newly created dom element.

One way to solve this, is to use _cf, but obviously its not for production


Purpposal:

  1. expose _cf in some way
  2. execute some tear down actions during unmount phase

Content Security Policy - Nonce not set

Hi, I'm using the ant.design. In the config I have set up:

<ConfigProvider
  csp={{ nonce: `${process.env.REACT_APP_GENERATED_NONCE_VALUE}` }}
>              
<Code />
</ConfigProvider>

dynamicCSS.js:73 : Refused to apply inline style because it violates the following Content Security Policy directive:
"style-src 'self' 'nonce-CODE'".

How can I fix this issue?

Support for Web Components

Hello,

will there be an option to customize where the styles will be injected at runtime by the CSS-in-JS implementation?

We are currently using Antd v4 within Web Components to author micro frontends. Each micro frontend is a separate Web Component which internally uses a number of Antd components. We're using shadow DOM to isolate the styles of the different micro frontends.

I briefly looked through the code in this repository. If I understood the code correctly, the styles will currently be injected into the head of the document? This would break our approach to micro frontends as the Antd styles wouldn't be able to penetrate into the shadow DOM of our Web Components.

From my very basic understanding, it may be simple to add that feature. However, I am unaware of any constraints related to SSR.

The updateCSS function from rc-util already provides a way to override the HTML element where the styles will be injected using the attachTo option. Also, the StyleProvider already checks whether there is a parent StyleContext present. By providing a parent StyleContext in the application code it could be possible to implement a mechanism to override the HTML element where the styles will be injected:

  export interface StyleContextProps {
    autoClear?: boolean;
    mock?: 'server' | 'client';
    cache: CacheEntity;
    defaultCache: boolean;
+   attachTo: Element;
  }

Since Antd v4 isn't compatible with React 18, we will have to upgrade Antd v5 eventually. We would greatly appreciate it if there could be a solution to this problem.

Kind regards,
Felix Schorer

可以添加一个hashPrefix属性能自定义前缀吗

// Generate different prefix to make user selector break in production env.
// This helps developer not to do style override directly on the hash id.
var hashPrefix = process.env.NODE_ENV !== 'production' ? 'css-dev-only-do-not-override' : 'css';

demo/eg ghostButtonStyle merge

in page /docs/examples/components/Button.tsx.
maybe genSolidButtonStyle function can be applied to all buttonStyle.

pull request: #62

在umi4的项目上向后兼容样式出现了报错(360上用antd5样式错乱)

packages:
"@ant-design/cssinjs": "^1.5.0",
"antd": "^5.1.1",
"umi": "^4.0.41"

参考:https://ant-design.antgroup.com/docs/react/compatible-style-cn#css-%E9%80%BB%E8%BE%91%E5%B1%9E%E6%80%A7

use:
// src/layouts/index.tsx
return (


<Context.Provider value={contextValue}>

</Context.Provider>


);

err:

  • The above error occurred in the component:
  • Uncaught TypeError: Cannot read properties of null (reading 'useContext')
  • Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons

Antd CSS-in-js performance comparison with styled-components and Emotion

CSS-in-Js performance testing

The data presents a comparison of the performance of three CSS-in-JS libraries: Styled Components, Emotion, and Antd (cssInJS). The performance is measured in two ways, the percentage of components that are successfully rendered and the total blocking time.

In terms of the percentage of components that are successfully rendered, the results are similar for the three libraries. As the number of components increases, the performance decreases for all three libraries. Styled Components and Emotion have a relatively higher performance compared to Antd cssInJS, especially at lower component numbers. For example, when the number of components is 10, Styled Components and Emotion have a performance of 97% and 96% respectively, while Antd cssInJS has a performance of only 90%.

In terms of total blocking time, the results show a clear difference between the three libraries. As the number of components increases, the total blocking time of Styled Components and Emotion increases at a slower pace compared to Antd cssInJS. For example, when the number of components is 200, the total blocking time of Styled Components is 350, Emotion is 450, while Antd cssInJS is 2450. This suggests that Styled Components and Emotion might be more suitable options for projects that require low total blocking time.

Total blocking time of Styled Components and Emotion also increases with increasing component numbers. At the highest number of components (5000), the total blocking time of Styled Components is 4540, Emotion is 5500, while Antd cssInJS's total blocking time is not possible to calculate.

PR: SmashTaps/css-in-js-solution-evaluation#1 (comment)

Performance testing copy

React version : "^18.2.0"
AntD version : "^5.1.6"
Emotion : "^11.10.5"
Styled-component version : ^5.3.6"

Tested PC

Processor 11th Gen Intel(R) Core(TM) i5-11300H @ 3.10GHz 2.61 GHz
Installed RAM 16.0 GB
System type 64-bit operating system, x64-based processor

Antd5 not support ssr for turbo monerepo nextjs?

Reproduction link
https://github.com/AsuraLuo/Turbo-Nextjs-Antd-Ecommerce

Steps to reproduce
https://github.com/AsuraLuo/Turbo-Nextjs-Antd-Ecommerce

import Document, { Html, Head, Main, NextScript } from 'next/document'
import { createCache, extractStyle, StyleProvider } from '@ant-design/cssinjs'
import { Helmet } from 'react-helmet'

interface HeadlessProps {
  helmet: any
}

class HeadlessDocument extends Document<HeadlessProps> {
  get helmetHtmlAttrComponents() {
    return this.props.helmet.htmlAttributes.toComponent()
  }

  get helmetBodyAttrComponents() {
    return this.props.helmet.bodyAttributes.toComponent()
  }

  get helmetHeadComponents() {
    return Object.keys(this.props.helmet)
      .filter((el) => el !== 'htmlAttributes' && el !== 'bodyAttributes')
      .map((el) => this.props.helmet[el].toComponent())
  }

  render(): JSX.Element {
    return (
      <Html {...this.helmetHtmlAttrComponents}>
        <Head>{this.helmetHeadComponents}</Head>
        <body {...this.helmetBodyAttrComponents}>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

// It's compatible with static-site generation (SSG).
HeadlessDocument.getInitialProps = async (ctx) => {
  // Resolution order
  //
  // On the server:
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. document.getInitialProps
  // 4. app.render
  // 5. page.render
  // 6. document.render
  //
  // On the server with error:
  // 1. document.getInitialProps
  // 2. app.render
  // 3. page.render
  // 4. document.render
  //
  // On the client
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. app.render
  // 4. page.render
  const cache = createCache()
  const originalRenderPage = ctx.renderPage

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: (App) => (props) =>
        (
          <StyleProvider cache={cache}>
            <App {...props} />
          </StyleProvider>
        )
    })

  const initialProps = await Document.getInitialProps(ctx)
  // Generate the css string for the styles coming from jss
  const css = extractStyle(cache)

  return {
    ...initialProps,
    styles: (
      <>
        {initialProps.styles}
        <style
          id="jss-server-side"
          key="jss-server-side"
          dangerouslySetInnerHTML={{ __html: css }}
        />
      </>
    ),
    helmet: Helmet.renderStatic()
  }
}

export default HeadlessDocument
import { Button } from 'antd'   // SSR CSS Working
import { Button } from '@ecommerce/ui' // SSR CSS Not Working

Missing condition to check if body is loaded at `StyleContext.tsx`

Hello,
We are converting our React components to WebComponents (with AntDesign 4 everything worked fine). We've upgraded to V5, and when we build the React components then we include the built file in our sites written in pure HTML (included in the <head>).
But as in the screenshot below, an error is detected. I think the condition in file src/StyleContext.tsx:13 is missing the document.body check, this will avoid some issues in the future, as V5 of antd has just been released.
I thank you for your work, and for the correction that you could bring 🙏.

Capture d’écran 2022-11-16 à 16 00 01

Capture d’écran 2022-11-16 à 16 00 20

renderToPipeableStream compatible solution

https://ant.design/docs/react/customize-theme#server-side-render-ssr currently suggests using renderToString - and for good reason. It requires the entire page to be rendered to correctly extract the CSS.

renderToPipeableStream means there are pieces of the page incrementally streaming. Therefore, the styles needed must suspend to stream as well - otherwise you're stuck waiting for the entire page to load to stream the extractStyle (which causes a flash of unstyled content), or if you put it too early you miss some of the css entirely.

Instead of extractStyles, you could have a component called Styles that you render in your renderToPipeableStream

function Document({children}) {
  return (
    <html>
      <head>
        <meta charSet={charSet} />
        <Styles />
        <title>{title}</title>
      </head>
      <body>
        <div id={rootId}>{children}</div>
      </body>
    </html>
  );
}

The key to making a suspending component work correctly is the https://reactjs.org/docs/hooks-reference.html#usesyncexternalstore api as this will still cause "re-renders" during SSR streaming.

v1.3.1 loads the styles after page load in Next.js making the page look unstyled for a split second

(I also left the same comment here, on the AntDesign 5 release issue)


Does anyone have problems with the new release of AntDesign's cssinjs(v1.3.1) in Next.js?

It seems the page loads without any styles and after a split second, the page loads the styles and everything is ok. But it's really annoying to see that split second of an un-styled app 😢 I still have a yarn.lock file with cssinjs v1.1.0 and I created this video to show the difference (pay attention at the reload button to see when I refresh the page):

Before (using a yarn.lock file that requires cssinjss v.1.1.0):

Screen.Recording.2022-12-28.at.17.08.37.mov

After (using the latest version of AntDesign which comes with cssinjs v.1.31):

Screen.Recording.2022-12-28.at.17.07.17.mov

In case anyone wants to test this, here is the info from the yarn.lock file that sets the version for cssinjs:

// when you want to use cssinjs v1.1.0:
"@ant-design/cssinjs@^1.0.0":
  version "1.1.0"
  resolved "https://registry.npmjs.org/@ant-design/cssinjs/-/cssinjs-1.1.0.tgz"
  integrity sha512-9kfWCnlcWZLMc184HL7zGUU3odKo/5HBMNxDxhSds2DoIzi/ojmmOU1A1butWVDSPcAbLyNQ85vxUI8mkkHrlA==
  dependencies:
    "@babel/runtime" "^7.11.1"
    "@emotion/hash" "^0.8.0"
    "@emotion/unitless" "^0.7.5"
    classnames "^2.3.1"
    csstype "^3.0.10"
    rc-util "^5.24.2"
    stylis "^4.0.13"
// when you want to use cssinjs v1.3.1:
"@ant-design/cssinjs@^1.0.0":
  version "1.3.1"
  resolved "https://registry.yarnpkg.com/@ant-design/cssinjs/-/cssinjs-1.3.1.tgz#45967a0ef93188a336532087f97ee09d30f8cf51"
  integrity sha512-lFy/DhxH/fMaYaMRTaUBLkgoQHgmD56cMeEemqjkcBfk0zzUje11elx8LsqYquJ3okTUdmQTWxDSeG6gQ+S8Lg==
  dependencies:
    "@babel/runtime" "^7.11.1"
    "@emotion/hash" "^0.8.0"
    "@emotion/unitless" "^0.7.5"
    classnames "^2.3.1"
    csstype "^3.0.10"
    rc-util "^5.24.2"
    shallowequal "^1.1.0"
    stylis "^4.0.13"

内置的transform方法在处理calc时有可能清掉空格导致出错

🐛 bug 描述
内置的transform方法在处理样式时,遇到'()'时会根据空格分组处理然后合并,合并时会丢失空格,导致calc语法出错,具体出错如下:
image

📷 复现步骤
将example/logicalProperties中的paddingInline值修改为calc语法即可复现
image

🏞 期望结果
transform方法能够正确处理calc语法

💻 修复方法
是否可以使用数组保存中间状态
image

How to use antd/cssinjs to define custom classname

What problem does this feature solve?

In experimental version I noticed that there is a long-awaited support for JSS. Unfortunately, it is unclear how to use antd JSS implementation to define custom classNames like in react-jss. I see in the code, that useStyle hook is used const [wrapSSR, hashId] = useStyle(prefixCls);, but it returns a wrapper for the component, when I need an object with css class names. Is there a way to do so with your lib?

What does the proposed API look like?

see above

NextJS 14 Flicker CSS Issue

I think the library need to adapt NextJS 14.

'use client'

import React from 'react'
import { createCache, extractStyle, StyleProvider } from '@ant-design/cssinjs'
import type Entity from '@ant-design/cssinjs/es/Cache'
import { useServerInsertedHTML } from 'next/navigation'

const StyledComponentsRegistry = ({ children }: React.PropsWithChildren) => {
  const cache = React.useMemo<Entity>(() => createCache(), [])
  useServerInsertedHTML(() => (
    <style id="antd" dangerouslySetInnerHTML={{ __html: extractStyle(cache, true) }} />
  ))
  return <StyleProvider cache={cache}>{children}</StyleProvider>
}

export default StyledComponentsRegistry

The flicker still happening after implementing this guide from antd design documentation. When I tried to downgrade to NextJS 13, it works. The flicker css only happens on NextJS 14.

pro-components 里StyleProvider hashPriority='high' 会失效

🐛 bug 描述

pro-components 导致 StyleProvider hashPriority='high' 失效,使用tailwindcss后在layout里面的button就有问题,外边的正常

📷 复现步骤

codesandbox

🏞 期望结果

在pro-components 组件内的 样式也正常

💻 复现代码

https://codesandbox.io/p/github/faner11/react-antd/draft/goofy-solomon?file=%2Fsrc%2Fmain.tsx

© 版本信息

  • "@ant-design/pro-components": "^2.3.58"
  • "antd": "^5.2.3"
  • "@ant-design/cssinjs": "^1.6.0",

image

我在pro-components库提过这个问题,他们给的方案并不能解决问题
ant-design/pro-components#6681

How to use ant theme object inside styled components from emotion

How to use ant theme object inside styled components from emotion like Mui?
Normally I do it in Mui like

import { Theme as MuiTheme } from "@mui/material/styles";

declare module "@emotion/react" {
  export interface Theme extends MuiTheme {}
}

and access theme variable inside styled components like

import styled from "@emotion/styled";

export const StyledDiv = styled.div`
    .MuiToggleButtonGroup-root {
        ${({ theme }) => theme.breakpoints.down("md")} {
          flex-wrap: wrap;
        }
    
        .MuiButtonBase-root {
            background-color: ${({ theme }) => theme.palette.common.white};
            color: ${({ theme }) => theme.palette.custom.greyChateau};
        }
    }
`

How I will get theme object in Ant-design cssinjs solution?

How to customize components styles?

According to UI design I want to add some specific styles to ant components. I found that I can not do it with tokens, because tokens has limited list of properties. Thats why I need another approach.
According to the documentation it is unclear how to add custom styles to components. Can you provide examples?

使用 legacyLogicalPropertiesTransformer ProLayout aside组件submenu样式显示出现问题

packages:
"@ant-design/cssinjs": "^1.5.6",
"@ant-design/pro-components": "^2.3.57",
"antd": "^5.2.2",

image

image

use:

import { ConfigProvider, theme } from 'antd';
import { legacyLogicalPropertiesTransformer, StyleProvider } from '@ant-design/cssinjs';
import zhCN from 'antd/locale/zh_CN';
import enUS from 'antd/locale/en_US';
import { PRIMARY_ACTIVE_COLOR, PRIMARY_COLOR } from '@/constants/color';

const ANTDLocaleMap = {
  'zh-CN': zhCN,
  'en-US': enUS,
};

export default function AntdConfigProvider({
  language,
  children,
}: {
  language: string;
  children: React.ReactElement;
}) {
  return (
    <ConfigProvider
      theme={{
        token: {
          colorPrimary: PRIMARY_COLOR,
          colorLink: PRIMARY_COLOR,
          colorLinkHover: PRIMARY_ACTIVE_COLOR,
          colorLinkActive: PRIMARY_ACTIVE_COLOR,
          colorBgLayout: '#fff',
        },
        components: {
          Layout: {
            colorBgHeader: 'linear-gradient(180deg, #248668, #11604D)',
            colorText: '#fff',
            controlHeight: 60,
          },
          Tree: {
            colorText: PRIMARY_COLOR,
          },
        },
        algorithm: theme.defaultAlgorithm,
      }}
      locale={ANTDLocaleMap[language]}
      componentSize="middle"
      virtual
    >
      <StyleProvider transformers={[legacyLogicalPropertiesTransformer]}>{children}</StyleProvider>
    </ConfigProvider>
  );
}

Cache singleton causes problems with multi-StyleProvider apps (or WebComponents)

We use Lit WebComponents to structure our Micro/UI-Composition "widgets".
In ant 4 we injected our styles and overrides in each WC´s head.
The new StyleProvider however provides us with a convenient component={Element} props.

But when instantiating the WebComponent multiple times we see that Ant reuses the Context config and injects the style only in the first component (e.g. the config is a singleton).

Expected:
The CSS to be injected in the specified Element as specified for each element (in our case each WC's shadowroot).

Actuall:
Injected in the first provided Element and ignoring the additional configs.

Repro:
https://stackblitz.com/edit/react-ts-isblup?file=index.tsx,index.html

Similar to #28

@felixschorer Did you not come across this problem?

prependQueue style 样式丢失

我的 chrome 插件(用的 plasmo 框架)有两个 shadowDom 的 content_script 注入,其中随机的出现部分 antd 样式丢失,比如 ant-tooltip

image 发现所在的 shadowRoot 中相关的 style 标签为空了 image

而同一个页面另外个 shadowRoot 正常:
image
对应的 style 标签内容正常:
image

两个 shadowRoot 的 StyleProvider 写法也没区别:

<StyleProvider container={document.getElementById(SEARCH_ENHANCE_ID).shadowRoot}>

<StyleProvider container={document.getElementById(HOST_ID).shadowRoot}>

依赖版本:
"@ant-design/cssinjs": "^1.10.1",
"antd": "^5.6.3",

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.