File size: 2,516 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
import { useUiTranslator } from '@react-page/editor';
import React, { useCallback, useState } from 'react';
import { Range } from 'slate';
import { useSlate } from 'slate-react';
import useAddPlugin from '../hooks/useAddPlugin';
import usePluginIsActive from '../hooks/usePluginIsActive';
import usePluginIsDisabled from '../hooks/usePluginIsDisabled';
import useRemovePlugin from '../hooks/useRemovePlugin';
import type {
PluginButtonProps,
SlatePluginDefinition,
} from '../types/slatePluginDefinitions';
import PluginControls from './PluginControls';
import ToolbarButton from './ToolbarButton';
type Props = {
plugin: SlatePluginDefinition;
dark?: boolean;
} & PluginButtonProps;
function PluginButton(props: Props) {
const { plugin, dark } = props;
const { t } = useUiTranslator();
const hasControls = Boolean(plugin.controls);
const [showControls, setShowControls] = useState(false);
const editor = useSlate();
const isActive = usePluginIsActive(plugin);
const isVoid =
plugin.pluginType === 'component' &&
(plugin.object === 'inline' || plugin.object === 'block') &&
plugin.isVoid;
const shouldInsertWithText =
plugin.pluginType === 'component' &&
(plugin.object === 'inline' || plugin.object === 'mark') &&
(!editor.selection || Range.isCollapsed(editor.selection)) &&
!isActive &&
!isVoid;
const add = useAddPlugin(plugin);
const remove = useRemovePlugin(plugin);
const close = useCallback(() => setShowControls(false), [setShowControls]);
const onClick = React.useCallback(
(e: React.MouseEvent<HTMLElement>) => {
e.preventDefault();
if (hasControls || shouldInsertWithText) {
setShowControls(!showControls);
} else {
if (isActive) {
remove();
} else {
add();
}
}
},
[isActive, hasControls, showControls, shouldInsertWithText]
);
const isDisabled = usePluginIsDisabled(plugin);
return (
<>
<ToolbarButton
onClick={onClick}
disabled={isDisabled}
isActive={isActive}
dark={dark}
icon={
plugin.icon ??
(plugin.pluginType === 'component'
? plugin.deserialize?.tagName ?? ''
: '')
}
toolTip={t(plugin.label) ?? ''}
/>
{(hasControls || shouldInsertWithText) && showControls ? (
<PluginControls {...props} open={showControls} close={close} />
) : null}
</>
);
}
export default React.memo(PluginButton);
|