client/src/components/SlateEditor/AnnotationPlugin.js
changeset 173 0e6703cd0968
parent 172 4b780ebbedc6
child 174 ac1a026edd58
equal deleted inserted replaced
172:4b780ebbedc6 173:0e6703cd0968
     1 function AnnotationPlugin(options) {
       
     2 
       
     3   const { onChange } = options
       
     4 
       
     5   return {
       
     6     onSelect(event, editor, next) {
       
     7       event.preventDefault()
       
     8 
       
     9       const { value } = editor
       
    10       const { selection } = value
       
    11       const { start, end} = selection
       
    12 
       
    13       if (selection.isCollapsed) {
       
    14         return next();
       
    15       }
       
    16 
       
    17       const 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       // Concatenate the nodes text
       
    36       const text = nodes.map((node) => {
       
    37         let textStart = start.isInNode(node) ? start.offset : 0;
       
    38         let textEnd = end.isAtEndOfNode(node) ? end.offset : node.text.length;
       
    39         return node.text.substring(textStart,textEnd);
       
    40       }).join('\n');
       
    41 
       
    42       if (onChange) {
       
    43         onChange(text, start.offset, end.offset);
       
    44       }
       
    45 
       
    46       return next();
       
    47 
       
    48     }
       
    49 
       
    50   };
       
    51 }
       
    52 
       
    53 export default AnnotationPlugin;