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

Allow static children in shadow: false mode #56

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
75 changes: 62 additions & 13 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { h, cloneElement, render, hydrate } from 'preact';
import { h, Fragment, cloneElement, render, hydrate } from 'preact';

export default function register(Component, tagName, propNames, options) {
function PreactElement() {
const inst = Reflect.construct(HTMLElement, [], PreactElement);
inst._vdomComponent = Component;
inst._root =
options && options.shadow ? inst.attachShadow({ mode: 'open' }) : inst;
inst._shadowEnabled = options && options.shadow;
inst._root = inst._shadowEnabled
? inst.attachShadow({ mode: 'open' })
: inst;
return inst;
}

PreactElement.prototype = Object.create(HTMLElement.prototype);
PreactElement.prototype.constructor = PreactElement;
PreactElement.prototype.connectedCallback = connectedCallback;
Expand All @@ -24,15 +27,21 @@ export default function register(Component, tagName, propNames, options) {
propNames.forEach((name) => {
Object.defineProperty(PreactElement.prototype, name, {
get() {
return this._vdom.props[name];
if (this._vdom) {
return this._vdom.props[name];
}

if (!this._props) this._props = {};

return this._props[name];
},
set(v) {
if (this._vdom) {
this.attributeChangedCallback(name, null, v);
} else {
if (!this._props) this._props = {};
this._props[name] = v;
this.connectedCallback();
this._props[toCamelCase(name)] = v;
}

// Reflect property changes to attributes if the value is a primitive
Expand Down Expand Up @@ -79,7 +88,7 @@ function connectedCallback() {
this._vdom = h(
ContextProvider,
{ ...this._props, context },
toVdom(this, this._vdomComponent)
toVdom(this, this._vdomComponent, this._shadowEnabled)
);
(this.hasAttribute('hydrate') ? hydrate : render)(this._vdom, this._root);
}
Expand Down Expand Up @@ -114,24 +123,35 @@ function disconnectedCallback() {
* after having fired the event.
*/
function Slot(props, context) {
const { shadow, addContextListener, removeContextListener, ...rest } = props;

const ref = (r) => {
if (!r) {
this.ref.removeEventListener('_preact', this._listener);
removeContextListener(this._listener, this.ref);
} else {
this.ref = r;
if (!this._listener) {
this._listener = (event) => {
event.stopPropagation();
event.detail.context = context;
};
r.addEventListener('_preact', this._listener);
addContextListener(this._listener, this.ref);
}
}
};
return h('slot', { ...props, ref });

if (!shadow && !this._listener) {
this._listener = (event) => {
event.stopPropagation();
event.detail.context = context;
};
addContextListener(this._listener);
}

return h(shadow ? 'slot' : Fragment, { ...rest, ref });
}

function toVdom(element, nodeName) {
function toVdom(element, nodeName, shadow) {
if (element.nodeType === 3) return element.data;
if (element.nodeType !== 1) return null;
let children = [],
Expand All @@ -147,17 +167,46 @@ function toVdom(element, nodeName) {
}

for (i = cn.length; i--; ) {
const vnode = toVdom(cn[i], null);
const vnode = toVdom(cn[i], null, shadow);
// Move slots correctly
const name = cn[i].slot;
if (name) {
props[name] = h(Slot, { name }, vnode);
props[name] = h(
Slot,
{
name,
shadow,
addContextListener(listener, element = cn[i]) {
Copy link

@tillsc tillsc Nov 9, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't work as expected. When called via addContextListener(this._listener); (see Line 148) element is undefined.
I fixed this by defining a const childElement = cn[i]; at the beginning of the for loop and using childElement instead of cn[i]. So in this case the line would be:

addContextListener(listener, element = childElement) {

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I can see this seems to be a transpiler (in my case rollup) bug...

Rollup transpiles from

let i = 0;
for (i = 1; i--;) {
  do_something_with(cn[i])
}

to code like

var i = 0;
function _loop() {
  do_something_with(cn[i])
}
for (i = 1; i--;) {
  loop();
}

Which doesn't make any sense....

element.addEventListener('_preact', listener);
},
removeContextListener(listener, element = cn[i]) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same Problem here as in 148

element.removeEventListener('_preact', listener);
},
},
vnode
);
} else {
children[i] = vnode;
}
}

// Only wrap the topmost node with a slot
const wrappedChildren = nodeName ? h(Slot, null, children) : children;
const wrappedProps = {
shadow,
addContextListener(listener, e = element) {
e.addEventListener('_preact', listener);
},
removeContextListener(listener, e = element) {
e.removeEventListener('_preact', listener);
},
};

const wrappedChildren = nodeName ? h(Slot, wrappedProps, children) : children;

// Remove all children from the topmost node in non-shadow mode
if (!shadow && nodeName) {
element.innerHTML = '';
}

return h(nodeName || element.nodeName.toLowerCase(), props, wrappedChildren);
}
53 changes: 53 additions & 0 deletions src/index.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,9 @@ describe('web components', () => {
}

registerElement(DisplayTheme, 'x-display-theme', [], { shadow: true });
registerElement(DisplayTheme, 'x-display-theme-no-shadow', [], {
shadow: false,
});

function Parent({ children, theme = 'dark' }) {
return (
Expand All @@ -222,6 +225,7 @@ describe('web components', () => {
}

registerElement(Parent, 'x-parent', ['theme'], { shadow: true });
registerElement(Parent, 'x-parent-no-shadow', ['theme'], { shadow: false });

it('passes context over custom element boundaries', async () => {
const el = document.createElement('x-parent');
Expand All @@ -245,4 +249,53 @@ describe('web components', () => {
});
assert.equal(getShadowHTML(), '<p>Active theme: sunny</p>');
});

it('passes context over custom element boundaries (no shadow)', async () => {
const el = document.createElement('x-parent-no-shadow');

const noSlot = document.createElement('x-display-theme-no-shadow');
el.appendChild(noSlot);

root.appendChild(el);
assert.equal(
root.innerHTML,
'<x-parent-no-shadow><div class="children"><x-display-theme-no-shadow><p>Active theme: dark</p></x-display-theme-no-shadow></div></x-parent-no-shadow>'
);

const getDisplayThemeHTML = () =>
document.querySelector('x-display-theme-no-shadow').innerHTML;
assert.equal(getDisplayThemeHTML(), '<p>Active theme: dark</p>');

// Trigger context update
act(() => {
el.setAttribute('theme', 'sunny');
});
assert.equal(getDisplayThemeHTML(), '<p>Active theme: sunny</p>');
});

function NoShadow({ children }) {
return <div class="children">{children}</div>;
}

registerElement(NoShadow, 'x-no-shadow-parent', [], { shadow: false });

registerElement(NoShadow, 'x-no-shadow-children', [], { shadow: false });

it('correctly draws children without shadow', async () => {
const el = document.createElement('x-no-shadow-parent');

const elementChildren = document.createElement('x-no-shadow-children');

const spanChildren = document.createElement('span');
spanChildren.innerHTML = 'hello world';

elementChildren.appendChild(spanChildren);
el.appendChild(elementChildren);

root.appendChild(el);
assert.equal(
root.innerHTML,
'<x-no-shadow-parent><div class="children"><x-no-shadow-children><div class="children"><span>hello world</span></div></x-no-shadow-children></div></x-no-shadow-parent>'
);
});
});