Skip to content

Commit

Permalink
Pulls in the changes from #35973 to check whether an image has been d…
Browse files Browse the repository at this point in the history
…eleted from the attachments.

If the image block was not replaced with an embed,  and it's not an external image, and it's been deleted from the database, clear the attributes and trigger the placeholder.
  • Loading branch information
ramonjd committed May 23, 2022
1 parent 78cea0f commit cfa08c3
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
16 changes: 12 additions & 4 deletions packages/block-library/src/image/edit.js
Expand Up @@ -26,6 +26,7 @@ import { image as icon } from '@wordpress/icons';
* Internal dependencies
*/
import Image from './image';
import { isMediaFileDeleted } from './utils';

/**
* Module constants
Expand Down Expand Up @@ -164,12 +165,19 @@ export function ImageEdit( {
url
)
);

// If the image block was not replaced with an embed,
// and it's not an external image,
// and it's been deleted from the database,
// clear the attributes and trigger the placeholder.
if ( ! isReplaced ) {
setAttributes( {
url: undefined,
id: undefined,
if ( id && ! isReplaced && ! isExternalImage( id, url ) ) {
isMediaFileDeleted( id ).then( ( isFileDeleted ) => {
if ( isFileDeleted ) {
setAttributes( {
url: undefined,
id: undefined,
} );
}
} );
}
}
Expand Down
23 changes: 23 additions & 0 deletions packages/block-library/src/image/utils.js
Expand Up @@ -3,6 +3,11 @@
*/
import { isEmpty, each, get } from 'lodash';

/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';

/**
* Internal dependencies
*/
Expand Down Expand Up @@ -72,3 +77,21 @@ export function getImageSizeAttributes( image, size ) {

return {};
}

/**
* Performs a GET request on an image file to confirm whether it has been deleted from the database.
*
* @param {number=} mediaId The id of the image.
* @return {Promise} Media Object Promise.
*/
export async function isMediaFileDeleted( mediaId ) {
try {
const response = await apiFetch( {
path: `/wp/v2/media/${ mediaId }`,
} );
const isMediaFileAvailable = response && response?.id === mediaId;
return ! isMediaFileAvailable;
} catch ( err ) {
return true;
}
}

0 comments on commit cfa08c3

Please sign in to comment.