Skip to content

Commit

Permalink
fix: collect cosmoz-tab element from nested slots
Browse files Browse the repository at this point in the history
This collects nested slotted cosmoz-tab elements:
slot> slot> cosmoz-tab
  • Loading branch information
megheaiulian authored and cristinecula committed Oct 13, 2020
1 parent a0ba5c1 commit 616fde5
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/use-tabs.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
useHashParam, link
} from './use-hash-param';
import {
choose, getName, isValid
choose, collect, getName, isValid
} from './utils';

const useTabSelectedEffect = (host, selectedTab) => {
Expand Down Expand Up @@ -64,7 +64,7 @@ const useTabSelectedEffect = (host, selectedTab) => {
return {
tabs,
selectedTab,
onSlot: useCallback(({ target }) => requestAnimationFrame(() => setTabs(target.assignedElements().filter(el => el.matches('cosmoz-tab')))), []),
onSlot: useCallback(({ target }) => requestAnimationFrame(() => setTabs(collect(target))), []),
onSelect: useCallback(e => {
if (e.button !== 0 || e.metaKey || e.ctrlKey) {
return;
Expand Down
12 changes: 11 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,21 @@ const isValid = tab => !tab.hidden && !tab.disabled,
}
const selectedTab = tabs.find(tab => getName(tab) === selected);
return selectedTab && isValid(selectedTab) ? selectedTab : tabs.find(isValid);
};
},
collect = slot => slot.assignedElements().flatMap(el => {
if (el.matches('cosmoz-tab')) {
return [el];
}
if (el.matches('slot')) {
return collect(el);
}
return [];
});


export {
choose,
collect,
isValid,
getIcon,
getIconStyle,
Expand Down
34 changes: 34 additions & 0 deletions test/cosmoz-tabs-slot.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {
assert, html, fixture, nextFrame
} from '@open-wc/testing';

import '../cosmoz-tabs.js';
import { component } from 'haunted';

suiteSetup(() => {
if (customElements.get('slot-test')) {
return;
}
customElements.define('slot-test', component(() => html`
<cosmoz-tabs>
<cosmoz-tab name="tab0" heading="Tab0">1</cosmoz-tab>
<slot></slot>
</cosmoz-tabs>
`));
});

suite('cosmoz-tabs slot', () => {
test('collects cosmoz-tabs from slot', async () => {
const el = await fixture(html`
<slot-test>
<cosmoz-tab name="tab1">2</cosmoz-tab>
<span name="notatab2">3</span>
</slot-test>
`),
tabs = el.shadowRoot.querySelector('cosmoz-tabs');
await nextFrame();
tabs.selected = 'tab1';
await nextFrame();
assert.equal(el.querySelector('cosmoz-tab').getAttribute('is-selected'), '');
});
});

0 comments on commit 616fde5

Please sign in to comment.