corvée(dépendances) ajoute Carbon Fields

This commit is contained in:
gcch 2024-08-09 18:45:01 +02:00
commit 62368587e5
459 changed files with 72750 additions and 26 deletions

View file

@ -0,0 +1,315 @@
/**
* External dependencies.
*/
import cx from 'classnames';
import { Component, Fragment } from '@wordpress/element';
import { ToolbarGroup, PanelBody } from '@wordpress/components';
import {
InnerBlocks,
BlockControls,
InspectorControls
} from '@wordpress/editor';
import { withSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import {
get,
map,
find
} from 'lodash';
/**
* Carbon Fields dependencies.
*/
import { getFieldType } from '@carbon-fields/core';
/**
* Internal dependencies.
*/
import './style.scss';
import Field from '../field';
import ServerSideRender from '../server-side-render';
class BlockEdit extends Component {
/**
* Local state.
*
* @type {Object}
*/
state = {
mode: this.props.container.settings.mode,
currentTab: this.props.supportsTabs
? Object.keys( this.props.container.settings.tabs )[ 0 ]
: null
};
/**
* Handles the change of the field's value.
*
* @param {string} fieldId
* @param {mixed} value
* @return {void}
*/
handleFieldChange = ( fieldId, value ) => {
const { attributes, setAttributes } = this.props;
const fieldName = fieldId.replace( /^.+__(.+)?$/, '$1' );
setAttributes( {
data: {
...attributes.data,
[ fieldName ]: value
}
} );
}
/**
* Handles changing of the mode.
*
* @return {void}
*/
handleModeChange = () => {
this.setState( {
mode: this.isInEditMode ? 'preview' : 'edit'
} );
}
/**
* Handles changing on the tabs.
*
* @param {string} tab
* @return {void}
*/
handleTabChange = ( tab ) => {
this.setState( {
currentTab: tab
} );
}
/**
* Returns whether the block is in edit mode.
*
* @return {boolean}
*/
get isInEditMode() {
return this.state.mode === 'edit';
}
/**
* Returns whether the block is in edit mode.
*
* @return {boolean}
*/
get isInPreviewMode() {
return this.state.mode === 'preview';
}
/**
* Renders a field.
*
* @param {Object} field
* @param {number} index
* @return {Object}
*/
renderField = ( field, index ) => {
const {
clientId,
container,
attributes
} = this.props;
const FieldEdit = getFieldType( field.type, 'block' );
if ( ! FieldEdit ) {
return null;
}
const id = `cf-${ clientId }__${ field.base_name }`;
const value = get( attributes.data, field.base_name, field.default_value );
return (
<Field
key={ index }
id={ id }
field={ field }
>
<FieldEdit
id={ id }
containerId={ container.id }
blockId={ clientId }
value={ value }
field={ field }
name={ field.base_name }
onChange={ this.handleFieldChange }
/>
</Field>
);
}
/**
* Renders the fields in tabs.
*
* @param {string[]} fieldNames
* @return {Object[]}
*/
renderTabbedFields( fieldNames ) {
const { fields } = this.props;
return map( fieldNames, ( fieldName, index ) => {
const field = find( fields, [ 'name', fieldName ] );
return this.renderField( field, index );
} );
}
/**
* Renders the fields that aren't in tabs.
*
* @return {Object}
*/
renderNonTabbedFields() {
return (
<div className="cf-block__fields">
{ this.props.fields.map( this.renderField ) }
</div>
);
}
/**
* Render the component.
*
* @return {Object}
*/
render() {
const { currentTab } = this.state;
const {
clientId,
container,
supportsTabs,
supportsPreview,
supportsInnerBlocks
} = this.props;
const innerBlocks = ( ( supportsInnerBlocks && this.isInEditMode ) && (
<div className="cf-block__inner-blocks">
<InnerBlocks
template={ container.settings.inner_blocks.template }
templateLock={ container.settings.inner_blocks.template_lock }
allowedBlocks={ container.settings.inner_blocks.allowed_blocks }
/>
</div>
) );
return (
<Fragment>
{ container.settings.inner_blocks.position === 'above' && innerBlocks }
{ supportsPreview && (
<BlockControls>
<ToolbarGroup label="Options" controls={ [ {
icon: this.isInEditMode
? 'visibility'
: 'hidden',
title: this.isInEditMode
? __( 'Show preview', 'carbon-fields-ui' )
: __( 'Hide preview', 'carbon-fields-ui' ),
onClick: this.handleModeChange
} ] } />
</BlockControls>
) }
{ ( this.isInEditMode && supportsTabs ) && (
<div className="cf-block__tabs">
<ul className="cf-block__tabs-list">
{ map( container.settings.tabs, ( fieldNames, tabName ) => {
const classes = cx(
'cf-block__tabs-item',
{
'cf-block__tabs-item--current': tabName === currentTab
}
);
return (
<li
key={ tabName }
className={ classes }
onClick={ () => this.handleTabChange( tabName ) }
>
{ tabName }
</li>
);
} ) }
</ul>
</div>
) }
{ this.isInEditMode && (
supportsTabs
? (
map( container.settings.tabs, ( fieldNames, tabName ) => {
return (
<div className="cf-block__fields" key={ tabName } hidden={ tabName !== currentTab }>
{ this.renderTabbedFields( fieldNames ) }
</div>
);
} )
)
: (
this.renderNonTabbedFields()
)
) }
{ this.isInPreviewMode && (
<div className="cf-block__preview">
<ServerSideRender clientId={ clientId } />
</div>
) }
{ container.settings.inner_blocks.position === 'below' && innerBlocks }
{ this.isInPreviewMode && (
<InspectorControls>
{
supportsTabs
? (
map( container.settings.tabs, ( fieldNames, tabName ) => {
return (
<PanelBody key={ tabName } title={ tabName }>
<div className="cf-block__fields">
{ this.renderTabbedFields( fieldNames ) }
</div>
</PanelBody>
);
} )
)
: (
<PanelBody title={ __( 'Fields', 'carbon-fields-ui' ) }>
{ this.renderNonTabbedFields() }
</PanelBody>
)
}
</InspectorControls>
) }
</Fragment>
);
}
}
export default withSelect( ( select, { clientId, name } ) => {
const { hasBlockSupport } = select( 'core/blocks' );
const { getBlockRootClientId } = select( 'core/block-editor' );
const {
getContainerDefinitionByBlockName,
getFieldDefinitionsByBlockName
} = select( 'carbon-fields/blocks' );
const rootClientId = getBlockRootClientId( clientId );
return {
container: getContainerDefinitionByBlockName( name ),
fields: getFieldDefinitionsByBlockName( name ),
supportsTabs: hasBlockSupport( name, 'tabs' ),
supportsPreview: hasBlockSupport( name, 'preview' ) && ! rootClientId,
supportsInnerBlocks: hasBlockSupport( name, 'innerBlocks' )
};
} )( BlockEdit );

View file

@ -0,0 +1,51 @@
/* ==========================================================================
Block
========================================================================== */
.cf-block__tabs {
margin-bottom: $size-base * 4;
}
.cf-block__tabs-list {
.wp-block & {
display: flex;
padding: 0;
margin: 0;
list-style: none outside none;
}
}
.cf-block__tabs-item {
padding: $size-base * 2;
margin: 0;
font-family: $wp-font;
font-size: $wp-font-size;
line-height: 1;
cursor: pointer;
&--current {
box-shadow: 0 3px 0 $wp-color-medium-blue;
}
}
.cf-block__fields {
display: flex;
flex-wrap: wrap;
&[hidden] {
display: none;
}
.wp-block & {
margin: $size-base * -2;
}
}
.cf-block__preview {
min-height: 100px;
}
.cf-block__inner-blocks .block-list-appender {
margin-top: 32px;
margin-bottom: 32px;
}

View file

@ -0,0 +1,41 @@
/**
* External dependencies.
*/
import { Component } from '@wordpress/element';
import { InnerBlocks } from '@wordpress/editor';
class BlockSave extends Component {
/**
* Render the component.
*
* @return {null}
*/
render() {
return null;
}
}
/**
* Adds the content of inner blocks to the saved content.
*
* @param {mixed} element
* @param {Object} blockType
* @return {mixed}
*/
function addInnerBlocksContent( element, blockType ) {
if ( ! /^carbon\-fields\/.+$/.test( blockType.name ) ) {
return element;
}
if ( ! blockType.supports.innerBlocks ) {
return element;
}
return (
<InnerBlocks.Content />
);
}
wp.hooks.addFilter( 'blocks.getSaveElement', 'carbon-fields/blocks', addInnerBlocksContent );
export default BlockSave;

View file

@ -0,0 +1,11 @@
/**
* Carbon Fields dependencies.
*/
import { Field, withFilters } from '@carbon-fields/core';
/**
* Internal dependencies.
*/
import './style.scss';
export default withFilters( 'carbon-fields.field-wrapper.block' )( Field );

View file

@ -0,0 +1,47 @@
/* ==========================================================================
Field
========================================================================== */
.cf-field {
.block-editor & {
font-family: $wp-font;
font-size: $wp-font-size;
line-height: $wp-line-height;
color: $gb-dark-gray-500;
padding: $size-base * 2;
min-width: 0;
}
.wp-block-widget-area & {
padding: 6.5px 20px;
}
.edit-post-sidebar .cf-block__fields > & {
padding: $size-base 0 0;
}
.block-editor .cf-complex & {
border-width: 1px 1px 0 0;
border-style: solid;
border-color: $wp-color-gray-light-500;
}
.edit-post-sidebar .cf-complex & {
border-color: $gb-dark-gray-150;
}
}
.cf-field__label {
font-size: 13px;
font-weight: 600;
color: $wp-color-dark-gray;
.block-editor & {
margin-bottom: 4px;
}
.wp-block-widget-area & {
margin-bottom: 6.5px;
}
}

View file

@ -0,0 +1,18 @@
/**
* The external dependencies.
*/
import { __, sprintf } from '@wordpress/i18n';
/**
* Render a notice to inform the user that the field doesn't have
* any options.
*
* @return {React.Element}
*/
const NotSupportedField = ( { type } ) => (
<em>
{ sprintf( __( `Field of type '%s' is not supported in Gutenberg.`, 'carbon-fields-ui' ), [ type ] ) }
</em>
);
export default NotSupportedField;

View file

@ -0,0 +1,154 @@
/**
* External dependencies.
*/
import apiFetch from '@wordpress/api-fetch';
import { Component, RawHTML } from '@wordpress/element';
import { Placeholder, Spinner } from '@wordpress/components';
import { withSelect } from '@wordpress/data';
import { serialize } from '@wordpress/blocks';
import { __, sprintf } from '@wordpress/i18n';
import { isEqual, debounce } from 'lodash';
/**
* This component is slightly modified version of the `ServerSideRender` component
* that comes by default with Gutenberg.
*
* @see https://github.com/WordPress/gutenberg/tree/master/packages/components/src/server-side-render
*/
class ServerSideRender extends Component {
/**
* Local state.
*
* @type {Object}
*/
state = {
response: null
};
/**
* Lifecycle hook.
*
* @return {void}
*/
componentDidMount() {
this.isStillMounted = true;
// Do the initial rendering.
this.fetch( this.props );
// Only debounce once the initial fetch occurs to ensure that the first
// renders show data as soon as possible.
this.fetch = debounce( this.fetch, 500 );
}
/**
* Lifecycle hook.
*
* @return {void}
*/
componentWillUnmount() {
this.isStillMounted = false;
}
/**
* Lifecycle hook.
*
* @param {Object} prevProps
* @return {void}
*/
componentDidUpdate( prevProps ) {
if ( ! isEqual( prevProps, this.props ) ) {
this.fetch( this.props );
}
}
/**
* Fetch the preview of the block.
*
* @param {Object} props
* @return {void}
*/
fetch( props ) {
if ( ! this.isStillMounted ) {
return;
}
if ( null !== this.state.response ) {
this.setState( { response: null } );
}
const { block } = props;
// Store the latest fetch request so that when we process it, we can
// check if it is the current request, to avoid race conditions on slow networks.
const fetchRequest = this.currentFetchRequest = apiFetch( {
method: 'post',
path: '/carbon-fields/v1/block-renderer',
data: {
name: block.name,
content: serialize( [ block ] )
}
} )
.then( ( response ) => {
if ( this.isStillMounted && fetchRequest === this.currentFetchRequest && response && response.rendered ) {
this.setState( {
response: response.rendered
} );
}
} )
.catch( ( error ) => {
if ( this.isStillMounted && fetchRequest === this.currentFetchRequest ) {
this.setState( {
response: {
error: true,
errorMsg: error.message
}
} );
}
} );
}
/**
* Render the component.
*
* @return {Object}
*/
render() {
const { response } = this.state;
const { className } = this.props;
if ( ! response ) {
return (
<Placeholder className={ className }>
<Spinner />
</Placeholder>
);
} else if ( response.error ) {
return (
<Placeholder className={ className }>
{ sprintf( __( 'Error loading block: %s', 'carbon-fields-ui' ), response.errorMsg ) }
</Placeholder>
);
} else if ( ! response.length ) {
return (
<Placeholder className={ className }>
{ __( 'No results found.', 'carbon-fields-ui' ) }
</Placeholder>
);
}
return (
<RawHTML key="html" className={ className }>
{ response }
</RawHTML>
);
}
}
export default withSelect( ( select, { clientId } ) => {
const { getBlock } = select( 'core/block-editor' );
return {
block: getBlock( clientId )
};
} )( ServerSideRender );

View file

@ -0,0 +1,55 @@
/**
* External dependencies.
*/
import { addFilter } from '@wordpress/hooks';
import { select } from '@wordpress/data';
import { get, find } from 'lodash';
/**
* Carbon Fields dependencies.
*/
import { withProps } from '@carbon-fields/core';
/**
* Internal dependencies.
*/
import './style.scss';
addFilter( 'carbon-fields.association.block', 'carbon-fields/blocks', withProps( ( props ) => {
return {
hierarchyResolver() {
// Get the block that contains the field.
const block = select( 'core/block-editor' ).getBlock( props.blockId );
// Get the path.
const path = props.id.split( '__' );
// Remove the chunk that contains the block identifier.
path.shift();
// Get the hierarchy.
let hierarchy = path.shift();
let accessor = `data.${ hierarchy }`;
// Visit every branch in the tree so we can get the full hierarchy.
while ( path.length > 0 ) {
const chunk = path.shift();
const isGroup = chunk.indexOf( 'cf-' ) === 0;
if ( isGroup ) {
const groups = get( block.attributes, `${ accessor }` );
const group = find( groups, [ '_id', chunk ] );
const groupIndex = groups.indexOf( group );
accessor = `${ accessor }.${ groupIndex }`;
hierarchy = `${ hierarchy }[${ groupIndex }]:${ group._type }/`;
} else {
accessor = `${ accessor }.${ chunk }`;
hierarchy = `${ hierarchy }${ chunk }`;
}
}
return hierarchy;
}
};
} ) );

View file

@ -0,0 +1,72 @@
/* ==========================================================================
Association
========================================================================== */
.cf-association__cols {
.block-editor & {
border-top-width: 1px;
margin-top: 4px;
}
.edit-post-sidebar & {
border-color: $gb-dark-gray-150;
flex-direction: column;
}
.edit-post-sidebar &::before {
background-color: $gb-dark-gray-150;
display: none;
}
}
.cf-association__counter {
.edit-post-sidebar & {
display: none;
}
}
.cf-association__option {
.edit-post-sidebar & {
height: 40px;
}
.edit-post-sidebar & + & {
border-top-color: $gb-dark-gray-150;
}
}
.cf-association__option-thumb {
.edit-post-sidebar & {
display: none;
}
}
.cf-association__option-content {
.edit-post-sidebar & {
align-items: flex-start;
flex-direction: column;
min-width: 0;
}
}
.cf-association__option-title {
.edit-post-sidebar & {
width: 100%;
}
}
.cf-association__option-actions {
.edit-post-sidebar .cf-association__col:first-child & {
min-width: 0;
}
.edit-post-sidebar & {
margin-left: auto;
}
}
.cf-association__option-action {
.edit-post-sidebar &--edit {
display: none;
}
}

View file

@ -0,0 +1,4 @@
/**
* Internal dependencies.
*/
import './style.scss';

View file

@ -0,0 +1,15 @@
/* ------------------------------------------------------------ *\
Block Preview iFrame
\* ------------------------------------------------------------ */
body.block-editor-iframe__body {
.cf-block-preview {
display: block;
}
// Hide all other fields except the HTML fields with preview
// Also check if there is preview field at all or just show all fields
.cf-block__fields:has(.cf-block-preview) .cf-field:not(.cf-block-preview) {
display: none;
}
}

View file

@ -0,0 +1,325 @@
/**
* External dependencies.
*/
import produce from 'immer';
import { Component } from '@wordpress/element';
import { addFilter } from '@wordpress/hooks';
import {
get,
set,
find,
omit,
assign,
mapKeys,
without,
cloneDeep,
findIndex
} from 'lodash';
/**
* Carbon Fields dependencies.
*/
import { uniqueId } from '@carbon-fields/core';
/**
* Internal dependencies.
*/
import './style.scss';
import Field from '../../components/field';
class ComplexField extends Component {
/**
* Local state.
*
* @type {Object}
*/
state = {
collapsedGroups: this.props.value.reduce( ( accumulator, { _id, _type } ) => {
const group = find( this.props.field.groups, [ 'name', _type ] );
if ( ! group.collapsed ) {
return accumulator;
}
return accumulator.concat( _id );
}, [] )
};
/**
* Returns a list of group values.
*
* @return {Array}
*/
getGroupValues() {
return this.props.value.map( ( group ) => {
const values = mapKeys( omit( group, [ '_id', '_type' ] ), ( value, key ) => key.replace( /\-/g, '_' ) );
return [ group._type, values ];
} );
}
/**
* Handles adding of group.
*
* @param {Object} group
* @param {Function} callback
* @return {void}
*/
handleAddGroup = ( group, callback ) => {
const {
id,
value,
onChange
} = this.props;
const data = {};
data._id = uniqueId();
data._type = group.name;
group.fields.reduce( ( accumulator, field ) => {
accumulator[ field.base_name ] = field.default_value;
return accumulator;
}, data );
onChange( id, value.concat( data ) );
callback( data );
}
/**
* Handles cloning of group.
*
* @param {Object} group
* @param {Function} callback
* @return {void}
*/
handleCloneGroup = ( group, callback ) => {
const {
id,
value,
onChange
} = this.props;
const index = value.indexOf( group );
const clonedGroup = cloneDeep( group );
clonedGroup._id = uniqueId();
onChange( id, produce( value, ( draft ) => {
draft.splice( index + 1, 0, clonedGroup );
} ) );
callback( clonedGroup );
}
/**
* Handles removing of group.
*
* @param {Object} group
* @return {void}
*/
handleRemoveGroup = ( group ) => {
const {
id,
value,
onChange
} = this.props;
const groupIndex = findIndex( value, [ '_id', group._id ] );
onChange( id, produce( value, ( draft ) => {
draft.splice( groupIndex, 1 );
} ) );
this.setState( ( { collapsedGroups } ) => ( {
collapsedGroups: without( collapsedGroups, group._id )
} ) );
}
/**
* Handles expanding/collapsing of group.
*
* @param {string} groupId
* @return {void}
*/
handleToggleGroup = ( groupId ) => {
this.setState( ( { collapsedGroups } ) => {
if ( collapsedGroups.indexOf( groupId ) > -1 ) {
collapsedGroups = without( collapsedGroups, groupId );
} else {
collapsedGroups = [ ...collapsedGroups, groupId ];
}
return { collapsedGroups };
} );
}
/**
* Handles expanding/collapsing of all groups.
*
* @return {void}
*/
handleToggleAllGroups = () => {
const { value } = this.props;
this.setState( ( { collapsedGroups } ) => {
if ( collapsedGroups.length !== value.length ) {
collapsedGroups = value.map( ( group ) => group._id );
} else {
collapsedGroups = [];
}
return { collapsedGroups };
} );
}
/**
* Handles setuping of group.
*
* @param {Object} group
* @param {Object} props
* @return {Object}
*/
handleGroupSetup = ( group, props ) => {
const fields = get( find( this.props.field.groups, [ 'name', group._type ] ), 'fields', [] );
const values = omit( group, [ '_id', '_type' ] );
return assign( {}, props, {
id: group._id,
fields: fields,
collapsed: this.state.collapsedGroups.indexOf( group._id ) > -1,
context: 'block',
values
} );
}
/**
* Handles setuping of group's field.
*
* @param {Object} field
* @param {Object} props
* @param {Object} groupProps
* @return {Array}
*/
handleGroupFieldSetup = ( field, props, groupProps ) => {
const { blockId } = this.props;
const id = `${ this.props.id }__${ groupProps.id }__${ field.base_name }`;
const value = get( groupProps, `values.${ field.base_name }` );
return [ Field, assign( {}, props, {
key: id,
id: id,
name: field.base_name,
containerId: this.props.containerId,
blockId,
field,
value,
onChange: this.handleGroupFieldChange
} ) ];
}
/**
* Handles the change of group field.
*
* @param {string} fieldId
* @param {mixed} fieldValue
* @return {void}
*/
handleGroupFieldChange = ( fieldId, fieldValue ) => {
const {
id,
value,
onChange
} = this.props;
onChange( id, produce( value, ( draft ) => {
const path = fieldId.split( '__' );
const fieldName = path.pop();
const group = find( draft, [ '_id', path.pop() ] );
set( group, fieldName, fieldValue );
} ) );
}
/**
* Renders the component.
*
* @return {Object}
*/
render() {
const {
handleGroupSetup,
handleGroupFieldSetup,
handleAddGroup,
handleCloneGroup,
handleRemoveGroup,
handleToggleGroup,
handleToggleAllGroups
} = this;
const { value, children } = this.props;
const groupValues = this.getGroupValues();
const allGroupsAreCollapsed = this.state.collapsedGroups.length === value.length;
return children( {
groupValues,
allGroupsAreCollapsed,
handleGroupSetup,
handleGroupFieldSetup,
handleAddGroup,
handleCloneGroup,
handleRemoveGroup,
handleToggleGroup,
handleToggleAllGroups
} );
}
}
addFilter( 'carbon-fields.complex.block', 'carbon-fields/blocks', ( OriginalComplexField ) => ( props ) => {
const {
id,
name,
value,
error,
field
} = props;
return (
<ComplexField { ...props }>
{ ( {
groupValues,
allGroupsAreCollapsed,
handleGroupSetup,
handleGroupFieldSetup,
handleAddGroup,
handleCloneGroup,
handleRemoveGroup,
handleToggleGroup,
handleToggleAllGroups
} ) => (
<OriginalComplexField
groupIdKey="_id"
groupFilterKey="_type"
id={ id }
name={ name }
value={ value }
error={ error }
field={ field }
groupValues={ groupValues }
allGroupsAreCollapsed={ allGroupsAreCollapsed }
onGroupSetup={ handleGroupSetup }
onGroupFieldSetup={ handleGroupFieldSetup }
onAddGroup={ handleAddGroup }
onCloneGroup={ handleCloneGroup }
onRemoveGroup={ handleRemoveGroup }
onToggleGroup={ handleToggleGroup }
onToggleAllGroups={ handleToggleAllGroups }
onChange={ props.onChange }
/>
) }
</ComplexField>
);
} );

View file

@ -0,0 +1,89 @@
/* ==========================================================================
Complex
========================================================================== */
.cf-complex__placeholder-label {
font-size: $wp-font-size;
line-height: $wp-line-height;
}
.cf-complex__inserter-menu {
.block-editor & {
z-index: 10;
list-style: none outside none;
border: 1px solid $gb-light-gray-500;
box-shadow: 0 3px 30px rgba($gb-dark-gray-900, .1);
background-color: $color-white;
&::before,
&::after {
position: absolute;
top: 50%;
right: 100%;
width: 0;
height: 0;
border-width: 8px 8px 8px 0;
border-style: solid;
margin-top: -8px;
content: '';
}
&::before {
border-color: transparent $gb-light-gray-500;
margin-right: 1px;
}
&::after {
border-color: transparent $color-white;
}
}
}
.cf-complex__inserter-item {
.block-editor & {
color: $gb-dark-gray-600;
&:hover {
color: $gb-dark-gray-900;
}
}
}
.cf-complex__inserter-button {
.edit-post-sidebar .cf-complex__tabs & {
border-color: $gb-dark-gray-150;
}
}
.cf-complex__tabs-item {
.block-editor & {
color: $gb-dark-gray-500;
}
.block-editor &--current {
color: $gb-dark-gray-900;
}
.edit-post-sidebar & {
border-color: $gb-dark-gray-150;
}
}
.cf-complex__group-head {
.edit-post-sidebar & {
border-color: $gb-dark-gray-150;
}
}
.cf-complex__group-body {
.edit-post-sidebar & {
display: block;
border-color: $gb-dark-gray-150;
}
}
.cf-complex__group-actions {
.edit-post-sidebar &--tabbed {
border-color: $gb-dark-gray-150;
}
}

View file

@ -0,0 +1,96 @@
/**
* External dependencies.
*/
import { format } from '@wordpress/date';
import { Component } from '@wordpress/element';
import { addFilter } from '@wordpress/hooks';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies.
*/
import './style.scss';
class DateTimeField extends Component {
/**
* Handles the change.
*
* @param {Date[]} selectedDates
* @param {string} selectedDateStr
* @return {void}
*/
handleChange = ( selectedDates, selectedDateStr ) => {
const {
id,
onChange,
value,
field
} = this.props;
const formattedDate = format( field.storage_format, selectedDateStr );
if ( formattedDate !== value ) {
onChange( id, formattedDate );
}
}
/**
* Renders the component.
*
* @return {Object}
*/
render() {
const { handleChange } = this;
const { children } = this.props;
return children( {
handleChange
} );
}
}
addFilter( 'carbon-fields.date_time.block', 'carbon-fields/blocks', ( OriginalDateTimeField ) => ( props ) => {
return (
<DateTimeField { ...props }>
{ ( {
handleChange
} ) => (
<OriginalDateTimeField
buttonText={ __( 'Select Date', 'carbon-fields-ui' ) }
{ ...props }
onChange={ handleChange }
/>
) }
</DateTimeField>
);
} );
addFilter( 'carbon-fields.date.block', 'carbon-fields/blocks', ( OriginalDateField ) => ( props ) => {
return (
<DateTimeField { ...props }>
{ ( {
handleChange
} ) => (
<OriginalDateField
{ ...props }
onChange={ handleChange }
/>
) }
</DateTimeField>
);
} );
addFilter( 'carbon-fields.time.block', 'carbon-fields/blocks', ( OriginalTimeField ) => ( props ) => {
return (
<DateTimeField { ...props }>
{ ( {
handleChange
} ) => (
<OriginalTimeField
{ ...props }
onChange={ handleChange }
/>
) }
</DateTimeField>
);
} );

View file

@ -0,0 +1,44 @@
/* ==========================================================================
DateTime
========================================================================== */
.cf-datetime__inner {
.edit-post-sidebar & {
position: relative;
}
.edit-post-sidebar &::before {
position: absolute;
top: 50%;
left: 9px;
display: inline-block;
margin-top: -10px;
}
}
.cf-datetime__input {
.wp-block .cf-field & {
min-width: 0;
border-color: $wp-color-gray-light-500;
border-radius: 0;
&:focus {
box-shadow: none;
}
}
.edit-post-sidebar .cf-field & {
padding-left: 35px;
}
}
.cf-datetime__button {
.wp-block & {
height: auto;
border-color: $wp-color-gray-light-500;
}
.edit-post-sidebar & {
display: none;
}
}

View file

@ -0,0 +1,21 @@
/**
* External dependencies.
*/
import { addFilter } from '@wordpress/hooks';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies.
*/
import './style.scss';
addFilter( 'carbon-fields.file.block', 'carbon-fields/blocks', ( OriginalFileField ) => ( props ) => {
return (
<OriginalFileField
buttonLabel={ __( 'Select File', 'carbon-fields-ui' ) }
mediaLibraryButtonLabel={ __( 'Use File', 'carbon-fields-ui' ) }
mediaLibraryTitle={ __( 'Select File', 'carbon-fields-ui' ) }
{ ...props }
/>
);
} );

View file

@ -0,0 +1,21 @@
/* ==========================================================================
File
========================================================================== */
.cf-file__inner {
.edit-post-sidebar & {
border-color: $gb-dark-gray-150;
}
}
.cf-file__content {
.edit-post-sidebar & {
border-color: $gb-dark-gray-150;
}
}
.cf-file__name {
.edit-post-sidebar & {
border-color: $gb-dark-gray-150;
}
}

View file

@ -0,0 +1,11 @@
/**
* External dependencies.
*/
import { addFilter } from '@wordpress/hooks';
/**
* The internal dependencies.
*/
import NotSupportedField from '../../components/not-supported-field';
addFilter( 'carbon-fields.footer_scripts.block', 'carbon-fields/blocks', () => ( props ) => <NotSupportedField type={ props.field.type } /> );

View file

@ -0,0 +1,11 @@
/**
* External dependencies.
*/
import { addFilter } from '@wordpress/hooks';
/**
* The internal dependencies.
*/
import NotSupportedField from '../../components/not-supported-field';
addFilter( 'carbon-fields.header_scripts.block', 'carbon-fields/blocks', () => ( props ) => <NotSupportedField type={ props.field.type } /> );

View file

@ -0,0 +1,11 @@
/**
* External dependencies.
*/
import { addFilter } from '@wordpress/hooks';
/**
* The internal dependencies.
*/
import NotSupportedField from '../../components/not-supported-field';
addFilter( 'carbon-fields.hidden.block', 'carbon-fields/blocks', () => ( props ) => <NotSupportedField type={ props.field.type } /> );

View file

@ -0,0 +1,16 @@
/**
* External dependencies.
*/
import { addFilter } from '@wordpress/hooks';
import { __ } from '@wordpress/i18n';
addFilter( 'carbon-fields.image.block', 'carbon-fields/blocks', ( OriginalImageField ) => ( props ) => {
return (
<OriginalImageField
buttonLabel={ __( 'Select Image', 'carbon-fields-ui' ) }
mediaLibraryButtonLabel={ __( 'Use Image', 'carbon-fields-ui' ) }
mediaLibraryTitle={ __( 'Select Image', 'carbon-fields-ui' ) }
{ ...props }
/>
);
} );

View file

@ -0,0 +1,63 @@
/**
* External dependencies.
*/
import { compose } from '@wordpress/compose';
import { addFilter } from '@wordpress/hooks';
import { withDispatch } from '@wordpress/data';
/**
* Carbon Fields dependencies.
*/
import { withValidation } from '@carbon-fields/core';
/**
* Internal dependencies.
*/
import withConditionalLogic from '../hocs/with-conditional-logic';
import isGutenberg from '../../metaboxes/utils/is-gutenberg';
/**
* Connects every field to the store.
*/
addFilter( 'carbon-fields.field-edit.block', 'carbon-fields/blocks', compose(
withConditionalLogic,
withDispatch( ( dispatch ) => {
// Widgets support - WordPress 5.8
if ( isGutenberg() ) {
const { lockPostSaving, unlockPostSaving } = dispatch( 'core/editor' );
return {
lockSaving: lockPostSaving,
unlockSaving: unlockPostSaving
};
}
return {};
} ),
withValidation
) );
/**
* Internal dependencies.
*/
import './association';
import './complex';
import './datetime';
import './file';
import './footer-scripts';
import './header-scripts';
import './hidden';
import './image';
import './map';
import './multiselect';
import './media-gallery';
import './oembed';
import './radio';
import './radio-image';
import './select';
import './set';
import './sidebar';
import './separator';
import './text';
import './textarea';
import './block-preview';

View file

@ -0,0 +1,4 @@
/**
* Internal dependencies.
*/
import './style.scss';

View file

@ -0,0 +1,15 @@
/* ==========================================================================
Map
========================================================================== */
.cf-map__canvas {
.edit-post-sidebar & {
border-color: $gb-dark-gray-150;
border-top-width: 1px;
margin-top: $size-base;
}
.block-editor .cf-map__search:focus-within ~ & {
border-color: $wp-color-medium-blue;
}
}

View file

@ -0,0 +1,21 @@
/**
* External dependencies.
*/
import { addFilter } from '@wordpress/hooks';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies.
*/
import './style.scss';
addFilter( 'carbon-fields.media_gallery.block', 'carbon-fields/blocks', ( OriginalMediaGalleryField ) => ( props ) => {
return (
<OriginalMediaGalleryField
buttonLabel={ __( 'Select Attachments', 'carbon-fields-ui' ) }
mediaLibraryButtonLabel={ __( 'Use Attachments', 'carbon-fields-ui' ) }
mediaLibraryTitle={ __( 'Select Attachments', 'carbon-fields-ui' ) }
{ ...props }
/>
);
} );

View file

@ -0,0 +1,69 @@
/* ==========================================================================
Media Gallery
========================================================================== */
.cf-media-gallery__item {
.block-editor & {
@media (min-width: 1440px) {
flex-basis: 16.6667%;
}
@media (min-width: 1680px) {
flex-basis: 16.6667%;
}
}
.edit-post-sidebar & {
flex-basis: 50%;
}
}
.cf-media-gallery__inner {
.wp-block & {
border: 1px solid $wp-color-gray-light-500;
}
.edit-post-sidebar & {
border: 1px solid $gb-dark-gray-150;
}
}
.cf-media-gallery__actions {
.wp-block & {
border-top: 1px solid $wp-color-gray-light-500;
}
.edit-post-sidebar & {
border-top: 1px solid $gb-dark-gray-150;
}
}
.cf-media-gallery__item-inner {
.wp-block & {
border: 1px solid $wp-color-gray-light-500;
}
.edit-post-sidebar & {
border: 1px solid $gb-dark-gray-150;
}
}
.cf-media-gallery__item-preview {
.block-editor & {
background-color: $wp-color-gray-light-200;
}
}
.cf-media-gallery__item-name {
.block-editor & {
background-color: $wp-color-gray-light-200;
}
.wp-block & {
border-top: 1px solid $wp-color-gray-light-500;
}
.edit-post-sidebar & {
border-top: 1px solid $gb-dark-gray-150;
}
}

View file

@ -0,0 +1,4 @@
/**
* Internal dependencies.
*/
import './style.scss';

View file

@ -0,0 +1,20 @@
/* ==========================================================================
Multiselect
========================================================================== */
.cf-multiselect__control {
.wp-block & {
border-radius: 0;
}
.edit-post-sidebar &,
.edit-post-sidebar &:hover {
border-color: $gb-dark-gray-150;
}
.edit-post-sidebar &--is-focused,
.edit-post-sidebar &--is-focused:hover {
border-color: $wp-color-medium-blue;
box-shadow: 0 0 0 1px $wp-color-medium-blue;
}
}

View file

@ -0,0 +1,4 @@
/**
* Internal dependencies.
*/
import './style.scss';

View file

@ -0,0 +1,16 @@
/* ==========================================================================
oEmbed
========================================================================== */
.cf-oembed__preview {
.edit-post-sidebar & {
border-color: $gb-dark-gray-150;
border-top-width: 1px;
margin-top: $size-base;
}
.block-editor .cf-oembed:focus-within & {
border-color: $wp-color-medium-blue;
}
}

View file

@ -0,0 +1,4 @@
/**
* Internal dependencies.
*/
import './style.scss';

View file

@ -0,0 +1,38 @@
/* ==========================================================================
Radio Image
========================================================================== */
.cf-radio__list-item {
.block-editor & {
margin: 0;
}
.wp-block .cf-radio-image & {
@media (min-width: 1440px) {
flex-basis: 25%;
}
@media (min-width: 1680px) {
flex-basis: 25%;
}
}
.edit-post-sidebar .cf-radio-image & {
flex-basis: 33.3333%;
}
}
.cf-radio-image__image {
.wp-block & {
border: 1px solid $wp-color-gray-light-500;
}
.edit-post-sidebar & {
border: 1px solid $gb-dark-gray-150;
}
.block-editor .cf-radio__input:focus ~ .cf-radio__label &,
.block-editor .cf-radio__input:checked ~ .cf-radio__label & {
outline: 2px solid $wp-color-medium-blue;
}
}

View file

@ -0,0 +1,4 @@
/**
* Internal dependencies.
*/
import './style.scss';

View file

@ -0,0 +1,9 @@
/* ==========================================================================
Radio
========================================================================== */
.cf-radio__list {
.wp-block & {
list-style: none outside none;
}
}

View file

@ -0,0 +1,4 @@
/**
* Internal dependencies.
*/
import './style.scss';

View file

@ -0,0 +1,14 @@
/* ==========================================================================
Select
========================================================================== */
.cf-select__input {
.wp-block .cf-field & {
border-color: $wp-color-gray-light-500;
border-radius: 0;
&:focus {
box-shadow: none;
}
}
}

View file

@ -0,0 +1,4 @@
/**
* Internal dependencies.
*/
import './style.scss';

View file

@ -0,0 +1,9 @@
/* ==========================================================================
Separator
========================================================================== */
.cf-separator {
.block-editor & h3 {
margin: 0;
}
}

View file

@ -0,0 +1,4 @@
/**
* Internal dependencies.
*/
import './style.scss';

View file

@ -0,0 +1,9 @@
/* ==========================================================================
Set
========================================================================== */
.cf-set__list {
.wp-block & {
list-style: none outside none;
}
}

View file

@ -0,0 +1,11 @@
/**
* External dependencies.
*/
import { addFilter } from '@wordpress/hooks';
/**
* The internal dependencies.
*/
import NotSupportedField from '../../components/not-supported-field';
addFilter( 'carbon-fields.sidebar.block', 'carbon-fields/blocks', () => ( props ) => <NotSupportedField type={ props.field.type } /> );

View file

@ -0,0 +1,4 @@
/**
* Internal dependencies.
*/
import './style.scss';

View file

@ -0,0 +1,14 @@
/* ==========================================================================
Text
========================================================================== */
.cf-text__input {
.wp-block .cf-field & {
border-color: $wp-color-gray-light-500;
border-radius: 0;
&:focus {
box-shadow: none;
}
}
}

View file

@ -0,0 +1,4 @@
/**
* Internal dependencies.
*/
import './style.scss';

View file

@ -0,0 +1,16 @@
/* ==========================================================================
Textarea
========================================================================== */
.cf-textarea__input {
.wp-block .cf-field & {
border-color: $wp-color-gray-light-500;
border-radius: 0;
transition: border-color $transition-base;
&:focus {
border-color: $wp-color-medium-blue;
box-shadow: none;
}
}
}

View file

@ -0,0 +1,131 @@
/**
* External dependencies.
*/
import distinctUntilChanged from 'callbag-distinct-until-changed';
import { select } from '@wordpress/data';
import { pipe, map } from 'callbag-basics';
import {
get,
has,
omit,
assign,
repeat,
mapKeys,
findIndex,
startsWith
} from 'lodash';
/**
* Carbon Fields dependencies.
*/
import { fromSelector, withConditionalLogic } from '@carbon-fields/core';
/**
* Adds the `parent.` parent prefix to field's name.
*
* @param {Object[]} fields
* @param {number} depth
* @return {Array[]}
*/
function mapParentPrefix( fields, depth = 0 ) {
return mapKeys( fields, ( value, key ) => `${ repeat( 'parent.', depth ) }${ key }` );
}
/**
* Returns whether the given string is a group identifier.
*
* @param {string} id
* @return {boolean}
*/
function isComplexGroupIdentifier( id ) {
return startsWith( id, 'cf-' );
}
/**
* The function used to track dependencies required
* by conditional logic.
*
* @param {Object} props
* @return {Object}
*/
function input( props ) {
return pipe(
fromSelector( select( 'core/block-editor' ).getBlock, props.blockId ),
distinctUntilChanged(),
map( ( blockData ) => blockData?.attributes?.data )
);
}
/**
* The function that provides the data that needs to be
* evaluated by conditional logic.
*
* @param {Object} props
* @param {Object} fields
* @return {Object}
*/
function output( props, fields ) {
const isTopLevelField = has( fields, props.field.base_name );
let siblingFields = {};
if ( isTopLevelField ) {
siblingFields = mapParentPrefix( omit( fields, [ props.field.base_name ] ) );
} else {
// Get the hierarchy.
const path = props.id.split( '__' );
// Remove the chunk with identifier of block since
// we already have it.
path.shift();
// Remove the chunk with name of root field.
const rootFieldName = path.shift();
// Remove the chunk with name of field since
// we already have it.
path.pop();
// Keep reference to the depth
// so we can add the `parent.` prefix.
let depth = path.reduce( ( accumulator, chunk ) => {
return isComplexGroupIdentifier( chunk )
? accumulator
: accumulator + 1;
}, 0 );
// Collect fields that are siblings of root field.
siblingFields = omit( fields, [ rootFieldName ] );
siblingFields = mapParentPrefix( siblingFields, depth + 1 );
// Keep reference to the full path of the field.
let pathPrefix = rootFieldName;
while ( path.length > 0 ) {
const chunk = path.shift();
const isGroup = isComplexGroupIdentifier( chunk );
const isNestedComplex = ! isGroup;
if ( isGroup ) {
const groupIndex = findIndex( get( fields, pathPrefix ), [ '_id', chunk ] );
pathPrefix = `${ pathPrefix }.${ groupIndex }`;
let groupFields = get( fields, pathPrefix );
groupFields = omit( groupFields, [ '_id', '_type', props.field.base_name ] );
groupFields = mapParentPrefix( groupFields, depth );
assign( siblingFields, groupFields );
}
if ( isNestedComplex ) {
pathPrefix = `${ pathPrefix }.${ chunk }`;
depth--;
}
}
}
return siblingFields;
}
export default withConditionalLogic( input, output );

View file

@ -0,0 +1,75 @@
/* eslint no-console: [ 'error', { allow: [ 'error' ] } ] */
/**
* External dependencies.
*/
import { dispatch } from '@wordpress/data';
import { registerBlockType } from '@wordpress/blocks';
import { setLocaleData } from '@wordpress/i18n';
import {
get,
kebabCase,
isPlainObject
} from 'lodash';
/**
* Internal dependencies.
*/
import './fields';
import './store';
import BlockEdit from './components/block-edit';
import BlockSave from './components/block-save';
import transformFieldsToAttributes from './utils/transform-fields-to-attributes';
/**
* Sets the locale data for the package type
*/
setLocaleData( window.cf.config.locale, 'carbon-fields-ui' );
/**
* Register the blocks.
*/
const containerDefinitions = {};
const fieldDefinitions = {};
get( window.cf, 'preloaded.blocks', [] ).forEach( ( container ) => {
const name = kebabCase( container.id ).replace( 'carbon-fields-container-', '' );
const fields = transformFieldsToAttributes( container.fields );
const getBlockSetting = ( key, def = null ) => get( container, `settings.${ key }`, def );
containerDefinitions[ name ] = container;
fieldDefinitions[ name ] = container.fields.map( ( field ) => ( { ...field } ) );
registerBlockType( `carbon-fields/${ name }`, {
title: container.title,
icon: getBlockSetting( 'icon' ),
parent: getBlockSetting( 'parent', [] ),
category: getBlockSetting( 'category.slug' ),
keywords: getBlockSetting( 'keywords', [] ),
description: getBlockSetting( 'description', '' ),
attributes: {
data: {
type: 'object',
default: fields
}
},
supports: {
tabs: isPlainObject( getBlockSetting( 'tabs' ) ),
preview: getBlockSetting( 'preview' ),
innerBlocks: getBlockSetting( 'inner_blocks.enabled' ),
alignWide: false,
anchor: false,
html: false
},
edit: BlockEdit,
save: BlockSave,
example: true,
} );
} );
/**
* Load the definitions in store.
*/
dispatch( 'carbon-fields/blocks' ).setupContainerDefinitions( containerDefinitions );
dispatch( 'carbon-fields/blocks' ).setupFieldDefinitions( fieldDefinitions );

View file

@ -0,0 +1,29 @@
/**
* Returns an action object used to setup the definitions state when first opening an editor.
*
* @param {Object} definitions
* @return {Object}
*/
export function setupContainerDefinitions( definitions ) {
return {
type: 'SETUP_CONTAINER_DEFINITIONS',
payload: {
definitions
}
};
}
/**
* Returns an action object used to setup the definitions state when first opening an editor.
*
* @param {Object} definitions
* @return {Object}
*/
export function setupFieldDefinitions( definitions ) {
return {
type: 'SETUP_FIELD_DEFINITIONS',
payload: {
definitions
}
};
}

View file

@ -0,0 +1,20 @@
/**
* External dependencies.
*/
import { registerStore } from '@wordpress/data';
/**
* Internal dependencies.
*/
import reducer from './reducer';
import * as actions from './actions';
import * as selectors from './selectors';
/**
* Register the store.
*/
registerStore( 'carbon-fields/blocks', {
reducer,
actions,
selectors
} );

View file

@ -0,0 +1,43 @@
/**
* External dependencies.
*/
import { combineReducers } from '@wordpress/data';
/**
* The reducer that keeps track of container definitions keyed by block's name.
*
* @param {Object} state
* @param {Object} action
* @return {Object}
*/
export function containerDefinitionsByBlockName( state = {}, action ) {
switch ( action.type ) {
case 'SETUP_CONTAINER_DEFINITIONS':
return action.payload.definitions;
default:
return state;
}
}
/**
* The reducer that keeps track of field definitions keyed by block's name.
*
* @param {Object} state
* @param {Object} action
* @return {Object}
*/
export function fieldDefinitionsByBlockName( state = {}, action ) {
switch ( action.type ) {
case 'SETUP_FIELD_DEFINITIONS':
return action.payload.definitions;
default:
return state;
}
}
export default combineReducers( {
containerDefinitionsByBlockName,
fieldDefinitionsByBlockName
} );

View file

@ -0,0 +1,25 @@
/**
* Get the container by a given block name.
*
* @param {Object} state
* @param {string} blockName
* @return {Object}
*/
export function getContainerDefinitionByBlockName( state, blockName ) {
return state.containerDefinitionsByBlockName[
blockName.replace( 'carbon-fields/', '' )
] || {};
}
/**
* Get the fields by a given block name.
*
* @param {Object} state
* @param {string} blockName
* @return {Object[]}
*/
export function getFieldDefinitionsByBlockName( state, blockName ) {
return state.fieldDefinitionsByBlockName[
blockName.replace( 'carbon-fields/', '' )
] || [];
}

View file

@ -0,0 +1,14 @@
/**
* Transforms the fields to an attributes set.
*
* @param {Object[]} fields
* @return {Object}
*/
export default function transformFieldsToAttributes( fields ) {
return fields.reduce( ( attributes, field ) => {
return {
...attributes,
[ field.base_name ]: field.default_value
};
}, {} );
}