diff --git a/src/tabs/tp-tabs.ts b/src/tabs/tp-tabs.ts index 882a6a0..3356635 100644 --- a/src/tabs/tp-tabs.ts +++ b/src/tabs/tp-tabs.ts @@ -59,11 +59,14 @@ export class TPTabsElement extends HTMLElement { return; } + // Get current nested tab if has. + const currentNestedTab = this.getCurrentNestedTab( currentTab ); + // Update nav items. const navItems: NodeListOf = this.querySelectorAll( 'tp-tabs-nav-item' ); if ( navItems ) { navItems.forEach( ( navItem: TPTabsNavItemElement ): void => { - if ( navItem.isCurrentTab( currentTab ) ) { + if ( navItem.isCurrentTab( currentTab ) || ( currentNestedTab && navItem.isCurrentTab( currentNestedTab ) ) ) { navItem.setAttribute( 'active', 'yes' ); } else { navItem.removeAttribute( 'active' ); @@ -75,7 +78,7 @@ export class TPTabsElement extends HTMLElement { const tabs: NodeListOf = this.querySelectorAll( 'tp-tabs-tab' ); if ( tabs ) { tabs.forEach( ( tab: TPTabsTabElement ): void => { - if ( currentTab === tab.getAttribute( 'id' ) ) { + if ( currentTab === tab.getAttribute( 'id' ) || ( currentNestedTab && currentNestedTab === tab.getAttribute( 'id' ) ) ) { tab.setAttribute( 'open', 'yes' ); } else { tab.removeAttribute( 'open' ); @@ -92,10 +95,8 @@ export class TPTabsElement extends HTMLElement { return; } - const urlHash: string = window.location.hash; - if ( '' !== urlHash ) { - this.setAttribute( 'current-tab', urlHash.replace( '#', '' ) ); - } + // Set current assiociated tab. + this.setCurrentTab(); } /** @@ -104,6 +105,35 @@ export class TPTabsElement extends HTMLElement { * @param {string} tabId Tab ID. */ setCurrentTab( tabId: string = '' ): void { - this.setAttribute( 'current-tab', tabId ); + if ( '' !== tabId ) { + this.setAttribute( 'current-tab', tabId ); + } + + // Set current tab based on current url hash. + const urlHash: string = window.location.hash; + if ( '' !== urlHash ) { + const currentLink: HTMLAnchorElement | null = this.querySelector( `a[href="${ urlHash }"]` ); + const currentTab = currentLink?.closest( 'tp-tabs' ); + currentTab?.setAttribute( 'current-tab', urlHash.replace( '#', '' ) ); + } + } + + /** + * Get current nested tab. + * + * @param {string} currentTab Tab ID. + * + * @return {string} If has Nested current tab or empty. + */ + getCurrentNestedTab( currentTab: string = '' ): string { + if ( '' === currentTab ) { + return ''; + } + + const currentTabElement = this.querySelector( `tp-tabs-tab[id="${ currentTab }"]` ); + const currentNestedTabElement = currentTabElement?.querySelector( 'tp-tabs' ); + const currentNestedTab = currentNestedTabElement?.getAttribute( 'current-tab' ); + + return currentNestedTab ?? ''; } }