Skip to content

Experiment: Connect block attributes with custom fields via UI #176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: trunk
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
218 changes: 218 additions & 0 deletions assets/src/js/bindings/block-editor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
/**
* WordPress dependencies
*/
import { useState, useEffect, useCallback, useMemo } from '@wordpress/element';
import { addFilter } from '@wordpress/hooks';
import { createHigherOrderComponent } from '@wordpress/compose';
import {
InspectorControls,
useBlockBindingsUtils,
} from '@wordpress/block-editor';
import {
PanelBody,
ComboboxControl,
PanelRow,
Button,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';
import { store as coreDataStore } from '@wordpress/core-data';
import { store as editorStore } from '@wordpress/editor';

const BLOCK_BINDINGS_ALLOWED_BLOCKS = {
'core/paragraph': [ 'content' ],
'core/heading': [ 'content' ],
'core/image': [ 'id', 'url', 'title', 'alt' ],
'core/button': [ 'url', 'text', 'linkTarget', 'rel' ],
};

/**
* Gets the bindable attributes for a given block.
*
* @param {string} blockName The name of the block.
*
* @return {string[]} The bindable attributes for the block.
*/
function getBindableAttributes( blockName ) {
return BLOCK_BINDINGS_ALLOWED_BLOCKS[ blockName ];
}

/**
* Add custom controls to all blocks
*/
const withCustomControls = createHigherOrderComponent( ( BlockEdit ) => {
return ( props ) => {
const bindableAttributes = getBindableAttributes( props.name );
const { updateBlockBindings, removeAllBlockBindings } =
useBlockBindingsUtils();

const { postType, postId } = useSelect( ( select ) => {
const { getCurrentPostType, getCurrentPostId } =
select( editorStore );
return {
postType: getCurrentPostType(),
postId: getCurrentPostId(),
};
}, [] );

const fieldsGroups = useSelect(
( select ) => {
const { getEditedEntityRecord } = select( coreDataStore );

if ( ! postType || ! postId ) {
return undefined;
}

const record = getEditedEntityRecord(
'postType',
postType,
postId
);
return record?.scf_field_groups;
},
[ postType, postId ]
);

const currentBindings = props.attributes?.metadata?.bindings || {};

// Memoize the fields transformation to prevent unnecessary recalculations
const fields = useMemo(
() =>
fieldsGroups?.reduce( ( acc, fieldGroup ) => {
const groupFields =
fieldGroup.fields?.map( ( field ) => ( {
...field,
fieldGroupTitle: fieldGroup.title,
name: field.name,
label: field.label,
value: field.value,
} ) ) || [];

return [ ...acc, ...groupFields ];
}, [] ) || [],
[ fieldsGroups ]
);

// Memoize the fieldsSuggestions to avoid recreating on every render
const fieldsSuggestions = useMemo(
() =>
fields.map( ( field ) => ( {
value: field.name,
label: field.label,
} ) ),
[ fields ]
);

// Initialize the field state with an empty object to track multiple attributes
const [ boundFields, setBoundFields ] = useState( {} );

// Memoize the stringified currentBindings to avoid unnecessary effect runs
const currentBindingsKey = useMemo(
() => JSON.stringify( currentBindings ),
[ currentBindings ]
);

// Initialize bound fields from current bindings when they change
useEffect( () => {
if ( Object.keys( currentBindings ).length > 0 ) {
const initialBoundFields = {};

// Extract field values from current bindings
Object.keys( currentBindings ).forEach( ( attribute ) => {
if ( currentBindings[ attribute ]?.args?.key ) {
initialBoundFields[ attribute ] =
currentBindings[ attribute ].args.key;
}
} );

setBoundFields( initialBoundFields );
}
}, [ currentBindingsKey ] );

// Memoize the change handler to prevent creating new function on each render
const handleFieldChange = useCallback(
( attribute, value ) => {
setBoundFields( ( prevState ) => ( {
...prevState,
[ attribute ]: value,
} ) );

updateBlockBindings( {
[ attribute ]: {
source: 'acf/field',
args: {
key: value,
},
},
} );
},
[ updateBlockBindings ]
);

if ( fieldsSuggestions.length === 0 || ! bindableAttributes ) {
return <BlockEdit { ...props } />;
}

return (
<>
<BlockEdit { ...props } />
<InspectorControls>
<PanelBody
title={ __(
'Connect to a field',
'secure-custom-fields'
) }
initialOpen={ true }
>
{ bindableAttributes.map( ( attribute ) => (
<PanelRow key={ `scf-field-${ attribute }` }>
<ComboboxControl
__next40pxDefaultSize
__nextHasNoMarginBottom
__experimentalShowHowTo={ false }
__experimentalExpandOnFocus={ true }
__experimentalAutoSelectFirstMatch={ true }
label={ attribute }
placeholder={ __(
'Select a field',
'secure-custom-fields'
) }
options={ fieldsSuggestions }
value={ boundFields[ attribute ] || '' }
onChange={ ( value ) =>
handleFieldChange( attribute, value )
}
key={ `scf-field-${ attribute }` }
/>
</PanelRow>
) ) }
<PanelRow>
<Button
onClick={ () => {
removeAllBlockBindings();
setBoundFields( {} );
} }
__next40pxDefaultSize
isDestructive
>
{ __(
'Clear All Fields',
'secure-custom-fields'
) }
</Button>
</PanelRow>
</PanelBody>
</InspectorControls>
</>
);
};
}, 'withCustomControls' );

// Only register the filter if the connect_fields beta feature is enabled
if ( window.scf?.betaFeatures?.connect_fields ) {
addFilter(
'editor.BlockEdit',
'secure-custom-fields/with-custom-controls',
withCustomControls
);
}
1 change: 1 addition & 0 deletions assets/src/js/bindings/index.js
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
import './sources.js';
import './block-editor.js';
3 changes: 3 additions & 0 deletions assets/src/sass/_forms.scss
Original file line number Diff line number Diff line change
Expand Up @@ -315,3 +315,6 @@ p.submit .acf-spinner {
}
}

.scf-field-token-field {
margin-bottom: 2em;
}
51 changes: 26 additions & 25 deletions includes/admin/beta-features.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ class SCF_Admin_Beta_Features {
* @return void
*/
public function __construct() {
// Temporarily disabled - will be enabled when beta feature is ready
// add_action( 'admin_menu', array( $this, 'admin_menu' ), 20 );
add_action( 'admin_menu', array( $this, 'admin_menu' ), 20 );
}

/**
Expand Down Expand Up @@ -78,26 +77,6 @@ public function get_beta_features() {
return $this->beta_features;
}

/**
* Localizes the beta features data.
*
* @since SCF 6.5.0
*
* @return void
*/
public function localize_beta_features() {
$beta_features = array();
foreach ( $this->get_beta_features() as $name => $beta_feature ) {
$beta_features[ $name ] = $beta_feature->is_enabled();
}

acf_localize_data(
array(
'betaFeatures' => $beta_features,
)
);
}

/**
* This function will add the SCF beta features menu item to the WP admin
*
Expand All @@ -115,7 +94,7 @@ public function admin_menu() {
$page = add_submenu_page( 'edit.php?post_type=acf-field-group', __( 'Beta Features', 'secure-custom-fields' ), __( 'Beta Features', 'secure-custom-fields' ), acf_get_setting( 'capability' ), 'scf-beta-features', array( $this, 'html' ) );

add_action( 'load-' . $page, array( $this, 'load' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'localize_beta_features' ), 20 );
add_action( 'admin_enqueue_scripts', array( $this, 'add_beta_features_script' ), 20 );
}

/**
Expand Down Expand Up @@ -155,7 +134,7 @@ public function admin_body_class( $classes ) {
*/
private function include_beta_features() {
acf_include( 'includes/admin/beta-features/class-scf-beta-feature.php' );
acf_include( 'includes/admin/beta-features/class-scf-beta-feature-editor-sidebar.php' );
acf_include( 'includes/admin/beta-features/class-scf-beta-feature-connect-fields.php' );

add_action( 'scf/include_admin_beta_features', array( $this, 'register_beta_features' ) );

Expand All @@ -170,7 +149,7 @@ private function include_beta_features() {
* @return void
*/
public function register_beta_features() {
scf_register_admin_beta_feature( 'SCF_Admin_Beta_Feature_Editor_Sidebar' );
scf_register_admin_beta_feature( 'SCF_Admin_Beta_Feature_Connect_Fields' );
}

/**
Expand Down Expand Up @@ -255,6 +234,28 @@ public function metabox_html( $post, $metabox ) {
acf_nonce_input( $beta_feature->name );
echo '</form>';
}

/**
* Adds the editor sidebar script to the page.
*
* @since SCF 6.5.0
*
* @return void
*/
public function add_beta_features_script() {
// Check if the connected fields feature is enabled

$script = 'window.scf = window.scf || {};
window.scf = window.scf || {};
window.scf.betaFeatures = window.scf.betaFeatures || {};';
foreach ( $this->get_beta_features() as $name => $beta_feature ) {
if ( $beta_feature->is_enabled() ) {
$script .= sprintf( 'window.scf.betaFeatures.%s = true;', esc_js( $name ) );
}
}

wp_add_inline_script( 'wp-block-editor', $script, 'before' );
}
}

// initialize
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php
/**
* Connect Fields Feature
*
* This beta feature allows moving field group elements to the editor sidebar.
*
* @package Secure Custom Fields
* @since SCF 6.5.0
*/

if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}

if ( ! class_exists( 'SCF_Admin_Beta_Feature_Connect_Fields' ) ) :
/**
* Class SCF_Admin_Beta_Feature_Connect_Fields
*
* Implements a beta feature to move field group elements to the editor sidebar
* for a cleaner interface.
*
* @package Secure Custom Fields
* @since SCF 6.5.0
*/
class SCF_Admin_Beta_Feature_Connect_Fields extends SCF_Admin_Beta_Feature {

/**
* Initialize the beta feature.
*
* @return void
*/
protected function initialize() {
$this->name = 'connect_fields';
$this->title = __( 'Connect Fields', 'secure-custom-fields' );
$this->description = __( 'Connects field to binding compatible blocks.', 'secure-custom-fields' );
}
}
endif;
Loading
Loading