summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/content_editor/services/content_editor.js
blob: 56badf965ee9a2425b4b689830461867c2e0c59a (plain)
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
72
73
74
75
76
77
import { TextSelection } from 'prosemirror-state';
import { LOADING_CONTENT_EVENT, LOADING_SUCCESS_EVENT, LOADING_ERROR_EVENT } from '../constants';

/* eslint-disable no-underscore-dangle */
export class ContentEditor {
  constructor({ tiptapEditor, serializer, deserializer, eventHub, languageLoader }) {
    this._tiptapEditor = tiptapEditor;
    this._serializer = serializer;
    this._deserializer = deserializer;
    this._eventHub = eventHub;
    this._languageLoader = languageLoader;
  }

  get tiptapEditor() {
    return this._tiptapEditor;
  }

  get eventHub() {
    return this._eventHub;
  }

  get empty() {
    const doc = this.tiptapEditor?.state.doc;

    // Makes sure the document has more than one empty paragraph
    return doc.childCount === 0 || (doc.childCount === 1 && doc.child(0).childCount === 0);
  }

  dispose() {
    this.tiptapEditor.destroy();
  }

  disposeAllEvents() {
    this._eventHub.dispose();
  }

  async setSerializedContent(serializedContent) {
    const {
      _tiptapEditor: editor,
      _deserializer: deserializer,
      _eventHub: eventHub,
      _languageLoader: languageLoader,
    } = this;
    const { doc, tr } = editor.state;
    const selection = TextSelection.create(doc, 0, doc.content.size);

    try {
      eventHub.$emit(LOADING_CONTENT_EVENT);
      const result = await deserializer.deserialize({
        schema: editor.schema,
        content: serializedContent,
      });

      if (Object.keys(result).length !== 0) {
        const { document, dom } = result;

        await languageLoader.loadLanguagesFromDOM(dom);

        tr.setSelection(selection)
          .replaceSelectionWith(document, false)
          .setMeta('preventUpdate', true);
        editor.view.dispatch(tr);
      }

      eventHub.$emit(LOADING_SUCCESS_EVENT);
    } catch (e) {
      eventHub.$emit(LOADING_ERROR_EVENT, e);
      throw e;
    }
  }

  getSerializedContent() {
    const { _tiptapEditor: editor, _serializer: serializer } = this;

    return serializer.serialize({ schema: editor.schema, content: editor.getJSON() });
  }
}