client/src/components/SlateEditor/AnnotationPlugin.js
author ymh <ymh.work@gmail.com>
Mon, 08 Oct 2018 18:35:47 +0200
changeset 168 ea92f4fe783d
parent 157 client/src/AnnotationPlugin.js@5c3af4f10e92
child 172 4b780ebbedc6
permissions -rw-r--r--
- move SlateEditor and dependencies to its own folder - remove Immutable - remove redux-persist-immutable - remobe redux-immutable - update libraries - added tests on store manipulations (accessor and reducers)

function AnnotationPlugin(options) {

  const { onChange } = options

  return {
    onSelect(event, change) {
      event.preventDefault()

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

      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
      value.document.nodes.forEach((node) => {
        if (start.isInNode(node)) {
          hasStarted = true;
        }
        if (hasStarted && !hasEnded) {
          nodes.push(node);
        }
        if (end.isAtEndOfNode(node)) {
          hasEnded = true;
        }
      });

      let text = '';

      // Concatenate the nodes text
      if (nodes.length === 1) {
        text = nodes[0].text.substring(start.offset, end.offset);
      } else {
        text = nodes.map((node) => {
          if (start.isInNode(node)) return node.text.substring(start.offset);
          if (end.isAtEndOfNode(node)) return node.text.substring(0, end.offset);
          return node.text;
        }).join('\n');
      }

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

  };
}

export default AnnotationPlugin;