Projekt

Obecné

Profil

Stáhnout (2.5 KB) Statistiky
| Větev: | Tag: | Revize:
1
import { AnnotationInfo } from '../api';
2

    
3
export interface SelectionInfo {
4
    startElementId: number;
5
    endElementId: number;
6
    startPositionOriginalDocument: number;
7
    endPositionOriginalDocument: number;
8
    selectionLengthOriginalDocument: number;
9
}
10
export function GetSelectionInfo(annotation: AnnotationInfo): SelectionInfo | null {
11
    const selection = window.getSelection();
12
    if (!selection) {
13
        return null;
14
    }
15
    if (!annotation?.tagStartPositions || !annotation.tagLengths) {
16
        console.log('start or lengths not found');
17
        return null;
18
    }
19

    
20
    let startTag = selection.anchorNode;
21
    let endTag = selection.focusNode;
22

    
23
    if (!startTag || !endTag) {
24
        console.log('Selection not found');
25
        return null;
26
    }
27

    
28
    if (startTag.nodeName.includes('#')) {
29
        startTag = startTag.parentNode;
30
    }
31
    if (endTag.nodeName.includes('#')) {
32
        endTag = endTag.parentNode;
33
    }
34
    if (!startTag || !endTag) {
35
        console.log('Selection element not found');
36
        return null;
37
    }
38

    
39
    if (!(startTag instanceof Element)) {
40
        console.log('StartTag is not instance of Element');
41
        return null;
42
    }
43
    if (!(endTag instanceof Element)) {
44
        console.log('EndTag is not instance of Element');
45
        return null;
46
    }
47

    
48
    let startElement = startTag as Element;
49
    let endElement = endTag as Element;
50

    
51
    let startId: number = Number(startElement.getAttribute('aswi-tag-id')) ?? -1;
52
    let endId: number = Number(endElement.getAttribute('aswi-tag-id')) ?? -1;
53

    
54
    let startPosition =
55
        annotation.tagStartPositions[startId] +
56
        annotation.tagLengths[startId] +
57
        selection.anchorOffset;
58
    let endPosition =
59
        annotation.tagStartPositions[endId] +
60
        annotation.tagLengths[endId] +
61
        selection.focusOffset -
62
        1;
63

    
64
    // need to switch start and end elements (selection was in the opposite way then expected)
65
    if (startPosition > endPosition) {
66
        let temp = startPosition;
67
        startPosition = endPosition;
68
        endPosition = temp;
69

    
70
        temp = startId;
71
        startId = endId;
72
        endId = temp;
73

    
74
        const tempElement = startElement;
75
        startElement = endElement;
76
        endElement = tempElement;
77
    }
78

    
79
    const length = endPosition - startPosition + 1;
80

    
81
    return {
82
        endElementId: endId,
83
        startElementId: startId,
84
        startPositionOriginalDocument: startPosition,
85
        endPositionOriginalDocument: endPosition,
86
        selectionLengthOriginalDocument: length,
87
    };
88
}
(4-4/4)