client/src/components/SlateEditor/AnnotationPlugin.js
changeset 172 4b780ebbedc6
parent 168 ea92f4fe783d
equal deleted inserted replaced
171:03334a31130a 172:4b780ebbedc6
     1 function AnnotationPlugin(options) {
     1 function AnnotationPlugin(options) {
     2 
     2 
     3   const { onChange } = options
     3   const { onChange } = options
     4 
     4 
     5   return {
     5   return {
     6     onSelect(event, change) {
     6     onSelect(event, editor, next) {
     7       event.preventDefault()
     7       event.preventDefault()
     8 
     8 
     9       const { value } = change
     9       const { value } = editor
    10       const { selection } = value
    10       const { selection } = value
    11       const { start, end} = selection
    11       const { start, end} = selection
    12 
    12 
    13       if (selection.isCollapsed) {
    13       if (selection.isCollapsed) {
    14         return;
    14         return next();
    15       }
    15       }
    16 
    16 
    17       let nodes = [];
    17       const nodes = [];
    18       let hasStarted = false;
    18       let hasStarted = false;
    19       let hasEnded = false;
    19       let hasEnded = false;
    20 
    20 
    21       // Keep only the relevant nodes,
    21       // Keep only the relevant nodes,
    22       // i.e. nodes which are contained within selection
    22       // i.e. nodes which are contained within selection
    30         if (end.isAtEndOfNode(node)) {
    30         if (end.isAtEndOfNode(node)) {
    31           hasEnded = true;
    31           hasEnded = true;
    32         }
    32         }
    33       });
    33       });
    34 
    34 
    35       let text = '';
       
    36 
       
    37       // Concatenate the nodes text
    35       // Concatenate the nodes text
    38       if (nodes.length === 1) {
    36       const text = nodes.map((node) => {
    39         text = nodes[0].text.substring(start.offset, end.offset);
    37         let textStart = start.isInNode(node) ? start.offset : 0;
    40       } else {
    38         let textEnd = end.isAtEndOfNode(node) ? end.offset : node.text.length;
    41         text = nodes.map((node) => {
    39         return node.text.substring(textStart,textEnd);
    42           if (start.isInNode(node)) return node.text.substring(start.offset);
    40       }).join('\n');
    43           if (end.isAtEndOfNode(node)) return node.text.substring(0, end.offset);
       
    44           return node.text;
       
    45         }).join('\n');
       
    46       }
       
    47 
    41 
    48       if (onChange) {
    42       if (onChange) {
    49         onChange(text, start.offset, end.offset);
    43         onChange(text, start.offset, end.offset);
    50       }
    44       }
       
    45 
       
    46       return next();
       
    47 
    51     }
    48     }
    52 
    49 
    53   };
    50   };
    54 }
    51 }
    55 
    52