Is there any way to edit CSS/JS of WebComponent? - javascript

I am a web developer and recently started working with Ionic 4 which is based on Web Component. I was trying to edit the CSS of the components but I was not able to edit the same and later on figured out that it was because of Web-Components which do have #shadow-root.
My Question is, Is there any way to edit the CSS and JS of a Web Component.
If not, why is it there?
The drawbacks of the same according to me are:
- Not able to apply the custom CSS into the child components of the Component.
- Plugins like Stylus will be useless as the CSS won't be applied and we won't be able to get the dark mode.

The Component Author decides the level of styling that can be applied.
no #shadow-root
All global CSS applied
all children are part of the main document DOM
ShadowDOM created with this.attachShadow({mode:"open"})
No global CSS applied
CSS Properties (if used by the Component author) are applied
You can access the shadowRoot and overwrite everything inside
(this is like buying an IKEA table and putting a saw in it)
shadowDOM created with this.attachShadow({mode:"closed"})
No global CSS applied
CSS Properties (if used by the Component author) are applied
You can not access the shadowRoot
Documentation
source: https://developers.google.com/web/fundamentals/web-components/shadowdom
TL;DR
Shadow DOM removes the brittleness of building web apps. The
brittleness comes from the global nature of HTML, CSS, and JS. Over
the years we've invented an exorbitant number of tools to circumvent
the issues. For example, when you use a new HTML id/class, there's no
telling if it will conflict with an existing name used by the page.
Subtle bugs creep up, CSS specificity becomes a huge issue (!important
all the things!), style selectors grow out of control, and performance
can suffer. The list goes on.
Shadow DOM fixes CSS and DOM. It introduces scoped styles to the web
platform. Without tools or naming conventions, you can bundle CSS with
markup, hide implementation details,
and author self-contained components in vanilla JavaScript.
Read all about styling components:
https://developers.google.com/web/fundamentals/web-components/shadowdom#styling
(not a standard yet) https://developers.google.com/web/updates/2019/02/constructable-stylesheets

Related

Why cant I customize the styling of web component libraries, beyond themes? saps UI5

Why can't I customize the styling of web component libraries i.e UI5, beyond themes? I have tried everything from inline styling to wrapping the web components in Styled-components. I tried using :host(), ::slott. I've tried to inject style tags into the template itself. I'm really at a loss, I wasn't able to change one pixel of styling. I'm leaning towards the issue being multiple shadow dom or encapsulated CSS.
<TabContainer backgroundDesign={"red"} ref={ToggleRef} className={`webCompToggleTabBar`} id="UI5TabContainer" tabs-overflow-mode="StartAndEnd" collapsed fixed>
{Object.keys(Tabs).map((subTemplate, i) => {
return (<Tab className="webCompToggleTab" key={Math.random()} additional-text={subTemplate} name={subTemplate} />);
</TabContainer>
Now the outer Tabcontainer is easilystyled with any type of styling, but when I attempt to style any of the tabContainer's inner Tabs...crickets
Just for clarity, I am building a lit-html wrapper around pre-built web-component libraries to work with React and Angular. But I need to be able to restyle the imported web-components
so the issue with styling web components from freely available libraries are:
Web components are usually created using the shadowDOM, this is great for
encapsulation. But when you want to go back in and try to override that
encapsulation and completely overwrite the web components CSS. You will
get stuck in the top layer of the web component, just outside it's shadowDOM(if there using it). With some libraries,
this is done on purpose, others allow you to do this but you may have
to fork over some hefty cash to use those libraries.
Fortunately, there are some things you can do to spice up the web-
components. CSS variables, A lot of libraries build CSS variables into
their components for theming. So one thing you can do is find their list of CSS variables either on their Documents page or in the elements tab in your browser and just cut and paste them
in.
If this is not enough for you there is another option.
You can create your own web components in a way very similar to
creating them in ReactJS. There is a tool called Stencil which
gives you a way to create web component using typescript and CSS.
Stencil solved all my issues, it has all the polyfills built in.
It sets up all your testing and deploying. https://stenciljs.com/

Extjs default class properties

I came across a defualt class called 'x-btn-over' on Extjs which is triggered on a mouse hover. I wanted to ask what the default properties of this class is? Also where can I find all the list of these built-in classes. The docs doesn't seem to cover these properties. Thanks
These css classes are generated when the application is built. It's not documented because it is not recommended to use them for styling ExtJS apps (though you can guess them by using an inspector tool like "Inspect Element" in Chrome dev tools). Although nothing would stop you to use these css classes in scss files and manually created stylesheets, and personally I use it sometimes when I want to do a quick and dirty solution, it should be avoided because chances are these values could be changed or removed in a new version of the framework.
The ExtJS framework has its own theming system.
The scss variables are usually documented in the "Theme Variables" section of a component. For example: Button theme variables
To find "over" related scss variables filter the properties with "over" and scroll down to the "Theme variable" section:

How do Web Components and the Shadow DOM prevent leaky CSS across components?

In 2008 our team investigated GWT - a technology for writing web components for Javascript in Java which would compile down.
A new member of the team said:
You will have a problem with the CSS of the component and the page clashing with each other.
It turned out he was correct.
I was having a conversation with a friend today about Web Components. I asked him how you stop the CSS of the page and the components clashing with each other.
He said:
With Web Components and the Shadow DOM it is all under control. It solves the problem of leaky CSS.
My question is: How do Web Components and the Shadow DOM prevent leaky CSS across components?
Because Shadow DOM was designed precisely to solve problems met when developping Web Components, as stated by Google in the introduction to Shadow DOM:
Isolated DOM: A component's DOM is self-contained (e.g. document.querySelector() won't return nodes in the component's shadow DOM).
Scoped CSS: CSS defined inside shadow DOM is scoped to it. Style rules don't leak out and page styles don't bleed in.
Simplifies CSS - Scoped DOM means you can use simple CSS selectors, more generic id/class names, and not worry about naming conflicts.
It is achieved by CSS Scoping with the introduction of a new, separate DOM tree called the Shadow DOM, that will locally replace the initial DOM called the Light DOM.

Which parts should go in the shadow DOM and the light DOM?

I'm learning web components. When designing a custom element, I have to decide what is going to be hidden in the the shadow DOM. The remainder will then be exposed in the light DOM.
As far as I understand, the APIs allow two extreme use cases with different tradeoffs:
hide almost nothing in the shadow DOM, most of the element's content is in the light DOM and in the element's attributes:
this allows an HTML author to provide anything for the component to display without writing JS;
this is close to the status quo regarding searchability and accessibility
but there is little reward for the work involved; I add complexity with components but they don't encapsulate anything (everything is exposed).
hide almost everything in the shadow DOM, the element's innerHTML is empty:
this requires the element to be instantiated from JS;
this locks usage a lot more because instantiating from JS is more strict (type-wise) than using HTML slots and attributes;
this may be less searchable and accessible (I'm not sure whether this is the case);
I currently lean toward hiding everything in the shadow DOM for the following reasons:
I intend to instantiate everything from JS. I'm not going to author pages in HTML manually. It would be more work to code both an HTML API and a JS API.
It's less cognitive work to hide everything. I don't need to find a right balance about which information is visible in the light DOM.
It's closer to most JS frameworks I'm familiar with.
Am I missing something?
Edit
Thank you, I am answered that it depends on the use case which partially answers my question. But I'm still missing an answer regarding the case I'm in: I'd rather not support slots for some of my components.
I'll add an example for each extreme of the spectrum:
Light-DOM-heavy component: the component user has to insert elements into slots
<template id=light-email-view>
<div>
<div><slot name=from></slot></div>
<ul><slot name=to></slot></ul>
<h1><slot name=subject></slot></h1>
<div><slot name=content></slot></div>
<ul><slot name=attachements></slot></ul>
<div class=zero-attachment-fallback>no attachments</div>
</div>
</template>
Shadow-DOM-heavy component: the component user has to use the JS API
<template id=shadow-email-view>
<div></div>
</template>
<script>
...
let view = document.createElement('shadow-email-view');
// this method renders the email in the shadow DOM entirely
view.renderFromOject(email);
container.appendChild(view);
</script>
In the first example, the component author has more work to do since they need to "parse" the DOM: they have to count attachments to toggle the fallback; basically, any transformation of input that isn't the browser copying an element from the light DOM into the matching shadow DOM slot. Then they need to listen for attribute changes and whatnot. The component user also has more work, they have to insert the right elements into the right slots, some of them non-trivial (the email content may have to be linkified).
In the second example, the component author doesn't need to implement support for instantiating from HTML with slots. But the component user has to instantiate from JS. All the rendering is done in the .renderFromObject method by the component author. Some additional methods provide hooks to update the view if needed.
One may advocate for a middle ground by having the component offer both slots and JS helpers to fill those. But I don't see the point if the component isn't to be used by HTML authors and that's still more work.
So, is putting everything with the shadow DOM viable or should I provide slots because not doing so isn't standard compliant and my code is going to break on some user agent expecting them (ignoring older UAs that are not at all aware of custom elements)?
#supersharp has nailed it.
One thing I see with Web Components is that people tend to have their component do way too much instead of breaking into smaller components.
Let's consider some native elements:
<form> there is no shadow DOM and the only thing it does is read values out of its children form elements to be able to do an HTTP GET, POST, etc.
<video> 100% shadowDOM and the only thing it uses the app supplied children for is to define what video will be playing. The user can not adjust any CSS for the shadow children of the <video> tag. Nor should they be allowed to. The only thing the <video> tag allows is the ability to hide or show those shadow children. The <audio> tag does the same thing.
<h1> to <h6> No shadow. All this does is set a default font-size and display the children.
The <img> tag uses shadow children to display the image and the Alt-Text.
Like #supersharp has said the use of shadowDOM is based on the element. I would go further to say that shadowDOM should be a well thought out choice. I will add that you need to remember that these are supposed to be components and not apps.
Yes, you can encapsulate your entire app into one component, but the browsers didn't attempt to do that with Native components. The more specialized you can make your components to more reusable they become.
Avoid adding anything into your Web Components that is not vanilla JS, in other words, do not add any framework code into your components unless you never want to share them with someone that does not use that framework. The components I write are 100% Vanilla JS and no CSS frameworks. And they are used in Angular, React and vue with no changes to the code.
But chose the use of shadowDOM for each component written. And, if you must work in a browser that does not natively support Web Components that you may not want to use shadowDOM at all.
One last thing. If you write a component that does not use shadowDOM but it has CSS then you have to be careful where you place the CSS since your component might be placed into someone else's shadowDOM. If your CSS was placed in the <head> tag then it will fail inside the other shadowDOM. I use this code to prevent that problem:
function setCss(el, styleEl) {
let comp = (styleEl instanceof DocumentFragment ? styleEl.querySelector('style') : styleEl).getAttribute('component');
if (!comp) {
throw new Error('Your `<style>` tag must set the attribute `component` to the component name. (Like: `<style component="my-element">`)');
}
let doc = document.head; // If shadow DOM isn't supported place the CSS in `<head>`
// istanbul ignore else
if (el.getRootNode) {
doc = el.getRootNode();
// istanbul ignore else
if (doc === document) {
doc = document.head;
}
}
// istanbul ignore else
if (!doc.querySelector(`style[component="${comp}"]`)) {
doc.appendChild(styleEl.cloneNode(true));
}
}
export default setCss;
The choice is 100% dependent on the use case.
Also:
if you want the user to be able to format your custom element with global CSS style attributes, you may opt for the normal, light DOM.
you're right: in the Shadow DOM, "this may be less searchable": the document.querySelector() method won't inspect the Shadow DOM content.
as a consequence, some third-pary JS library may fail to integrate easily with Shadow DOM
if you intend to use a Custom Element polyfill for legacy browsers, you may avoid Shadow DOM because some of its features cannot be really polyfilled.
in many cases, the answer is to provide a mix of Light DOM and Shadow DOM. As suggested by #JaredSmith:
Shadow DOM for the Web Component author,
Light DOM for the Web Compoent user, intergrated in the Shadow DOM with <slot>.
As a conclusion, you should consider the context in which your Web Component will be used to decide whether Shadow DOM is required or not.
Answer to the Edit
Considering your use case, I would create a custom element and:
let the user populate the light DOM with atomic value(s): type element <div class="mail-to"> or custom sub-components <mail-to> as suggested by #Intervalia,
use a Shadow DOM to mask the light DOM,
use Javascript: this.querySelectorAll('.mail-to') or this.querySelectorAll('mail-to') instead of <slot> to extract data from the light DOM and copy (or move) them to the Shadow DOM.
This way users won't have to learn the <slot> working, and the developer will be able to format the web component rendering with more freedom.
<email-view>
<mail-to>guillaume#stackoverflow.com</mail-to>
<mail-to>joe#google.fr</mail-to>
<mail-from>supersharp#cyber-nation.fr</mail-from>
<mail-body>hello world!</mail-body>
<email-view>
Alright. Setting aside for a moment that I think this is a bad questionable idea, here's some code that should do what you want (I didn't run it, but it should work):
class FooElement extends HTMLElement {
constructor () {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(document.importNode(template.content, true));
}
_xformObject (object) {
// turn the obj into DOM nodes
}
renderFromObject (object) {
// you may need to do something fancier than appendChild,
// you can always query the shadowRoot and insert it at
// a specific point in shadow DOM
this.shadowRoot.appendChild(this._xformObject(object));
}
}
You'll have to register the custom element of course.
Now sometimes you really can't get away from doing something like this. But it should be the absolute last resort. See below:
Why I think this is a bad questionable idea, and how to make it better:
One of the main draws to web components is that it enables declarative HTML markup rather than procedural JS DOM manipulations. While providing an API like what you're talking about is certainly a big step up from e.g. creating a table by creating a table node, creating a row node, creating some tds, appending them to the row, then appending that to the table, I (and I think most) developers are of the idea that if your custom element requires direct JavaScript manipulation by the user, then it's not really an HTML element: it's a JavaScript interface.
Let me qualify that a little. When I say "requires" JavaScript I mean there's no way to drop it on the page with some appropriate attributes and wind up with the thing you want. When I say "direct" I mean by calling methods of the object representation of the element directly rather than say toggling an element attribute. To put my point in code:
// good
myCustomElement.setAttribute("toggled-on", true);
// this isn't *bad*, but don't *force* people to do this
myCustomElement.toggleState();
You may want to still provide the second as part of your public API as a convenience to your users, but requiring it seems beyond the pale. Now one issue is that you obviously can't easily pass complex data structures to an HTML attribute (Polymer has helpers for this if you're using Polymer).
But if that's the case, rather than have that be part of the element API, I'd provide a standalone function that returns the appropriate DOM structure rather than baking that in to an element. You could even make it a class method of your custom element class if that's how you roll.
Consider the case where you have a List element that renders an arbitrary number of Item elements. I think it's great to provide a convenience method that takes an array and updates the (light) DOM. But users should be able to append them directly as well.
Your use case may require hacking around the problem. Sometimes you really do legit need to use an antipattern. But consider carefully whether that's the case in your element.
This is purely dependent on your case. But as a general rule, if you find yourself buried in a hell of nested shadow roots, then you may consider going easy on using shadow doms.
Like the follow example illustrates:
<my-outer-element>
shadowRoot
<slot1> ---Reveal dom
<my-inner-element>
shadowRoot
....

How to import Stylesheets for AngularJS components?

Due to certain circumstances, I'm forced to move my Angular 2 App to AngularJS.
Most of my Components have their own StyleUrl property for their specific stylesheets. So far searching online, I haven't found a way to do so in AngularJS, except integrating Webpack to my project, however I'm having trouble doing so.
I was wondering if there's another way, and if there isn't, what's the proper way of using Webpack for this?
EDIT: 5/9/2017:
Wanted to give an update on my situation. After some testing on the Dynamic CSS loading module which Yeshwanth provided, I discovered that the component CSS leaked to the outside DOM, which meant I had to keep searching for another solution.
Eventually I resigned to use the SCSS approach: Inside the component template, define one, big, encapsuling div element, and give it an ID of some kind. Then, inside an .scss file, write the style block for that ID and INSIDE that block place all of your component styles. After compiling the SCSS file, the resulting css file will act only on the component's elements.
I'm not sure if this fully emulates the emulated Shadow Dom of Angular 2, but for my purposes it was enough. Hope this helps.
I think in angular 1.x you cannot import style specific to your component.
But the dynamic css loading might come handy.
Please refer this

Categories