Passed
Push — master ( 578b04...dc97f6 )
by Michael
03:06
created

FootnoteMenuItemDispatcher.js ➔ ... ➔ ???   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 17
c 1
b 0
f 0
nc 4
dl 0
loc 26
rs 9.55
nop 2
1
import AbstractMenuItemDispatcher from './AbstractMenuItemDispatcher';
2
import MenuItem from '../MenuItem';
3
import { svgIcon } from '../MDI';
4
import footnoteSchema from '../../../nodeviews/Footnote/footnoteSchema';
5
6
export default class FootnoteMenuItemDispatcher extends AbstractMenuItemDispatcher {
7
    static isAvailable(schema) {
8
        return !!schema.nodes.footnote;
9
    }
10
11
    static getMenuItem(schema) {
12
        if (!this.isAvailable(schema)) {
13
            throw new Error('Footnote not available in schema!');
14
        }
15
        return new MenuItem({
16
            command: (state, dispatch) => {
17
                const { $from } = state.selection;
18
19
                const index = $from.index();
20
                if (!$from.parent.canReplaceWith(index, index, schema.nodes.footnote)) {
21
                    return false;
22
                }
23
24
                const selectedContent = state.selection.content().content.toJSON();
25
                const footnoteDoc = {
26
                    type: 'doc',
27
                    content: selectedContent || [{ type: 'paragraph' }],
28
                };
29
                try {
30
                    footnoteSchema.nodeFromJSON(footnoteDoc);
31
                } catch (e) {
32
                    return false;
33
                }
34
35
                if (dispatch) {
36
                    const footnoteNode = schema.nodes.footnote.create({ contentJSON: JSON.stringify(footnoteDoc) });
37
                    dispatch(state.tr.replaceSelectionWith(footnoteNode));
38
                }
39
40
                return true;
41
            },
42
            icon: svgIcon('note-plus-outline'),
43
            label: 'Add a footnote',
44
        });
45
    }
46
}
47