Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#36 Retain existing CSS classes on buttons on size change #45

Merged
merged 2 commits into from
Nov 6, 2024
Merged
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
21 changes: 19 additions & 2 deletions assets/js/block-filters/buttons.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,38 @@ import {
Button,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import TokenList from '@wordpress/token-list';

/**
* Renders the edit component for the button block.
*
* @param {Object} props - The properties passed to the component.
* @param {Object} props.attributes - The attributes of the button block.
* @param {string} props.attributes.buttonSize - The size of the button.
* @param {string} props.attributes.className - The current classname.
* @param {Function} props.setAttributes - The function to set the attributes of the button block.
* @return {JSX.Element} The rendered edit component.
*/
function Edit({ attributes: { buttonSize }, setAttributes }) {
function Edit({ attributes: { buttonSize, className }, setAttributes }) {
// Replace the current size with a new size in the existing list of classes, but only if a value for them exists.
const replaceActiveSize = (currentSize, newSize) => {
const currentClasses = new TokenList(className);

if (currentSize) {
currentClasses.remove(`has-size-${currentSize}`);
}

if (newSize) {
currentClasses.add(`has-size-${newSize}`);
}

return currentClasses.value;
};

const handleChange = (newSize) => {
// Check if we are toggling the size off
const size = buttonSize === newSize ? undefined : newSize;
const buttonClass = buttonSize !== newSize ? 'has-size-' + newSize : '';
const buttonClass = replaceActiveSize(buttonSize, size);

// Update attributes.
setAttributes({
Expand Down
Loading