aboutsummaryrefslogtreecommitdiff
path: root/resources/assets/javascripts/lib/wysiwyg.js
blob: 489af2f426cb164f4edb2214cdaf62e68bbca15a (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/**
 * wysiwyg.js - Replace HTML textareas with WYSIWYG editor.
 */
import parseOptions from './parse_options.js';
import WikiLink from '../cke/wiki-link/wiki-link.js';

const wysiwyg = {
    // NOTE keep this function in sync with Markup class
    htmlMarker: '<!--HTML-->',
    htmlMarkerRegExp: /^\s*<!--\s*HTML.*?-->/i,

    isHtml: function isHtml(text) {
        // NOTE keep this function in sync with
        // Markup::isHtml in Markup.class.php
        return this.hasHtmlMarker(text);
    },
    hasHtmlMarker: function hasHtmlMarker(text) {
        // NOTE keep this function in sync with
        // Markup::hasHtmlMarker in Markup.class.php
        return this.htmlMarkerRegExp.test(text);
    },
    markAsHtml: function markAsHtml(text) {
        // NOTE keep this function in sync with
        // Markup::markAsHtml in Markup.class.php
        if (this.hasHtmlMarker(text) || text.trim() == '') {
            return text; // marker already set, don't set twice
        }
        return this.htmlMarker + text;
    },

    getEditor,
    hasEditor,

    replace(textarea) {
        if (!hasEditor(textarea)) {
            if (isTextareaVisible(textarea)) {
                return replaceTextarea(textarea);
            }
        } else if (isEditorHidden(textarea)) {
            destroyTextarea(textarea);
        }
    },
};

export default wysiwyg;

function isTextareaVisible(textarea) {
    return $(textarea).is(':visible');
}

function isEditorHidden(textarea) {
    if (!hasEditor(textarea)) {
        return false;
    }
    const editor = getEditor(textarea);
    return editor && editor.ui && $(editor.ui.element).is(':hidden');
}

async function replaceTextarea(textarea) {
    await loadMathJax();

    setEditor(textarea, {});

    const chunk = await STUDIP.loadChunk('wysiwyg');

    const $textarea = textarea instanceof jQuery ? textarea : $(textarea);
    const { options, editorType } = parseEditorOptions($textarea.attr('data-editor'));
    const editor = await createEditor(chunk, textarea, editorType, options);
    enhanceEditor($textarea, editor);

    setEditor(textarea, editor);
    $textarea.trigger('load.wysiwyg');

    return editor;
}

function destroyTextarea(textarea) {
    if (!hasEditor(textarea)) {
        throw new Error('Trying to destroy a non-existing editor instance.');
    }

    const editor = getEditor(textarea);
    editor.destroy(true);
    unsetEditor(textarea);
}

// create an unused id
function createNewId(prefix) {
    var i = 0;
    while ($('#' + prefix + i).length > 0) {
        i++;
    }
    return prefix + i;
}

const instances = new Map();

function getEditor(textarea) {
    return textarea?.id !== '' ? instances.get(textarea.id) : null;
}

function hasEditor(textarea) {
    return textarea.id !== '' && instances.has(textarea.id);
}

function setEditor(textarea, editor) {
    if (textarea.id === '') {
        textarea.id = createNewId('wysiwyg');
    }
    instances.set(textarea.id, editor);
}

function unsetEditor(textarea) {
    instances.delete(textarea.id);
}

////////////////////////////////////////////////////////////////////////////////
function parseEditorOptions(data) {
    const result = { options: {}, editorType: 'classic' };

    if (data) {
        const parsed = parseOptions(data);

        const toolbar = getToolbarOptions(parsed);
        if (toolbar) {
            result.options.toolbar = toolbar;
        }

        if (parsed.removePlugins) {
            result.options.removePlugins = parsed.removePlugins.split(',');
        }

        if (parsed.extraPlugins) {
            const pluginMap = { WikiLink };
            result.options.extraPlugins = parsed.extraPlugins.split(',').reduce((memo, plugin) => {
                return plugin in pluginMap ? [...memo, pluginMap[plugin]] : memo;
            }, []);
        }

        if (parsed.type) {
            if (['balloon', 'classic'].includes(parsed.type)) {
                result.editorType = parsed.type;
            }
        }
    }

    return result;
}

function getToolbarOptions(parsed) {
    if (parsed.toolbar === 'small') {
        return {
            removeItems: [
                'undo',
                'redo',
                'findAndReplace',
                'strikethrough',
                'horizontalLine',
                'insertBlockQuote',
                'splitBlockQuote',
                'removeBlockQuote',
            ],
        };
    } else if (parsed.toolbar === 'minimal') {
        return {
            items: [
                'bold',
                'italic',
                'underline',
                'subscript',
                'superscript',
                '|',
                'removeFormat',
                '|',
                'bulletedList',
                'numberedList',
                '|',
                'fontColor',
                'fontBackgroundColor',
                '|',
                'link',
                'math',
                'specialCharacters',
            ],
        };
    }

    return null;
}

function loadMathJax() {
    if (window.MathJax && window.MathJax.Hub) {
        return Promise.resolve(window.MathJax);
    } else if (window.STUDIP && window.STUDIP.loadChunk) {
        return window.STUDIP.loadChunk('mathjax');
    }

    return Promise.reject(new Error('Could not load MathJax'));
}

function createEditor(chunk, textarea, editorType, options) {
    switch (editorType) {
        case 'classic':
            return chunk.createClassicEditorFromTextarea(textarea, options);
        case 'balloon':
            return chunk.createBalloonEditorFromTextarea(textarea, options);
    }

    throw new Error('No such type of WYSIWYG editor.');
}

function enhanceEditor($textarea, ckeditor) {
    // make sure HTML marker is always set, in
    // case contents are cut-off by the backend
    $textarea.closest('form').submit(() => {
        ckeditor.setData(wysiwyg.markAsHtml(ckeditor.getData()));
        ckeditor.updateSourceElement();
    });

    // focus the editor if requested
    if ($textarea.is('[autofocus]')) {
        ckeditor.focus();
    }

    ckeditor.ui.focusTracker.on('change:isFocused', (evt, name, isFocused) => {
        if (!isFocused) {
            ckeditor.sourceElement.value = wysiwyg.markAsHtml(ckeditor.getData());
        }
    });

    // Tell MathJax v2.7 to leave the editor alone
    ckeditor.ui.element.classList.add('tex2jax_ignore');

    return ckeditor;
}