tiptap/packages/react/src/FloatingMenu.tsx

53 lines
1.1 KiB
TypeScript
Raw Normal View History

import React, {
useEffect, useState,
} from 'react'
import { FloatingMenuPlugin, FloatingMenuPluginProps } from '@tiptap/extension-floating-menu'
2021-04-01 21:55:19 +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,
children: React.ReactNode
2021-04-01 21:55:19 +08:00
}
export const FloatingMenu = (props: FloatingMenuProps) => {
const [element, setElement] = useState<HTMLDivElement | null>(null)
2021-04-01 21:55:19 +08:00
useEffect(() => {
if (!element) {
return
}
if (props.editor.isDestroyed) {
2021-10-12 17:38:01 +08:00
return
}
const {
pluginKey = 'floatingMenu',
editor,
tippyOptions = {},
shouldShow = null,
} = props
2021-04-01 21:55:19 +08:00
const plugin = FloatingMenuPlugin({
2021-08-13 18:33:06 +08:00
pluginKey,
2021-04-01 21:55:19 +08:00
editor,
element,
2021-04-16 18:42:56 +08:00
tippyOptions,
shouldShow,
})
2021-04-01 21:55:19 +08:00
editor.registerPlugin(plugin)
return () => editor.unregisterPlugin(pluginKey)
}, [
props.editor,
element,
])
2021-04-01 21:55:19 +08:00
return (
<div ref={setElement} className={props.className} style={{ visibility: 'hidden' }}>
2021-04-01 21:55:19 +08:00
{props.children}
</div>
)
}