client/src/components/SlateEditor/AnnotationPlugin.js
author ymh <ymh.work@gmail.com>
Tue, 13 Nov 2018 16:46:15 +0100
changeset 172 4b780ebbedc6
parent 168 ea92f4fe783d
permissions -rw-r--r--
- Upgrade libraries - Make things work again

function AnnotationPlugin(options) {

  const { onChange } = options

  return {
    onSelect(event, editor, next) {
      event.preventDefault()

      const { value } = editor
      const { selection } = value
      const { start, end} = selection

      if (selection.isCollapsed) {
        return next();
      }

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

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

      // Concatenate the nodes text
      const text = nodes.map((node) => {
        let textStart = start.isInNode(node) ? start.offset : 0;
        let textEnd = end.isAtEndOfNode(node) ? end.offset : node.text.length;
        return node.text.substring(textStart,textEnd);
      }).join('\n');

      if (onChange) {
        onChange(text, start.offset, end.offset);
      }

      return next();

    }

  };
}

export default AnnotationPlugin;