client/src/AnnotationPlugin.js
changeset 19 f1b125b95fe9
child 102 b0e36664f1f2
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/client/src/AnnotationPlugin.js	Tue Jun 06 15:56:41 2017 +0200
@@ -0,0 +1,57 @@
+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);
+      }
+    }
+
+  };
+}
+
+export default AnnotationPlugin;