File size: 1,863 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 |
import React, { useEffect, useRef } from 'react';
import { Portal } from 'react-portal';
import { useSlate } from 'slate-react';
import useTextIsSelected from '../hooks/useTextIsSelected';
import type { SlateProps } from '../types/component';
import PluginButton from './PluginButton';
const HoverButtons = ({
plugins,
translations,
}: Pick<SlateProps, 'plugins' | 'translations'>) => {
const showHoverToolbar = useTextIsSelected();
const toolbarRef = useRef<HTMLDivElement>(null);
const editor = useSlate();
useEffect(() => {
const toolbar = toolbarRef.current;
if (!showHoverToolbar || !toolbar) {
return;
}
const s = window.getSelection();
try {
const oRange = s?.getRangeAt(0); // get the text range
const oRect = oRange?.getBoundingClientRect();
if (oRect) {
const { left, top, width } = oRect;
toolbar.style.opacity = '1';
toolbar.style.top = `${top + window.scrollY - toolbar.offsetHeight}px`;
toolbar.style.left = `${
left + window.scrollX - toolbar.offsetWidth / 2 + width / 2
}px`;
}
} catch (e) {
// ignore
}
}, [editor, showHoverToolbar]);
return (
<Portal>
<div
className={
'react-page-plugins-content-slate-inline-toolbar ' +
(showHoverToolbar
? ''
: 'react-page-plugins-content-slate-inline-toolbar--hidden')
}
style={{ padding: 0 }}
ref={toolbarRef}
>
{plugins &&
plugins.map((plugin, i: number) =>
plugin.addHoverButton ? (
<PluginButton
dark
translations={translations}
key={i}
plugin={plugin}
/>
) : null
)}
</div>
</Portal>
);
};
export default HoverButtons;
|