1+ // eslint-disable-next-line import/no-unresolved
2+ import { toClassName } from '../../scripts/aem.js' ;
3+
4+ export default async function decorate ( block ) {
5+ // build tablist
6+ const tablist = document . createElement ( 'div' ) ;
7+ tablist . className = 'tabs-list' ;
8+ tablist . setAttribute ( 'role' , 'tablist' ) ;
9+
10+ // decorate tabs and tabpanels
11+ const tabs = [ ...block . children ] . map ( ( child ) => child . firstElementChild ) ;
12+ tabs . forEach ( ( tab , i ) => {
13+ const id = toClassName ( tab . textContent ) ;
14+
15+ // decorate tabpanel
16+ const tabpanel = block . children [ i ] ;
17+ tabpanel . className = 'tabs-panel' ;
18+ tabpanel . id = `tabpanel-${ id } ` ;
19+ tabpanel . setAttribute ( 'aria-hidden' , ! ! i ) ;
20+ tabpanel . setAttribute ( 'aria-labelledby' , `tab-${ id } ` ) ;
21+ tabpanel . setAttribute ( 'role' , 'tabpanel' ) ;
22+
23+ // build tab button
24+ const button = document . createElement ( 'button' ) ;
25+ button . className = 'tabs-tab' ;
26+ button . id = `tab-${ id } ` ;
27+ button . innerHTML = tab . innerHTML ;
28+ button . setAttribute ( 'aria-controls' , `tabpanel-${ id } ` ) ;
29+ button . setAttribute ( 'aria-selected' , ! i ) ;
30+ button . setAttribute ( 'role' , 'tab' ) ;
31+ button . setAttribute ( 'type' , 'button' ) ;
32+ button . addEventListener ( 'click' , ( ) => {
33+ block . querySelectorAll ( '[role=tabpanel]' ) . forEach ( ( panel ) => {
34+ panel . setAttribute ( 'aria-hidden' , true ) ;
35+ } ) ;
36+ tablist . querySelectorAll ( 'button' ) . forEach ( ( btn ) => {
37+ btn . setAttribute ( 'aria-selected' , false ) ;
38+ } ) ;
39+ tabpanel . setAttribute ( 'aria-hidden' , false ) ;
40+ button . setAttribute ( 'aria-selected' , true ) ;
41+ } ) ;
42+ tablist . append ( button ) ;
43+ tab . remove ( ) ;
44+ } ) ;
45+
46+ block . prepend ( tablist ) ;
47+ }
0 commit comments