client/src/AnnotationPlugin.js
author salimr <riwad.salim@yahoo.fr>
Tue, 14 Aug 2018 20:39:55 +0200
changeset 144 8b950885ddae
parent 102 b0e36664f1f2
child 157 5c3af4f10e92
permissions -rw-r--r--
Add local font and assets. Override Bootstrap css varriables. Add specific css files

function AnnotationPlugin(options) {

  const { onChange } = options

  return {
    onSelect(event, data, state, editor) {
      event.preventDefault()

      const selection = data.selection;

      const startOffset = selection.startOffset;
      const endOffset = selection.endOffset;

      if (selection.isCollapsed) {
        return;
      }

      let nodes = [];
      let hasStarted = false;
      let hasEnded = false;

      // Keep only the relevant nodes,
      // i.e. nodes which are contained within selection
      state.document.nodes.forEach((node) => {
        if (selection.hasStartIn(node)) {
          hasStarted = true;
        }
        if (hasStarted && !hasEnded) {
          nodes.push(node);
        }
        if (selection.hasEndIn(node)) {
          hasEnded = true;
        }
      });

      let text = '';

      // Concatenate the nodes text
      if (nodes.length === 1) {
        text = nodes[0].text.substring(startOffset, endOffset);
      } else {
        text = nodes.map((node) => {
          if (selection.hasStartIn(node)) return node.text.substring(startOffset);
          if (selection.hasEndIn(node)) return node.text.substring(0, endOffset);
          return node.text;
        }).join('\n');
      }

      if (onChange) {
        onChange(text, startOffset, endOffset);
      }
    }

  };
}

export default AnnotationPlugin;