index.js
2 years ago
useAuthors.js
3 years ago
useDebounceState.js
4 years ago
useDeviceAttributes.js
2 years ago
useDeviceType.js
2 years ago
useInnerBlocksCount.js
4 years ago
useRecordsReducer.js
3 years ago
useSelectedBlockElements.js
2 years ago
useStyleIndicator.js
2 years ago
useTaxonomies.js
4 years ago
useTaxonomyRecords.js
3 years ago
useDeviceType.js
52 lines
| 1 | import { useDispatch, useSelect, dispatch } from '@wordpress/data'; |
| 2 | import { useEffect } from '@wordpress/element'; |
| 3 | import useLocalStorageState from 'use-local-storage-state'; |
| 4 | |
| 5 | export default ( initialDeviceType = 'Desktop' ) => { |
| 6 | const [ localDeviceType, setLocalDeviceType ] = useLocalStorageState( |
| 7 | 'generateblocksDeviceType', { |
| 8 | ssr: true, |
| 9 | defaultValue: initialDeviceType, |
| 10 | } |
| 11 | ); |
| 12 | |
| 13 | if ( ! dispatch( 'core/edit-post' ) || ( generateBlocksInfo && ! generateBlocksInfo.syncResponsivePreviews ) ) { |
| 14 | const setDeviceType = ( type ) => { |
| 15 | setLocalDeviceType( type ); |
| 16 | }; |
| 17 | |
| 18 | return [ localDeviceType, setDeviceType ]; |
| 19 | } |
| 20 | |
| 21 | const { |
| 22 | __experimentalSetPreviewDeviceType: setPreviewDeviceType = () => {}, |
| 23 | } = useDispatch( 'core/edit-post' ); |
| 24 | |
| 25 | const previewDeviceType = useSelect( ( select ) => { |
| 26 | const { |
| 27 | __experimentalGetPreviewDeviceType: experimentalGetPreviewDeviceType = () => false, |
| 28 | } = select( 'core/edit-post' ); |
| 29 | |
| 30 | return experimentalGetPreviewDeviceType(); |
| 31 | }, [] ); |
| 32 | |
| 33 | useEffect( () => { |
| 34 | if ( previewDeviceType !== localDeviceType ) { |
| 35 | setLocalDeviceType( previewDeviceType ); |
| 36 | } |
| 37 | }, [ previewDeviceType ] ); |
| 38 | |
| 39 | const setDeviceType = ( type ) => { |
| 40 | setPreviewDeviceType( type ); |
| 41 | setLocalDeviceType( type ); |
| 42 | }; |
| 43 | |
| 44 | // Here we are anticipating the return of the correct device value, instead of waiting another update from the useEffect above. |
| 45 | // This avoids attributes with old values when changing devices using the core buttons. |
| 46 | if ( previewDeviceType !== localDeviceType ) { |
| 47 | return [ previewDeviceType, setDeviceType ]; |
| 48 | } |
| 49 | |
| 50 | return [ localDeviceType, setDeviceType ]; |
| 51 | }; |
| 52 |