Proyectos de Subversion Moodle

Rev

| 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
/* eslint-disable no-unused-vars */
16
 
17
/**
18
 * The Atto WYSIWG pluggable editor, written for Moodle.
19
 *
20
 * @module     moodle-editor_atto-editor
21
 * @package    editor_atto
22
 * @copyright  2013 Damyon Wiese  <damyon@moodle.com>
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 * @main       moodle-editor_atto-editor
25
 */
26
 
27
/**
28
 * @module moodle-editor_atto-editor
29
 * @submodule editor-base
30
 */
31
 
32
var LOGNAME = 'moodle-editor_atto-editor';
33
var CSS = {
34
        CONTENT: 'editor_atto_content',
35
        CONTENTWRAPPER: 'editor_atto_content_wrap',
36
        TOOLBAR: 'editor_atto_toolbar',
37
        WRAPPER: 'editor_atto',
38
        HIGHLIGHT: 'highlight'
39
    },
40
    rangy = window.rangy;
41
 
42
/**
43
 * The Atto editor for Moodle.
44
 *
45
 * @namespace M.editor_atto
46
 * @class Editor
47
 * @constructor
48
 * @uses M.editor_atto.EditorClean
49
 * @uses M.editor_atto.EditorFilepicker
50
 * @uses M.editor_atto.EditorSelection
51
 * @uses M.editor_atto.EditorStyling
52
 * @uses M.editor_atto.EditorTextArea
53
 * @uses M.editor_atto.EditorToolbar
54
 * @uses M.editor_atto.EditorToolbarNav
55
 */
56
 
57
function Editor() {
58
    Editor.superclass.constructor.apply(this, arguments);
59
}
60
 
61
Y.extend(Editor, Y.Base, {
62
 
63
    /**
64
     * List of known block level tags.
65
     * Taken from "https://developer.mozilla.org/en-US/docs/HTML/Block-level_elements".
66
     *
67
     * @property BLOCK_TAGS
68
     * @type {Array}
69
     */
70
    BLOCK_TAGS: [
71
        'address',
72
        'article',
73
        'aside',
74
        'audio',
75
        'blockquote',
76
        'canvas',
77
        'dd',
78
        'div',
79
        'dl',
80
        'fieldset',
81
        'figcaption',
82
        'figure',
83
        'footer',
84
        'form',
85
        'h1',
86
        'h2',
87
        'h3',
88
        'h4',
89
        'h5',
90
        'h6',
91
        'header',
92
        'hgroup',
93
        'hr',
94
        'noscript',
95
        'ol',
96
        'output',
97
        'p',
98
        'pre',
99
        'section',
100
        'table',
101
        'tfoot',
102
        'ul',
103
        'video'
104
    ],
105
 
106
    PLACEHOLDER_CLASS: 'atto-tmp-class',
107
    ALL_NODES_SELECTOR: '[style],font[face]',
108
    FONT_FAMILY: 'fontFamily',
109
 
110
    /**
111
     * The wrapper containing the editor.
112
     *
113
     * @property _wrapper
114
     * @type Node
115
     * @private
116
     */
117
    _wrapper: null,
118
 
119
    /**
120
     * A reference to the content editable Node.
121
     *
122
     * @property editor
123
     * @type Node
124
     */
125
    editor: null,
126
 
127
    /**
128
     * A reference to the original text area.
129
     *
130
     * @property textarea
131
     * @type Node
132
     */
133
    textarea: null,
134
 
135
    /**
136
     * A reference to the label associated with the original text area.
137
     *
138
     * @property textareaLabel
139
     * @type Node
140
     */
141
    textareaLabel: null,
142
 
143
    /**
144
     * A reference to the list of plugins.
145
     *
146
     * @property plugins
147
     * @type object
148
     */
149
    plugins: null,
150
 
151
    /**
152
     * An indicator of the current input direction.
153
     *
154
     * @property coreDirection
155
     * @type string
156
     */
157
    coreDirection: null,
158
 
159
    /**
160
     * Enable/disable the empty placeholder content.
161
     *
162
     * @property enableAppropriateEmptyContent
163
     * @type Boolean
164
     */
165
    enableAppropriateEmptyContent: null,
166
 
167
    /**
168
     * Event Handles to clear on editor destruction.
169
     *
170
     * @property _eventHandles
171
     * @private
172
     */
173
    _eventHandles: null,
174
 
175
    initializer: function() {
176
        var template;
177
 
178
        // Note - it is not safe to use a CSS selector like '#' + elementid because the id
179
        // may have colons in it - e.g.  quiz.
180
        this.textarea = Y.one(document.getElementById(this.get('elementid')));
181
 
182
        if (!this.textarea) {
183
            // No text area found.
184
            Y.log('Text area not found - unable to setup editor for ' + this.get('elementid'),
185
                    'error', LOGNAME);
186
            return;
187
        }
188
 
189
        var extraclasses = this.textarea.getAttribute('class');
190
 
191
        this._eventHandles = [];
192
 
193
        var description = Y.Node.create('<div class="sr-only">' + M.util.get_string('richtexteditor', 'editor_atto') + '</div>');
194
        this._wrapper = Y.Node.create('<div class="' + CSS.WRAPPER + '" role="application" />');
195
        this._wrapper.appendChild(description);
196
        this._wrapper.setAttribute('aria-describedby', description.generateID());
197
        template = Y.Handlebars.compile('<div id="{{elementid}}editable" ' +
198
                'contenteditable="true" ' +
199
                'role="textbox" ' +
200
                'spellcheck="true" ' +
201
                'aria-live="off" ' +
202
                'class="{{CSS.CONTENT}} ' + extraclasses + '" ' +
203
                '/>');
204
        this.editor = Y.Node.create(template({
205
            elementid: this.get('elementid'),
206
            CSS: CSS
207
        }));
208
 
209
        // Add a labelled-by attribute to the contenteditable.
210
        this.textareaLabel = Y.one('[for="' + this.get('elementid') + '"]');
211
        if (this.textareaLabel) {
212
            this.textareaLabel.generateID();
213
            this.editor.setAttribute('aria-labelledby', this.textareaLabel.get("id"));
214
        }
215
 
216
        // Set diretcion according to current page language.
217
        this.coreDirection = Y.one('body').hasClass('dir-rtl') ? 'rtl' : 'ltr';
218
 
219
        // Enable the placeholder for empty content.
220
        this.enablePlaceholderForEmptyContent();
221
 
222
        // Add everything to the wrapper.
223
        this.setupToolbar();
224
 
225
        // Editable content wrapper.
226
        var content = Y.Node.create('<div class="' + CSS.CONTENTWRAPPER + '" />');
227
        content.appendChild(this.editor);
228
        this._wrapper.appendChild(content);
229
 
230
        // Style the editor. According to the styles.css: 20 is the line-height, 8 is padding-top + padding-bottom.
231
        this.editor.setStyle('minHeight', ((20 * this.textarea.getAttribute('rows')) + 8) + 'px');
232
 
233
        if (Y.UA.ie === 0) {
234
            // We set a height here to force the overflow because decent browsers allow the CSS property resize.
235
            this.editor.setStyle('height', ((20 * this.textarea.getAttribute('rows')) + 8) + 'px');
236
        }
237
 
238
        // Disable odd inline CSS styles.
239
        this.disableCssStyling();
240
 
241
        // Use paragraphs not divs.
242
        if (document.queryCommandSupported('DefaultParagraphSeparator')) {
243
            document.execCommand('DefaultParagraphSeparator', false, 'p');
244
        }
245
 
246
        // Add the toolbar and editable zone to the page.
247
        this.textarea.get('parentNode').insert(this._wrapper, this.textarea).
248
                setAttribute('class', 'editor_atto_wrap');
249
 
250
        // Hide the old textarea.
251
        this.textarea.hide();
252
 
253
        // Set up custom event for editor updated.
254
        Y.mix(Y.Node.DOM_EVENTS, {'form:editorUpdated': true});
255
        this.textarea.on('form:editorUpdated', function() {
256
            this.updateEditorState();
257
        }, this);
258
 
259
        // Copy the text to the contenteditable div.
260
        this.updateFromTextArea();
261
 
262
        // Publish the events that are defined by this editor.
263
        this.publishEvents();
264
 
265
        // Add handling for saving and restoring selections on cursor/focus changes.
266
        this.setupSelectionWatchers();
267
 
268
        // Add polling to update the textarea periodically when typing long content.
269
        this.setupAutomaticPolling();
270
 
271
        // Setup plugins.
272
        this.setupPlugins();
273
 
274
        // Initialize the auto-save timer.
275
        this.setupAutosave();
276
        // Preload the icons for the notifications.
277
        this.setupNotifications();
278
    },
279
 
280
    /**
281
     * Focus on the editable area for this editor.
282
     *
283
     * @method focus
284
     * @chainable
285
     */
286
    focus: function() {
287
        this.editor.focus();
288
 
289
        return this;
290
    },
291
 
292
    /**
293
     * Publish events for this editor instance.
294
     *
295
     * @method publishEvents
296
     * @private
297
     * @chainable
298
     */
299
    publishEvents: function() {
300
        /**
301
         * Fired when changes are made within the editor.
302
         *
303
         * @event change
304
         */
305
        this.publish('change', {
306
            broadcast: true,
307
            preventable: true
308
        });
309
 
310
        /**
311
         * Fired when all plugins have completed loading.
312
         *
313
         * @event pluginsloaded
314
         */
315
        this.publish('pluginsloaded', {
316
            fireOnce: true
317
        });
318
 
319
        this.publish('atto:selectionchanged', {
320
            prefix: 'atto'
321
        });
322
 
323
        return this;
324
    },
325
 
326
    /**
327
     * Set up automated polling of the text area to update the textarea.
328
     *
329
     * @method setupAutomaticPolling
330
     * @chainable
331
     */
332
    setupAutomaticPolling: function() {
333
        this._registerEventHandle(this.editor.on(['keyup', 'cut'], this.updateOriginal, this));
334
        this._registerEventHandle(this.editor.on('paste', this.pasteCleanup, this));
335
 
336
        // Call this.updateOriginal after dropped content has been processed.
337
        this._registerEventHandle(this.editor.on('drop', this.updateOriginalDelayed, this));
338
 
339
        return this;
340
    },
341
 
342
    /**
343
     * Calls updateOriginal on a short timer to allow native event handlers to run first.
344
     *
345
     * @method updateOriginalDelayed
346
     * @chainable
347
     */
348
    updateOriginalDelayed: function() {
349
        Y.soon(Y.bind(this.updateOriginal, this));
350
 
351
        return this;
352
    },
353
 
354
    setupPlugins: function() {
355
        // Clear the list of plugins.
356
        this.plugins = {};
357
 
358
        var plugins = this.get('plugins');
359
 
360
        var groupIndex,
361
            group,
362
            pluginIndex,
363
            plugin,
364
            pluginConfig;
365
 
366
        for (groupIndex in plugins) {
367
            group = plugins[groupIndex];
368
            if (!group.plugins) {
369
                // No plugins in this group - skip it.
370
                continue;
371
            }
372
            for (pluginIndex in group.plugins) {
373
                plugin = group.plugins[pluginIndex];
374
 
375
                pluginConfig = Y.mix({
376
                    name: plugin.name,
377
                    group: group.group,
378
                    editor: this.editor,
379
                    toolbar: this.toolbar,
380
                    host: this
381
                }, plugin);
382
 
383
                // Add a reference to the current editor.
384
                if (typeof Y.M['atto_' + plugin.name] === "undefined") {
385
                    Y.log("Plugin '" + plugin.name + "' could not be found - skipping initialisation", "warn", LOGNAME);
386
                    continue;
387
                }
388
                this.plugins[plugin.name] = new Y.M['atto_' + plugin.name].Button(pluginConfig);
389
            }
390
        }
391
 
392
        // Some plugins need to perform actions once all plugins have loaded.
393
        this.fire('pluginsloaded');
394
 
395
        return this;
396
    },
397
 
398
    enablePlugins: function(plugin) {
399
        this._setPluginState(true, plugin);
400
    },
401
 
402
    disablePlugins: function(plugin) {
403
        this._setPluginState(false, plugin);
404
    },
405
 
406
    _setPluginState: function(enable, plugin) {
407
        var target = 'disableButtons';
408
        if (enable) {
409
            target = 'enableButtons';
410
        }
411
 
412
        if (plugin) {
413
            this.plugins[plugin][target]();
414
        } else {
415
            Y.Object.each(this.plugins, function(currentPlugin) {
416
                currentPlugin[target]();
417
            }, this);
418
        }
419
    },
420
 
421
    /**
422
     * Update the state of the editor.
423
     */
424
    updateEditorState: function() {
425
        var disabled = this.textarea.hasAttribute('readonly'),
426
            editorfield = Y.one('#' + this.get('elementid') + 'editable');
427
        // Enable/Disable all plugins.
428
        this._setPluginState(!disabled);
429
        // Enable/Disable content of editor.
430
        if (editorfield) {
431
            editorfield.setAttribute('contenteditable', !disabled);
432
        }
433
    },
434
 
435
    /**
436
     * Enable the empty placeholder for empty content.
437
     */
438
    enablePlaceholderForEmptyContent: function() {
439
        this.enableAppropriateEmptyContent = true;
440
    },
441
 
442
    /**
443
     * Disable the empty placeholder for empty content.
444
     */
445
    disablePlaceholderForEmptyContent: function() {
446
        this.enableAppropriateEmptyContent = false;
447
    },
448
 
449
    /**
450
     * Register an event handle for disposal in the destructor.
451
     *
452
     * @method _registerEventHandle
453
     * @param {EventHandle} The Event Handle as returned by Y.on, and Y.delegate.
454
     * @private
455
     */
456
    _registerEventHandle: function(handle) {
457
        this._eventHandles.push(handle);
458
    }
459
 
460
}, {
461
    NS: 'editor_atto',
462
    ATTRS: {
463
        /**
464
         * The unique identifier for the form element representing the editor.
465
         *
466
         * @attribute elementid
467
         * @type String
468
         * @writeOnce
469
         */
470
        elementid: {
471
            value: null,
472
            writeOnce: true
473
        },
474
 
475
        /**
476
         * The contextid of the form.
477
         *
478
         * @attribute contextid
479
         * @type Integer
480
         * @writeOnce
481
         */
482
        contextid: {
483
            value: null,
484
            writeOnce: true
485
        },
486
 
487
        /**
488
         * Plugins with their configuration.
489
         *
490
         * The plugins structure is:
491
         *
492
         *     [
493
         *         {
494
         *             "group": "groupName",
495
         *             "plugins": [
496
         *                 "pluginName": {
497
         *                     "configKey": "configValue"
498
         *                 },
499
         *                 "pluginName": {
500
         *                     "configKey": "configValue"
501
         *                 }
502
         *             ]
503
         *         },
504
         *         {
505
         *             "group": "groupName",
506
         *             "plugins": [
507
         *                 "pluginName": {
508
         *                     "configKey": "configValue"
509
         *                 }
510
         *             ]
511
         *         }
512
         *     ]
513
         *
514
         * @attribute plugins
515
         * @type Object
516
         * @writeOnce
517
         */
518
        plugins: {
519
            value: {},
520
            writeOnce: true
521
        }
522
    }
523
});
524
 
525
// The Editor publishes custom events that can be subscribed to.
526
Y.augment(Editor, Y.EventTarget);
527
 
528
Y.namespace('M.editor_atto').Editor = Editor;
529
 
530
// Function for Moodle's initialisation.
531
Y.namespace('M.editor_atto.Editor').init = function(config) {
532
    return new Y.M.editor_atto.Editor(config);
533
};