jetformbuilder
/
modules
/
framework
/
blocks-style-manager
/
assets
/
src
/
hoc-wrappers
/
with-block-class.js
jetformbuilder
/
modules
/
framework
/
blocks-style-manager
/
assets
/
src
/
hoc-wrappers
Last commit date
with-block-class.js
3 months ago
with-styles-controls.js
3 months ago
with-block-class.js
75 lines
| 1 | import { createHigherOrderComponent } from '@wordpress/compose'; |
| 2 | import { useSelect } from '@wordpress/data'; |
| 3 | import { useEffect } from '@wordpress/element'; |
| 4 | |
| 5 | export const withBlockUniqueClass = createHigherOrderComponent( ( BlockListBlockComponent ) => { |
| 6 | return ( props ) => { |
| 7 | const { |
| 8 | name, |
| 9 | className = '', |
| 10 | clientId, |
| 11 | setAttributes, |
| 12 | attributes, |
| 13 | } = props; |
| 14 | |
| 15 | // Pull the block’s registration info |
| 16 | const blockType = useSelect( |
| 17 | ( select ) => select( 'core/blocks' ).getBlockType( name ), |
| 18 | [ name ] |
| 19 | ); |
| 20 | |
| 21 | // If crocoblock_styles support is present, add our class |
| 22 | if ( blockType?.supports?.crocoblock_styles ) { |
| 23 | |
| 24 | const uniqueClass = props?.attributes?.[ window.crocoStyleEditorData.support_name ]?.[ '_uniqueClassName' ]; |
| 25 | |
| 26 | useEffect( () => { |
| 27 | if ( window.crocoBlockStyleEditor.classIsUsed( uniqueClass, clientId ) ) { |
| 28 | // If the class is already used, we need to generate a new one |
| 29 | const newUniqueClass = generateUniqueClassName(); |
| 30 | |
| 31 | setAttributes( { |
| 32 | [ window.crocoStyleEditorData.support_name ]: { |
| 33 | ...attributes[ window.crocoStyleEditorData.support_name ], |
| 34 | _uniqueClassName: newUniqueClass, |
| 35 | }, |
| 36 | } ); |
| 37 | } |
| 38 | }, [] ); |
| 39 | |
| 40 | return ( |
| 41 | <BlockListBlockComponent |
| 42 | { ...props } |
| 43 | className={ `${ className } ${ uniqueClass }`.trim() } |
| 44 | /> |
| 45 | ); |
| 46 | } |
| 47 | |
| 48 | // Otherwise render unmodified |
| 49 | return <BlockListBlockComponent |
| 50 | { ...props } |
| 51 | />; |
| 52 | }; |
| 53 | }, 'withBlockUniqueClass' ); |
| 54 | |
| 55 | export const generateUniqueClassName = () => { |
| 56 | |
| 57 | const length = 8; |
| 58 | |
| 59 | let chars = 'abcdefghijklmnopqrstuvwxyz0123456789'; |
| 60 | let result = ''; |
| 61 | |
| 62 | for ( let i = 0; i < length; i++ ) { |
| 63 | |
| 64 | if ( i === 0 ) { |
| 65 | // Ensure the first character is a letter |
| 66 | result += chars.charAt( Math.floor( Math.random() * 26 ) ); |
| 67 | continue; |
| 68 | } |
| 69 | |
| 70 | result += chars.charAt( Math.floor( Math.random() * chars.length ) ); |
| 71 | } |
| 72 | |
| 73 | return window.crocoStyleEditorData.class_prefix + result; |
| 74 | } |
| 75 |