|
/* eslint-disable import/no-extraneous-dependencies */ |
|
/* eslint-disable import/no-unresolved */ |
|
/** |
|
* WordPress dependencies |
|
*/ |
|
import { registerBlockStyle } from '@wordpress/blocks'; |
|
import { addFilter } from '@wordpress/hooks'; |
|
import { __ } from '@wordpress/i18n'; |
|
|
|
const BUTTON_COLOR_CUSTOM_PROPERTY = '--button--color'; |
|
|
|
registerBlockStyle('core/button', { |
|
name: 'outline-only', |
|
label: __('Outline', 'av-block-theme'), |
|
}); |
|
|
|
const sanitizeColorSlug = (slug = '') => `${slug}`.toLowerCase().replace(/[^a-z0-9-]/g, ''); |
|
|
|
const getButtonBackgroundCssValue = (attributes = {}) => { |
|
if (attributes?.backgroundColor) { |
|
const slug = sanitizeColorSlug(attributes.backgroundColor); |
|
|
|
if (slug) { |
|
return `var(--wp--preset--color--${slug})`; |
|
} |
|
} |
|
|
|
if (attributes?.style?.color?.background) { |
|
return attributes.style.color.background; |
|
} |
|
|
|
return ''; |
|
}; |
|
|
|
const applyButtonColorCustomProperty = (props = {}, attributes = {}) => { |
|
const backgroundValue = getButtonBackgroundCssValue(attributes); |
|
|
|
if (!backgroundValue) { |
|
return props; |
|
} |
|
|
|
const currentStyle = props.style ?? {}; |
|
|
|
if (currentStyle[BUTTON_COLOR_CUSTOM_PROPERTY] === backgroundValue) { |
|
return props; |
|
} |
|
|
|
return { |
|
...props, |
|
style: { |
|
...currentStyle, |
|
[BUTTON_COLOR_CUSTOM_PROPERTY]: backgroundValue, |
|
}, |
|
}; |
|
}; |
|
|
|
addFilter('blocks.registerBlockType', 'block-theme/core-button/text-only', (settings, name) => { |
|
if (name !== 'core/button') { |
|
return settings; |
|
} |
|
|
|
const existingGetEditWrapperProps = settings?.getEditWrapperProps; |
|
|
|
return { |
|
...settings, |
|
getEditWrapperProps(attributes) { |
|
const wrapperProps = existingGetEditWrapperProps ? existingGetEditWrapperProps(attributes) : {}; |
|
|
|
return applyButtonColorCustomProperty(wrapperProps, attributes); |
|
}, |
|
}; |
|
}); |
|
|
|
addFilter('blocks.getSaveContent.extraProps', 'block-theme/core-button/text-only', (props, blockType, attributes) => { |
|
if (blockType?.name !== 'core/button') { |
|
return props; |
|
} |
|
|
|
return applyButtonColorCustomProperty(props ?? {}, attributes); |
|
}); |