Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Preflight html styles to include shadow DOM :host pseudo-class #11200

Merged

Conversation

brandonmcconnell
Copy link
Contributor

This PR simply replaces html with :root, :host to support all :root and :host contexts:

  • :root supports…
    • html (same as plainly using html)
    • SVG root scope
  • :host supports…
    • ShadowDOM shadow root scope

@jonathandewitt-dev
Copy link

This would be great for Tailwind in the Shadow DOM, especially for react-shadow-scope, which currently transforms the styles with a quick regex replace at runtime. This is a super simple low-impact change that could simplify things a lot.

Maybe worth noting, maybe not - but using Tailwind in shadow DOM would make global styles irrelevant, like the body tag and potentially some other cases too. In the spirit of generating only the CSS that's used, it might be nice to add a shadow DOM flag in the config.

@brandonmcconnell
Copy link
Contributor Author

brandonmcconnell commented May 10, 2023

Which tests are failing? When I run npm run build && npm test locally, all tests pass.

@RobinMalfait Nvm after merging your recent sass and cssnano version bumps, the build errors disappear AFAICT

@jonathandewitt-dev
Copy link

Question: does this affect how the Tailwind config might add rules to this selector?

@brandonmcconnell
Copy link
Contributor Author

brandonmcconnell commented May 10, 2023

@jonathandewitt-dev no, I don't believe this preflight style affects how any selectors are built.

@RobinMalfait can you confirm this?

@jonathandewitt-dev
Copy link

That might be the desired result, actually. I can imagine a situation where someone is using Tailwind in the shadow DOM, but their configuration generates a stylesheet that targets selectors outside the scope. Like, the theme configuration, for example.

@RobinMalfait
Copy link
Contributor

@jonathandewitt-dev no, I don't believe this preflight style affects how any selectors are built.

@RobinMalfait can you confirm this?

It shouldn't affect this 👍


I rebased this PR on top of master such that we only have to look at a single commit instead of 10+ commits 👍

@brandonmcconnell
Copy link
Contributor Author

@RobinMalfait Thanks!

To @jonathandewitt-dev's point, I think he was asking if you use the config to override some default root-related styles like font-size or line-height, do those get applied to html as well, as that would require the same treatment if that's the case.

Although, to my knowledge, overriding any such values in the config only affects utilities and not any styles actually applied at the root.

Could you confirm this as well? Thanks again!

@jonathandewitt-dev
Copy link

That's precisely what I was asking, yep! Where Tailwind normally replaces styles on html or body, we should be sure to include (or exclude) the necessary parts for shadow encapsulated scopes where those styles would otherwise be inert.

I confirmed that the configuration does indeed modify styles in the html selector. I don't know how the compiler targets this, but I have to imagine it looks for html and modifies the rules from there, or else it adds a new html selector.

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      fontFamily: {
        sans: ['Orbitron'],
      },
    },
  },
  plugins: [],
}

image

@brandonmcconnell
Copy link
Contributor Author

@jonathandewitt-dev Ooo interesting I wasn't aware it did that. I'll poke around the codebase a bit more to see if I can find where that's coming from.

@jonathandewitt-dev
Copy link

@brandonmcconnell you may want to include :scope either in addition to or in place of :root as according to this explanation of the new @scope rule:

@scope (.theme-black) {
  :scope {
    background-color: black;
    color: white;
  }         
  a {
    color: #35adce;
  }
}

:scope isn’t a new pseudo-class. Its been in browsers for years but was previously pretty pointless when used in a stylesheet because outside of a @scope block it always means the same as :root

@brandonmcconnell
Copy link
Contributor Author

@brandonmcconnell you may want to include :scope either in addition to or in place of :root as according to this explanation of the new @scope rule

I am not sure if adding :scope outside of an actual scope rule would have the desired effect, and it may actually add some of these root styles in places people might not expect. As :scoped styles are a bit more flexible, that may be better suited as a user-choice.

It may be worth considering making the root selector user configurable, so the default could be :root, :host, but then allow the user to change that to anything they like from their config.

@adamwathan
Copy link
Member

@brandonmcconnell Before we explore merging this, can you share some very concrete examples (with code + demos) of things that someone might want to do that currently don't work in Tailwind that would work when this is merged? Will make it a lot easier to make a decision on 👍

@brandonmcconnell
Copy link
Contributor Author

@adamwathan - In essence, this PR allows tailwind styles to permeate all scopes, even the ShadowDOM, rather than only the top document.

@jonathandewitt-dev made a solid point about the implications of this in regard to the ShadowDOM here: #11200 (comment)

@jonathandewitt-dev, could you share any other helpful examples or information contributing to the value of this change, seeing as you are the author of the package you mentioned?

@jonathandewitt-dev
Copy link

@adamwathan @brandonmcconnell

There's not much to add that I haven't already said, but just for a summary - adding :host will allow us to gracefully use encapsulated shadow scopes, because those scopes don't have access to global styles.

The use case is primarily to avoid clashing with other libraries. Tailwind depends on global CSS classes, which may collide with custom or other third party classes. For incremental adoption, or even just adoption in an isolated micro-frontend, it would help to have that two-way encapsulation that protects those styles from global collisions.

The package I authored is not popular, but the approach is not unusual. It might serve as an illustration of how this could be used in a real-world scenario.

image

What's happening above, under the hood, is Tailwind's main CSS file is being converted to a single constructed style sheet, which can then be adopted/shared by each of these shadow roots.

@brandonmcconnell
Copy link
Contributor Author

Thanks, @jonathandewitt-dev!

In short, the ShadowDOM is the primary way to set up custom web components (not to be confused with JS framework components), doesn't inherently have access to the global scope and cannot use Tailwind's preflight styles as they do not use an html element.

This PR retains support for the existing html scope and also supports all additional standard and ShadowDOM scopes.

Tailwind CSS. Everywhere you need it.

@adamwathan
Copy link
Member

I've never done any Shadow DOM stuff so forgive me for needing some real ELI5 explanations here with extremely concrete examples. What I'd love to see is a demo that shows something that is currently broken that I can open in my browser and see being broken and understand why that's surprising — does that make sense?

For example, based on what I'm getting out of what you guys are saying, it sounds like maybe one example of this could be that using the border class doesn't work properly in the Shadow DOM because our quirky border reset we apply in Preflight to make that work doesn't work in the Shadow DOM?

I literally don't even know how styling works in the Shadow DOM at all to be clear, I am absolutely and completely ignorant of this technology 😂

Is the idea here that if you mount a normal Tailwind-generated stylesheet within a shadow DOM tree, that the classes and stuff in that stylesheet work, but anything targeting html or body don't end up doing anything because those elements don't exist? I think that makes sense to me and I understand why it would be beneficial to make that work.

Are there any downsides or things that would break? Could anyone be relying on that behavior today deliberately?

@jonathandewitt-dev
Copy link

jonathandewitt-dev commented Sep 8, 2023

Sure thing! I think there is a multitiered answer to this question, so I'll try to explain in steps.

At its most basic, here is a minimal example of shadow DOM (this uses its declarative syntax, so no JS is needed here.)

<style> .container { background-color: red; } </style>

<div class="container">This is outside the shadow DOM. It honors global styles.</div>

<div>
  <template shadowrootmode="closed">
    <style> .container { font-size: 2rem; } </style>
    <div class="container">This is inside the shadow DOM. It inherits nothing from global styles. Styles defined inside here don't leak out of this scope.</div>
  </template>
</div>

<div class="container">Even after the shadow DOM above, the styles inside it don't cascade to affect the outside world.</div>

In the devtools, you'll see the shadow root appear differently, because it's more or less "hidden" away from the outside world.

image

Originally, shadow DOM was not exposed for developers to use. It was used to style things like the video playback controls in a <video> tag. (It would be pretty wonky if those controls were easily messed up by unexpected global styles.) Then the w3c collectively decided it would be useful to expose the shadow DOM to developers as a tool for strong encapsulation.

This is useful for Tailwind because it guarantees isolated scopes that cannot be touched by third-party styles. If a project is using Bootstrap, for example, you could still use Tailwind without worrying about whether it's compatible. Just basically ignore it, and guarantee your Tailwind styles look the same no matter where they're used.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">

<x-tailwind>
  <template shadowrootmode="open">
    <style>/* tailwind styles here */</style>
    <div class="text-slate-900 font-extrabold text-2xl">
      Tailwind could be used inside the shadow DOM, instead of globally. This could be great for incremental adoption!
    </div>
  </template>
</x-tailwind>

Now, there's a couple problems here.

  1. It's repetitive to keep spitting ALL of tailwind into style tags
  2. The html selector doesn't select anything in shadow scopes

To resolve number 1 here is pretty interesting. Constructable Stylesheets allow you to use the browser's CSS parser to create a single stylesheet reference that can be passed around by JavaScript. You then can "adopt" these stylesheets from either the global document object in the DOM, or individual shadow roots. For example:

const tailwindEl = document.querySelector('x-tailwind');
const stylesheet = new CSSStyleSheet();
stylesheet.replaceSync(/* tailwind css string */);
tailwindEl.shadowRoot.adoptedStyleSheets = [stylesheet];

This is nothing Tailwind should specifically be responsible for, but since you wanted a detailed explanation, I figured I'd throw this in there too. My package essentially takes care of all this for you, with React.

Moving on to number 2, this part falls on Tailwind.

... anything targeting html or body don't end up doing anything because those elements don't exist?

Yes, each shadow root does not own its own html or body tags, so selecting them does nothing. The :host selector actually selects the outer element where the shadow root is attached. In the above case, that would select the <x-tailwind> element I made up.

You can demonstrate this issue in action:

<div>
  <template shadowrootmode="open">
    <style>
      html {
        line-height: 1.5;
        -webkit-text-size-adjust: 100%;
        -moz-tab-size: 4;
        -o-tab-size: 4;
        tab-size: 4;
        font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
        font-feature-settings: normal;
        font-variation-settings: normal;
      }
    </style>
    <div>
      The HTML selector doesn't select anything in this scope. Try swapping the <code>html</code> selector with the <code>:host</code> selector and watch what happens.
    </div>
  </template>
</div>

Are there any downsides or things that would break? Could anyone be relying on that behavior today deliberately?

When used at the global level, :root and html target the same element. As long as you're targeting both :root and :host, I can't think of any scenario where this could break something. But just in case I'm missing one, here's what I know about the behavior of :root versus html:

  • :root has a higher specificity level than html.
  • :root may target <html>, <svg>, <xml>, etc, depending on what document the CSS is styling.

Also worth mentioning, I think it would be useful to add a quick little all: initial; above all the :root, :host style rules to guarantee there's no contamination from the global scope. There are few things that can pass through a shadow DOM boundary, but nevertheless, more than zero. There may be some things that make sense to inherit, such as visibility or cursor.

But that may end up being branched off into its own separate conversation, tbh. Personally, I would be happy even with just html, :host.

brandonmcconnell and others added 2 commits September 8, 2023 10:24
Supports SVG root scope, ShadowDOM, and presumably other root scopes
@brandonmcconnell
Copy link
Contributor Author

@reinink Did you notice any adverse effects to using :root over html?

:root seemed like the better option to me second target any root scopes, like SVG roots, do Tailwind CSS Stylesheets could be imported and used directly within a SVG file. It also has the added perk that :root has higher specificity than html.


https://developer.mozilla.org/en-US/docs/Web/CSS/:root

@jonathandewitt-dev
Copy link

After mulling it over, I suppose someone could be depending on that level of specificity. If somone added html overrides after the Tailwind stylesheet, their overrides may break.

@reinink
Copy link
Member

reinink commented Sep 8, 2023

Hey @jonathandewitt-dev, thanks so much for that detailed explanation. I meant to respond sooner after making those changes (actually had the following written up already), but got distracted with something else.

I think we've got a decent handle on how this shadow DOM stuff works now, and I think your last solution is actually the right approach — to use html, :host instead of :root, :host, since the primary motivation for this change is to support the shadow DOM.

Our concern with using :root is the higher specificity over html. If someone has made changes to their html styles, switching Preflight to use :root would prevent those overrides from working. For example, the user's custom line-height here would no longer be applied:

@tailwind base;

html {
  line-height: 1;
}

As for the suggestion to add all: initial; to the top of Preflight, this feels like it could cause similar breaking changes. I think for now if you're working with the shadow DOM, just insert this rule yourself, since that's trivial enough to do.

Given all that, I've gone ahead and updated this PR to use html, :host.

Thanks to you and @brandonmcconnell for this contribution 👍

@reinink reinink changed the title Extend preflight html styles to support other :root, :host scopes Update Preflight html styles to include shadow DOM :host pseudo-class Sep 8, 2023
@brandonmcconnell
Copy link
Contributor Author

fwiw if someone added the style you mentioned to their stylesheet:

html {
  line-height: 1;
}

I believe it would still apply as it currently does, specifically targeting HTML, but not other root scopes.

They could also add it using :root if they wanted to have the same level of specificity:

:root {
  line-height: 1;
}

All that said, I agree that there would probably be breaking changes, even some we aren't considering it, so, if you think it's best not to move forward with :root for now, it's understandable.

@reinink
Copy link
Member

reinink commented Sep 8, 2023

I believe it would still apply as it currently does, specifically targeting HTML, but not other root scopes.

@brandonmcconnell I don't think so. Here's a Tailwind Play illustrating this problem: https://play.tailwindcss.com/Hu3RAA8yt8

But if we use html, :host it works fine.

They could also add it using :root if they wanted to have the same level of specificity:

Yup, but of course that would require making a change, so we still need to consider this a breaking change.

@reinink reinink merged commit 9faf109 into tailwindlabs:master Sep 8, 2023
10 checks passed
thecrypticace pushed a commit that referenced this pull request Dec 4, 2023
…lass (#11200)

* Extend current preflight `html` styles to support other root/host scopes

Supports SVG root scope, ShadowDOM, and presumably other root scopes

* Replace `:root` with `html`

* Update tests

* Update changelog

---------

Co-authored-by: Jonathan Reinink <jonathan@reinink.ca>
thecrypticace pushed a commit that referenced this pull request Dec 5, 2023
…lass (#11200)

* Extend current preflight `html` styles to support other root/host scopes

Supports SVG root scope, ShadowDOM, and presumably other root scopes

* Replace `:root` with `html`

* Update tests

* Update changelog

---------

Co-authored-by: Jonathan Reinink <jonathan@reinink.ca>
thecrypticace pushed a commit that referenced this pull request Dec 18, 2023
…lass (#11200)

* Extend current preflight `html` styles to support other root/host scopes

Supports SVG root scope, ShadowDOM, and presumably other root scopes

* Replace `:root` with `html`

* Update tests

* Update changelog

---------

Co-authored-by: Jonathan Reinink <jonathan@reinink.ca>
@brandonmcconnell
Copy link
Contributor Author

@reinink I just stumbled across this old PR and realized that replacing :root with :where(:root) in your Play reduces its specificity, allowing both either :root or html to override the default style while also adding support for non-html :root contexts.

Not sure how helpful that would be, but let me know if you want me to put in a PR for that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

5 participants