sources.js
84 lines
| 1 | /** |
| 2 | * WordPress dependencies. |
| 3 | */ |
| 4 | import { __ } from '@wordpress/i18n'; |
| 5 | import { registerBlockBindingsSource } from '@wordpress/blocks'; |
| 6 | import { store as coreDataStore } from '@wordpress/core-data'; |
| 7 | |
| 8 | /** |
| 9 | * Get the value of a specific field from the ACF fields. |
| 10 | * |
| 11 | * @param {Object} fields The ACF fields object. |
| 12 | * @param {string} fieldName The name of the field to retrieve. |
| 13 | * @returns {string} The value of the specified field, or undefined if not found. |
| 14 | */ |
| 15 | const getFieldValue = ( fields, fieldName ) => fields?.acf?.[ fieldName ]; |
| 16 | |
| 17 | const resolveImageAttribute = ( imageObj, attribute ) => { |
| 18 | if ( ! imageObj ) return ''; |
| 19 | switch ( attribute ) { |
| 20 | case 'url': |
| 21 | case 'content': |
| 22 | return imageObj.source_url; |
| 23 | case 'alt': |
| 24 | return imageObj.alt_text || ''; |
| 25 | case 'title': |
| 26 | return imageObj.title?.rendered || ''; |
| 27 | default: |
| 28 | return ''; |
| 29 | } |
| 30 | }; |
| 31 | |
| 32 | registerBlockBindingsSource( { |
| 33 | name: 'acf/field', |
| 34 | label: 'SCF Fields', |
| 35 | getValues( { context, bindings, select } ) { |
| 36 | const { getEditedEntityRecord, getMedia } = select( coreDataStore ); |
| 37 | let fields = |
| 38 | context?.postType && context?.postId |
| 39 | ? getEditedEntityRecord( |
| 40 | 'postType', |
| 41 | context.postType, |
| 42 | context.postId |
| 43 | ) |
| 44 | : undefined; |
| 45 | const result = {}; |
| 46 | |
| 47 | Object.entries( bindings ).forEach( |
| 48 | ( [ attribute, { args } = {} ] ) => { |
| 49 | const fieldName = args?.key; |
| 50 | |
| 51 | const fieldValue = getFieldValue( fields, fieldName ); |
| 52 | if ( typeof fieldValue === 'object' && fieldValue !== null ) { |
| 53 | let value = ''; |
| 54 | |
| 55 | if ( fieldValue[ attribute ] ) { |
| 56 | value = fieldValue[ attribute ]; |
| 57 | } else if ( attribute === 'content' && fieldValue.url ) { |
| 58 | value = fieldValue.url; |
| 59 | } |
| 60 | |
| 61 | result[ attribute ] = value; |
| 62 | } else if ( typeof fieldValue === 'number' ) { |
| 63 | if ( attribute === 'content' ) { |
| 64 | result[ attribute ] = fieldValue.toString() || ''; |
| 65 | } else { |
| 66 | const imageObj = getMedia( fieldValue ); |
| 67 | result[ attribute ] = resolveImageAttribute( |
| 68 | imageObj, |
| 69 | attribute |
| 70 | ); |
| 71 | } |
| 72 | } else { |
| 73 | result[ attribute ] = fieldValue || ''; |
| 74 | } |
| 75 | } |
| 76 | ); |
| 77 | |
| 78 | return result; |
| 79 | }, |
| 80 | canUserEditValue() { |
| 81 | return false; |
| 82 | }, |
| 83 | } ); |
| 84 |