MDL-54796 forms: Editor restore event created.
[moodle.git] / lib / editor / atto / yui / build / moodle-editor_atto-editor / moodle-editor_atto-editor-debug.js
CommitLineData
adca7326
DW
1YUI.add('moodle-editor_atto-editor', function (Y, NAME) {
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
ad3f8cd1 17/* eslint-disable no-unused-vars */
adca7326
DW
18
19/**
62467795 20 * The Atto WYSIWG pluggable editor, written for Moodle.
adca7326 21 *
62467795 22 * @module moodle-editor_atto-editor
adca7326
DW
23 * @package editor_atto
24 * @copyright 2013 Damyon Wiese <damyon@moodle.com>
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
62467795 26 * @main moodle-editor_atto-editor
adca7326
DW
27 */
28
29/**
62467795
AN
30 * @module moodle-editor_atto-editor
31 * @submodule editor-base
adca7326 32 */
62467795
AN
33
34var LOGNAME = 'moodle-editor_atto-editor';
35var CSS = {
36 CONTENT: 'editor_atto_content',
37 CONTENTWRAPPER: 'editor_atto_content_wrap',
38 TOOLBAR: 'editor_atto_toolbar',
39 WRAPPER: 'editor_atto',
40 HIGHLIGHT: 'highlight'
557f44d9
AN
41 },
42 rangy = window.rangy;
adca7326
DW
43
44/**
62467795 45 * The Atto editor for Moodle.
adca7326 46 *
62467795
AN
47 * @namespace M.editor_atto
48 * @class Editor
49 * @constructor
50 * @uses M.editor_atto.EditorClean
51 * @uses M.editor_atto.EditorFilepicker
52 * @uses M.editor_atto.EditorSelection
53 * @uses M.editor_atto.EditorStyling
54 * @uses M.editor_atto.EditorTextArea
55 * @uses M.editor_atto.EditorToolbar
56 * @uses M.editor_atto.EditorToolbarNav
adca7326 57 */
62467795
AN
58
59function Editor() {
60 Editor.superclass.constructor.apply(this, arguments);
61}
62
63Y.extend(Editor, Y.Base, {
adca7326 64
34f5867a
DW
65 /**
66 * List of known block level tags.
67 * Taken from "https://developer.mozilla.org/en-US/docs/HTML/Block-level_elements".
68 *
62467795 69 * @property BLOCK_TAGS
34f5867a
DW
70 * @type {Array}
71 */
72 BLOCK_TAGS : [
73 'address',
74 'article',
75 'aside',
76 'audio',
77 'blockquote',
78 'canvas',
79 'dd',
80 'div',
81 'dl',
82 'fieldset',
83 'figcaption',
84 'figure',
85 'footer',
86 'form',
87 'h1',
88 'h2',
89 'h3',
90 'h4',
91 'h5',
92 'h6',
93 'header',
94 'hgroup',
95 'hr',
96 'noscript',
97 'ol',
98 'output',
99 'p',
100 'pre',
101 'section',
102 'table',
103 'tfoot',
104 'ul',
62467795
AN
105 'video'
106 ],
d321f68b 107
af6a2e94 108 PLACEHOLDER_CLASS: 'atto-tmp-class',
bed1abbc
AD
109 ALL_NODES_SELECTOR: '[style],font[face]',
110 FONT_FAMILY: 'fontFamily',
34f5867a 111
adca7326 112 /**
62467795
AN
113 * The wrapper containing the editor.
114 *
115 * @property _wrapper
116 * @type Node
117 * @private
adca7326 118 */
62467795 119 _wrapper: null,
adca7326
DW
120
121 /**
62467795
AN
122 * A reference to the content editable Node.
123 *
124 * @property editor
125 * @type Node
adca7326 126 */
62467795 127 editor: null,
adca7326
DW
128
129 /**
62467795
AN
130 * A reference to the original text area.
131 *
132 * @property textarea
133 * @type Node
adca7326 134 */
62467795 135 textarea: null,
adca7326
DW
136
137 /**
62467795
AN
138 * A reference to the label associated with the original text area.
139 *
140 * @property textareaLabel
141 * @type Node
adca7326 142 */
62467795 143 textareaLabel: null,
adca7326
DW
144
145 /**
62467795
AN
146 * A reference to the list of plugins.
147 *
148 * @property plugins
149 * @type object
adca7326 150 */
62467795 151 plugins: null,
adca7326 152
4dbc02f6
AN
153 /**
154 * Event Handles to clear on editor destruction.
155 *
156 * @property _eventHandles
157 * @private
158 */
159 _eventHandles: null,
160
62467795
AN
161 initializer: function() {
162 var template;
adca7326 163
62467795
AN
164 // Note - it is not safe to use a CSS selector like '#' + elementid because the id
165 // may have colons in it - e.g. quiz.
166 this.textarea = Y.one(document.getElementById(this.get('elementid')));
26f8822d 167
62467795
AN
168 if (!this.textarea) {
169 // No text area found.
170 Y.log('Text area not found - unable to setup editor for ' + this.get('elementid'),
171 'error', LOGNAME);
172 return;
173 }
26f8822d 174
4dbc02f6
AN
175 this._eventHandles = [];
176
62467795
AN
177 this._wrapper = Y.Node.create('<div class="' + CSS.WRAPPER + '" />');
178 template = Y.Handlebars.compile('<div id="{{elementid}}editable" ' +
179 'contenteditable="true" ' +
180 'role="textbox" ' +
181 'spellcheck="true" ' +
182 'aria-live="off" ' +
183 'class="{{CSS.CONTENT}}" ' +
184 '/>');
185 this.editor = Y.Node.create(template({
186 elementid: this.get('elementid'),
187 CSS: CSS
188 }));
67d3fe45 189
6d9a83c2
DW
190 // Add a labelled-by attribute to the contenteditable.
191 this.textareaLabel = Y.one('[for="' + this.get('elementid') + '"]');
192 if (this.textareaLabel) {
193 this.textareaLabel.generateID();
194 this.editor.setAttribute('aria-labelledby', this.textareaLabel.get("id"));
195 }
67d3fe45 196
62467795
AN
197 // Add everything to the wrapper.
198 this.setupToolbar();
67d3fe45 199
62467795
AN
200 // Editable content wrapper.
201 var content = Y.Node.create('<div class="' + CSS.CONTENTWRAPPER + '" />');
202 content.appendChild(this.editor);
203 this._wrapper.appendChild(content);
0fa78b80 204
2f0a1236
FM
205 // Style the editor. According to the styles.css: 20 is the line-height, 8 is padding-top + padding-bottom.
206 this.editor.setStyle('minHeight', ((20 * this.textarea.getAttribute('rows')) + 8) + 'px');
207
208 if (Y.UA.ie === 0) {
209 // We set a height here to force the overflow because decent browsers allow the CSS property resize.
210 this.editor.setStyle('height', ((20 * this.textarea.getAttribute('rows')) + 8) + 'px');
211 }
212
62467795
AN
213 // Disable odd inline CSS styles.
214 this.disableCssStyling();
adca7326 215
e92a39cf
DP
216 // Use paragraphs not divs.
217 if (document.queryCommandSupported('DefaultParagraphSeparator')) {
218 document.execCommand('DefaultParagraphSeparator', false, 'p');
219 }
220
62467795 221 // Add the toolbar and editable zone to the page.
369a63ac
DC
222 this.textarea.get('parentNode').insert(this._wrapper, this.textarea).
223 setAttribute('class', 'editor_atto_wrap');
adca7326 224
62467795
AN
225 // Hide the old textarea.
226 this.textarea.hide();
adca7326 227
62467795
AN
228 // Copy the text to the contenteditable div.
229 this.updateFromTextArea();
adca7326 230
62467795
AN
231 // Publish the events that are defined by this editor.
232 this.publishEvents();
adca7326 233
62467795
AN
234 // Add handling for saving and restoring selections on cursor/focus changes.
235 this.setupSelectionWatchers();
adca7326 236
4dbc02f6
AN
237 // Add polling to update the textarea periodically when typing long content.
238 this.setupAutomaticPolling();
239
62467795
AN
240 // Setup plugins.
241 this.setupPlugins();
2ba6706d
DW
242
243 // Initialize the auto-save timer.
244 this.setupAutosave();
8a5db547
DW
245 // Preload the icons for the notifications.
246 this.setupNotifications();
48bdf86f
DW
247 },
248
249 /**
62467795 250 * Focus on the editable area for this editor.
48bdf86f 251 *
62467795
AN
252 * @method focus
253 * @chainable
48bdf86f 254 */
62467795
AN
255 focus: function() {
256 this.editor.focus();
257
258 return this;
48bdf86f
DW
259 },
260
261 /**
62467795 262 * Publish events for this editor instance.
48bdf86f 263 *
62467795
AN
264 * @method publishEvents
265 * @private
266 * @chainable
48bdf86f 267 */
62467795
AN
268 publishEvents: function() {
269 /**
270 * Fired when changes are made within the editor.
271 *
272 * @event change
273 */
274 this.publish('change', {
275 broadcast: true,
276 preventable: true
277 });
48bdf86f 278
62467795
AN
279 /**
280 * Fired when all plugins have completed loading.
281 *
282 * @event pluginsloaded
283 */
284 this.publish('pluginsloaded', {
285 fireOnce: true
286 });
48bdf86f 287
62467795
AN
288 this.publish('atto:selectionchanged', {
289 prefix: 'atto'
290 });
48bdf86f 291
62467795 292 return this;
3ee53a42
DW
293 },
294
4dbc02f6
AN
295 /**
296 * Set up automated polling of the text area to update the textarea.
297 *
298 * @method setupAutomaticPolling
299 * @chainable
300 */
301 setupAutomaticPolling: function() {
a7fdadc9
EM
302 this._registerEventHandle(this.editor.on(['keyup', 'cut'], this.updateOriginal, this));
303 this._registerEventHandle(this.editor.on('paste', this.pasteCleanup, this));
4dbc02f6 304
10fae277
PN
305 // Call this.updateOriginal after dropped content has been processed.
306 this._registerEventHandle(this.editor.on('drop', this.updateOriginalDelayed, this));
307
308 return this;
309 },
310
311 /**
312 * Calls updateOriginal on a short timer to allow native event handlers to run first.
313 *
314 * @method updateOriginalDelayed
315 * @chainable
316 */
317 updateOriginalDelayed: function() {
318 Y.soon(Y.bind(this.updateOriginal, this));
319
4dbc02f6
AN
320 return this;
321 },
322
62467795
AN
323 setupPlugins: function() {
324 // Clear the list of plugins.
325 this.plugins = {};
326
327 var plugins = this.get('plugins');
adca7326 328
62467795
AN
329 var groupIndex,
330 group,
331 pluginIndex,
332 plugin,
333 pluginConfig;
334
335 for (groupIndex in plugins) {
336 group = plugins[groupIndex];
337 if (!group.plugins) {
338 // No plugins in this group - skip it.
339 continue;
340 }
341 for (pluginIndex in group.plugins) {
342 plugin = group.plugins[pluginIndex];
343
344 pluginConfig = Y.mix({
345 name: plugin.name,
346 group: group.group,
347 editor: this.editor,
348 toolbar: this.toolbar,
349 host: this
350 }, plugin);
351
352 // Add a reference to the current editor.
353 if (typeof Y.M['atto_' + plugin.name] === "undefined") {
354 Y.log("Plugin '" + plugin.name + "' could not be found - skipping initialisation", "warn", LOGNAME);
355 continue;
356 }
357 this.plugins[plugin.name] = new Y.M['atto_' + plugin.name].Button(pluginConfig);
358 }
adca7326 359 }
62467795
AN
360
361 // Some plugins need to perform actions once all plugins have loaded.
362 this.fire('pluginsloaded');
363
364 return this;
adca7326
DW
365 },
366
62467795
AN
367 enablePlugins: function(plugin) {
368 this._setPluginState(true, plugin);
369 },
3ee53a42 370
62467795
AN
371 disablePlugins: function(plugin) {
372 this._setPluginState(false, plugin);
3ee53a42
DW
373 },
374
62467795
AN
375 _setPluginState: function(enable, plugin) {
376 var target = 'disableButtons';
377 if (enable) {
378 target = 'enableButtons';
3ee53a42 379 }
3ee53a42 380
62467795
AN
381 if (plugin) {
382 this.plugins[plugin][target]();
383 } else {
384 Y.Object.each(this.plugins, function(currentPlugin) {
385 currentPlugin[target]();
386 }, this);
3ee53a42 387 }
4dbc02f6
AN
388 },
389
390 /**
391 * Register an event handle for disposal in the destructor.
392 *
393 * @method _registerEventHandle
394 * @param {EventHandle} The Event Handle as returned by Y.on, and Y.delegate.
395 * @private
396 */
397 _registerEventHandle: function(handle) {
398 this._eventHandles.push(handle);
62467795 399 }
3ee53a42 400
62467795
AN
401}, {
402 NS: 'editor_atto',
403 ATTRS: {
404 /**
405 * The unique identifier for the form element representing the editor.
406 *
407 * @attribute elementid
408 * @type String
409 * @writeOnce
410 */
411 elementid: {
412 value: null,
413 writeOnce: true
414 },
adca7326 415
2ba6706d
DW
416 /**
417 * The contextid of the form.
418 *
419 * @attribute contextid
420 * @type Integer
421 * @writeOnce
422 */
423 contextid: {
424 value: null,
425 writeOnce: true
426 },
427
62467795
AN
428 /**
429 * Plugins with their configuration.
430 *
431 * The plugins structure is:
432 *
433 * [
434 * {
435 * "group": "groupName",
436 * "plugins": [
437 * "pluginName": {
438 * "configKey": "configValue"
439 * },
440 * "pluginName": {
441 * "configKey": "configValue"
442 * }
443 * ]
444 * },
445 * {
446 * "group": "groupName",
447 * "plugins": [
448 * "pluginName": {
449 * "configKey": "configValue"
450 * }
451 * ]
452 * }
453 * ]
454 *
455 * @attribute plugins
456 * @type Object
457 * @writeOnce
458 */
459 plugins: {
460 value: {},
461 writeOnce: true
adca7326 462 }
62467795
AN
463 }
464});
465
466// The Editor publishes custom events that can be subscribed to.
467Y.augment(Editor, Y.EventTarget);
468
469Y.namespace('M.editor_atto').Editor = Editor;
470
471// Function for Moodle's initialisation.
472Y.namespace('M.editor_atto.Editor').init = function(config) {
473 return new Y.M.editor_atto.Editor(config);
474};
475// This file is part of Moodle - http://moodle.org/
476//
477// Moodle is free software: you can redistribute it and/or modify
478// it under the terms of the GNU General Public License as published by
479// the Free Software Foundation, either version 3 of the License, or
480// (at your option) any later version.
481//
482// Moodle is distributed in the hope that it will be useful,
483// but WITHOUT ANY WARRANTY; without even the implied warranty of
484// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
485// GNU General Public License for more details.
486//
487// You should have received a copy of the GNU General Public License
488// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
489
75c86d13
DW
490/**
491 * A notify function for the Atto editor.
492 *
493 * @module moodle-editor_atto-notify
19549f8b 494 * @submodule notify
75c86d13
DW
495 * @package editor_atto
496 * @copyright 2014 Damyon Wiese
497 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
498 */
499
19549f8b
DW
500var LOGNAME_NOTIFY = 'moodle-editor_atto-editor-notify',
501 NOTIFY_INFO = 'info',
502 NOTIFY_WARNING = 'warning';
503
75c86d13
DW
504function EditorNotify() {}
505
506EditorNotify.ATTRS= {
507};
508
75c86d13
DW
509EditorNotify.prototype = {
510
511 /**
19549f8b 512 * A single Y.Node for this editor. There is only ever one - it is replaced if a new message comes in.
75c86d13
DW
513 *
514 * @property messageOverlay
19549f8b 515 * @type {Node}
75c86d13
DW
516 */
517 messageOverlay: null,
518
8a5db547
DW
519 /**
520 * A single timer object that can be used to cancel the hiding behaviour.
521 *
522 * @property hideTimer
523 * @type {timer}
524 */
525 hideTimer: null,
526
527 /**
528 * Initialize the notifications.
529 *
530 * @method setupNotifications
531 * @chainable
532 */
533 setupNotifications: function() {
534 var preload1 = new Image(),
535 preload2 = new Image();
536
537 preload1.src = M.util.image_url('i/warning', 'moodle');
538 preload2.src = M.util.image_url('i/info', 'moodle');
539
540 return this;
541 },
542
75c86d13
DW
543 /**
544 * Show a notification in a floaty overlay somewhere in the atto editor text area.
545 *
546 * @method showMessage
19549f8b
DW
547 * @param {String} message The translated message (use get_string)
548 * @param {String} type Must be either "info" or "warning"
549 * @param {Number} timeout Time in milliseconds to show this message for.
75c86d13
DW
550 * @chainable
551 */
8a5db547 552 showMessage: function(message, type, timeout) {
19549f8b
DW
553 var messageTypeIcon = '',
554 intTimeout,
555 bodyContent;
75c86d13
DW
556
557 if (this.messageOverlay === null) {
558 this.messageOverlay = Y.Node.create('<div class="editor_atto_notification"></div>');
559
f1018cd6 560 this.messageOverlay.hide(true);
3a7887ba 561 this.textarea.get('parentNode').append(this.messageOverlay);
75c86d13
DW
562
563 this.messageOverlay.on('click', function() {
f1018cd6 564 this.messageOverlay.hide(true);
75c86d13 565 }, this);
8a5db547 566 }
75c86d13 567
8a5db547
DW
568 if (this.hideTimer !== null) {
569 this.hideTimer.cancel();
75c86d13
DW
570 }
571
19549f8b 572 if (type === NOTIFY_WARNING) {
6bfd450a 573 messageTypeIcon = '<img src="' +
75c86d13
DW
574 M.util.image_url('i/warning', 'moodle') +
575 '" alt="' + M.util.get_string('warning', 'moodle') + '"/>';
19549f8b 576 } else if (type === NOTIFY_INFO) {
6bfd450a 577 messageTypeIcon = '<img src="' +
75c86d13
DW
578 M.util.image_url('i/info', 'moodle') +
579 '" alt="' + M.util.get_string('info', 'moodle') + '"/>';
8a5db547 580 } else {
19549f8b 581 Y.log('Invalid message type specified: ' + type + '. Must be either "info" or "warning".', 'debug', LOGNAME_NOTIFY);
8a5db547
DW
582 }
583
584 // Parse the timeout value.
19549f8b
DW
585 intTimeout = parseInt(timeout, 10);
586 if (intTimeout <= 0) {
587 intTimeout = 60000;
75c86d13
DW
588 }
589
8a5db547
DW
590 // Convert class to atto_info (for example).
591 type = 'atto_' + type;
592
19549f8b 593 bodyContent = Y.Node.create('<div class="' + type + '" role="alert" aria-live="assertive">' +
75c86d13
DW
594 messageTypeIcon + ' ' +
595 Y.Escape.html(message) +
596 '</div>');
597 this.messageOverlay.empty();
598 this.messageOverlay.append(bodyContent);
f1018cd6 599 this.messageOverlay.show(true);
75c86d13 600
19549f8b
DW
601 this.hideTimer = Y.later(intTimeout, this, function() {
602 Y.log('Hide Atto notification.', 'debug', LOGNAME_NOTIFY);
8a5db547 603 this.hideTimer = null;
9e12b0fa
JD
604 if (this.messageOverlay.inDoc()) {
605 this.messageOverlay.hide(true);
606 }
8a5db547
DW
607 });
608
75c86d13
DW
609 return this;
610 }
611
612};
613
614Y.Base.mix(Y.M.editor_atto.Editor, [EditorNotify]);
615// This file is part of Moodle - http://moodle.org/
616//
617// Moodle is free software: you can redistribute it and/or modify
618// it under the terms of the GNU General Public License as published by
619// the Free Software Foundation, either version 3 of the License, or
620// (at your option) any later version.
621//
622// Moodle is distributed in the hope that it will be useful,
623// but WITHOUT ANY WARRANTY; without even the implied warranty of
624// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
625// GNU General Public License for more details.
626//
627// You should have received a copy of the GNU General Public License
628// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
629
62467795
AN
630/**
631 * @module moodle-editor_atto-editor
632 * @submodule textarea
633 */
adca7326 634
62467795
AN
635/**
636 * Textarea functions for the Atto editor.
637 *
638 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
639 *
640 * @namespace M.editor_atto
641 * @class EditorTextArea
642 */
643
644function EditorTextArea() {}
645
646EditorTextArea.ATTRS= {
647};
648
649EditorTextArea.prototype = {
4dbc02f6
AN
650
651 /**
652 * Return the appropriate empty content value for the current browser.
653 *
654 * Different browsers use a different content when they are empty and
655 * we must set this reliable across the board.
656 *
657 * @method _getEmptyContent
658 * @return String The content to use representing no user-provided content
659 * @private
660 */
661 _getEmptyContent: function() {
662 if (Y.UA.ie && Y.UA.ie < 10) {
663 return '<p></p>';
664 } else {
665 return '<p><br></p>';
666 }
667 },
668
adca7326 669 /**
62467795 670 * Copy and clean the text from the textarea into the contenteditable div.
adca7326 671 *
62467795
AN
672 * If the text is empty, provide a default paragraph tag to hold the content.
673 *
674 * @method updateFromTextArea
675 * @chainable
adca7326 676 */
62467795
AN
677 updateFromTextArea: function() {
678 // Clear it first.
679 this.editor.setHTML('');
680
9029ce75
EM
681 // Copy cleaned HTML to editable div.
682 this.editor.append(this._cleanHTML(this.textarea.get('value')));
62467795
AN
683
684 // Insert a paragraph in the empty contenteditable div.
685 if (this.editor.getHTML() === '') {
4dbc02f6 686 this.editor.setHTML(this._getEmptyContent());
adca7326 687 }
9029ce75
EM
688
689 return this;
adca7326
DW
690 },
691
692 /**
62467795
AN
693 * Copy the text from the contenteditable to the textarea which it replaced.
694 *
695 * @method updateOriginal
696 * @chainable
adca7326 697 */
62467795 698 updateOriginal : function() {
4dbc02f6
AN
699 // Get the previous and current value to compare them.
700 var oldValue = this.textarea.get('value'),
701 newValue = this.getCleanHTML();
702
703 if (newValue === "" && this.isActive()) {
704 // The content was entirely empty so get the empty content placeholder.
705 newValue = this._getEmptyContent();
706 }
5ec54dd1 707
4dbc02f6
AN
708 // Only call this when there has been an actual change to reduce processing.
709 if (oldValue !== newValue) {
710 // Insert the cleaned content.
711 this.textarea.set('value', newValue);
5ec54dd1 712
4dbc02f6
AN
713 // Trigger the onchange callback on the textarea, essentially to notify moodle-core-formchangechecker.
714 this.textarea.simulate('change');
715
716 // Trigger handlers for this action.
717 this.fire('change');
718 }
719
720 return this;
62467795
AN
721 }
722};
534cf7b7 723
62467795
AN
724Y.Base.mix(Y.M.editor_atto.Editor, [EditorTextArea]);
725// This file is part of Moodle - http://moodle.org/
726//
727// Moodle is free software: you can redistribute it and/or modify
728// it under the terms of the GNU General Public License as published by
729// the Free Software Foundation, either version 3 of the License, or
730// (at your option) any later version.
731//
732// Moodle is distributed in the hope that it will be useful,
733// but WITHOUT ANY WARRANTY; without even the implied warranty of
734// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
735// GNU General Public License for more details.
736//
737// You should have received a copy of the GNU General Public License
738// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
ad3f8cd1
DP
739/* global NOTIFY_WARNING, NOTIFY_INFO */
740/* eslint-disable no-unused-vars */
adca7326 741
2ba6706d
DW
742/**
743 * A autosave function for the Atto editor.
744 *
745 * @module moodle-editor_atto-autosave
746 * @submodule autosave-base
747 * @package editor_atto
748 * @copyright 2014 Damyon Wiese
749 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
750 */
751
6bfd450a 752var SUCCESS_MESSAGE_TIMEOUT = 5000,
19549f8b
DW
753 RECOVER_MESSAGE_TIMEOUT = 60000,
754 LOGNAME_AUTOSAVE = 'moodle-editor_atto-editor-autosave';
2ba6706d
DW
755
756function EditorAutosave() {}
757
758EditorAutosave.ATTRS= {
6bfd450a
DW
759 /**
760 * Enable/Disable auto save for this instance.
761 *
762 * @attribute autosaveEnabled
763 * @type Boolean
764 * @writeOnce
765 */
766 autosaveEnabled: {
767 value: true,
768 writeOnce: true
769 },
770
771 /**
772 * The time between autosaves (in seconds).
773 *
774 * @attribute autosaveFrequency
19549f8b 775 * @type Number
6bfd450a
DW
776 * @default 60
777 * @writeOnce
778 */
779 autosaveFrequency: {
780 value: 60,
781 writeOnce: true
56579fb6
DW
782 },
783
c07f86ce
DW
784 /**
785 * Unique hash for this page instance. Calculated from $PAGE->url in php.
786 *
787 * @attribute pageHash
788 * @type String
789 * @writeOnce
790 */
791 pageHash: {
792 value: '',
793 writeOnce: true
6bfd450a 794 }
2ba6706d
DW
795};
796
797EditorAutosave.prototype = {
798
799 /**
800 * The text that was auto saved in the last request.
801 *
802 * @property lastText
803 * @type string
804 */
e924e1b3 805 lastText: "",
2ba6706d
DW
806
807 /**
808 * Autosave instance.
809 *
810 * @property autosaveInstance
811 * @type string
812 */
813 autosaveInstance: null,
814
b803df81
DW
815 /**
816 * Autosave Timer.
817 *
818 * @property autosaveTimer
819 * @type object
820 */
821 autosaveTimer: null,
822
2ba6706d
DW
823 /**
824 * Initialize the autosave process
825 *
826 * @method setupAutosave
827 * @chainable
828 */
829 setupAutosave: function() {
6bfd450a 830 var draftid = -1,
c4e2c671 831 form,
6bfd450a 832 optiontype = null,
557f44d9 833 options = this.get('filepickeroptions'),
240a9de4 834 params;
2ba6706d
DW
835
836 if (!this.get('autosaveEnabled')) {
837 // Autosave disabled for this instance.
838 return;
839 }
840
2ba6706d 841 this.autosaveInstance = Y.stamp(this);
2ba6706d
DW
842 for (optiontype in options) {
843 if (typeof options[optiontype].itemid !== "undefined") {
844 draftid = options[optiontype].itemid;
845 }
846 }
847
848 // First see if there are any saved drafts.
849 // Make an ajax request.
2ba6706d 850 params = {
2ba6706d
DW
851 contextid: this.get('contextid'),
852 action: 'resume',
2ba6706d
DW
853 draftid: draftid,
854 elementid: this.get('elementid'),
855 pageinstance: this.autosaveInstance,
c07f86ce 856 pagehash: this.get('pageHash')
2ba6706d
DW
857 };
858
240a9de4
FM
859 this.autosaveIo(params, this, {
860 success: function(response) {
861 if (response === null) {
862 // This can happen when there is nothing to resume from.
863 return;
864 } else if (!response) {
865 Y.log('Invalid response received.', 'debug', LOGNAME_AUTOSAVE);
866 return;
867 }
868
869 // Revert untouched editor contents to an empty string.
870 // Check for FF and Chrome.
871 if (response.result === '<p></p>' || response.result === '<p><br></p>' ||
872 response.result === '<br>') {
873 response.result = '';
874 }
875
876 // Check for IE 9 and 10.
877 if (response.result === '<p>&nbsp;</p>' || response.result === '<p><br>&nbsp;</p>') {
878 response.result = '';
879 }
880
881 if (response.error || typeof response.result === 'undefined') {
882 Y.log('Error occurred recovering draft text: ' + response.error, 'debug', LOGNAME_AUTOSAVE);
557f44d9
AN
883 this.showMessage(M.util.get_string('errortextrecovery', 'editor_atto'),
884 NOTIFY_WARNING, RECOVER_MESSAGE_TIMEOUT);
240a9de4
FM
885 } else if (response.result !== this.textarea.get('value') &&
886 response.result !== '') {
887 Y.log('Autosave text found - recover it.', 'debug', LOGNAME_AUTOSAVE);
888 this.recoverText(response.result);
2ba6706d 889 }
240a9de4
FM
890 this._fireSelectionChanged();
891
892 },
893 failure: function() {
894 this.showMessage(M.util.get_string('errortextrecovery', 'editor_atto'),
895 NOTIFY_WARNING, RECOVER_MESSAGE_TIMEOUT);
19549f8b 896 }
2ba6706d
DW
897 });
898
899 // Now setup the timer for periodic saves.
6bfd450a 900 var delay = parseInt(this.get('autosaveFrequency'), 10) * 1000;
b803df81 901 this.autosaveTimer = Y.later(delay, this, this.saveDraft, false, true);
2ba6706d
DW
902
903 // Now setup the listener for form submission.
c4e2c671
AN
904 form = this.textarea.ancestor('form');
905 if (form) {
240a9de4
FM
906 this.autosaveIoOnSubmit(form, {
907 action: 'reset',
908 contextid: this.get('contextid'),
909 elementid: this.get('elementid'),
910 pageinstance: this.autosaveInstance,
911 pagehash: this.get('pageHash')
912 });
c4e2c671 913 }
2ba6706d
DW
914 return this;
915 },
916
2ba6706d 917 /**
6bfd450a 918 * Recover a previous version of this text and show a message.
2ba6706d
DW
919 *
920 * @method recoverText
921 * @param {String} text
922 * @chainable
923 */
924 recoverText: function(text) {
6bfd450a
DW
925 this.editor.setHTML(text);
926 this.saveSelection();
927 this.updateOriginal();
928 this.lastText = text;
929
557f44d9
AN
930 this.showMessage(M.util.get_string('textrecovered', 'editor_atto'),
931 NOTIFY_INFO, RECOVER_MESSAGE_TIMEOUT);
2ba6706d 932
b5594973
AG
933 // Fire an event that the editor content has changed.
934 require(['core/event'], function(event) {
935 event.notifyEditorContentRestored();
936 });
937
2ba6706d
DW
938 return this;
939 },
940
941 /**
942 * Save a single draft via ajax.
943 *
944 * @method saveDraft
945 * @chainable
946 */
947 saveDraft: function() {
557f44d9 948 var url, params;
b803df81
DW
949
950 if (!this.editor.getDOMNode()) {
951 // Stop autosaving if the editor was removed from the page.
952 this.autosaveTimer.cancel();
953 return;
954 }
3a7887ba
DW
955 // Only copy the text from the div to the textarea if the textarea is not currently visible.
956 if (!this.editor.get('hidden')) {
957 this.updateOriginal();
958 }
2ba6706d
DW
959 var newText = this.textarea.get('value');
960
961 if (newText !== this.lastText) {
19549f8b 962 Y.log('Autosave text', 'debug', LOGNAME_AUTOSAVE);
2ba6706d
DW
963
964 // Make an ajax request.
56579fb6 965 url = M.cfg.wwwroot + this.get('autosaveAjaxScript');
2ba6706d
DW
966 params = {
967 sesskey: M.cfg.sesskey,
968 contextid: this.get('contextid'),
969 action: 'save',
970 drafttext: newText,
971 elementid: this.get('elementid'),
c07f86ce 972 pagehash: this.get('pageHash'),
2ba6706d
DW
973 pageinstance: this.autosaveInstance
974 };
19549f8b
DW
975
976 // Reusable error handler - must be passed the correct context.
240a9de4 977 var ajaxErrorFunction = function(response) {
19549f8b 978 var errorDuration = parseInt(this.get('autosaveFrequency'), 10) * 1000;
240a9de4 979 Y.log('Error while autosaving text', 'warn', LOGNAME_AUTOSAVE);
19549f8b
DW
980 Y.log(response, 'warn', LOGNAME_AUTOSAVE);
981 this.showMessage(M.util.get_string('autosavefailed', 'editor_atto'), NOTIFY_WARNING, errorDuration);
982 };
2ba6706d 983
240a9de4
FM
984 this.autosaveIo(params, this, {
985 failure: ajaxErrorFunction,
986 success: function(response) {
987 if (response && response.error) {
988 Y.soon(Y.bind(ajaxErrorFunction, this, [response]));
989 } else {
990 // All working.
991 this.lastText = newText;
992 this.showMessage(M.util.get_string('autosavesucceeded', 'editor_atto'),
993 NOTIFY_INFO, SUCCESS_MESSAGE_TIMEOUT);
2ba6706d 994 }
19549f8b 995 }
2ba6706d 996 });
2ba6706d
DW
997 }
998 return this;
999 }
1000};
1001
1002Y.Base.mix(Y.M.editor_atto.Editor, [EditorAutosave]);
1003// This file is part of Moodle - http://moodle.org/
1004//
1005// Moodle is free software: you can redistribute it and/or modify
1006// it under the terms of the GNU General Public License as published by
1007// the Free Software Foundation, either version 3 of the License, or
1008// (at your option) any later version.
1009//
1010// Moodle is distributed in the hope that it will be useful,
1011// but WITHOUT ANY WARRANTY; without even the implied warranty of
1012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1013// GNU General Public License for more details.
1014//
1015// You should have received a copy of the GNU General Public License
1016// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
1017
240a9de4
FM
1018/**
1019 * A autosave function for the Atto editor.
1020 *
1021 * @module moodle-editor_atto-autosave-io
1022 * @submodule autosave-io
1023 * @package editor_atto
1024 * @copyright 2016 Frédéric Massart
1025 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1026 */
1027
1028var EditorAutosaveIoDispatcherInstance = null;
1029
1030function EditorAutosaveIoDispatcher() {
1031 EditorAutosaveIoDispatcher.superclass.constructor.apply(this, arguments);
1032 this._submitEvents = {};
1033 this._queue = [];
1034 this._throttle = null;
1035}
1036EditorAutosaveIoDispatcher.NAME = 'EditorAutosaveIoDispatcher';
1037EditorAutosaveIoDispatcher.ATTRS = {
1038
1039 /**
1040 * The relative path to the ajax script.
1041 *
1042 * @attribute autosaveAjaxScript
1043 * @type String
1044 * @default '/lib/editor/atto/autosave-ajax.php'
1045 * @readOnly
1046 */
1047 autosaveAjaxScript: {
1048 value: '/lib/editor/atto/autosave-ajax.php',
1049 readOnly: true
1050 },
1051
1052 /**
1053 * The time buffer for the throttled requested.
1054 *
1055 * @attribute delay
1056 * @type Number
1057 * @default 50
1058 * @readOnly
1059 */
1060 delay: {
1061 value: 50,
1062 readOnly: true
1063 }
1064
1065};
1066Y.extend(EditorAutosaveIoDispatcher, Y.Base, {
1067
1068 /**
1069 * Dispatch an IO request.
1070 *
1071 * This method will put the requests in a queue in order to attempt to bulk them.
1072 *
1073 * @param {Object} params The parameters of the request.
1074 * @param {Object} context The context in which the callbacks are called.
1075 * @param {Object} callbacks Object with 'success', 'complete', 'end', 'failure' and 'start' as
1076 * optional keys defining the callbacks to call. Success and Complete
1077 * functions will receive the response as parameter. Success and Complete
1078 * may receive an object containing the error key, use this to confirm
1079 * that no errors occured.
1080 * @return {Void}
1081 */
1082 dispatch: function(params, context, callbacks) {
1083 if (this._throttle) {
1084 this._throttle.cancel();
1085 }
1086
1087 this._throttle = Y.later(this.get('delay'), this, this._processDispatchQueue);
1088 this._queue.push([params, context, callbacks]);
1089 },
1090
1091 /**
1092 * Dispatches the requests in the queue.
1093 *
1094 * @return {Void}
1095 */
1096 _processDispatchQueue: function() {
1097 var queue = this._queue,
1098 data = {};
1099
1100 this._queue = [];
1101 if (queue.length < 1) {
1102 return;
1103 }
1104
1105 Y.Array.each(queue, function(item, index) {
1106 data[index] = item[0];
1107 });
1108
1109 Y.io(M.cfg.wwwroot + this.get('autosaveAjaxScript'), {
1110 method: 'POST',
1111 data: Y.QueryString.stringify({
1112 actions: data,
1113 sesskey: M.cfg.sesskey
1114 }),
1115 on: {
1116 start: this._makeIoEventCallback('start', queue),
1117 complete: this._makeIoEventCallback('complete', queue),
1118 failure: this._makeIoEventCallback('failure', queue),
1119 end: this._makeIoEventCallback('end', queue),
1120 success: this._makeIoEventCallback('success', queue)
1121 }
1122 });
1123 },
1124
1125 /**
1126 * Creates a function that dispatches an IO response to callbacks.
1127 *
1128 * @param {String} event The type of event.
1129 * @param {Array} queue The queue.
1130 * @return {Function}
1131 */
1132 _makeIoEventCallback: function(event, queue) {
1133 var noop = function() {};
1134 return function() {
1135 var response = arguments[1],
1136 parsed = {};
1137
1138 if ((event == 'complete' || event == 'success') && (typeof response !== 'undefined'
1139 && typeof response.responseText !== 'undefined' && response.responseText !== '')) {
1140
1141 // Success and complete events need to parse the response.
1142 parsed = JSON.parse(response.responseText) || {};
1143 }
1144
1145 Y.Array.each(queue, function(item, index) {
1146 var context = item[1],
1147 cb = (item[2] && item[2][event]) || noop,
1148 arg;
1149
1150 if (parsed && parsed.error) {
1151 // The response is an error, we send it to everyone.
1152 arg = parsed;
1153 } else if (parsed) {
1154 // The response was parsed, we only communicate the relevant portion of the response.
1155 arg = parsed[index];
1156 }
1157
1158 cb.apply(context, [arg]);
1159 });
1160 };
1161 },
1162
1163 /**
1164 * Form submit handler.
1165 *
1166 * @param {EventFacade} e The event.
1167 * @return {Void}
1168 */
1169 _onSubmit: function(e) {
1170 var data = {},
1171 id = e.currentTarget.generateID(),
1172 params = this._submitEvents[id];
1173
1174 if (!params || params.ios.length < 1) {
1175 return;
1176 }
1177
1178 Y.Array.each(params.ios, function(param, index) {
1179 data[index] = param;
1180 });
1181
1182 Y.io(M.cfg.wwwroot + this.get('autosaveAjaxScript'), {
1183 method: 'POST',
1184 data: Y.QueryString.stringify({
1185 actions: data,
1186 sesskey: M.cfg.sesskey
1187 }),
1188 sync: true
1189 });
1190 },
1191
1192 /**
1193 * Registers a request to be made on form submission.
1194 *
1195 * @param {Node} node The forum node we will listen to.
1196 * @param {Object} params Parameters for the IO request.
1197 * @return {Void}
1198 */
1199 whenSubmit: function(node, params) {
1200 if (typeof this._submitEvents[node.generateID()] === 'undefined') {
1201 this._submitEvents[node.generateID()] = {
1202 event: node.on('submit', this._onSubmit, this),
1203 ios: []
1204 };
1205 }
1206 this._submitEvents[node.get('id')].ios.push([params]);
1207 }
1208
1209});
1210EditorAutosaveIoDispatcherInstance = new EditorAutosaveIoDispatcher();
1211
1212
1213function EditorAutosaveIo() {}
1214EditorAutosaveIo.prototype = {
1215
1216 /**
1217 * Dispatch an IO request.
1218 *
1219 * This method will put the requests in a queue in order to attempt to bulk them.
1220 *
1221 * @param {Object} params The parameters of the request.
1222 * @param {Object} context The context in which the callbacks are called.
1223 * @param {Object} callbacks Object with 'success', 'complete', 'end', 'failure' and 'start' as
1224 * optional keys defining the callbacks to call. Success and Complete
1225 * functions will receive the response as parameter. Success and Complete
1226 * may receive an object containing the error key, use this to confirm
1227 * that no errors occured.
1228 * @return {Void}
1229 */
1230 autosaveIo: function(params, context, callbacks) {
1231 EditorAutosaveIoDispatcherInstance.dispatch(params, context, callbacks);
1232 },
1233
1234 /**
1235 * Registers a request to be made on form submission.
1236 *
1237 * @param {Node} form The forum node we will listen to.
1238 * @param {Object} params Parameters for the IO request.
1239 * @return {Void}
1240 */
1241 autosaveIoOnSubmit: function(form, params) {
1242 EditorAutosaveIoDispatcherInstance.whenSubmit(form, params);
1243 }
1244
1245};
1246Y.Base.mix(Y.M.editor_atto.Editor, [EditorAutosaveIo]);
1247// This file is part of Moodle - http://moodle.org/
1248//
1249// Moodle is free software: you can redistribute it and/or modify
1250// it under the terms of the GNU General Public License as published by
1251// the Free Software Foundation, either version 3 of the License, or
1252// (at your option) any later version.
1253//
1254// Moodle is distributed in the hope that it will be useful,
1255// but WITHOUT ANY WARRANTY; without even the implied warranty of
1256// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1257// GNU General Public License for more details.
1258//
1259// You should have received a copy of the GNU General Public License
1260// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
ad3f8cd1 1261/* global LOGNAME */
240a9de4 1262
62467795
AN
1263/**
1264 * @module moodle-editor_atto-editor
1265 * @submodule clean
1266 */
adca7326 1267
62467795
AN
1268/**
1269 * Functions for the Atto editor to clean the generated content.
1270 *
1271 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
1272 *
1273 * @namespace M.editor_atto
1274 * @class EditorClean
1275 */
adca7326 1276
62467795 1277function EditorClean() {}
adca7326 1278
62467795
AN
1279EditorClean.ATTRS= {
1280};
adca7326 1281
62467795 1282EditorClean.prototype = {
8951d614 1283 /**
62467795
AN
1284 * Clean the generated HTML content without modifying the editor content.
1285 *
1286 * This includes removes all YUI ids from the generated content.
8951d614 1287 *
62467795 1288 * @return {string} The cleaned HTML content.
8951d614 1289 */
62467795
AN
1290 getCleanHTML: function() {
1291 // Clone the editor so that we don't actually modify the real content.
9389ff57
FM
1292 var editorClone = this.editor.cloneNode(true),
1293 html;
8951d614 1294
62467795
AN
1295 // Remove all YUI IDs.
1296 Y.each(editorClone.all('[id^="yui"]'), function(node) {
1297 node.removeAttribute('id');
1298 });
8951d614 1299
62467795 1300 editorClone.all('.atto_control').remove(true);
9389ff57
FM
1301 html = editorClone.get('innerHTML');
1302
1303 // Revert untouched editor contents to an empty string.
1304 if (html === '<p></p>' || html === '<p><br></p>') {
1305 return '';
1306 }
8951d614 1307
62467795 1308 // Remove any and all nasties from source.
9389ff57 1309 return this._cleanHTML(html);
8951d614
JM
1310 },
1311
adca7326 1312 /**
62467795
AN
1313 * Clean the HTML content of the editor.
1314 *
1315 * @method cleanEditorHTML
1316 * @chainable
adca7326 1317 */
62467795
AN
1318 cleanEditorHTML: function() {
1319 var startValue = this.editor.get('innerHTML');
1320 this.editor.set('innerHTML', this._cleanHTML(startValue));
5ec54dd1 1321
62467795
AN
1322 return this;
1323 },
fe0d2477 1324
62467795
AN
1325 /**
1326 * Clean the specified HTML content and remove any content which could cause issues.
1327 *
1328 * @method _cleanHTML
1329 * @private
1330 * @param {String} content The content to clean
1331 * @return {String} The cleaned HTML
1332 */
1333 _cleanHTML: function(content) {
3ef96361 1334 // Removing limited things that can break the page or a disallowed, like unclosed comments, style blocks, etc.
62467795
AN
1335
1336 var rules = [
3ef96361
EM
1337 // Remove any style blocks. Some browsers do not work well with them in a contenteditable.
1338 // Plus style blocks are not allowed in body html, except with "scoped", which most browsers don't support as of 2015.
1339 // Reference: "http://stackoverflow.com/questions/1068280/javascript-regex-multiline-flag-doesnt-work"
1340 {regex: /<style[^>]*>[\s\S]*?<\/style>/gi, replace: ""},
1341
a7fdadc9
EM
1342 // Remove any open HTML comment opens that are not followed by a close. This can completely break page layout.
1343 {regex: /<!--(?![\s\S]*?-->)/gi, replace: ""},
62467795
AN
1344
1345 // Source: "http://www.codinghorror.com/blog/2006/01/cleaning-words-nasty-html.html"
a7fdadc9 1346 // Remove forbidden tags for content, title, meta, style, st0-9, head, font, html, body, link.
d784f5ed 1347 {regex: /<\/?(?:title|meta|style|st\d|head|font|html|body|link)[^>]*?>/gi, replace: ""}
62467795 1348 ];
adca7326 1349
3ef96361
EM
1350 return this._filterContentWithRules(content, rules);
1351 },
1352
1353 /**
1354 * Take the supplied content and run on the supplied regex rules.
1355 *
1356 * @method _filterContentWithRules
1357 * @private
1358 * @param {String} content The content to clean
1359 * @param {Array} rules An array of structures: [ {regex: /something/, replace: "something"}, {...}, ...]
1360 * @return {String} The cleaned content
1361 */
1362 _filterContentWithRules: function(content, rules) {
62467795
AN
1363 var i = 0;
1364 for (i = 0; i < rules.length; i++) {
1365 content = content.replace(rules[i].regex, rules[i].replace);
adca7326
DW
1366 }
1367
62467795 1368 return content;
a7fdadc9
EM
1369 },
1370
1371 /**
1372 * Intercept and clean html paste events.
1373 *
1374 * @method pasteCleanup
1375 * @param {Object} sourceEvent The YUI EventFacade object
1376 * @return {Boolean} True if the passed event should continue, false if not.
1377 */
1378 pasteCleanup: function(sourceEvent) {
1379 // We only expect paste events, but we will check anyways.
1380 if (sourceEvent.type === 'paste') {
1381 // The YUI event wrapper doesn't provide paste event info, so we need the underlying event.
1382 var event = sourceEvent._event;
1383 // Check if we have a valid clipboardData object in the event.
1384 // IE has a clipboard object at window.clipboardData, but as of IE 11, it does not provide HTML content access.
73e14433
EM
1385 if (event && event.clipboardData && event.clipboardData.getData && event.clipboardData.types) {
1386 // Check if there is HTML type to be pasted, if we can get it, we want to scrub before insert.
a7fdadc9
EM
1387 var types = event.clipboardData.types;
1388 var isHTML = false;
73e14433
EM
1389 // Different browsers use different containers to hold the types, so test various functions.
1390 if (typeof types.contains === 'function') {
a7fdadc9
EM
1391 isHTML = types.contains('text/html');
1392 } else if (typeof types.indexOf === 'function') {
1393 isHTML = (types.indexOf('text/html') > -1);
a7fdadc9
EM
1394 }
1395
1396 if (isHTML) {
1397 // Get the clipboard content.
1398 var content;
1399 try {
1400 content = event.clipboardData.getData('text/html');
1401 } catch (error) {
1402 // Something went wrong. Fallback.
1403 this.fallbackPasteCleanupDelayed();
1404 return true;
1405 }
1406
1407 // Stop the original paste.
1408 sourceEvent.preventDefault();
1409
1410 // Scrub the paste content.
3ef96361 1411 content = this._cleanPasteHTML(content);
a7fdadc9
EM
1412
1413 // Save the current selection.
1414 // Using saveSelection as it produces a more consistent experience.
1415 var selection = window.rangy.saveSelection();
1416
1417 // Insert the content.
1418 this.insertContentAtFocusPoint(content);
1419
1420 // Restore the selection, and collapse to end.
1421 window.rangy.restoreSelection(selection);
1422 window.rangy.getSelection().collapseToEnd();
1423
1424 // Update the text area.
1425 this.updateOriginal();
1426 return false;
1427 } else {
73e14433
EM
1428 // Due to poor cross browser clipboard compatibility, the failure to find html doesn't mean it isn't there.
1429 // Wait for the clipboard event to finish then fallback clean the entire editor.
1430 this.fallbackPasteCleanupDelayed();
a7fdadc9
EM
1431 return true;
1432 }
1433 } else {
1434 // If we reached a here, this probably means the browser has limited (or no) clipboard support.
73e14433 1435 // Wait for the clipboard event to finish then fallback clean the entire editor.
a7fdadc9
EM
1436 this.fallbackPasteCleanupDelayed();
1437 return true;
1438 }
1439 }
1440
1441 // We should never get here - we must have received a non-paste event for some reason.
1442 // Um, just call updateOriginalDelayed() - it's safe.
1443 this.updateOriginalDelayed();
1444 return true;
1445 },
1446
1447 /**
1448 * Cleanup code after a paste event if we couldn't intercept the paste content.
1449 *
1450 * @method fallbackPasteCleanup
1451 * @chainable
1452 */
1453 fallbackPasteCleanup: function() {
1454 Y.log('Using fallbackPasteCleanup for atto cleanup', 'debug', LOGNAME);
1455
1456 // Save the current selection (cursor position).
1457 var selection = window.rangy.saveSelection();
1458
1459 // Get, clean, and replace the content in the editable.
1460 var content = this.editor.get('innerHTML');
3ef96361 1461 this.editor.set('innerHTML', this._cleanPasteHTML(content));
a7fdadc9
EM
1462
1463 // Update the textarea.
1464 this.updateOriginal();
1465
1466 // Restore the selection (cursor position).
1467 window.rangy.restoreSelection(selection);
1468
1469 return this;
1470 },
1471
1472 /**
1473 * Calls fallbackPasteCleanup on a short timer to allow the paste event handlers to complete.
1474 *
1475 * @method fallbackPasteCleanupDelayed
1476 * @chainable
1477 */
1478 fallbackPasteCleanupDelayed: function() {
1479 Y.soon(Y.bind(this.fallbackPasteCleanup, this));
1480
1481 return this;
3ef96361
EM
1482 },
1483
1484 /**
1485 * Cleanup html that comes from WYSIWYG paste events. These are more likely to contain messy code that we should strip.
1486 *
1487 * @method _cleanPasteHTML
1488 * @private
1489 * @param {String} content The html content to clean
1490 * @return {String} The cleaned HTML
1491 */
1492 _cleanPasteHTML: function(content) {
1493 // Return an empty string if passed an invalid or empty object.
1494 if (!content || content.length === 0) {
1495 return "";
1496 }
1497
1498 // Rules that get rid of the real-nasties and don't care about normalize code (correct quotes, white spaces, etc).
1499 var rules = [
6ea68e23 1500 // Stuff that is specifically from MS Word and similar office packages.
cfb32192
DM
1501 // Remove all garbage after closing html tag.
1502 {regex: /<\s*\/html\s*>([\s\S]+)$/gi, replace: ""},
6ea68e23
EM
1503 // Remove if comment blocks.
1504 {regex: /<!--\[if[\s\S]*?endif\]-->/gi, replace: ""},
1505 // Remove start and end fragment comment blocks.
1506 {regex: /<!--(Start|End)Fragment-->/gi, replace: ""},
3ef96361
EM
1507 // Remove any xml blocks.
1508 {regex: /<xml[^>]*>[\s\S]*?<\/xml>/gi, replace: ""},
1509 // Remove any <?xml><\?xml> blocks.
1510 {regex: /<\?xml[^>]*>[\s\S]*?<\\\?xml>/gi, replace: ""},
1511 // Remove <o:blah>, <\o:blah>.
df7a9fd4 1512 {regex: /<\/?\w+:[^>]*>/gi, replace: ""}
3ef96361
EM
1513 ];
1514
1515 // Apply the first set of harsher rules.
1516 content = this._filterContentWithRules(content, rules);
1517
1518 // Apply the standard rules, which mainly cleans things like headers, links, and style blocks.
1519 content = this._cleanHTML(content);
1520
1521 // Check if the string is empty or only contains whitespace.
1522 if (content.length === 0 || !content.match(/\S/)) {
1523 return content;
1524 }
1525
1526 // Now we let the browser normalize the code by loading it into the DOM and then get the html back.
1527 // This gives us well quoted, well formatted code to continue our work on. Word may provide very poorly formatted code.
1528 var holder = document.createElement('div');
1529 holder.innerHTML = content;
1530 content = holder.innerHTML;
1531 // Free up the DOM memory.
1532 holder.innerHTML = "";
1533
1534 // Run some more rules that care about quotes and whitespace.
1535 rules = [
8e202bd8
EM
1536 // Get all class attributes so we can work on them.
1537 {regex: /(<[^>]*?class\s*?=\s*?")([^>"]*)(")/gi, replace: function(match, group1, group2, group3) {
1538 // Remove MSO classes.
1539 group2 = group2.replace(/(?:^|[\s])[\s]*MSO[_a-zA-Z0-9\-]*/gi,"");
1540 // Remove Apple- classes.
1541 group2 = group2.replace(/(?:^|[\s])[\s]*Apple-[_a-zA-Z0-9\-]*/gi,"");
1542 return group1 + group2 + group3;
1543 }},
3ef96361 1544 // Remove OLE_LINK# anchors that may litter the code.
1b6ce030 1545 {regex: /<a [^>]*?name\s*?=\s*?"OLE_LINK\d*?"[^>]*?>\s*?<\/a>/gi, replace: ""}
3ef96361
EM
1546 ];
1547
91445c63
DW
1548 // Clean all style attributes from the text.
1549 content = this._cleanStyles(content);
1550
3ef96361
EM
1551 // Apply the rules.
1552 content = this._filterContentWithRules(content, rules);
1553
1554 // Reapply the standard cleaner to the content.
1555 content = this._cleanHTML(content);
1556
1b6ce030
EM
1557 // Clean unused spans out of the content.
1558 content = this._cleanSpans(content);
1559
3ef96361 1560 return content;
1b6ce030
EM
1561 },
1562
91445c63
DW
1563 /**
1564 * Clean all inline styles from pasted text.
1565 *
1566 * This code intentionally doesn't use YUI Nodes. YUI was quite a bit slower at this, so using raw DOM objects instead.
1567 *
1568 * @method _cleanStyles
1569 * @private
1570 * @param {String} content The content to clean
1571 * @return {String} The cleaned HTML
1572 */
1573 _cleanStyles: function(content) {
1574 var holder = document.createElement('div');
1575 holder.innerHTML = content;
1576 var elementsWithStyle = holder.querySelectorAll('[style]');
1577 var i = 0;
1578
1579 for (i = 0; i < elementsWithStyle.length; i++) {
1580 elementsWithStyle[i].removeAttribute('style');
1581 }
1582
1583 var elementsWithClass = holder.querySelectorAll('[class]');
1584 for (i = 0; i < elementsWithClass.length; i++) {
1585 elementsWithClass[i].removeAttribute('class');
1586 }
1587
1588 return holder.innerHTML;
1589 },
1b6ce030
EM
1590 /**
1591 * Clean empty or un-unused spans from passed HTML.
1592 *
1593 * This code intentionally doesn't use YUI Nodes. YUI was quite a bit slower at this, so using raw DOM objects instead.
1594 *
1595 * @method _cleanSpans
1596 * @private
1597 * @param {String} content The content to clean
1598 * @return {String} The cleaned HTML
1599 */
1600 _cleanSpans: function(content) {
1601 // Return an empty string if passed an invalid or empty object.
1602 if (!content || content.length === 0) {
1603 return "";
1604 }
1605 // Check if the string is empty or only contains whitespace.
1606 if (content.length === 0 || !content.match(/\S/)) {
1607 return content;
1608 }
1609
1610 var rules = [
1611 // Remove unused class, style, or id attributes. This will make empty tag detection easier later.
1612 {regex: /(<[^>]*?)(?:[\s]*(?:class|style|id)\s*?=\s*?"\s*?")+/gi, replace: "$1"}
1613 ];
1614 // Apply the rules.
1615 content = this._filterContentWithRules(content, rules);
1616
1617 // Reference: "http://stackoverflow.com/questions/8131396/remove-nested-span-without-id"
1618
1619 // This is better to run detached from the DOM, so the browser doesn't try to update on each change.
1620 var holder = document.createElement('div');
1621 holder.innerHTML = content;
1622 var spans = holder.getElementsByTagName('span');
1623
1624 // Since we will be removing elements from the list, we should copy it to an array, making it static.
1625 var spansarr = Array.prototype.slice.call(spans, 0);
1626
1627 spansarr.forEach(function(span) {
1628 if (!span.hasAttributes()) {
1629 // If no attributes (id, class, style, etc), this span is has no effect.
1630 // Move each child (if they exist) to the parent in place of this span.
1631 while (span.firstChild) {
1632 span.parentNode.insertBefore(span.firstChild, span);
1633 }
1634
1635 // Remove the now empty span.
1636 span.parentNode.removeChild(span);
1637 }
1638 });
1639
1640 return holder.innerHTML;
62467795
AN
1641 }
1642};
adca7326 1643
62467795
AN
1644Y.Base.mix(Y.M.editor_atto.Editor, [EditorClean]);
1645// This file is part of Moodle - http://moodle.org/
1646//
1647// Moodle is free software: you can redistribute it and/or modify
1648// it under the terms of the GNU General Public License as published by
1649// the Free Software Foundation, either version 3 of the License, or
1650// (at your option) any later version.
1651//
1652// Moodle is distributed in the hope that it will be useful,
1653// but WITHOUT ANY WARRANTY; without even the implied warranty of
1654// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1655// GNU General Public License for more details.
1656//
1657// You should have received a copy of the GNU General Public License
1658// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
adca7326 1659
dc9ca4ac
DT
1660/**
1661 * @module moodle-editor_atto-editor
1662 * @submodule commands
1663 */
1664
1665/**
1666 * Selection functions for the Atto editor.
1667 *
1668 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
1669 *
1670 * @namespace M.editor_atto
1671 * @class EditorCommand
1672 */
1673
1674function EditorCommand() {}
1675
1676EditorCommand.ATTRS= {
1677};
1678
1679EditorCommand.prototype = {
1680 /**
1681 * Applies a callback method to editor if selection is uncollapsed or waits for input to select first.
1682 * @method applyFormat
1683 * @param e EventTarget Event to be passed to callback if selection is uncollapsed
1684 * @param method callback A callback method which changes editor when text is selected.
1685 * @param object context Context to be used for callback method
1686 * @param array args Array of arguments to pass to callback
1687 */
1688 applyFormat: function(e, callback, context, args) {
1689 function handleInsert(e, callback, context, args, anchorNode, anchorOffset) {
1690 // After something is inputed, select it and apply the formating function.
1691 Y.soon(Y.bind(function(e, callback, context, args, anchorNode, anchorOffset) {
1692 var selection = window.rangy.getSelection();
1693
1694 // Set the start of the selection to where it was when the method was first called.
1695 var range = selection.getRangeAt(0);
1696 range.setStart(anchorNode, anchorOffset);
1697 selection.setSingleRange(range);
1698
1699 // Now apply callback to the new text that is selected.
1700 callback.apply(context, [e, args]);
1701
1702 // Collapse selection so cursor is at end of inserted material.
1703 selection.collapseToEnd();
c8719db1
DT
1704
1705 // Save save selection and editor contents.
1706 this.saveSelection();
1707 this.updateOriginal();
dc9ca4ac
DT
1708 }, this, e, callback, context, args, anchorNode, anchorOffset));
1709 }
1710
1711 // Set default context for the method.
1712 context = context || this;
1713
1714 // Check whether range is collapsed.
1715 var selection = window.rangy.getSelection();
1716
1717 if (selection.isCollapsed) {
1718 // Selection is collapsed so listen for input into editor.
1719 var handle = this.editor.once('input', handleInsert, this, callback, context, args,
1720 selection.anchorNode, selection.anchorOffset);
1721
1722 // Cancel if selection changes before input.
1723 this.editor.onceAfter(['click', 'selectstart'], handle.detach, handle);
1724
1725 return;
1726 }
1727
1728 // The range is not collapsed; so apply callback method immediately.
1729 callback.apply(context, [e, args]);
1730
c8719db1
DT
1731 // Save save selection and editor contents.
1732 this.saveSelection();
1733 this.updateOriginal();
dc9ca4ac
DT
1734 },
1735
1736 /**
1737 * Replaces all the tags in a node list with new type.
1738 * @method replaceTags
1739 * @param NodeList nodelist
1740 * @param String tag
1741 */
1742 replaceTags: function(nodelist, tag) {
1743 // We mark elements in the node list for iterations.
1744 nodelist.setAttribute('data-iterate', true);
1745 var node = this.editor.one('[data-iterate="true"]');
1746 while (node) {
1747 var clone = Y.Node.create('<' + tag + ' />')
1748 .setAttrs(node.getAttrs())
1749 .removeAttribute('data-iterate');
1750 // Copy class and style if not blank.
1751 if (node.getAttribute('style')) {
1752 clone.setAttribute('style', node.getAttribute('style'));
1753 }
1754 if (node.getAttribute('class')) {
1755 clone.setAttribute('class', node.getAttribute('class'));
1756 }
1757 // We use childNodes here because we are interested in both type 1 and 3 child nodes.
1758 var children = node.getDOMNode().childNodes, child;
1759 child = children[0];
1760 while (typeof child !== "undefined") {
1761 clone.append(child);
1762 child = children[0];
1763 }
1764 node.replace(clone);
1765 node = this.editor.one('[data-iterate="true"]');
1766 }
1767 },
1768
1769 /**
1770 * Change all tags with given type to a span with CSS class attribute.
1771 * @method changeToCSS
1772 * @param String tag Tag type to be changed to span
1773 * @param String markerClass CSS class that corresponds to desired tag
1774 */
1775 changeToCSS: function(tag, markerClass) {
1776 // Save the selection.
1777 var selection = window.rangy.saveSelection();
1778
1779 // Remove display:none from rangy markers so browser doesn't delete them.
1780 this.editor.all('.rangySelectionBoundary').setStyle('display', null);
1781
1782 // Replace tags with CSS classes.
1783 this.editor.all(tag).addClass(markerClass);
1784 this.replaceTags(this.editor.all('.' + markerClass), 'span');
1785
1786 // Restore selection and toggle class.
1787 window.rangy.restoreSelection(selection);
1788 },
1789
1790 /**
1791 * Change spans with CSS classes in editor into elements with given tag.
1792 * @method changeToCSS
1793 * @param String markerClass CSS class that corresponds to desired tag
1794 * @param String tag New tag type to be created
1795 */
1796 changeToTags: function(markerClass, tag) {
1797 // Save the selection.
1798 var selection = window.rangy.saveSelection();
1799
1800 // Remove display:none from rangy markers so browser doesn't delete them.
1801 this.editor.all('.rangySelectionBoundary').setStyle('display', null);
1802
1803 // Replace spans with given tag.
1804 this.replaceTags(this.editor.all('span[class="' + markerClass + '"]'), tag);
1805 this.editor.all(tag + '[class="' + markerClass + '"]').removeAttribute('class');
1806 this.editor.all('.' + markerClass).each(function(n) {
1807 n.wrap('<' + tag + '/>');
1808 n.removeClass(markerClass);
1809 });
1810
1811 // Remove CSS classes.
1812 this.editor.all('[class="' + markerClass + '"]').removeAttribute('class');
1813 this.editor.all(tag).removeClass(markerClass);
1814
1815 // Restore selection.
1816 window.rangy.restoreSelection(selection);
1817 }
1818};
1819
1820Y.Base.mix(Y.M.editor_atto.Editor, [EditorCommand]);
1821// This file is part of Moodle - http://moodle.org/
1822//
1823// Moodle is free software: you can redistribute it and/or modify
1824// it under the terms of the GNU General Public License as published by
1825// the Free Software Foundation, either version 3 of the License, or
1826// (at your option) any later version.
1827//
1828// Moodle is distributed in the hope that it will be useful,
1829// but WITHOUT ANY WARRANTY; without even the implied warranty of
1830// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1831// GNU General Public License for more details.
1832//
1833// You should have received a copy of the GNU General Public License
1834// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
1835
62467795
AN
1836/**
1837 * @module moodle-editor_atto-editor
1838 * @submodule toolbar
1839 */
adca7326 1840
62467795
AN
1841/**
1842 * Toolbar functions for the Atto editor.
1843 *
1844 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
1845 *
1846 * @namespace M.editor_atto
1847 * @class EditorToolbar
1848 */
adca7326 1849
62467795 1850function EditorToolbar() {}
34f5867a 1851
62467795
AN
1852EditorToolbar.ATTRS= {
1853};
adca7326 1854
62467795 1855EditorToolbar.prototype = {
adca7326 1856 /**
62467795
AN
1857 * A reference to the toolbar Node.
1858 *
1859 * @property toolbar
1860 * @type Node
adca7326 1861 */
62467795 1862 toolbar: null,
adca7326 1863
c63f9053
AN
1864 /**
1865 * A reference to any currently open menus in the toolbar.
1866 *
1867 * @property openMenus
1868 * @type Array
1869 */
1870 openMenus: null,
1871
86a83e3a 1872 /**
62467795 1873 * Setup the toolbar on the editor.
86a83e3a 1874 *
62467795
AN
1875 * @method setupToolbar
1876 * @chainable
86a83e3a 1877 */
62467795
AN
1878 setupToolbar: function() {
1879 this.toolbar = Y.Node.create('<div class="' + CSS.TOOLBAR + '" role="toolbar" aria-live="off"/>');
c63f9053 1880 this.openMenus = [];
62467795 1881 this._wrapper.appendChild(this.toolbar);
86a83e3a 1882
62467795
AN
1883 if (this.textareaLabel) {
1884 this.toolbar.setAttribute('aria-labelledby', this.textareaLabel.get("id"));
1885 }
86a83e3a 1886
62467795
AN
1887 // Add keyboard navigation for the toolbar.
1888 this.setupToolbarNavigation();
86a83e3a 1889
62467795
AN
1890 return this;
1891 }
1892};
86a83e3a 1893
62467795
AN
1894Y.Base.mix(Y.M.editor_atto.Editor, [EditorToolbar]);
1895// This file is part of Moodle - http://moodle.org/
1896//
1897// Moodle is free software: you can redistribute it and/or modify
1898// it under the terms of the GNU General Public License as published by
1899// the Free Software Foundation, either version 3 of the License, or
1900// (at your option) any later version.
1901//
1902// Moodle is distributed in the hope that it will be useful,
1903// but WITHOUT ANY WARRANTY; without even the implied warranty of
1904// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1905// GNU General Public License for more details.
1906//
1907// You should have received a copy of the GNU General Public License
1908// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
ad3f8cd1 1909/* global LOGNAME */
62467795
AN
1910
1911/**
1912 * @module moodle-editor_atto-editor
1913 * @submodule toolbarnav
1914 */
1915
1916/**
1917 * Toolbar Navigation functions for the Atto editor.
1918 *
1919 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
1920 *
1921 * @namespace M.editor_atto
1922 * @class EditorToolbarNav
1923 */
1924
1925function EditorToolbarNav() {}
1926
1927EditorToolbarNav.ATTRS= {
1928};
1929
1930EditorToolbarNav.prototype = {
1931 /**
1932 * The current focal point for tabbing.
1933 *
1934 * @property _tabFocus
1935 * @type Node
1936 * @default null
1937 * @private
1938 */
1939 _tabFocus: null,
1940
1941 /**
1942 * Set up the watchers for toolbar navigation.
1943 *
1944 * @method setupToolbarNavigation
1945 * @chainable
1946 */
1947 setupToolbarNavigation: function() {
1948 // Listen for Arrow left and Arrow right keys.
1949 this._wrapper.delegate('key',
1950 this.toolbarKeyboardNavigation,
1951 'down:37,39',
1952 '.' + CSS.TOOLBAR,
1953 this);
c63f9053
AN
1954 this._wrapper.delegate('focus',
1955 function(e) {
1956 this._setTabFocus(e.currentTarget);
1957 }, '.' + CSS.TOOLBAR + ' button', this);
62467795
AN
1958
1959 return this;
86a83e3a
DW
1960 },
1961
adca7326 1962 /**
62467795
AN
1963 * Implement arrow key navigation for the buttons in the toolbar.
1964 *
1965 * @method toolbarKeyboardNavigation
1966 * @param {EventFacade} e - the keyboard event.
adca7326 1967 */
62467795
AN
1968 toolbarKeyboardNavigation: function(e) {
1969 // Prevent the default browser behaviour.
1970 e.preventDefault();
adca7326 1971
62467795 1972 // On cursor moves we loops through the buttons.
b9d065ed 1973 var buttons = this.toolbar.all('button'),
62467795 1974 direction = 1,
af31595b 1975 button,
62467795
AN
1976 current = e.target.ancestor('button', true);
1977
b9d065ed
FM
1978 if (e.keyCode === 37) {
1979 // Moving left so reverse the direction.
1980 direction = -1;
26f8822d 1981 }
b269f635 1982
b9d065ed
FM
1983 button = this._findFirstFocusable(buttons, current, direction);
1984 if (button) {
1985 button.focus();
5e543b4f 1986 this._setTabFocus(button);
b9d065ed
FM
1987 } else {
1988 Y.log("Unable to find a button to focus on", 'debug', LOGNAME);
62467795 1989 }
b9d065ed 1990 },
adca7326 1991
b9d065ed
FM
1992 /**
1993 * Find the first focusable button.
1994 *
1995 * @param {NodeList} buttons A list of nodes.
1996 * @param {Node} startAt The node in the list to start the search from.
1997 * @param {Number} direction The direction in which to search (1 or -1).
1998 * @return {Node | Undefined} The Node or undefined.
1999 * @method _findFirstFocusable
2000 * @private
2001 */
2002 _findFirstFocusable: function(buttons, startAt, direction) {
2003 var checkCount = 0,
2004 group,
2005 candidate,
2006 button,
2007 index;
2008
2009 // Determine which button to start the search from.
2010 index = buttons.indexOf(startAt);
2011 if (index < -1) {
2012 Y.log("Unable to find the button in the list of buttons", 'debug', LOGNAME);
2013 index = 0;
62467795
AN
2014 }
2015
b9d065ed 2016 // Try to find the next.
af31595b 2017 while (checkCount < buttons.size()) {
62467795
AN
2018 index += direction;
2019 if (index < 0) {
2020 index = buttons.size() - 1;
2021 } else if (index >= buttons.size()) {
2022 // Handle wrapping.
2023 index = 0;
2024 }
af31595b
FM
2025
2026 candidate = buttons.item(index);
adca7326 2027
62467795
AN
2028 // Add a counter to ensure we don't get stuck in a loop if there's only one visible menu item.
2029 checkCount++;
af31595b 2030
62467795 2031 // Loop while:
af31595b
FM
2032 // * we haven't checked every button;
2033 // * the button is hidden or disabled;
2034 // * the group is hidden.
2035 if (candidate.hasAttribute('hidden') || candidate.hasAttribute('disabled')) {
2036 continue;
2037 }
2038 group = candidate.ancestor('.atto_group');
2039 if (group.hasAttribute('hidden')) {
2040 continue;
2041 }
2042
2043 button = candidate;
2044 break;
62467795 2045 }
af31595b 2046
b9d065ed
FM
2047 return button;
2048 },
2049
2050 /**
2051 * Check the tab focus.
2052 *
2053 * When we disable or hide a button, we should call this method to ensure that the
2054 * focus is not currently set on an inaccessible button, otherwise tabbing to the toolbar
2055 * would be impossible.
2056 *
2057 * @method checkTabFocus
2058 * @chainable
2059 */
2060 checkTabFocus: function() {
2061 if (this._tabFocus) {
2062 if (this._tabFocus.hasAttribute('disabled') || this._tabFocus.hasAttribute('hidden')
2063 || this._tabFocus.ancestor('.atto_group').hasAttribute('hidden')) {
2064 // Find first available button.
557f44d9 2065 var button = this._findFirstFocusable(this.toolbar.all('button'), this._tabFocus, -1);
b9d065ed
FM
2066 if (button) {
2067 if (this._tabFocus.compareTo(document.activeElement)) {
2068 // We should also move the focus, because the inaccessible button also has the focus.
2069 button.focus();
2070 }
2071 this._setTabFocus(button);
2072 }
2073 }
62467795 2074 }
b9d065ed 2075 return this;
62467795 2076 },
d088a835 2077
62467795
AN
2078 /**
2079 * Sets tab focus for the toolbar to the specified Node.
2080 *
2081 * @method _setTabFocus
2082 * @param {Node} button The node that focus should now be set to
2083 * @chainable
2084 * @private
2085 */
2086 _setTabFocus: function(button) {
2087 if (this._tabFocus) {
2088 // Unset the previous entry.
2089 this._tabFocus.setAttribute('tabindex', '-1');
2090 }
26f8822d 2091
62467795
AN
2092 // Set up the new entry.
2093 this._tabFocus = button;
2094 this._tabFocus.setAttribute('tabindex', 0);
4c37c1f4 2095
62467795
AN
2096 // And update the activedescendant to point at the currently selected button.
2097 this.toolbar.setAttribute('aria-activedescendant', this._tabFocus.generateID());
3ee53a42 2098
62467795
AN
2099 return this;
2100 }
2101};
67d3fe45 2102
62467795
AN
2103Y.Base.mix(Y.M.editor_atto.Editor, [EditorToolbarNav]);
2104// This file is part of Moodle - http://moodle.org/
2105//
2106// Moodle is free software: you can redistribute it and/or modify
2107// it under the terms of the GNU General Public License as published by
2108// the Free Software Foundation, either version 3 of the License, or
2109// (at your option) any later version.
2110//
2111// Moodle is distributed in the hope that it will be useful,
2112// but WITHOUT ANY WARRANTY; without even the implied warranty of
2113// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2114// GNU General Public License for more details.
2115//
2116// You should have received a copy of the GNU General Public License
2117// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
ad3f8cd1 2118/* global rangy */
adca7326 2119
62467795
AN
2120/**
2121 * @module moodle-editor_atto-editor
2122 * @submodule selection
2123 */
adca7326 2124
62467795
AN
2125/**
2126 * Selection functions for the Atto editor.
2127 *
2128 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
2129 *
2130 * @namespace M.editor_atto
2131 * @class EditorSelection
2132 */
fcb5b5c4 2133
62467795 2134function EditorSelection() {}
fcb5b5c4 2135
62467795
AN
2136EditorSelection.ATTRS= {
2137};
3ee53a42 2138
62467795 2139EditorSelection.prototype = {
3ee53a42
DW
2140
2141 /**
62467795
AN
2142 * List of saved selections per editor instance.
2143 *
2144 * @property _selections
2145 * @private
3ee53a42 2146 */
62467795 2147 _selections: null,
adca7326
DW
2148
2149 /**
62467795
AN
2150 * A unique identifier for the last selection recorded.
2151 *
2152 * @property _lastSelection
2153 * @param lastselection
2154 * @type string
2155 * @private
adca7326 2156 */
62467795 2157 _lastSelection: null,
adca7326
DW
2158
2159 /**
62467795
AN
2160 * Whether focus came from a click event.
2161 *
2162 * This is used to determine whether to restore the selection or not.
2163 *
2164 * @property _focusFromClick
2165 * @type Boolean
2166 * @default false
2167 * @private
adca7326 2168 */
62467795 2169 _focusFromClick: false,
adca7326 2170
90902953
DM
2171 /**
2172 * Whether if the last gesturemovestart event target was contained in this editor or not.
2173 *
2174 * @property _gesturestartededitor
2175 * @type Boolean
2176 * @default false
2177 * @private
2178 */
2179 _gesturestartededitor: false,
2180
adca7326 2181 /**
62467795
AN
2182 * Set up the watchers for selection save and restoration.
2183 *
2184 * @method setupSelectionWatchers
2185 * @chainable
adca7326 2186 */
62467795
AN
2187 setupSelectionWatchers: function() {
2188 // Save the selection when a change was made.
2189 this.on('atto:selectionchanged', this.saveSelection, this);
adca7326 2190
62467795 2191 this.editor.on('focus', this.restoreSelection, this);
adca7326 2192
62467795
AN
2193 // Do not restore selection when focus is from a click event.
2194 this.editor.on('mousedown', function() {
2195 this._focusFromClick = true;
2196 }, this);
adca7326 2197
62467795
AN
2198 // Copy the current value back to the textarea when focus leaves us and save the current selection.
2199 this.editor.on('blur', function() {
2200 // Clear the _focusFromClick value.
2201 this._focusFromClick = false;
adca7326 2202
62467795
AN
2203 // Update the original text area.
2204 this.updateOriginal();
2205 }, this);
adca7326 2206
8bca3609 2207 this.editor.on(['keyup', 'focus'], function(e) {
ee376395 2208 Y.soon(Y.bind(this._hasSelectionChanged, this, e));
8bca3609 2209 }, this);
e3050641 2210
90902953
DM
2211 Y.one(document.body).on('gesturemovestart', function(e) {
2212 if (this._wrapper.contains(e.target._node)) {
2213 this._gesturestartededitor = true;
2214 } else {
2215 this._gesturestartededitor = false;
2216 }
2217 }, null, this);
923589d7 2218
90902953
DM
2219 Y.one(document.body).on('gesturemoveend', function(e) {
2220 if (!this._gesturestartededitor) {
2221 // Ignore the event if movestart target was not contained in the editor.
923589d7
DM
2222 return;
2223 }
2224 Y.soon(Y.bind(this._hasSelectionChanged, this, e));
1f0d77f7
EM
2225 }, {
2226 // Standalone will make sure all editors receive the end event.
2227 standAlone: true
2228 }, this);
e3050641 2229
62467795 2230 return this;
b269f635
DW
2231 },
2232
adca7326 2233 /**
62467795
AN
2234 * Work out if the cursor is in the editable area for this editor instance.
2235 *
2236 * @method isActive
2237 * @return {boolean}
adca7326 2238 */
62467795
AN
2239 isActive: function() {
2240 var range = rangy.createRange(),
2241 selection = rangy.getSelection();
adca7326 2242
62467795
AN
2243 if (!selection.rangeCount) {
2244 // If there was no range count, then there is no selection.
2245 return false;
2246 }
adca7326 2247
1ce04361 2248 // We can't be active if the editor doesn't have focus at the moment.
9b9a3abf
DT
2249 if (!document.activeElement ||
2250 !(this.editor.compareTo(document.activeElement) || this.editor.contains(document.activeElement))) {
1ce04361
AN
2251 return false;
2252 }
2253
62467795
AN
2254 // Check whether the range intersects the editor selection.
2255 range.selectNode(this.editor.getDOMNode());
2256 return range.intersectsRange(selection.getRangeAt(0));
adca7326
DW
2257 },
2258
2259 /**
62467795
AN
2260 * Create a cross browser selection object that represents a YUI node.
2261 *
2262 * @method getSelectionFromNode
2263 * @param {Node} YUI Node to base the selection upon.
2264 * @return {[rangy.Range]}
adca7326 2265 */
62467795 2266 getSelectionFromNode: function(node) {
d321f68b
DW
2267 var range = rangy.createRange();
2268 range.selectNode(node.getDOMNode());
2269 return [range];
adca7326
DW
2270 },
2271
26f8822d 2272 /**
62467795
AN
2273 * Save the current selection to an internal property.
2274 *
2275 * This allows more reliable return focus, helping improve keyboard navigation.
2276 *
2277 * Should be used in combination with {{#crossLink "M.editor_atto.EditorSelection/restoreSelection"}}{{/crossLink}}.
2278 *
2279 * @method saveSelection
26f8822d 2280 */
62467795 2281 saveSelection: function() {
36265972
AN
2282 if (this.isActive()) {
2283 this._selections = this.getSelection();
2284 }
26f8822d
DW
2285 },
2286
2287 /**
62467795
AN
2288 * Restore any stored selection when the editor gets focus again.
2289 *
2290 * Should be used in combination with {{#crossLink "M.editor_atto.EditorSelection/saveSelection"}}{{/crossLink}}.
2291 *
2292 * @method restoreSelection
26f8822d 2293 */
62467795
AN
2294 restoreSelection: function() {
2295 if (!this._focusFromClick) {
2296 if (this._selections) {
2297 this.setSelection(this._selections);
26f8822d
DW
2298 }
2299 }
62467795 2300 this._focusFromClick = false;
26f8822d
DW
2301 },
2302
adca7326 2303 /**
62467795
AN
2304 * Get the selection object that can be passed back to setSelection.
2305 *
2306 * @method getSelection
2307 * @return {array} An array of rangy ranges.
adca7326 2308 */
62467795 2309 getSelection: function() {
d321f68b 2310 return rangy.getSelection().getAllRanges();
adca7326
DW
2311 },
2312
2313 /**
62467795
AN
2314 * Check that a YUI node it at least partly contained by the current selection.
2315 *
2316 * @method selectionContainsNode
2317 * @param {Node} The node to check.
2318 * @return {boolean}
adca7326 2319 */
62467795 2320 selectionContainsNode: function(node) {
d321f68b 2321 return rangy.getSelection().containsNode(node.getDOMNode(), true);
adca7326
DW
2322 },
2323
3ee53a42 2324 /**
62467795
AN
2325 * Runs a filter on each node in the selection, and report whether the
2326 * supplied selector(s) were found in the supplied Nodes.
3ee53a42 2327 *
62467795
AN
2328 * By default, all specified nodes must match the selection, but this
2329 * can be controlled with the requireall property.
2330 *
2331 * @method selectionFilterMatches
3ee53a42 2332 * @param {String} selector
62467795
AN
2333 * @param {NodeList} [selectednodes] For performance this should be passed. If not passed, this will be looked up each time.
2334 * @param {Boolean} [requireall=true] Used to specify that "any" match is good enough.
3ee53a42
DW
2335 * @return {Boolean}
2336 */
62467795
AN
2337 selectionFilterMatches: function(selector, selectednodes, requireall) {
2338 if (typeof requireall === 'undefined') {
d321f68b
DW
2339 requireall = true;
2340 }
3ee53a42
DW
2341 if (!selectednodes) {
2342 // Find this because it was not passed as a param.
62467795 2343 selectednodes = this.getSelectedNodes();
3ee53a42 2344 }
62467795
AN
2345 var allmatch = selectednodes.size() > 0,
2346 anymatch = false;
2347
2348 var editor = this.editor,
2349 stopFn = function(node) {
e76ae807
FM
2350 // The function getSelectedNodes only returns nodes within the editor, so this test is safe.
2351 return node === editor;
62467795
AN
2352 };
2353
e76ae807
FM
2354 // If we do not find at least one match in the editor, no point trying to find them in the selection.
2355 if (!editor.one(selector)) {
2356 return false;
2357 }
2358
67d3fe45
SH
2359 selectednodes.each(function(node){
2360 // Check each node, if it doesn't match the tags AND is not within the specified tags then fail this thing.
d321f68b
DW
2361 if (requireall) {
2362 // Check for at least one failure.
62467795 2363 if (!allmatch || !node.ancestor(selector, true, stopFn)) {
d321f68b
DW
2364 allmatch = false;
2365 }
2366 } else {
2367 // Check for at least one match.
62467795 2368 if (!anymatch && node.ancestor(selector, true, stopFn)) {
d321f68b
DW
2369 anymatch = true;
2370 }
3ee53a42 2371 }
67d3fe45 2372 }, this);
d321f68b
DW
2373 if (requireall) {
2374 return allmatch;
2375 } else {
2376 return anymatch;
2377 }
3ee53a42
DW
2378 },
2379
2380 /**
67d3fe45
SH
2381 * Get the deepest possible list of nodes in the current selection.
2382 *
62467795
AN
2383 * @method getSelectedNodes
2384 * @return {NodeList}
3ee53a42 2385 */
62467795 2386 getSelectedNodes: function() {
d321f68b
DW
2387 var results = new Y.NodeList(),
2388 nodes,
2389 selection,
67d3fe45 2390 range,
d321f68b
DW
2391 node,
2392 i;
2393
2394 selection = rangy.getSelection();
2395
2396 if (selection.rangeCount) {
2397 range = selection.getRangeAt(0);
2398 } else {
2399 // Empty range.
2400 range = rangy.createRange();
67d3fe45 2401 }
d321f68b
DW
2402
2403 if (range.collapsed) {
e9883836
FM
2404 // We do not want to select all the nodes in the editor if we managed to
2405 // have a collapsed selection directly in the editor.
17f253fa
AN
2406 // It's also possible for the commonAncestorContainer to be the document, which selectNode does not handle
2407 // so we must filter that out here too.
2408 if (range.commonAncestorContainer !== this.editor.getDOMNode()
2409 && range.commonAncestorContainer !== Y.config.doc) {
e9883836
FM
2410 range = range.cloneRange();
2411 range.selectNode(range.commonAncestorContainer);
2412 }
d321f68b
DW
2413 }
2414
2415 nodes = range.getNodes();
2416
2417 for (i = 0; i < nodes.length; i++) {
2418 node = Y.one(nodes[i]);
62467795 2419 if (this.editor.contains(node)) {
d321f68b 2420 results.push(node);
67d3fe45
SH
2421 }
2422 }
2423 return results;
3ee53a42
DW
2424 },
2425
2426 /**
62467795 2427 * Check whether the current selection has changed since this method was last called.
67d3fe45 2428 *
62467795 2429 * If the selection has changed, the atto:selectionchanged event is also fired.
67d3fe45 2430 *
62467795 2431 * @method _hasSelectionChanged
67d3fe45
SH
2432 * @private
2433 * @param {EventFacade} e
62467795 2434 * @return {Boolean}
3ee53a42 2435 */
62467795 2436 _hasSelectionChanged: function(e) {
d321f68b 2437 var selection = rangy.getSelection(),
67d3fe45 2438 range,
d321f68b
DW
2439 changed = false;
2440
2441 if (selection.rangeCount) {
2442 range = selection.getRangeAt(0);
2443 } else {
2444 // Empty range.
2445 range = rangy.createRange();
67d3fe45 2446 }
d321f68b 2447
62467795
AN
2448 if (this._lastSelection) {
2449 if (!this._lastSelection.equals(range)) {
d321f68b 2450 changed = true;
62467795 2451 return this._fireSelectionChanged(e);
d321f68b 2452 }
67d3fe45 2453 }
62467795 2454 this._lastSelection = range;
d321f68b 2455 return changed;
67d3fe45 2456 },
3ee53a42 2457
67d3fe45
SH
2458 /**
2459 * Fires the atto:selectionchanged event.
2460 *
62467795 2461 * When the selectionchanged event is fired, the following arguments are provided:
67d3fe45 2462 * - event : the original event that lead to this event being fired.
67d3fe45
SH
2463 * - selectednodes : an array containing nodes that are entirely selected of contain partially selected content.
2464 *
62467795 2465 * @method _fireSelectionChanged
67d3fe45
SH
2466 * @private
2467 * @param {EventFacade} e
2468 */
62467795 2469 _fireSelectionChanged: function(e) {
67d3fe45 2470 this.fire('atto:selectionchanged', {
62467795
AN
2471 event: e,
2472 selectedNodes: this.getSelectedNodes()
67d3fe45
SH
2473 });
2474 },
2475
adca7326 2476 /**
62467795
AN
2477 * Get the DOM node representing the common anscestor of the selection nodes.
2478 *
2479 * @method getSelectionParentNode
2480 * @return {Element|boolean} The DOM Node for this parent, or false if no seletion was made.
adca7326 2481 */
62467795 2482 getSelectionParentNode: function() {
d321f68b
DW
2483 var selection = rangy.getSelection();
2484 if (selection.rangeCount) {
2485 return selection.getRangeAt(0).commonAncestorContainer;
34f5867a 2486 }
34f5867a 2487 return false;
adca7326
DW
2488 },
2489
adca7326
DW
2490 /**
2491 * Set the current selection. Used to restore a selection.
62467795
AN
2492 *
2493 * @method selection
2494 * @param {array} ranges A list of rangy.range objects in the selection.
adca7326 2495 */
62467795 2496 setSelection: function(ranges) {
d321f68b
DW
2497 var selection = rangy.getSelection();
2498 selection.setRanges(ranges);
34f5867a
DW
2499 },
2500
62467795
AN
2501 /**
2502 * Inserts the given HTML into the editable content at the currently focused point.
2503 *
2504 * @method insertContentAtFocusPoint
2505 * @param {String} html
39c6f62d 2506 * @return {Node} The YUI Node object added to the DOM.
62467795
AN
2507 */
2508 insertContentAtFocusPoint: function(html) {
2509 var selection = rangy.getSelection(),
2510 range,
2511 node = Y.Node.create(html);
2512 if (selection.rangeCount) {
2513 range = selection.getRangeAt(0);
2514 }
2515 if (range) {
2516 range.deleteContents();
2517 range.insertNode(node.getDOMNode());
2518 }
39c6f62d 2519 return node;
62467795
AN
2520 }
2521
2522};
2523
2524Y.Base.mix(Y.M.editor_atto.Editor, [EditorSelection]);
2525// This file is part of Moodle - http://moodle.org/
2526//
2527// Moodle is free software: you can redistribute it and/or modify
2528// it under the terms of the GNU General Public License as published by
2529// the Free Software Foundation, either version 3 of the License, or
2530// (at your option) any later version.
2531//
2532// Moodle is distributed in the hope that it will be useful,
2533// but WITHOUT ANY WARRANTY; without even the implied warranty of
2534// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2535// GNU General Public License for more details.
2536//
2537// You should have received a copy of the GNU General Public License
2538// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
ad3f8cd1 2539/* global rangy */
62467795
AN
2540
2541/**
2542 * @module moodle-editor_atto-editor
2543 * @submodule styling
2544 */
2545
2546/**
2547 * Editor styling functions for the Atto editor.
2548 *
2549 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
2550 *
2551 * @namespace M.editor_atto
2552 * @class EditorStyling
2553 */
2554
2555function EditorStyling() {}
2556
2557EditorStyling.ATTRS= {
2558};
2559
2560EditorStyling.prototype = {
f6bef145
FM
2561 /**
2562 * Disable CSS styling.
2563 *
62467795 2564 * @method disableCssStyling
f6bef145 2565 */
62467795 2566 disableCssStyling: function() {
f6bef145
FM
2567 try {
2568 document.execCommand("styleWithCSS", 0, false);
2569 } catch (e1) {
2570 try {
2571 document.execCommand("useCSS", 0, true);
2572 } catch (e2) {
2573 try {
2574 document.execCommand('styleWithCSS', false, false);
2575 } catch (e3) {
2576 // We did our best.
2577 }
2578 }
2579 }
2580 },
2581
2582 /**
2583 * Enable CSS styling.
2584 *
62467795 2585 * @method enableCssStyling
f6bef145 2586 */
62467795 2587 enableCssStyling: function() {
f6bef145
FM
2588 try {
2589 document.execCommand("styleWithCSS", 0, true);
2590 } catch (e1) {
2591 try {
2592 document.execCommand("useCSS", 0, false);
2593 } catch (e2) {
2594 try {
2595 document.execCommand('styleWithCSS', false, true);
2596 } catch (e3) {
2597 // We did our best.
2598 }
2599 }
2600 }
2faf4c45
SH
2601 },
2602
bed1abbc
AD
2603 /**
2604 * Change the formatting for the current selection.
62467795
AN
2605 *
2606 * This will wrap the selection in span tags, adding the provided classes.
bed1abbc
AD
2607 *
2608 * If the selection covers multiple block elements, multiple spans will be inserted to preserve the original structure.
2609 *
62467795 2610 * @method toggleInlineSelectionClass
bed1abbc
AD
2611 * @param {Array} toggleclasses - Class names to be toggled on or off.
2612 */
62467795 2613 toggleInlineSelectionClass: function(toggleclasses) {
af6a2e94 2614 var classname = toggleclasses.join(" ");
b3c10f9f 2615 var cssApplier = rangy.createClassApplier(classname, {normalize: true});
af6a2e94
DW
2616
2617 cssApplier.toggleSelection();
af6a2e94
DW
2618 },
2619
2620 /**
2621 * Change the formatting for the current selection.
2622 *
2623 * This will set inline styles on the current selection.
2624 *
7bb2069b 2625 * @method formatSelectionInlineStyle
af6a2e94
DW
2626 * @param {Array} styles - Style attributes to set on the nodes.
2627 */
2628 formatSelectionInlineStyle: function(styles) {
2629 var classname = this.PLACEHOLDER_CLASS;
b3c10f9f 2630 var cssApplier = rangy.createClassApplier(classname, {normalize: true});
af6a2e94
DW
2631
2632 cssApplier.applyToSelection();
2633
2634 this.editor.all('.' + classname).each(function (node) {
2635 node.removeClass(classname).setStyles(styles);
2636 }, this);
2637
af6a2e94
DW
2638 },
2639
2640 /**
2641 * Change the formatting for the current selection.
2642 *
2643 * Also changes the selection to the newly formatted block (allows applying multiple styles to a block).
2644 *
2645 * @method formatSelectionBlock
2646 * @param {String} [blocktag] Change the block level tag to this. Empty string, means do not change the tag.
2647 * @param {Object} [attributes] The keys and values for attributes to be added/changed in the block tag.
2648 * @return {Node|boolean} The Node that was formatted if a change was made, otherwise false.
2649 */
2650 formatSelectionBlock: function(blocktag, attributes) {
2651 // First find the nearest ancestor of the selection that is a block level element.
62467795 2652 var selectionparentnode = this.getSelectionParentNode(),
af6a2e94
DW
2653 boundary,
2654 cell,
2655 nearestblock,
2656 newcontent,
2657 match,
2658 replacement;
bed1abbc
AD
2659
2660 if (!selectionparentnode) {
2661 // No selection, nothing to format.
af6a2e94 2662 return false;
bed1abbc
AD
2663 }
2664
af6a2e94 2665 boundary = this.editor;
bed1abbc 2666
af6a2e94
DW
2667 selectionparentnode = Y.one(selectionparentnode);
2668
2669 // If there is a table cell in between the selectionparentnode and the boundary,
2670 // move the boundary to the table cell.
2671 // This is because we might have a table in a div, and we select some text in a cell,
2672 // want to limit the change in style to the table cell, not the entire table (via the outer div).
2673 cell = selectionparentnode.ancestor(function (node) {
2674 var tagname = node.get('tagName');
2675 if (tagname) {
2676 tagname = tagname.toLowerCase();
bed1abbc 2677 }
af6a2e94
DW
2678 return (node === boundary) ||
2679 (tagname === 'td') ||
2680 (tagname === 'th');
2681 }, true);
bed1abbc 2682
af6a2e94
DW
2683 if (cell) {
2684 // Limit the scope to the table cell.
2685 boundary = cell;
2686 }
adca7326 2687
af6a2e94
DW
2688 nearestblock = selectionparentnode.ancestor(this.BLOCK_TAGS.join(', '), true);
2689 if (nearestblock) {
2690 // Check that the block is contained by the boundary.
2691 match = nearestblock.ancestor(function (node) {
2692 return node === boundary;
2693 }, false);
bed1abbc 2694
af6a2e94
DW
2695 if (!match) {
2696 nearestblock = false;
bed1abbc 2697 }
af6a2e94 2698 }
bed1abbc 2699
af6a2e94
DW
2700 // No valid block element - make one.
2701 if (!nearestblock) {
2702 // There is no block node in the content, wrap the content in a p and use that.
2703 newcontent = Y.Node.create('<p></p>');
2704 boundary.get('childNodes').each(function (child) {
2705 newcontent.append(child.remove());
2706 });
2707 boundary.append(newcontent);
2708 nearestblock = newcontent;
2709 }
2710
2711 // Guaranteed to have a valid block level element contained in the contenteditable region.
2712 // Change the tag to the new block level tag.
2713 if (blocktag && blocktag !== '') {
2714 // Change the block level node for a new one.
2715 replacement = Y.Node.create('<' + blocktag + '></' + blocktag + '>');
2716 // Copy all attributes.
2717 replacement.setAttrs(nearestblock.getAttrs());
2718 // Copy all children.
2719 nearestblock.get('childNodes').each(function (child) {
2720 child.remove();
2721 replacement.append(child);
2722 });
2723
2724 nearestblock.replace(replacement);
2725 nearestblock = replacement;
bed1abbc 2726 }
af6a2e94
DW
2727
2728 // Set the attributes on the block level tag.
2729 if (attributes) {
2730 nearestblock.setAttrs(attributes);
2731 }
2732
2733 // Change the selection to the modified block. This makes sense when we might apply multiple styles
2734 // to the block.
2735 var selection = this.getSelectionFromNode(nearestblock);
2736 this.setSelection(selection);
2737
2738 return nearestblock;
bed1abbc 2739 }
af6a2e94 2740
adca7326 2741};
67d3fe45 2742
62467795
AN
2743Y.Base.mix(Y.M.editor_atto.Editor, [EditorStyling]);
2744// This file is part of Moodle - http://moodle.org/
2745//
2746// Moodle is free software: you can redistribute it and/or modify
2747// it under the terms of the GNU General Public License as published by
2748// the Free Software Foundation, either version 3 of the License, or
2749// (at your option) any later version.
2750//
2751// Moodle is distributed in the hope that it will be useful,
2752// but WITHOUT ANY WARRANTY; without even the implied warranty of
2753// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2754// GNU General Public License for more details.
2755//
2756// You should have received a copy of the GNU General Public License
2757// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
2758
2759/**
2760 * @module moodle-editor_atto-editor
2761 * @submodule filepicker
2762 */
adca7326
DW
2763
2764/**
62467795 2765 * Filepicker options for the Atto editor.