open-styleable v0.2.0
open-styleable
A proof-of-concept implementation of open-styleable shadow-roots, using a combination of:
- A build-time HTML transform for declarative shadow DOM
- A client-side script that overrides
attachShadow
Demo
View the hosted examples:
Edit the code live:
Usage
(See standalone setup instructions below if you're trying to use this in your own project) š
The access for open styles is controlled at the shadow-root level. Every shadow-root needs to explicitly opt-in using one of the following ways.
For declarative shadow DOM (DSD):
Add the
adopthoststylesattribute to the DSD template. This shadow-root will now automatically inherit all styles from the host context (i.e. the document or a parent shadow-root).<template shadowrootmode="open" adopthoststyles>ā¦</template>Alternatively, if you only want to adopt styles from the document and not from the parent shadow-root, then you can use
adoptpagestyles.<template shadowrootmode="open" adoptpagestyles>ā¦</template>
For client-rendered shadow-roots, use the adoptPageStyles and adoptHostStyles options when calling attachShadow.
- Use
adoptHostStylesto adopt all styles from the host context.this.attachShadow({ mode: "open", adoptHostStyles: true, }); - Use
adoptPageStylesto adopt all styles from the page/document only.this.attachShadow({ mode: "open", adoptPageStyles: true, });
!IMPORTANT There are some known limitations/caveats that you should be aware of.
Standalone setup
To use this "polyfill" in your own project:
- Install
open-styleablefrom npm (or use import maps).npm add open-styleable - Hook up the HTML transform into your templating system (see
.eleventy.jsfor an example). This should ideally be executed after all bundling steps.import { transformHtml } from "open-styleable";// assuming `htmlContent` is the original page content htmlContent = transformHtml(htmlContent); - Include the
/clientscript in your<head>before any custom elements are registered.
or from a CDN:<script> import "open-styleable/client"; </script><script src="https://esm.sh/open-styleable/client"></script>
!NOTE You do not always need to use both the build-time transform and the client-side script. They are completely independent and do different things.
Development
This demo is built with 11ty. All test pages go in the pages/ directory.
To run it locally, clone the repo and follow these steps:
Install dependencies.
npm installStart the dev server.
npm run devOpen up
localhost:1174in your browser.