Skip to content

Commit

Permalink
Add support for slot as props
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister committed Aug 26, 2020
1 parent 63e2903 commit eda464b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,21 @@ function toVdom(element, nodeName) {
a = element.attributes,
cn = element.childNodes;
for (i = a.length; i--; ) {
props[a[i].name] = a[i].value;
props[toCamelCase(a[i].name)] = a[i].value;
}
for (i = cn.length; i--; ) children[i] = toVdom(cn[i]);
if (a[i].name !== 'slot') {
props[a[i].name] = a[i].value;
props[toCamelCase(a[i].name)] = a[i].value;
}
}

for (i = cn.length; i--; ) {
const vnode = toVdom(cn[i]);
// Move slots correctly
const name = cn[i].slot;
if (name) {
props[name] = h('slot', { name }, vnode);
} else {
children[i] = vnode;
}
}
return h(nodeName || element.nodeName.toLowerCase(), props, children);
}
38 changes: 38 additions & 0 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,44 @@ it('renders ok, updates on attr change', () => {
document.body.removeChild(root);
});

function Foo({ text, children }) {
return (
<span class="wrapper">
<div class="children">{children}</div>
<div class="slotted">{text}</div>
</span>
);
}

registerElement(Foo, 'x-foo', [], { shadow: true });

it('renders slots as props with shadow DOM', () => {
const root = document.createElement('div');
const el = document.createElement('x-foo');

// <span slot="text">here is a slot</span>
const slot = document.createElement('span');
slot.textContent = 'here is a slot';
slot.slot = 'text';
el.appendChild(slot);

// <div>no slot</div>
const noSlot = document.createElement('div');
noSlot.textContent = 'no slot';
el.appendChild(noSlot);
el.appendChild(slot);

root.appendChild(el);
document.body.appendChild(root);

assert.equal(root.innerHTML, '<x-foo><div>no slot</div><span slot="text">here is a slot</span></x-foo>');

const shadowHTML = document.querySelector('x-foo').shadowRoot.innerHTML;
assert.equal(shadowHTML, '<span class="wrapper"><div class="children"><div>no slot</div></div><div class="slotted"><slot name="text"><span>here is a slot</span></slot></div></span>');

document.body.removeChild(root);
});

const kebabName = 'custom-date-long-name';
const camelName = 'customDateLongName';
const lowerName = camelName.toLowerCase();
Expand Down

0 comments on commit eda464b

Please sign in to comment.