client/src/components/SlateEditor/AnnotationPlugin.js
changeset 168 ea92f4fe783d
parent 157 5c3af4f10e92
child 172 4b780ebbedc6
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/client/src/components/SlateEditor/AnnotationPlugin.js	Mon Oct 08 18:35:47 2018 +0200
@@ -0,0 +1,56 @@
+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;