Support for gradient colors in Gutenberg richText inline highlight option

26 Views Asked by At

I want to add the support for the gradient colors in highlight option against any selected text. For reference please see this comment. I have seen this stackOverflow thread as well. It provides support to add gradient color on block level. I need it on selected text level as shown in the images

I can go to highlight option to give color to just the selected part

Here I have options of only solid colors

This is the result but I want to add the gradient background

As seen I only have the option of solid colors in toolbar highlight option. Is there any way I can get gradient colors there as well. Any response would be appreciated.

1

There are 1 best solutions below

0
S.Walsh On BEST ANSWER

As the gradient editor applies to the block level, the workaround I've found is using the Format API to register a custom format to add a gradient background to selected text within a paragraph block.

Note: The caveat with this method is a predefined gradient in the theme.json is used as the className and the gradient picker won't appear, as it is a block-level option (see screenshot below).

index.js

import { registerFormatType, toggleFormat } from '@wordpress/rich-text';
import { RichTextToolbarButton } from '@wordpress/block-editor';

const AddGradientButton = ({ isActive, onChange, value }) => {
    return (
        <RichTextToolbarButton
            icon="star-filled"
            title="Gradient Background"
            onClick={() => {
                onChange(
                    toggleFormat(value, {
                        type: 'gradient-background/warm-to-cool',
                    })
                );
            }}
            isActive={isActive}
        />
    );
};

registerFormatType('gradient-background/warm-to-cool', {
    title: 'Gradient Style',
    tagName: 'span', // uses <span>...</span> to wrap the selected text
    className: 'has-cool-to-warm-spectrum-gradient-background', // change to name of your predefined gradient
    edit: AddGradientButton,
});

Result in Editor: Text with Gradient inside Paragraph Block

Block content saved:

<!-- wp:paragraph -->
<p>Gradients <span class="has-cool-to-warm-spectrum-gradient-background">on text in a paragraph</span> of text.</p>
<!-- /wp:paragraph -->