summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/content_editor/services/content_editor.js
blob: 29553f4c2ca6b390aece3bd50b3db5383e966a1d (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
/* eslint-disable no-underscore-dangle */
export class ContentEditor {
  constructor({ tiptapEditor, serializer }) {
    this._tiptapEditor = tiptapEditor;
    this._serializer = serializer;
  }

  get tiptapEditor() {
    return this._tiptapEditor;
  }

  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);
  }

  async setSerializedContent(serializedContent) {
    const { _tiptapEditor: editor, _serializer: serializer } = this;

    editor.commands.setContent(
      await serializer.deserialize({ schema: editor.schema, content: serializedContent }),
    );
  }

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

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