builder icon indicating copy to clipboard operation
builder copied to clipboard

Naive ui style cannot be used in webcomponent

Open luoliwoshang opened this issue 1 year ago • 0 comments

#34

chinese version issue

Requirement

A button in widget that uses the component library of the current spx-gui project.

Problem

The style can be applied normally in the project of vue, but after exporting to webcompoent through vite, the components of naive ui cannot use the style correctly. environment naive-ui 2.37.3 css-render 0.15.12

investigate

The rendering of the Naive ui component uses css in js's scheme, which relies on the library css-Render. When rendering a naiveui component,The method _ mixins_ 1.useTheme is called to generate the corresponding style tag based on the attributes of the component and insert it into the head tag of document

// spx-gui\node_modules\naive-ui\lib\button\src\Button.js

const Button = (0, vue_1.defineComponent)({
    name: 'Button',
    props: exports.buttonProps,
    setup(props) {
    ...
     const themeRef = (0, _mixins_1.useTheme)('Button', '-button', index_cssr_1.default, styles_1.buttonLight, props, mergedClsPrefixRef);
     ...
     }
}

In the implementation of useTheme, it uses the mount method provided by css-render, but the mount of css-render on which naive ui depends does not support mounting to shadow dom

 // node_modules\css-render\lib\mount.js
 function mount(instance, node, id, props, head, silent, force, anchorMetaName, ssrAdapter){
    ...
    if (anchorMetaName) {
        const anchorMetaEl = document.head.querySelector(`meta[name="${anchorMetaName}"]`);
        if (anchorMetaEl) {
            document.head.insertBefore(target, anchorMetaEl);
            addElementToList(node.els, target);
            return target;
        }
    }
    if (head) {
        document.head.insertBefore(target, document.head.querySelector('style, link'));
    }
    else {
        document.head.appendChild(target);
    }
    addElementToList(node.els, target);
    return target;
}

https://github.com/07akioni/css-render/pull/1105 mount to shadow dom is already supported under this pr, but css-render does realease this new feature

Possible solutions

  1. Modify the use-theme logic and use a custom use-theme in the project to replace the original css mount scheme https://github.com/tusen-ai/naive-ui/blob/main/src/_mixins/use-theme.ts
  2. When use a naiveui component in widget, not only mount it to the page, but also get its style from the component library and the current project, and mount it to shadow dom through the new version of css-render

luoliwoshang avatar Mar 05 '24 11:03 luoliwoshang