File size: 2,214 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { objIsNode } from '@react-page/editor';
import type { Editor } from 'slate';
import { Transforms } from 'slate';

import { HtmlToSlate } from '../htmlToSlate';
import type { SlatePlugin } from '../types/SlatePlugin';

const withPaste =
  (plugins: SlatePlugin[], defaultPluginType: string) => (editor: Editor) => {
    const { insertData } = editor;
    const htmlToSlate = HtmlToSlate({ plugins });
    editor.insertData = async (data) => {
      const slateData = data.getData('application/x-slate-fragment');
      if (slateData) {
        insertData(data);
        return;
      }

      const html = data.getData('text/html');
      if (html) {
        const { slate } = await htmlToSlate(html);

        Transforms.insertFragment(editor, slate);
        return;
      }

      const text = data.getData('text/plain');
      if (text) {
        // check if its a react-page data
        try {
          const node = JSON.parse(text);
          if (objIsNode(node)) {
            return;
          }
        } catch (e) {
          //ignore
        }
        // if there are two subsequent line breks, insert paragraph, otherway insert soft line break
        const lines = text.split('\n');
        let nextWillbeParagraph = false;
        for (let i = 0; i < lines.length; i++) {
          const thisLine = lines[i];
          const nextLine = lines[i + 1];
          // add a \n, unless the next line is empty, then its either the last entry or the following wil be a paragraph
          const nextIsEmpty = !nextLine || !nextLine.trim();

          const thisLineText = thisLine + (nextIsEmpty ? '' : '\n');
          if (!thisLine.trim()) {
            // this line is empty,
            nextWillbeParagraph = true;
          } else if (nextWillbeParagraph) {
            Transforms.insertNodes(editor, {
              type: defaultPluginType,
              children: [{ text: thisLineText }],
            });
            nextWillbeParagraph = false;
          } else {
            Transforms.insertText(editor, thisLineText);
            nextWillbeParagraph = false;
          }
        }
        return;
      }

      insertData(data);
    };
    return editor;
  };

export default withPaste;