2021-12-22 19:13:36 +08:00
|
|
|
import React, {
|
|
|
|
useEffect, useState,
|
|
|
|
} from 'react'
|
2021-08-11 20:37:58 +08:00
|
|
|
import { FloatingMenuPlugin, FloatingMenuPluginProps } from '@tiptap/extension-floating-menu'
|
2021-04-01 21:55:19 +08:00
|
|
|
|
2021-08-24 00:44:40 +08:00
|
|
|
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>
|
|
|
|
|
|
|
|
export type FloatingMenuProps = Omit<Optional<FloatingMenuPluginProps, 'pluginKey'>, 'element'> & {
|
2021-04-01 21:55:19 +08:00
|
|
|
className?: string,
|
2022-04-11 16:45:50 +08:00
|
|
|
children: React.ReactNode
|
2021-04-01 21:55:19 +08:00
|
|
|
}
|
|
|
|
|
2022-04-11 16:45:50 +08:00
|
|
|
export const FloatingMenu = (props: FloatingMenuProps) => {
|
2021-12-22 19:13:36 +08:00
|
|
|
const [element, setElement] = useState<HTMLDivElement | null>(null)
|
2021-04-01 21:55:19 +08:00
|
|
|
|
|
|
|
useEffect(() => {
|
2021-12-22 19:13:36 +08:00
|
|
|
if (!element) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if (props.editor.isDestroyed) {
|
2021-10-12 17:38:01 +08:00
|
|
|
return
|
|
|
|
}
|
2021-10-12 17:09:00 +08:00
|
|
|
|
2021-08-11 20:37:58 +08:00
|
|
|
const {
|
2021-08-24 00:44:40 +08:00
|
|
|
pluginKey = 'floatingMenu',
|
2021-08-11 20:37:58 +08:00
|
|
|
editor,
|
2021-08-24 00:44:40 +08:00
|
|
|
tippyOptions = {},
|
|
|
|
shouldShow = null,
|
2021-08-11 20:37:58 +08:00
|
|
|
} = props
|
2021-04-01 21:55:19 +08:00
|
|
|
|
2021-12-22 19:13:36 +08:00
|
|
|
const plugin = FloatingMenuPlugin({
|
2021-08-13 18:33:06 +08:00
|
|
|
pluginKey,
|
2021-04-01 21:55:19 +08:00
|
|
|
editor,
|
2021-12-22 19:13:36 +08:00
|
|
|
element,
|
2021-04-16 18:42:56 +08:00
|
|
|
tippyOptions,
|
2021-08-11 20:37:58 +08:00
|
|
|
shouldShow,
|
2021-12-22 19:13:36 +08:00
|
|
|
})
|
2021-04-01 21:55:19 +08:00
|
|
|
|
2021-12-22 19:13:36 +08:00
|
|
|
editor.registerPlugin(plugin)
|
|
|
|
return () => editor.unregisterPlugin(pluginKey)
|
2021-10-12 17:09:00 +08:00
|
|
|
}, [
|
|
|
|
props.editor,
|
2021-12-22 19:13:36 +08:00
|
|
|
element,
|
2021-10-12 17:09:00 +08:00
|
|
|
])
|
2021-04-01 21:55:19 +08:00
|
|
|
|
|
|
|
return (
|
2021-12-22 19:13:36 +08:00
|
|
|
<div ref={setElement} className={props.className} style={{ visibility: 'hidden' }}>
|
2021-04-01 21:55:19 +08:00
|
|
|
{props.children}
|
|
|
|
</div>
|
|
|
|
)
|
|
|
|
}
|