AdminNav.jsx
88 lines
| 1 | import { useEffect } from '@wordpress/element'; |
| 2 | |
| 3 | import { navigate } from '@admin/router'; |
| 4 | |
| 5 | function normalizeAppPath( path ) { |
| 6 | if ( ! path || path === '/' ) { |
| 7 | return '/'; |
| 8 | } |
| 9 | |
| 10 | return path.startsWith( '/' ) ? path : `/${ path }`; |
| 11 | } |
| 12 | |
| 13 | function getCurrentAppPath() { |
| 14 | return normalizeAppPath( |
| 15 | new URLSearchParams( window.location.search ).get( 'path' ) |
| 16 | ); |
| 17 | } |
| 18 | |
| 19 | function syncAppSubmenuCurrent() { |
| 20 | const submenu = document.querySelector( |
| 21 | '#toplevel_page_advanced-ads .wp-submenu' |
| 22 | ); |
| 23 | if ( ! submenu ) { |
| 24 | return; |
| 25 | } |
| 26 | |
| 27 | const currentPath = getCurrentAppPath(); |
| 28 | |
| 29 | submenu.querySelectorAll( 'li.current, a.current' ).forEach( ( el ) => { |
| 30 | el.classList.remove( 'current' ); |
| 31 | } ); |
| 32 | |
| 33 | let matched = false; |
| 34 | |
| 35 | submenu.querySelectorAll( 'a.advads-app-link' ).forEach( ( anchor ) => { |
| 36 | const href = anchor.getAttribute( 'href' ); |
| 37 | if ( ! href || href.includes( 'admin.php' ) ) { |
| 38 | return; |
| 39 | } |
| 40 | |
| 41 | if ( normalizeAppPath( href ) === currentPath ) { |
| 42 | anchor.classList.add( 'current' ); |
| 43 | anchor.parentElement?.classList.add( 'current' ); |
| 44 | matched = true; |
| 45 | } |
| 46 | } ); |
| 47 | |
| 48 | if ( matched ) { |
| 49 | return; |
| 50 | } |
| 51 | |
| 52 | const appLink = submenu.querySelector( 'a[href*="page=advanced-ads-app"]' ); |
| 53 | if ( appLink ) { |
| 54 | appLink.classList.add( 'current' ); |
| 55 | appLink.parentElement?.classList.add( 'current' ); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | export function AdminNav() { |
| 60 | useEffect( () => { |
| 61 | const handler = ( e ) => { |
| 62 | const anchor = e.target.closest( 'a.advads-app-link' ); |
| 63 | if ( ! anchor ) { |
| 64 | return; |
| 65 | } |
| 66 | |
| 67 | const href = anchor.getAttribute( 'href' ); |
| 68 | if ( ! href ) { |
| 69 | return; |
| 70 | } |
| 71 | |
| 72 | e.preventDefault(); |
| 73 | |
| 74 | navigate( href ); |
| 75 | syncAppSubmenuCurrent(); |
| 76 | }; |
| 77 | |
| 78 | syncAppSubmenuCurrent(); |
| 79 | document.addEventListener( 'click', handler ); |
| 80 | |
| 81 | return () => { |
| 82 | document.removeEventListener( 'click', handler ); |
| 83 | }; |
| 84 | }, [ navigate ] ); |
| 85 | |
| 86 | return null; |
| 87 | } |
| 88 |