Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * TinyMCE Editor Manager.
18
 *
19
 * @module editor_tiny/editor
20
 * @copyright  2022 Andrew Lyons <andrew@nicols.co.uk>
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 */
23
 
24
import jQuery from 'jquery';
25
import Pending from 'core/pending';
11 efrain 26
import {getDefaultConfiguration, getDefaultQuickbarsSelectionToolbar} from './defaults';
1 efrain 27
import {getTinyMCE, baseUrl} from './loader';
28
import * as Options from './options';
29
import {addToolbarButton, addToolbarButtons, addToolbarSection,
30
    removeToolbarButton, removeSubmenuItem, updateEditorState} from './utils';
31
 
32
/**
33
 * Storage for the TinyMCE instances on the page.
34
 * @type {Map}
35
 */
36
const instanceMap = new Map();
37
 
38
/**
39
 * The default editor configuration.
40
 * @type {Object}
41
 */
42
let defaultOptions = {};
43
 
44
/**
45
 * Require the modules for the named set of TinyMCE plugins.
46
 *
47
 * @param {string[]} pluginList The list of plugins
48
 * @return {Promise[]} A matching set of Promises relating to the requested plugins
49
 */
50
const importPluginList = async(pluginList) => {
51
    // Fetch all of the plugins from the list of plugins.
52
    // If a plugin contains a '/' then it is assumed to be a Moodle AMD module to import.
53
    const pluginHandlers = await Promise.all(pluginList.map(pluginPath => {
54
        if (pluginPath.indexOf('/') === -1) {
55
            // A standard TinyMCE Plugin.
56
            return Promise.resolve(pluginPath);
57
        }
58
 
59
        return import(pluginPath);
60
    }));
61
 
62
    // Normalise the plugin data to a list of plugin names.
63
    // Two formats are supported:
64
    // - a string; and
65
    // - an array whose first element is the plugin name, and the second element is the plugin configuration.
66
    const pluginNames = pluginHandlers.map((pluginConfig) => {
67
        if (typeof pluginConfig === 'string') {
68
            return pluginConfig;
69
        }
70
        if (Array.isArray(pluginConfig)) {
71
            return pluginConfig[0];
72
        }
73
        return null;
74
    }).filter((value) => value);
75
 
76
    // Fetch the list of pluginConfig handlers.
77
    const pluginConfig = pluginHandlers.map((pluginConfig) => {
78
        if (Array.isArray(pluginConfig)) {
79
            return pluginConfig[1];
80
        }
81
        return null;
82
    }).filter((value) => value);
83
 
84
    return {
85
        pluginNames,
86
        pluginConfig,
87
    };
88
};
89
 
90
/**
91
 * Fetch the language data for the specified language.
92
 *
93
 * @param {string} language The language identifier
94
 * @returns {object}
95
 */
96
const fetchLanguage = (language) => fetch(
97
    `${M.cfg.wwwroot}/lib/editor/tiny/lang.php/${M.cfg.langrev}/${language}`
98
).then(response => response.json());
99
 
100
/**
101
 * Get a list of all Editors in a Map, keyed by the DOM Node that the Editor is associated with.
102
 *
103
 * @returns {Map<Node, Editor>}
104
 */
105
export const getAllInstances = () => new Map(instanceMap.entries());
106
 
107
/**
108
 * Get the TinyMCE instance for the specified Node ID.
109
 *
110
 * @param {string} elementId
111
 * @returns {TinyMCE|undefined}
112
 */
113
export const getInstanceForElementId = elementId => getInstanceForElement(document.getElementById(elementId));
114
 
115
/*
116
 * Get the TinyMCE instance for the specified HTMLElement.
117
 *
118
 * @param {HTMLElement} element
119
 * @returns {TinyMCE|undefined}
120
 */
121
export const getInstanceForElement = element => {
122
    const instance = instanceMap.get(element);
123
    if (instance && instance.removed) {
124
        instanceMap.delete(element);
125
        return undefined;
126
    }
127
    return instance;
128
};
129
 
130
/**
131
 * Set up TinyMCE for the selector at the specified HTML Node id.
132
 *
133
 * @param {object} config The configuration required to setup the editor
134
 * @param {string} config.elementId The HTML Node ID
135
 * @param {Object} config.options The editor plugin configuration
136
 */
137
export const setupForElementId = ({elementId, options}) => {
138
    const target = document.getElementById(elementId);
139
    // We will need to wrap the setupForTarget and editor.remove() calls in a setTimeout.
140
    // Because other events callbacks will still try to run on the removed instance.
141
    // This will cause an error on Firefox.
142
    // We need to make TinyMCE to remove itself outside the event loop.
143
    // @see https://github.com/tinymce/tinymce/issues/3129 for more details.
144
    setTimeout(() => {
145
        return setupForTarget(target, options);
146
    }, 1);
147
};
148
 
149
/**
150
 * Initialise the page with standard TinyMCE requirements.
151
 *
152
 * Currently this includes the language taken from the HTML lang property.
153
 */
154
const initialisePage = async() => {
155
    const lang = document.querySelector('html').lang;
156
 
157
    const [tinyMCE, langData] = await Promise.all([getTinyMCE(), fetchLanguage(lang)]);
158
    tinyMCE.addI18n(lang, langData);
159
};
160
initialisePage();
161
 
162
/**
163
 * Get the list of plugins to load for the specified configuration.
164
 *
165
 * If the specified configuration does not include a plugin configuration, then return the default configuration.
166
 *
167
 * @param {object} options
168
 * @param {array} [options.plugins=null] The plugin list
169
 * @returns {object}
170
 */
171
const getPlugins = ({plugins = null} = {}) => {
172
    if (plugins) {
173
        return plugins;
174
    }
175
 
176
    if (defaultOptions.plugins) {
177
        return defaultOptions.plugins;
178
    }
179
 
180
    return {};
181
};
182
 
183
/**
184
 * Adjust the editor size base on the target element.
185
 *
186
 * @param {TinyMCE} editor TinyMCE editor
187
 * @param {Node} target Target element
188
 */
189
const adjustEditorSize = (editor, target) => {
190
    let expectedEditingAreaHeight = 0;
191
    if (target.clientHeight) {
192
        expectedEditingAreaHeight = target.clientHeight;
193
    } else {
194
        // If the target element is hidden, we cannot get the lineHeight of the target element.
195
        // We don't have a proper way to retrieve the general lineHeight of the theme, so we use 22 here, it's equivalent to 1.5em.
196
        expectedEditingAreaHeight = target.rows * (parseFloat(window.getComputedStyle(target).lineHeight) || 22);
197
    }
198
    const currentEditingAreaHeight = editor.getContainer().querySelector('.tox-sidebar-wrap').clientHeight;
199
    if (currentEditingAreaHeight < expectedEditingAreaHeight) {
200
        // Change the height based on the target element's height.
201
        editor.getContainer().querySelector('.tox-sidebar-wrap').style.height = `${expectedEditingAreaHeight}px`;
202
    }
203
};
204
 
205
/**
206
 * Get the standard configuration for the specified options.
207
 *
208
 * @param {Node} target
209
 * @param {tinyMCE} tinyMCE
210
 * @param {object} options
211
 * @param {Array} plugins
212
 * @returns {object}
213
 */
214
const getStandardConfig = (target, tinyMCE, options, plugins) => {
215
    const lang = document.querySelector('html').lang;
216
 
217
    const config = Object.assign({}, getDefaultConfiguration(), {
218
        // eslint-disable-next-line camelcase
219
        base_url: baseUrl,
220
 
221
        // Set the editor target.
222
        // https://www.tiny.cloud/docs/tinymce/6/editor-important-options/#target
223
        target,
224
 
225
        // https://www.tiny.cloud/docs/tinymce/6/customize-ui/#set-maximum-and-minimum-heights-and-widths
226
        // Set the minimum height to the smallest height that we can fit the Menu bar, Tool bar, Status bar and the text area.
227
        // eslint-disable-next-line camelcase
228
        min_height: 175,
229
 
230
        // Base the height on the size of the text area.
231
        // In some cases, E.g.: The target is an advanced element, it will be hidden. We cannot get the height at this time.
232
        // So set the height to auto, and adjust it later by adjustEditorSize().
233
        height: target.clientHeight || 'auto',
234
 
235
        // Set the language.
236
        // https://www.tiny.cloud/docs/tinymce/6/ui-localization/#language
237
        // eslint-disable-next-line camelcase
238
        language: lang,
239
 
240
        // Load the editor stylesheet into the editor iframe.
241
        // https://www.tiny.cloud/docs/tinymce/6/add-css-options/
242
        // eslint-disable-next-line camelcase
243
        content_css: [
244
            options.css,
245
        ],
246
 
247
        // Do not convert URLs to relative URLs.
248
        // https://www.tiny.cloud/docs/tinymce/6/url-handling/#convert_urls
249
        // eslint-disable-next-line camelcase
250
        convert_urls: false,
251
 
252
        // Enabled 'advanced' a11y options.
253
        // This includes allowing role="presentation" from the image uploader.
254
        // https://www.tiny.cloud/docs/tinymce/6/accessibility/
255
        // eslint-disable-next-line camelcase
256
        a11y_advanced_options: true,
257
 
258
        // Add specific rules to the valid elements.
259
        // eslint-disable-next-line camelcase
260
        extended_valid_elements: 'script[*],p[*],i[*]',
261
 
262
        // Disable XSS Sanitisation.
263
        // We do this in PHP.
264
        // https://www.tiny.cloud/docs/tinymce/6/security/#turning-dompurify-off
265
        // Note: This feature has been backported from TinyMCE 6.4.0.
266
        // eslint-disable-next-line camelcase
267
        xss_sanitization: false,
268
 
269
        // Disable quickbars entirely.
270
        // The UI is not ideal and we'll wait for it to improve in future before we enable it in Moodle.
271
        // eslint-disable-next-line camelcase
272
        quickbars_insert_toolbar: '',
273
 
11 efrain 274
        // If the target element is too small, disable the quickbars selection toolbar.
275
        // The quickbars selection toolbar is not displayed correctly if the target element is too small.
276
        // See: https://github.com/tinymce/tinymce/issues/9693.
277
        quickbars_selection_toolbar: target.rows > 5 ? getDefaultQuickbarsSelectionToolbar() : false,
278
 
1 efrain 279
        // Override the standard block formats property (removing h1 & h2).
280
        // https://www.tiny.cloud/docs/tinymce/6/user-formatting-options/#block_formats
281
        // eslint-disable-next-line camelcase
282
        block_formats: 'Paragraph=p;Heading 3=h3;Heading 4=h4;Heading 5=h5;Heading 6=h6;Preformatted=pre',
283
 
284
        // The list of plugins to include in the instance.
285
        // https://www.tiny.cloud/docs/tinymce/6/editor-important-options/#plugins
286
        plugins: [
287
            ...plugins,
288
        ],
289
 
290
        // Skins
291
        skin: 'oxide',
292
 
293
        // Do not show the help link in the status bar.
294
        // https://www.tiny.cloud/docs/tinymce/latest/accessibility/#help_accessibility
295
        // eslint-disable-next-line camelcase
296
        help_accessibility: false,
297
 
298
        // Remove the "Upgrade" link for Tiny.
299
        // https://www.tiny.cloud/docs/tinymce/6/editor-premium-upgrade-promotion/
300
        promotion: false,
301
 
302
        // Allow the administrator to disable branding.
303
        // https://www.tiny.cloud/docs/tinymce/6/statusbar-configuration-options/#branding
304
        branding: options.branding,
305
 
306
        // Put th cells in a thead element.
307
        // https://www.tiny.cloud/docs/tinymce/6/table-options/#table_header_type
308
        // eslint-disable-next-line camelcase
309
        table_header_type: 'sectionCells',
310
 
311
        // Stored text in non-entity form.
312
        // https://www.tiny.cloud/docs/tinymce/6/content-filtering/#entity_encoding
313
        // eslint-disable-next-line camelcase
314
        entity_encoding: "raw",
315
 
316
        // Enable support for editors in scrollable containers.
317
        // https://www.tiny.cloud/docs/tinymce/6/ui-mode-configuration-options/#ui_mode
318
        // eslint-disable-next-line camelcase
319
        ui_mode: 'split',
320
 
321
        // Enable browser-supported spell checking.
322
        // https://www.tiny.cloud/docs/tinymce/latest/spelling/
323
        // eslint-disable-next-line camelcase
324
        browser_spellcheck: true,
325
 
326
        setup: (editor) => {
327
            Options.register(editor, options);
328
 
329
            editor.on('PreInit', function() {
330
                // Work around a bug in TinyMCE with Firefox.
331
                // When an editor is removed, and replaced with an identically attributed editor (same ID),
332
                // and the Firefox window is freshly opened (e.g. Behat, Private browsing), the wrong contentWindow
333
                // is assigned to the editor instance leading to an NS_ERROR_UNEXPECTED error in Firefox.
334
                // This is a workaround for that issue.
335
                this.contentWindow = this.iframeElement.contentWindow;
336
            });
337
            editor.on('init', function() {
338
                // Hide justify alignment sub-menu.
339
                removeSubmenuItem(editor, 'align', 'tiny:justify');
340
                // Adjust the editor size.
341
                adjustEditorSize(editor, target);
342
            });
343
 
344
            target.addEventListener('form:editorUpdated', function() {
345
                updateEditorState(editor, target);
346
            });
347
 
348
            target.dispatchEvent(new Event('form:editorUpdated'));
349
        },
350
    });
351
 
352
    config.toolbar = addToolbarSection(config.toolbar, 'content', 'formatting', true);
353
    config.toolbar = addToolbarButton(config.toolbar, 'content', 'link');
354
 
355
    // Add directionality plugins, always.
356
    config.toolbar = addToolbarSection(config.toolbar, 'directionality', 'alignment', true);
357
    config.toolbar = addToolbarButtons(config.toolbar, 'directionality', ['ltr', 'rtl']);
358
 
359
    // Remove the align justify button from the toolbar.
360
    config.toolbar = removeToolbarButton(config.toolbar, 'alignment', 'alignjustify');
361
 
362
    return config;
363
};
364
 
365
/**
366
 * Fetch the TinyMCE configuration for this editor instance.
367
 *
368
 * @param {HTMLElement} target
369
 * @param {TinyMCE} tinyMCE The TinyMCE API
370
 * @param {Object} options The editor plugin configuration
371
 * @param {object} pluginValues
372
 * @param {object} pluginValues.pluginConfig The list of plugin configuration
373
 * @param {object} pluginValues.pluginNames The list of plugins to load
374
 * @returns {object} The TinyMCE Configuration
375
 */
376
const getEditorConfiguration = (target, tinyMCE, options, pluginValues) => {
377
    const {
378
        pluginNames,
379
        pluginConfig,
380
    } = pluginValues;
381
 
382
    // Allow plugins to modify the configuration.
383
    // This seems a little strange, but we must double-process the config slightly.
384
 
385
    // First we fetch the standard configuration.
386
    const instanceConfig = getStandardConfig(target, tinyMCE, options, pluginNames);
387
 
388
    // Next we make any standard changes.
389
    // Here we remove the file menu, as it doesn't offer any useful functionality.
390
    // We only empty the items list so that a plugin may choose to add to it themselves later if they wish.
391
    if (instanceConfig.menu.file) {
392
        instanceConfig.menu.file.items = '';
393
    }
394
 
395
    // We disable the styles, backcolor, and forecolor plugins from the format menu.
396
    // These are not useful for Moodle and we don't want to encourage their use.
397
    if (instanceConfig.menu.format) {
398
        instanceConfig.menu.format.items = instanceConfig.menu.format.items
399
            // Remove forecolor and backcolor.
400
            .replace(/forecolor ?/, '')
401
            .replace(/backcolor ?/, '')
402
 
403
            // Remove fontfamily for now.
404
            .replace(/fontfamily ?/, '')
405
 
406
            // Remove fontsize for now.
407
            .replace(/fontsize ?/, '')
408
 
409
            // Remove styles - it just duplicates the format menu in a way which does not respect configuration
410
            .replace(/styles ?/, '')
411
 
412
            // Remove any duplicate separators.
413
            .replaceAll(/\| *\|/g, '|');
414
    }
415
 
11 efrain 416
    if (instanceConfig.quickbars_selection_toolbar !== false) {
417
        // eslint-disable-next-line camelcase
418
        instanceConfig.quickbars_selection_toolbar = instanceConfig.quickbars_selection_toolbar.replace('h2 h3', 'h3 h4 h5 h6');
419
    }
1 efrain 420
 
421
    // Next we call the `configure` function for any plugin which defines it.
422
    // We pass the current instanceConfig in here, to allow them to make certain changes to the global configuration.
423
    // For example, to add themselves to any menu, toolbar, and so on.
424
    // Any plugin which wishes to have configuration options must register those options here.
425
    pluginConfig.filter((pluginConfig) => typeof pluginConfig.configure === 'function').forEach((pluginConfig) => {
426
        const pluginInstanceOverride = pluginConfig.configure(instanceConfig, options);
427
        Object.assign(instanceConfig, pluginInstanceOverride);
428
    });
429
 
430
    // Next we convert the plugin configuration into a format that TinyMCE understands.
431
    Object.assign(instanceConfig, Options.getInitialPluginConfiguration(options));
432
 
433
    return instanceConfig;
434
};
435
 
436
/**
437
 * Check if the target for TinyMCE is in a modal or not.
438
 *
439
 * @param {HTMLElement} target Target to check
440
 * @returns {boolean} True if the target is in a modal form.
441
 */
442
const isModalMode = (target) => {
443
    return !!target.closest('[data-region="modal"]');
444
};
445
 
446
/**
447
 * Set up TinyMCE for the HTML Element.
448
 *
449
 * @param {HTMLElement} target
450
 * @param {Object} [options={}] The editor plugin configuration
451
 * @return {Promise<TinyMCE>} The TinyMCE instance
452
 */
453
export const setupForTarget = async(target, options = {}) => {
454
    const instance = getInstanceForElement(target);
455
    if (instance) {
456
        return Promise.resolve(instance);
457
    }
458
 
459
    // Register a new pending promise to ensure that Behat waits for the editor setup to complete before continuing.
460
    const pendingPromise = new Pending('editor_tiny/editor:setupForTarget');
461
 
462
    // Get the list of plugins.
463
    const plugins = getPlugins(options);
464
 
465
    // Fetch the tinyMCE API, and instantiate the plugins.
466
    const [tinyMCE, pluginValues] = await Promise.all([
467
        getTinyMCE(),
468
        importPluginList(Object.keys(plugins)),
469
    ]);
470
 
471
    // TinyMCE uses the element ID as a map key internally, even if the target has changed.
472
    // In the case where we have an editor in a modal form which has been detached from the DOM, but the editor not removed,
473
    // we need to manually destroy the editor.
474
    // We could theoretically do this with a Mutation Observer, but in some cases the Node may be moved,
475
    // or added back elsewhere in the DOM.
476
 
477
    // First remove any detached editors.
478
    tinyMCE.get().filter((editor) => !editor.getElement().isConnected).forEach((editor) => {
479
        editor.remove();
480
    });
481
 
482
    // Now check for any existing editor which shares the same ID.
483
    const existingEditor = tinyMCE.EditorManager.get(target.id);
484
    if (existingEditor) {
485
        if (existingEditor.getElement() === target) {
486
            pendingPromise.resolve();
487
            return Promise.resolve(existingEditor);
488
        } else {
489
            pendingPromise.resolve();
490
            throw new Error('TinyMCE instance already exists for different target with same ID');
491
        }
492
    }
493
 
494
    // Get the editor configuration for this editor.
495
    const instanceConfig = getEditorConfiguration(target, tinyMCE, options, pluginValues);
496
 
497
    // Initialise the editor instance for the given configuration.
498
    // At this point any plugin which has configuration options registered will have them applied for this instance.
499
    const [editor] = await tinyMCE.init(instanceConfig);
500
 
501
    // Update the textarea when the editor to set the field type for Behat.
502
    target.dataset.fieldtype = 'editor';
503
 
504
    // Store the editor instance in the instanceMap and register a listener on removal to remove it from the map.
505
    instanceMap.set(target, editor);
506
    editor.on('remove', ({target}) => {
507
        // Handle removal of the editor from the map on destruction.
508
        instanceMap.delete(target.targetElm);
509
        target.targetElm.dataset.fieldtype = null;
510
    });
511
 
512
    // If the editor is part of a form, also listen to the jQuery submit event.
513
    // The jQuery submit event will not trigger the native submit event, and therefore the content will not be saved.
514
    // We cannot rely on listening to the bubbled submit event on the document because other events on child nodes may
515
    // consume the data before it is saved.
516
    if (target.form) {
517
        jQuery(target.form).on('submit', () => {
518
            editor.save();
519
        });
520
    }
521
 
522
    // Save the editor content to the textarea when the editor is blurred.
523
    editor.on('blur', () => {
524
        editor.save();
525
    });
526
 
527
    // If the editor is in a modal, we need to hide the modal when window editor's window is opened.
528
    editor.on('OpenWindow', () => {
529
        const modals = document.querySelectorAll('[data-region="modal"]');
530
        if (modals) {
531
            modals.forEach((modal) => {
532
                if (!modal.classList.contains('hide')) {
533
                    modal.classList.add('hide');
534
                }
535
            });
536
        }
537
    });
538
 
539
    // If the editor's window is closed, we need to show the hidden modal back.
540
    editor.on('CloseWindow', () => {
541
        if (isModalMode(target)) {
542
            const modals = document.querySelectorAll('[data-region="modal"]');
543
            if (modals) {
544
                modals.forEach((modal) => {
545
                    if (modal.classList.contains('hide')) {
546
                        modal.classList.remove('hide');
547
                    }
548
                });
549
            }
550
        }
551
    });
552
 
553
    pendingPromise.resolve();
554
    return editor;
555
};
556
 
557
/**
558
 * Set the default editor configuration.
559
 *
560
 * This configuration is used when an editor is initialised without any configuration.
561
 *
562
 * @param {object} [options={}]
563
 */
564
export const configureDefaultEditor = (options = {}) => {
565
    defaultOptions = options;
566
};