-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathFloater.tsx
More file actions
61 lines (47 loc) · 1.58 KB
/
Floater.tsx
File metadata and controls
61 lines (47 loc) · 1.58 KB
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
import './style/floater.css'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { useEditorState, useEditorView } from './EditorProvider'
export const Floater: React.FC = ({ children }) => {
const view = useEditorView()
const state = useEditorState()
const [needsUpdate, setNeedsUpdate] = useState(Date.now())
// trigger redraw on resize and scroll events
useEffect(() => {
let handle: number
const handleEvent = () => {
if (handle) {
window.clearTimeout(handle)
}
handle = window.setTimeout(() => {
setNeedsUpdate(Date.now())
}, 50)
}
window.addEventListener('resize', handleEvent)
window.addEventListener('scroll', handleEvent)
return () => {
window.removeEventListener('resize', handleEvent)
window.removeEventListener('scroll', handleEvent)
}
}, [])
const menuRef = useRef<HTMLDivElement>(null)
const style = useMemo(() => {
if (!state.selection || state.selection.empty) {
return { left: -1000, top: 0 }
}
const coords = view.coordsAtPos(state.selection.$anchor.pos)
const offsetWidth = menuRef.current?.offsetWidth || 0
return {
left:
window.innerWidth - offsetWidth < coords.left
? coords.left - offsetWidth + 20
: coords.left,
top: coords.top - 30 > 0 ? coords.top - 30 : coords.top + 30,
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [menuRef, state, view, needsUpdate])
return (
<div ref={menuRef} className="prosemirror-floater" style={style}>
{children}
</div>
)
}