Skip to content

Commit

Permalink
Simplify
Browse files Browse the repository at this point in the history
  • Loading branch information
ellatrix committed Jan 31, 2024
1 parent 4da5fb0 commit c6877eb
Showing 1 changed file with 33 additions and 23 deletions.
56 changes: 33 additions & 23 deletions packages/core-data/src/entity-provider.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
/**
* WordPress dependencies
*/
import { createContext, useContext, useCallback } from '@wordpress/element';
import {
createContext,
useContext,
useCallback,
useMemo,
} from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import { parse, __unstableSerializeAndClean } from '@wordpress/blocks';

Expand Down Expand Up @@ -150,44 +155,49 @@ const parsedBlocksCache = new WeakMap();
export function useEntityBlockEditor( kind, name, { id: _id } = {} ) {
const providerId = useEntityId( kind, name );
const id = _id ?? providerId;
const { blocks, meta } = useSelect(
const { content, editedBlocks, meta, entityRecord } = useSelect(
( select ) => {
if ( ! id ) {
return {};
}
const { getEditedEntityRecord, getEntityRecord } =
select( STORE_NAME );
const editedRecord = getEditedEntityRecord( kind, name, id );

let editedBlocks = editedRecord.blocks;

if ( ! editedBlocks ) {
if (
editedRecord.content &&
typeof editedRecord.content !== 'function'
) {
// Attach the cache to the original record.
const entityRecord = getEntityRecord( kind, name, id );
editedBlocks = parsedBlocksCache.get( entityRecord );
if ( ! editedBlocks ) {
editedBlocks = parse( editedRecord.content );
parsedBlocksCache.set( entityRecord, editedBlocks );
}
} else {
editedBlocks = EMPTY_ARRAY;
}
}

return {
blocks: editedBlocks,
editedBlocks: editedRecord.blocks,
content: editedRecord.content,
meta: editedRecord.meta,
entityRecord: getEntityRecord( kind, name, id ),
};
},
[ kind, name, id ]
);
const { __unstableCreateUndoLevel, editEntityRecord } =
useDispatch( STORE_NAME );

const blocks = useMemo( () => {
if ( ! id ) {
return undefined;
}

if ( editedBlocks ) {
return editedBlocks;
}

if ( ! content || typeof content === 'function' ) {
return EMPTY_ARRAY;
}

let _blocks = parsedBlocksCache.get( entityRecord );

if ( ! _blocks ) {
_blocks = parse( content );
parsedBlocksCache.set( entityRecord, _blocks );
}

return _blocks;
}, [ id, editedBlocks, content ] );

const updateFootnotes = useCallback(
( _blocks ) => updateFootnotesFromMeta( _blocks, meta ),
[ meta ]
Expand Down

0 comments on commit c6877eb

Please sign in to comment.