forked from ianstormtaylor/slate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scroll-to-selection.js
39 lines (30 loc) · 976 Bytes
/
scroll-to-selection.js
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
import getWindow from 'get-window'
import isBackward from 'selection-is-backward'
/**
* Scroll the current selection's focus point into view if needed.
*
* @param {Selection} selection
*/
function scrollToSelection(selection) {
if (!selection.anchorNode) return
const window = getWindow(selection.anchorNode)
const backward = isBackward(selection)
const range = selection.getRangeAt(0)
const rect = range.getBoundingClientRect()
const { innerWidth, innerHeight, pageYOffset, pageXOffset } = window
const top = (backward ? rect.top : rect.bottom) + pageYOffset
const left = (backward ? rect.left : rect.right) + pageXOffset
const x = left < pageXOffset || innerWidth + pageXOffset < left
? left - innerWidth / 2
: pageXOffset
const y = top < pageYOffset || innerHeight + pageYOffset < top
? top - innerHeight / 2
: pageYOffset
window.scrollTo(x, y)
}
/**
* Export.
*
* @type {Function}
*/
export default scrollToSelection