index.js
97 lines
| 1 | /** |
| 2 | * WordPress dependencies |
| 3 | */ |
| 4 | import { __ } from '@wordpress/i18n'; |
| 5 | import { useCallback, useState } from '@wordpress/element'; |
| 6 | import { registerFormatType, removeFormat } from '@wordpress/rich-text'; |
| 7 | import { RichTextToolbarButton } from '@wordpress/block-editor'; |
| 8 | import { Icon } from '@wordpress/components'; |
| 9 | |
| 10 | /** |
| 11 | * Internal dependencies |
| 12 | */ |
| 13 | import { ReactComponent as IconSVG } from './icon.svg'; |
| 14 | import { default as InlineFontSizeUI, getActiveInlineFontSize } from './inline'; |
| 15 | |
| 16 | const name = 'vk-blocks/inline-font-size'; |
| 17 | |
| 18 | const iconStyle = { |
| 19 | width: '24px', |
| 20 | height: '24px', |
| 21 | }; |
| 22 | |
| 23 | function FontSizeEdit({ |
| 24 | value, |
| 25 | onChange, |
| 26 | isActive, |
| 27 | activeAttributes, |
| 28 | contentRef, |
| 29 | }) { |
| 30 | const shortcutType = 'primary'; |
| 31 | const shortcutChar = 'h'; |
| 32 | |
| 33 | const [isSettingFontSize, setIsSettingFontSize] = useState(false); |
| 34 | |
| 35 | const enableIsAddingFontSize = useCallback( |
| 36 | () => setIsSettingFontSize(true), |
| 37 | [setIsSettingFontSize] |
| 38 | ); |
| 39 | const disableIsAddingFontSize = useCallback( |
| 40 | () => setIsSettingFontSize(false), |
| 41 | [setIsSettingFontSize] |
| 42 | ); |
| 43 | |
| 44 | const activeInlineFontSize = getActiveInlineFontSize(value, name); |
| 45 | |
| 46 | const hasFontSizeToChoose = !!!value.length || !activeInlineFontSize; |
| 47 | if (!hasFontSizeToChoose && !isActive) { |
| 48 | return null; |
| 49 | } |
| 50 | |
| 51 | return ( |
| 52 | <> |
| 53 | <RichTextToolbarButton |
| 54 | title={__('Inline Font Size', 'vk-blocks')} |
| 55 | onClick={ |
| 56 | hasFontSizeToChoose |
| 57 | ? enableIsAddingFontSize |
| 58 | : () => onChange(removeFormat(value, name)) |
| 59 | } |
| 60 | shortcutType={shortcutType} |
| 61 | shortcutCharacter={shortcutChar} |
| 62 | className="format-library-text-color-button" |
| 63 | isActive={isActive} |
| 64 | icon={ |
| 65 | <> |
| 66 | <Icon icon={IconSVG} style={iconStyle} /> |
| 67 | </> |
| 68 | } |
| 69 | /> |
| 70 | {isSettingFontSize && ( |
| 71 | <InlineFontSizeUI |
| 72 | name={name} |
| 73 | onClose={disableIsAddingFontSize} |
| 74 | activeAttributes={activeAttributes} |
| 75 | value={value} |
| 76 | onChange={onChange} |
| 77 | contentRef={contentRef} |
| 78 | setIsSettingFontSize={setIsSettingFontSize} |
| 79 | /> |
| 80 | )} |
| 81 | </> |
| 82 | ); |
| 83 | } |
| 84 | |
| 85 | export const inlineFontSize = { |
| 86 | title: __('Inline font size', 'vk-blocks'), |
| 87 | tagName: 'span', |
| 88 | className: 'vk_inline-font-size', |
| 89 | attributes: { |
| 90 | data: 'data-fontSize', |
| 91 | style: 'style', |
| 92 | }, |
| 93 | edit: FontSizeEdit, |
| 94 | }; |
| 95 | |
| 96 | registerFormatType(name, inlineFontSize); |
| 97 |