Skip to content
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

Editor: Implement EntityProvider and use it to refactor custom sources with a backwards compatibility hook for meta sources. #17153

Merged
merged 6 commits into from
Sep 23, 2019
Merged
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/core-data/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@wordpress/api-fetch": "file:../api-fetch",
"@wordpress/data": "file:../data",
"@wordpress/deprecated": "file:../deprecated",
"@wordpress/element": "file:../element",
"@wordpress/is-shallow-equal": "file:../is-shallow-equal",
"@wordpress/url": "file:../url",
"equivalent-key-map": "^0.2.2",
Expand Down
90 changes: 90 additions & 0 deletions packages/core-data/src/entity-provider.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* WordPress dependencies
*/
import { createContext, useContext, useCallback } from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';

/**
* Internal dependencies
*/
import { defaultEntities, kinds } from './entities';

const _entities = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we avoid introducing new coding patterns for consistency (we don't really use _something in our codebase, I assume this is a way to tell it's a private thinig)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, changed.

...defaultEntities.reduce( ( acc, entity ) => {
if ( ! acc[ entity.kind ] ) {
acc[ entity.kind ] = {};
}
acc[ entity.kind ][ entity.name ] = { context: createContext() };
return acc;
}, {} ),
...kinds.reduce( ( acc, kind ) => {
acc[ kind.name ] = {};
return acc;
}, {} ),
};
const getEntity = ( kind, type ) => {
if ( ! _entities[ kind ] ) {
throw new Error( `Missing entity config for kind: ${ kind }.` );
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we remove this check, and just create an empty object, the first time a "kind" is requested, we can simplify furthere (remove the _entities initialization entirely. I'm not certain it adds much value to try to validate that it's an existing kind because we can also just pass a random entity "type" and it will pass the test (we don't validate entity names).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because type can be dynamic. kind cannot, you need an entity config for any of the API to work.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see why "kind" can't be dynamic in the future as well tbh. I still think it's . just useless code but I'm fine shipping that way.


if ( ! _entities[ kind ][ type ] ) {
_entities[ kind ][ type ] = { context: createContext() };
}

return _entities[ kind ][ type ];
};

/**
* Context provider component for providing
* an entity for a specific entity type.
*
* @param {Object} props The component's props.
* @param {string} props.kind The entity kind.
* @param {string} props.type The entity type.
* @param {number} props.id The entity ID.
* @param {*} props.children The children to wrap.
*
* @return {Object} The provided children, wrapped with
* the entity's context provider.
*/
export default function EntityProvider( { kind, type, id, children } ) {
const Provider = getEntity( kind, type ).context.Provider;
return <Provider value={ id }>{ children }</Provider>;
}

/**
* Hook that returns the value and a setter for the
* specified property of the nearest provided
* entity of the specified type.
*
* @param {string} kind The entity kind.
* @param {string} type The entity type.
* @param {string} prop The property name.
*
* @return {[*, Function]} A tuple where the first item is the
* property value and the second is the
* setter.
*/
export function useEntityProp( kind, type, prop ) {
const id = useContext( getEntity( kind, type ).context );

const value = useSelect(
( select ) => {
const entity = select( 'core' ).getEditedEntityRecord( kind, type, id );
return entity && entity[ prop ];
},
[ kind, type, id, prop ]
);

const { editEntityRecord } = useDispatch( 'core' );
const setValue = useCallback(
( newValue ) => {
editEntityRecord( kind, type, id, {
[ prop ]: newValue,
} );
},
[ kind, type, id, prop ]
);

return [ value, setValue ];
}
2 changes: 2 additions & 0 deletions packages/core-data/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,5 @@ registerStore( REDUCER_KEY, {
selectors: { ...selectors, ...entitySelectors },
resolvers: { ...resolvers, ...entityResolvers },
} );

export { default as EntityProvider, useEntityProp } from './entity-provider';
28 changes: 16 additions & 12 deletions packages/editor/src/components/provider/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { compose } from '@wordpress/compose';
import { Component } from '@wordpress/element';
import { withDispatch, withSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { EntityProvider } from '@wordpress/core-data';
import { BlockEditorProvider, transformStyles } from '@wordpress/block-editor';
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';
Expand Down Expand Up @@ -164,6 +165,7 @@ class EditorProvider extends Component {
const {
canUserUseUnfilteredHTML,
children,
post,
blocks,
resetEditorBlocks,
isReady,
Expand All @@ -185,18 +187,20 @@ class EditorProvider extends Component {
);

return (
<BlockEditorProvider
value={ blocks }
onInput={ resetEditorBlocksWithoutUndoLevel }
onChange={ resetEditorBlocks }
settings={ editorSettings }
useSubRegistry={ false }
>
{ children }
<ReusableBlocksButtons />
<ConvertToGroupButtons />
{ editorSettings.__experimentalBlockDirectory && <InserterMenuDownloadableBlocksPanel /> }
</BlockEditorProvider>
<EntityProvider kind="postType" type={ post.type } id={ post.id }>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, makes me think later once we have the "full site editing" modes, this entity provider wouldn't be added automatically but only when the "Post" block is used (for the other modes, not the regular one).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah

<BlockEditorProvider
value={ blocks }
onInput={ resetEditorBlocksWithoutUndoLevel }
onChange={ resetEditorBlocks }
settings={ editorSettings }
useSubRegistry={ false }
>
{ children }
<ReusableBlocksButtons />
<ConvertToGroupButtons />
{ editorSettings.__experimentalBlockDirectory && <InserterMenuDownloadableBlocksPanel /> }
</BlockEditorProvider>
</EntityProvider>
);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* WordPress dependencies
*/
import { getBlockType } from '@wordpress/blocks';
import { useEntityProp } from '@wordpress/core-data';
import { useMemo, useCallback } from '@wordpress/element';
import { createHigherOrderComponent } from '@wordpress/compose';
import { addFilter } from '@wordpress/hooks';

const EMPTY_OBJECT = {};
function useMetaAttributeSource( name, _attributes, _setAttributes ) {
const { attributes: attributeTypes = EMPTY_OBJECT } =
getBlockType( name ) || EMPTY_OBJECT;
let [ attributes, setAttributes ] = [ _attributes, _setAttributes ];

if ( Object.values( attributeTypes ).some( ( type ) => type.source === 'meta' ) ) {
// eslint-disable-next-line react-hooks/rules-of-hooks
const [ meta, setMeta ] = useEntityProp( 'postType', 'post', 'meta' );

// eslint-disable-next-line react-hooks/rules-of-hooks
attributes = useMemo(
() => ( {
..._attributes,
...Object.keys( attributeTypes ).reduce( ( acc, key ) => {
if ( attributeTypes[ key ].source === 'meta' ) {
acc[ key ] = meta[ attributeTypes[ key ].meta ];
}
return acc;
}, {} ),
} ),
[ attributeTypes, meta, _attributes ]
);

// eslint-disable-next-line react-hooks/rules-of-hooks
setAttributes = useCallback(
( ...args ) => {
Object.keys( args[ 0 ] ).forEach( ( key ) => {
if ( attributeTypes[ key ].source === 'meta' ) {
setMeta( { [ attributeTypes[ key ].meta ]: args[ 0 ][ key ] } );
}
} );
return _setAttributes( ...args );
},
[ attributeTypes, setMeta, _setAttributes ]
);
}

return [ attributes, setAttributes ];
}
const withMetaAttributeSource = createHigherOrderComponent(
( BlockListBlock ) => ( { attributes, setAttributes, name, ...props } ) => {
[ attributes, setAttributes ] = useMetaAttributeSource(
name,
attributes,
setAttributes
);
return (
<BlockListBlock
attributes={ attributes }
setAttributes={ setAttributes }
name={ name }
{ ...props }
/>
);
},
'withMetaAttributeSource'
);

addFilter(
'editor.BlockListBlock',
'core/editor/custom-sources-backwards-compatibility/with-meta-attribute-source',
withMetaAttributeSource
);
1 change: 1 addition & 0 deletions packages/editor/src/hooks/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/**
* Internal dependencies
*/
import './custom-sources-backwards-compatibility';
import './default-autocompleters';
Loading