index.js
95 lines
| 1 | import { PanelBody } from '@wordpress/components'; |
| 2 | import { applyFilters } from '@wordpress/hooks'; |
| 3 | import { forwardRef, useContext } from '@wordpress/element'; |
| 4 | import ApplyFilters from '../apply-filters/'; |
| 5 | import objectIsEmpty from '../../utils/object-is-empty'; |
| 6 | import useLocalStorageState from 'use-local-storage-state'; |
| 7 | import ControlsContext from '../../block-context'; |
| 8 | import classnames from 'classnames'; |
| 9 | |
| 10 | const PanelArea = forwardRef( function PanelArea( props, ref ) { |
| 11 | const { blockName } = useContext( ControlsContext ); |
| 12 | const { |
| 13 | icon, |
| 14 | className, |
| 15 | id, |
| 16 | state, |
| 17 | children, |
| 18 | title = false, |
| 19 | initialOpen = false, |
| 20 | showPanel = true, |
| 21 | hasGlobalStyle = false, |
| 22 | } = props; |
| 23 | |
| 24 | const [ panels, setPanels ] = useLocalStorageState( |
| 25 | 'generateblocksPanels', { |
| 26 | ssr: true, |
| 27 | defaultValue: {}, |
| 28 | } |
| 29 | ); |
| 30 | |
| 31 | const show = applyFilters( 'generateblocks.editor.showPanel', showPanel, id, props ); |
| 32 | |
| 33 | if ( ! show ) { |
| 34 | return null; |
| 35 | } |
| 36 | |
| 37 | if ( ! children || objectIsEmpty( children ) ) { |
| 38 | return null; |
| 39 | } |
| 40 | |
| 41 | return ( |
| 42 | <ApplyFilters |
| 43 | name="generateblocks.editor.panel" |
| 44 | blockName={ blockName } |
| 45 | state={ state } |
| 46 | panelRef={ ref } |
| 47 | { ...props } |
| 48 | > |
| 49 | <ApplyFilters |
| 50 | name={ 'generateblocks.panel.' + id } |
| 51 | props={ props } |
| 52 | state={ state } |
| 53 | > |
| 54 | { title ? ( |
| 55 | <PanelBody |
| 56 | ref={ ref } |
| 57 | title={ title } |
| 58 | initialOpen={ |
| 59 | 'undefined' !== typeof panels[ id ] |
| 60 | ? panels[ id ] |
| 61 | : initialOpen |
| 62 | } |
| 63 | icon={ icon } |
| 64 | className={ classnames( className, hasGlobalStyle && 'has-global-style' ) } |
| 65 | onToggle={ () => { |
| 66 | const isOpen = panels[ id ] || |
| 67 | ( |
| 68 | 'undefined' === typeof panels[ id ] && |
| 69 | initialOpen |
| 70 | ); |
| 71 | |
| 72 | setPanels( { |
| 73 | ...panels, |
| 74 | [ id ]: ! isOpen, |
| 75 | } ); |
| 76 | } } |
| 77 | > |
| 78 | { |
| 79 | applyFilters( 'generateblocks.editor.panelContents', children, id, props ) |
| 80 | } |
| 81 | </PanelBody> |
| 82 | ) : ( |
| 83 | <PanelBody> |
| 84 | { |
| 85 | applyFilters( 'generateblocks.editor.panelContents', children, id, props ) |
| 86 | } |
| 87 | </PanelBody> |
| 88 | ) } |
| 89 | </ApplyFilters> |
| 90 | </ApplyFilters> |
| 91 | ); |
| 92 | } ); |
| 93 | |
| 94 | export default PanelArea; |
| 95 |