disable-blocks.js
1 year ago
editor.scss
1 year ago
global-max-width.js
1 year ago
index.js
1 year ago
stores.js
1 year ago
style-html-attribute.js
1 year ago
toolbar-appenders.js
1 year ago
style-html-attribute.js
78 lines
| 1 | import { addFilter } from '@wordpress/hooks'; |
| 2 | import { replaceTags } from '../dynamic-tags/utils'; |
| 3 | |
| 4 | const cache = {}; |
| 5 | |
| 6 | function getCacheKey( clientId, context ) { |
| 7 | const { |
| 8 | 'generateblocks/loopIndex': loopIndex, |
| 9 | postId, |
| 10 | } = context; |
| 11 | |
| 12 | let key = ''; |
| 13 | |
| 14 | if ( loopIndex ) { |
| 15 | key += `${ loopIndex }_`; |
| 16 | } |
| 17 | |
| 18 | if ( postId ) { |
| 19 | key += `${ postId }_`; |
| 20 | } |
| 21 | |
| 22 | key += clientId; |
| 23 | |
| 24 | return key; |
| 25 | } |
| 26 | |
| 27 | addFilter( |
| 28 | 'generateblocks.editor.htmlAttributes.style', |
| 29 | 'generateblocks/styleWithReplacements', |
| 30 | async( style, props ) => { |
| 31 | const { context, clientId } = props; |
| 32 | |
| 33 | const previewEnabled = 'enabled' === generateBlocksEditor?.dynamicTagsPreview; |
| 34 | |
| 35 | if ( ! previewEnabled ) { |
| 36 | return style; |
| 37 | } |
| 38 | |
| 39 | // Check if any replacements need to be made |
| 40 | if ( ! style.includes( '{{' ) || ! style ) { |
| 41 | return style; |
| 42 | } |
| 43 | |
| 44 | const blockCacheKey = getCacheKey( clientId, context ); |
| 45 | |
| 46 | // Prime the cache for this block. |
| 47 | if ( ! cache[ blockCacheKey ] ) { |
| 48 | cache[ blockCacheKey ] = {}; |
| 49 | } |
| 50 | |
| 51 | // Get the cached result if available. |
| 52 | if ( cache[ blockCacheKey ][ style ] ) { |
| 53 | return cache[ blockCacheKey ][ style ]; |
| 54 | } |
| 55 | |
| 56 | const replacements = await replaceTags( { content: style, context, clientId } ); |
| 57 | |
| 58 | if ( ! replacements.length ) { |
| 59 | return style; |
| 60 | } |
| 61 | |
| 62 | const withReplacements = replacements.reduce( ( acc, { original, replacement, fallback } ) => { |
| 63 | if ( ! replacement ) { |
| 64 | return acc.replaceAll( original, fallback ); |
| 65 | } |
| 66 | |
| 67 | return acc.replaceAll( original, replacement ); |
| 68 | }, style ); |
| 69 | |
| 70 | const newStyle = withReplacements ? withReplacements : style; |
| 71 | |
| 72 | // Cache the result. |
| 73 | cache[ blockCacheKey ][ style ] = newStyle; |
| 74 | |
| 75 | return newStyle; |
| 76 | } |
| 77 | ); |
| 78 |