Skip to content

Commit 7e80b7a

Browse files
author
Jeffrey de Wit
committed
#36 Retain existing CSS classes on buttons on size change
1 parent 305bbb1 commit 7e80b7a

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

assets/js/block-filters/buttons.js

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,38 @@ import {
88
Button,
99
} from '@wordpress/components';
1010
import { __ } from '@wordpress/i18n';
11+
import TokenList from '@wordpress/token-list';
1112

1213
/**
1314
* Renders the edit component for the button block.
1415
*
1516
* @param {Object} props - The properties passed to the component.
1617
* @param {Object} props.attributes - The attributes of the button block.
1718
* @param {string} props.attributes.buttonSize - The size of the button.
19+
* @param {string} props.attributes.className - The current classname.
1820
* @param {Function} props.setAttributes - The function to set the attributes of the button block.
1921
* @return {JSX.Element} The rendered edit component.
2022
*/
21-
function Edit({ attributes: { buttonSize }, setAttributes }) {
23+
function Edit({ attributes: { buttonSize, className }, setAttributes }) {
24+
// Replace the current size with a new size in the existing list of classes, but only if a value for them exists.
25+
const replaceActiveSize = (currentSize, newSize) => {
26+
const currentClasses = new TokenList(className);
27+
28+
if (currentSize) {
29+
currentClasses.remove(`has-size-${currentSize}`);
30+
}
31+
32+
if (newSize) {
33+
currentClasses.add(`has-size-${newSize}`);
34+
}
35+
36+
return currentClasses.value;
37+
};
38+
2239
const handleChange = (newSize) => {
2340
// Check if we are toggling the size off
2441
const size = buttonSize === newSize ? undefined : newSize;
25-
const buttonClass = buttonSize !== newSize ? 'has-size-' + newSize : '';
42+
const buttonClass = replaceActiveSize(buttonSize, size);
2643

2744
// Update attributes.
2845
setAttributes({

0 commit comments

Comments
 (0)