Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ const Greeting = ({ name = 'World' }) => (
<p>Hello, {name}!</p>
);

register(Greeting, 'x-greeting', ['name'], { shadow: true, mode: 'open' });
// ^ ^ ^ ^ ^
// | HTML tag name | use shadow-dom |
register(Greeting, 'x-greeting', ['name'], { shadow: true, mode: 'open', adoptedStyleSheets: [] });
// ^ ^ ^ ^ ^ ^
// | HTML tag name | use shadow-dom | use adoptedStyleSheets
// Component definition Observed attributes Encapsulation mode for the shadow DOM tree
```

Expand Down
7 changes: 6 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { h, cloneElement, render, hydrate } from 'preact';

/**
* @typedef {import('preact').FunctionComponent<any> | import('preact').ComponentClass<any> | import('preact').FunctionalComponent<any> } ComponentDefinition
* @typedef {{ shadow: false } | { shadow: true, mode?: 'open' | 'closed' }} Options
* @typedef {{ shadow: false } | { shadow: true, mode?: 'open' | 'closed', adoptedStyleSheets?: CSSStyleSheet[] }} Options
* @typedef {HTMLElement & { _root: ShadowRoot | HTMLElement, _vdomComponent: ComponentDefinition, _vdom: ReturnType<typeof import("preact").h> | null }} PreactCustomElement
*/

Expand Down Expand Up @@ -47,6 +47,11 @@ export default function register(Component, tagName, propNames, options) {
options && options.shadow
? inst.attachShadow({ mode: options.mode || 'open' })
: inst;

if (options && options.adoptedStyleSheets) {
inst._root.adoptedStyleSheets = options.adoptedStyleSheets;
}

return inst;
}
PreactElement.prototype = Object.create(HTMLElement.prototype);
Expand Down
24 changes: 24 additions & 0 deletions src/index.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -309,4 +309,28 @@ describe('web components', () => {
assert.equal(myForm.elements[0].tagName, 'X-FORM-ASSOCIATED-CLASS');
assert.equal(myForm.elements[2].tagName, 'X-FORM-ASSOCIATED-FUNCTION');
});

it('supports the `adoptedStyleSheets` option', async () => {
function AdoptedStyleSheets() {
return <div className="styled-child">Adopted Style Sheets</div>;
}

const sheet = new CSSStyleSheet();
sheet.replaceSync('.styled-child { color: red; }');

registerElement(AdoptedStyleSheets, 'x-adopted-style-sheets', [], {
shadow: true,
adoptedStyleSheets: [sheet],
});

root.innerHTML = `<x-adopted-style-sheets></x-adopted-style-sheets>`;

const child = document
.querySelector('x-adopted-style-sheets')
.shadowRoot
.querySelector('.styled-child');

const style = getComputedStyle(child);
assert.equal(style.color, 'rgb(255, 0, 0)');
});
});