index.js
69 lines
| 1 | /** |
| 2 | * The Quick Access React App for Spectra Enhanced Editor. |
| 3 | */ |
| 4 | import { createRoot } from '@wordpress/element'; |
| 5 | import Sidebar from './components/Sidebar'; |
| 6 | |
| 7 | // Toggles the sidebar based on the url parameters. |
| 8 | export const toggleSidebar = ( url ) => { |
| 9 | const currentUrl = new URL( url ); |
| 10 | if ( '/wp-admin/site-editor.php' === currentUrl.pathname ) { |
| 11 | if ( 'edit' === currentUrl.searchParams.get( 'canvas' ) ) { |
| 12 | attachSidebarAfterLoading(); |
| 13 | } else { |
| 14 | const container = document.querySelector( '.srfm-ee-quick-access' ); |
| 15 | if ( container ) { |
| 16 | container.parentElement.remove(); |
| 17 | } |
| 18 | } |
| 19 | } |
| 20 | }; |
| 21 | |
| 22 | // Attaches the sidebar to the DOM. |
| 23 | export const attachSidebar = () => { |
| 24 | const interval = setInterval( () => { |
| 25 | const rootElement = document.querySelector( |
| 26 | '.interface-interface-skeleton__body' |
| 27 | ); |
| 28 | if ( ! rootElement ) { |
| 29 | return; |
| 30 | } |
| 31 | |
| 32 | const blockElement = document.querySelector( |
| 33 | '.srfm-ee-quick-access-container' |
| 34 | ); |
| 35 | if ( blockElement ) { |
| 36 | clearInterval( interval ); |
| 37 | return; |
| 38 | } |
| 39 | |
| 40 | clearInterval( interval ); |
| 41 | |
| 42 | let container = rootElement.querySelector( '.srfm-ee-quick-access' ); |
| 43 | |
| 44 | if ( ! container ) { |
| 45 | container = document.createElement( 'div' ); |
| 46 | container.classList.add( 'srfm-ee-quick-access-container' ); |
| 47 | rootElement.insertBefore( container, rootElement.firstChild ); |
| 48 | } |
| 49 | |
| 50 | const root = createRoot( container ); |
| 51 | root.render( <Sidebar /> ); |
| 52 | }, 100 ); |
| 53 | }; |
| 54 | |
| 55 | // Attaches the sidebar after the page is loaded ( in FSE editor). |
| 56 | const attachSidebarAfterLoading = () => { |
| 57 | const skeletonInterval = setInterval( () => { |
| 58 | const skeleton = document.querySelector( |
| 59 | '.edit-site-editor__interface-skeleton' |
| 60 | ); |
| 61 | if ( skeleton ) { |
| 62 | if ( ! skeleton.classList.contains( 'is-loading' ) ) { |
| 63 | clearInterval( skeletonInterval ); |
| 64 | attachSidebar(); |
| 65 | } |
| 66 | } |
| 67 | }, 100 ); |
| 68 | }; |
| 69 |