index.js
85 lines
| 1 | import { __ } from '@wordpress/i18n'; |
| 2 | import { Button, Tooltip } from '@wordpress/components'; |
| 3 | import { Icon, desktop, tablet, mobile } from '@wordpress/icons'; |
| 4 | import { memo, useCallback, useEffect } from '@wordpress/element'; |
| 5 | import { useDeviceType } from '../../../../hooks'; |
| 6 | import './editor.scss'; |
| 7 | import compatibleRender from '../../../../utils/compatible-render'; |
| 8 | |
| 9 | function DeviceButton( { deviceKey, label, isActive, onClick, icon } ) { |
| 10 | return ( |
| 11 | <Tooltip text={ label }> |
| 12 | <Button isPressed={ isActive } onClick={ () => onClick( deviceKey ) }> |
| 13 | <Icon icon={ icon } /> |
| 14 | </Button> |
| 15 | </Tooltip> |
| 16 | ); |
| 17 | } |
| 18 | |
| 19 | const MemoizedDeviceButton = memo( DeviceButton ); |
| 20 | |
| 21 | const devices = [ |
| 22 | { |
| 23 | key: 'Desktop', |
| 24 | label: __( 'Show options for all devices', 'generateblocks' ), |
| 25 | icon: desktop, |
| 26 | }, |
| 27 | { |
| 28 | key: 'Tablet', |
| 29 | label: __( 'Show options for tablet devices', 'generateblocks' ), |
| 30 | icon: tablet, |
| 31 | }, |
| 32 | { |
| 33 | key: 'Mobile', |
| 34 | label: __( 'Show options for mobile devices', 'generateblocks' ), |
| 35 | icon: mobile, |
| 36 | }, |
| 37 | ]; |
| 38 | |
| 39 | function ResponsiveTabButtons() { |
| 40 | const [ deviceType, setDeviceType ] = useDeviceType(); |
| 41 | const onClickDeviceButton = useCallback( setDeviceType, [] ); |
| 42 | |
| 43 | return ( |
| 44 | <> |
| 45 | { devices && devices.map( ( device ) => ( |
| 46 | <MemoizedDeviceButton |
| 47 | key={ device.key } |
| 48 | deviceKey={ device.key } |
| 49 | label={ device.label } |
| 50 | isActive={ deviceType === device.key } |
| 51 | icon={ device.icon } |
| 52 | onClick={ onClickDeviceButton } |
| 53 | /> |
| 54 | ) ) } |
| 55 | </> |
| 56 | ); |
| 57 | } |
| 58 | |
| 59 | function ResponsiveTabs() { |
| 60 | useEffect( () => { |
| 61 | const BlockInspectorControls = document.querySelector( '.block-editor-block-inspector' ); |
| 62 | const ResponsiveTabsElement = document.querySelector( '.gb-responsive-tabs' ); |
| 63 | |
| 64 | if ( ! BlockInspectorControls || ResponsiveTabsElement ) { |
| 65 | return; |
| 66 | } |
| 67 | |
| 68 | const panelHeader = document.querySelector( '.edit-post-sidebar .edit-post-sidebar__panel-tabs' ); |
| 69 | const panelHeaderHeight = panelHeader ? `${ panelHeader.offsetHeight }px` : 0; |
| 70 | const buttonWrapper = document.createElement( 'div' ); |
| 71 | buttonWrapper.classList.add( 'gb-responsive-tabs' ); |
| 72 | buttonWrapper.style.top = panelHeaderHeight; |
| 73 | BlockInspectorControls.prepend( buttonWrapper ); |
| 74 | |
| 75 | compatibleRender( |
| 76 | document.querySelector( '.gb-responsive-tabs' ), |
| 77 | <ResponsiveTabButtons /> |
| 78 | ); |
| 79 | }, [] ); |
| 80 | |
| 81 | return null; |
| 82 | } |
| 83 | |
| 84 | export default memo( ResponsiveTabs ); |
| 85 |