matthewp / haunted

React's Hooks API implemented for web components 👻
BSD 2-Clause "Simplified" License
2.58k stars 92 forks source link

Adopting Stylesheets #473

Closed bhollis closed 10 months ago

bhollis commented 11 months ago

Haunted looks really cool! However, one bit that I haven't been able to figure out is how to efficiently adopt stylesheets into the shadow root. For example, here's how Lit's ReactiveElement does it:

https://github.com/lit/lit/blob/main/packages/reactive-element/src/reactive-element.ts#L1016-L1027

They also have a css tagged template literal that helps make safe CSSStyleSheet objects.

It'd be great if Haunted's component had an affordance for adding stylesheets, or perhaps a way to hook into the element's connectedCallback to implement such a thing ourselves.

bennypowers commented 10 months ago

You could use useEffect

import {html, component, useEffect} from 'haunted';

const style = new CSSStyleSheet;
style.replaceSync(/* css */`
                  p { color: blue; }
                  `);

function SimpleGreeting() {

  useEffect(() => {
    this.shadowRoot.adoptedStyleSheets = [style]
  });

  return html`<p>Hello, ${this.name ?? 'Somebody'}!</p>`;
}

customElements.define('simple-greeting', component(SimpleGreeting, { observedAttributes: ['name'] }));

playground link

bhollis commented 10 months ago

That works, thanks!

bennypowers commented 10 months ago

see also https://github.com/matthewp/haunted/issues/121