-
-
Notifications
You must be signed in to change notification settings - Fork 118
/
cursor.ts
67 lines (58 loc) · 1.59 KB
/
cursor.ts
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
62
63
64
65
66
67
type Position = {
top: string
left: string
}
/**
* Returns position of cursor on the page.
* @param toStart Position of beginning of selection or end of selection.
*/
export function cursorPosition(toStart = true): Position | undefined {
const s = window.getSelection()!
if (s.rangeCount > 0) {
const cursor = document.createElement("span")
cursor.textContent = "|"
const r = s.getRangeAt(0).cloneRange()
r.collapse(toStart)
r.insertNode(cursor)
const {x, y, height} = cursor.getBoundingClientRect()
const top = (window.scrollY + y + height) + "px"
const left = (window.scrollX + x) + "px"
cursor.parentNode!.removeChild(cursor)
return {top, left}
}
return undefined
}
/**
* Returns selected text.
*/
export function selectedText() {
const s = window.getSelection()!
if (s.rangeCount === 0) return ''
return s.getRangeAt(0).toString()
}
/**
* Returns text before the cursor.
* @param editor Editor DOM node.
*/
export function textBeforeCursor(editor: Node) {
const s = window.getSelection()!
if (s.rangeCount === 0) return ''
const r0 = s.getRangeAt(0)
const r = document.createRange()
r.selectNodeContents(editor)
r.setEnd(r0.startContainer, r0.startOffset)
return r.toString()
}
/**
* Returns text after the cursor.
* @param editor Editor DOM node.
*/
export function textAfterCursor(editor: Node) {
const s = window.getSelection()!
if (s.rangeCount === 0) return ''
const r0 = s.getRangeAt(0)
const r = document.createRange()
r.selectNodeContents(editor)
r.setStart(r0.endContainer, r0.endOffset)
return r.toString()
}