import { css } from '@emotion/css'
import React, { MouseEvent, useEffect, useMemo, useRef } from 'react'
import { Descendant, Editor, Range, createEditor } from 'slate'
import { withHistory } from 'slate-history'
import {
Editable,
RenderLeafProps,
Slate,
useFocused,
useSlate,
withReact,
} from 'slate-react'
import { Button, Icon, Menu, Portal } from './components'
import { CustomEditor, CustomTextKey } from './custom-types.d'
const HoveringMenuExample = () => {
const editor = useMemo(() => withHistory(withReact(createEditor())), [])
return (
}
placeholder="Enter some text..."
onDOMBeforeInput={(event: InputEvent) => {
switch (event.inputType) {
case 'formatBold':
event.preventDefault()
return toggleMark(editor, 'bold')
case 'formatItalic':
event.preventDefault()
return toggleMark(editor, 'italic')
case 'formatUnderline':
event.preventDefault()
return toggleMark(editor, 'underline')
}
}}
/>
)
}
const toggleMark = (editor: CustomEditor, format: CustomTextKey) => {
const isActive = isMarkActive(editor, format)
if (isActive) {
Editor.removeMark(editor, format)
} else {
Editor.addMark(editor, format, true)
}
}
const isMarkActive = (editor: CustomEditor, format: CustomTextKey) => {
const marks = Editor.marks(editor)
return marks ? marks[format] === true : false
}
const Leaf = ({ attributes, children, leaf }: RenderLeafProps) => {
if (leaf.bold) {
children = {children}
}
if (leaf.italic) {
children = {children}
}
if (leaf.underline) {
children = {children}
}
return {children}
}
const HoveringToolbar = () => {
const ref = useRef(null)
const editor = useSlate()
const inFocus = useFocused()
useEffect(() => {
const el = ref.current
const { selection } = editor
if (!el) {
return
}
if (
!selection ||
!inFocus ||
Range.isCollapsed(selection) ||
Editor.string(editor, selection) === ''
) {
el.removeAttribute('style')
return
}
const domSelection = window.getSelection()
const domRange = domSelection!.getRangeAt(0)
const rect = domRange.getBoundingClientRect()
el.style.opacity = '1'
el.style.top = `${rect.top + window.pageYOffset - el.offsetHeight}px`
el.style.left = `${
rect.left + window.pageXOffset - el.offsetWidth / 2 + rect.width / 2
}px`
})
return (
)
}
interface FormatButtonProps {
format: CustomTextKey
icon: string
}
const FormatButton = ({ format, icon }: FormatButtonProps) => {
const editor = useSlate()
return (
)
}
const initialValue: Descendant[] = [
{
type: 'paragraph',
children: [
{
text: 'This example shows how you can make a hovering menu appear above your content, which you can use to make text ',
},
{ text: 'bold', bold: true },
{ text: ', ' },
{ text: 'italic', italic: true },
{ text: ', or anything else you might want to do!' },
],
},
{
type: 'paragraph',
children: [
{ text: 'Try it out yourself! Just ' },
{ text: 'select any piece of text and the menu will appear', bold: true },
{ text: '.' },
],
},
]
export default HoveringMenuExample