| 1 |
import { useEditModeStore } from '../state/edit-mode'; |
| 2 |
|
| 3 |
const NODE_ID = '#wp-admin-bar-extendify-quick-edit-toggle'; |
| 4 |
const AGENT_BTN_ID = 'wp-admin-bar-extendify-agent-btn'; |
| 5 |
const BOUND_MARK = '__extendifyQuickEditBound'; |
| 6 |
|
| 7 |
// The PHP-registered toggle belongs next to the agent button — a JS-injected |
| 8 |
// <li> that may land after this bundle, so watch the bar until it shows up. |
| 9 |
const positionToggle = (node) => { |
| 10 |
const agentBtn = document.getElementById(AGENT_BTN_ID); |
| 11 |
if (agentBtn) { |
| 12 |
agentBtn.after(node); |
| 13 |
return true; |
| 14 |
} |
| 15 |
document.getElementById('wp-admin-bar-root-default')?.prepend(node); |
| 16 |
return false; |
| 17 |
}; |
| 18 |
|
| 19 |
const followAgentButton = (node) => { |
| 20 |
if (positionToggle(node)) return; |
| 21 |
const bar = document.getElementById('wpadminbar'); |
| 22 |
if (!bar) return; |
| 23 |
const observer = new MutationObserver(() => { |
| 24 |
if (!document.getElementById(AGENT_BTN_ID)) return; |
| 25 |
positionToggle(node); |
| 26 |
observer.disconnect(); |
| 27 |
}); |
| 28 |
observer.observe(bar, { childList: true, subtree: true }); |
| 29 |
}; |
| 30 |
|
| 31 |
export const bindAdminBarToggle = () => { |
| 32 |
const link = document.querySelector(`${NODE_ID} a`); |
| 33 |
if (!link) return; |
| 34 |
|
| 35 |
const sync = () => { |
| 36 |
link.setAttribute( |
| 37 |
'aria-checked', |
| 38 |
useEditModeStore.getState().on ? 'true' : 'false', |
| 39 |
); |
| 40 |
}; |
| 41 |
sync(); |
| 42 |
|
| 43 |
if (link[BOUND_MARK]) return; |
| 44 |
link[BOUND_MARK] = true; |
| 45 |
|
| 46 |
followAgentButton(link.closest('li')); |
| 47 |
|
| 48 |
link.addEventListener('click', (e) => { |
| 49 |
e.preventDefault(); |
| 50 |
useEditModeStore.getState().toggle(); |
| 51 |
}); |
| 52 |
|
| 53 |
useEditModeStore.subscribe(sync); |
| 54 |
}; |
| 55 |
|