| 1 |
import { createContext, useCallback, useContext, useState } from "@wordpress/element"; |
| 2 |
|
| 3 |
// Create context |
| 4 |
export const TogglePanelBodyContext = createContext(); |
| 5 |
|
| 6 |
const addFlashClass = (target) => { |
| 7 |
const panelBodyEl = document.querySelectorAll(".sp-smart-post-tab-panel"); |
| 8 |
if (!panelBodyEl || !panelBodyEl.length) { |
| 9 |
return; |
| 10 |
} |
| 11 |
panelBodyEl.forEach((panel) => { |
| 12 |
panel.classList.toggle("sp-flash", Boolean(target)); |
| 13 |
}); |
| 14 |
}; |
| 15 |
|
| 16 |
// Create a context provider components |
| 17 |
export const TogglePanelBodyProvider = ({ blockName = "", children }) => { |
| 18 |
// const [ openPanel, setOpenPanel ] = useState( localStor.get() || '' ); |
| 19 |
const [openPanel, setOpenPanel] = useState("general"); |
| 20 |
|
| 21 |
const togglePanelBody = useCallback( |
| 22 |
(event = false, panel, blockName = false) => { |
| 23 |
// event?.stopPropagation?.(); |
| 24 |
const panelName = |
| 25 |
"object" === typeof event ? event?.target?.closest(".sp-panel-data")?.dataset?.component : event; |
| 26 |
const panelValue = panelName || panel; |
| 27 |
|
| 28 |
setOpenPanel(openPanel === panelValue && "string" === typeof event ? "" : panelValue); |
| 29 |
addFlashClass(event.target); |
| 30 |
}, |
| 31 |
[openPanel] |
| 32 |
); |
| 33 |
|
| 34 |
const contextValue = { |
| 35 |
openPanel: openPanel, |
| 36 |
togglePanelBody: togglePanelBody, |
| 37 |
}; |
| 38 |
|
| 39 |
return <TogglePanelBodyContext.Provider value={contextValue}>{children}</TogglePanelBodyContext.Provider>; |
| 40 |
}; |
| 41 |
|
| 42 |
export const usePanelBodyContext = () => { |
| 43 |
const context = useContext(TogglePanelBodyContext); |
| 44 |
// if ( ! isEditor() ) { |
| 45 |
// return { togglePanelBody: () => {}, openPanel: '' }; // Fallback for frontend; |
| 46 |
// } |
| 47 |
return context; |
| 48 |
}; |
| 49 |
|