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