From 7c09de3d501104e9858614555036324fc67c21a4 Mon Sep 17 00:00:00 2001 From: Tyler Bailey Date: Tue, 17 May 2022 16:12:00 -0400 Subject: [PATCH] Check if aspect ratio class exists before regenerating. Resets if the URL has changed. --- packages/block-library/src/embed/edit.js | 9 ++++++++- packages/block-library/src/embed/util.js | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/packages/block-library/src/embed/edit.js b/packages/block-library/src/embed/edit.js index c3e664385809c..838c8258ad58a 100644 --- a/packages/block-library/src/embed/edit.js +++ b/packages/block-library/src/embed/edit.js @@ -4,6 +4,7 @@ import { createUpgradedEmbedBlock, getClassNames, + removeAspectRatioClasses, fallback, getEmbedInfoByProvider, getMergedAttributesWithPreview, @@ -188,8 +189,14 @@ const EmbedEdit = ( props ) => { event.preventDefault(); } + // If the embed URL was changed, we need to reset the aspect ratio class. + // To do this we have to remove the existing ratio class so it can be recalculated. + const blockClass = removeAspectRatioClasses( + attributes.className + ); + setIsEditingURL( false ); - setAttributes( { url } ); + setAttributes( { url, className: blockClass } ); } } value={ url } cannotEmbed={ cannotEmbed } diff --git a/packages/block-library/src/embed/util.js b/packages/block-library/src/embed/util.js index 35bf4c5d2966e..7ed23b676c825 100644 --- a/packages/block-library/src/embed/util.js +++ b/packages/block-library/src/embed/util.js @@ -152,6 +152,21 @@ export const createUpgradedEmbedBlock = ( } ); }; +/** + * Determine if the block already has an aspect ratio class applied. + * + * @param {string} existingClassNames Existing block classes. + * @return {boolean} True or false if the classnames contain an aspect ratio class. + */ +export const hasAspectRatioClass = ( existingClassNames ) => { + if ( ! existingClassNames ) { + return false; + } + return ASPECT_RATIOS.some( ( { className } ) => + existingClassNames.includes( className ) + ); +}; + /** * Removes all previously set aspect ratio related classes and return the rest * existing class names. @@ -311,6 +326,14 @@ export const getMergedAttributesWithPreview = ( ignorePreviousClassName = false ) => { const { allowResponsive, className } = currentAttributes; + + // Aspect ratio classes are removed when the embed URL is updated. + // If the embed already has an aspect ratio class, that means the URL has not changed. + // Which also means no need to regenerate it. + if ( hasAspectRatioClass( className ) ) { + return currentAttributes; + } + return { ...currentAttributes, ...getAttributesFromPreview(