Skip to content

Commit

Permalink
Avoid mutating blockAttributes
Browse files Browse the repository at this point in the history
  • Loading branch information
tjcafferkey committed Jun 4, 2024
1 parent c18c7db commit 246eb14
Showing 1 changed file with 22 additions and 19 deletions.
41 changes: 22 additions & 19 deletions packages/blocks/src/api/parser/fix-custom-classname.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,27 +42,30 @@ export function getHTMLRootElementClasses( innerHTML ) {
* @return {Object} Filtered block attributes.
*/
export function fixCustomClassname( blockAttributes, blockType, innerHTML ) {
if ( hasBlockSupport( blockType, 'customClassName', true ) ) {
// To determine difference, serialize block given the known set of
// attributes, with the exception of `className`. This will determine
// the default set of classes. From there, any difference in innerHTML
// can be considered as custom classes.
const { className: omittedClassName, ...attributesSansClassName } =
blockAttributes;
const serialized = getSaveContent( blockType, attributesSansClassName );
const defaultClasses = getHTMLRootElementClasses( serialized );
const actualClasses = getHTMLRootElementClasses( innerHTML );
if ( ! hasBlockSupport( blockType, 'customClassName', true ) ) {
return blockAttributes;
}

const modifiedBlockAttributes = { ...blockAttributes };
// To determine difference, serialize block given the known set of
// attributes, with the exception of `className`. This will determine
// the default set of classes. From there, any difference in innerHTML
// can be considered as custom classes.
const { className: omittedClassName, ...attributesSansClassName } =
modifiedBlockAttributes;
const serialized = getSaveContent( blockType, attributesSansClassName );
const defaultClasses = getHTMLRootElementClasses( serialized );
const actualClasses = getHTMLRootElementClasses( innerHTML );

const customClasses = actualClasses.filter(
( className ) => ! defaultClasses.includes( className )
);
const customClasses = actualClasses.filter(
( className ) => ! defaultClasses.includes( className )
);

if ( customClasses.length ) {
blockAttributes.className = customClasses.join( ' ' );
} else if ( serialized ) {
delete blockAttributes.className;
}
if ( customClasses.length ) {
modifiedBlockAttributes.className = customClasses.join( ' ' );
} else if ( serialized ) {
delete modifiedBlockAttributes.className;
}

return blockAttributes;
return modifiedBlockAttributes;
}

0 comments on commit 246eb14

Please sign in to comment.