equal
deleted
inserted
replaced
1 function AnnotationPlugin(options) { |
|
2 |
|
3 const { onChange } = options |
|
4 |
|
5 return { |
|
6 onSelect(event, change) { |
|
7 event.preventDefault() |
|
8 |
|
9 const { value } = change |
|
10 const { selection } = value |
|
11 const { start, end} = selection |
|
12 |
|
13 if (selection.isCollapsed) { |
|
14 return; |
|
15 } |
|
16 |
|
17 let nodes = []; |
|
18 let hasStarted = false; |
|
19 let hasEnded = false; |
|
20 |
|
21 // Keep only the relevant nodes, |
|
22 // i.e. nodes which are contained within selection |
|
23 value.document.nodes.forEach((node) => { |
|
24 if (start.isInNode(node)) { |
|
25 hasStarted = true; |
|
26 } |
|
27 if (hasStarted && !hasEnded) { |
|
28 nodes.push(node); |
|
29 } |
|
30 if (end.isAtEndOfNode(node)) { |
|
31 hasEnded = true; |
|
32 } |
|
33 }); |
|
34 |
|
35 let text = ''; |
|
36 |
|
37 // Concatenate the nodes text |
|
38 if (nodes.length === 1) { |
|
39 text = nodes[0].text.substring(start.offset, end.offset); |
|
40 } else { |
|
41 text = nodes.map((node) => { |
|
42 if (start.isInNode(node)) return node.text.substring(start.offset); |
|
43 if (end.isAtEndOfNode(node)) return node.text.substring(0, end.offset); |
|
44 return node.text; |
|
45 }).join('\n'); |
|
46 } |
|
47 |
|
48 if (onChange) { |
|
49 onChange(text, start.offset, end.offset); |
|
50 } |
|
51 } |
|
52 |
|
53 }; |
|
54 } |
|
55 |
|
56 export default AnnotationPlugin; |
|