Skip to content
Closed
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
66 changes: 66 additions & 0 deletions packages/edit-widgets/src/store/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export function* saveEditedWidgetAreas() {
}
try {
yield* saveWidgetAreas( editedWidgetAreas );
yield* deleteRemovedWidgets();
yield dispatch(
'core/notices',
'createSuccessNotice',
Expand Down Expand Up @@ -270,6 +271,58 @@ function* trySaveWidgetArea( widgetAreaId ) {
}
}

function* deleteRemovedWidgets() {
const widgetIdToClientId = yield getWidgetToClientIdMapping();
const clientIdToWidgetId = invert( widgetIdToClientId );

const widgetAreas = yield select( 'core/edit-widgets', 'getWidgetAreas' );
const widgetBlocks = [];

for ( const widgetArea of widgetAreas ) {
const post = yield select(
'core',
'getEntityRecord',
KIND,
POST_TYPE,
buildWidgetAreaPostId( widgetArea.id )
);

widgetBlocks.push( ...post.blocks );
}

for ( const widgetBlock of widgetBlocks ) {
delete clientIdToWidgetId[ widgetBlock.clientId ];
}

for ( const clientId in clientIdToWidgetId ) {
if ( clientIdToWidgetId.hasOwnProperty( clientId ) ) {
dataDispatch( 'core' ).deleteEntityRecord(
'root',
'widget',
clientIdToWidgetId[ clientId ],
{ force: true }
);
}
}

const batch = yield dispatch(
'core/__experimental-batch-processing',
'processBatch',
'WIDGETS_API_FETCH',
'default'
);

if ( batch.state !== STATE_SUCCESS ) {
return;
}

for ( const clientId in clientIdToWidgetId ) {
if ( clientIdToWidgetId.hasOwnProperty( clientId ) ) {
yield removeWidgetIdForClientId( clientIdToWidgetId[ clientId ] );
}
}
}

/**
* Sets the clientId stored for a particular widgetId.
*
Expand All @@ -285,6 +338,19 @@ export function setWidgetIdForClientId( clientId, widgetId ) {
};
}

/**
* Removes the widget id -> client id mapping.
*
* @param {string} widgetId Widget id.
* @return {Object} Action.
*/
export function removeWidgetIdForClientId( widgetId ) {
return {
type: 'REMOVE_WIDGET_ID_FOR_CLIENT_ID',
widgetId,
};
}

/**
* Sets the open state of all the widget areas.
*
Expand Down
8 changes: 8 additions & 0 deletions packages/edit-widgets/src/store/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ export function mapping( state, action ) {
return newMapping;
}

if ( type === 'REMOVE_WIDGET_ID_FOR_CLIENT_ID' ) {
const newMapping = {
...state,
};
delete newMapping[ action.widgetId ];
return newMapping;
}

return state || {};
}

Expand Down