1 YUI.add('moodle-editor_atto-editor', function (Y, NAME) {
3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
19 * The Atto WYSIWG pluggable editor, written for Moodle.
21 * @module moodle-editor_atto-editor
22 * @package editor_atto
23 * @copyright 2013 Damyon Wiese <damyon@moodle.com>
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * @main moodle-editor_atto-editor
29 * @module moodle-editor_atto-editor
30 * @submodule editor-base
33 var LOGNAME = 'moodle-editor_atto-editor';
35 CONTENT: 'editor_atto_content',
36 CONTENTWRAPPER: 'editor_atto_content_wrap',
37 TOOLBAR: 'editor_atto_toolbar',
38 WRAPPER: 'editor_atto',
39 HIGHLIGHT: 'highlight'
44 * The Atto editor for Moodle.
46 * @namespace M.editor_atto
49 * @uses M.editor_atto.EditorClean
50 * @uses M.editor_atto.EditorFilepicker
51 * @uses M.editor_atto.EditorSelection
52 * @uses M.editor_atto.EditorStyling
53 * @uses M.editor_atto.EditorTextArea
54 * @uses M.editor_atto.EditorToolbar
55 * @uses M.editor_atto.EditorToolbarNav
59 Editor.superclass.constructor.apply(this, arguments);
62 Y.extend(Editor, Y.Base, {
65 * List of known block level tags.
66 * Taken from "https://developer.mozilla.org/en-US/docs/HTML/Block-level_elements".
68 * @property BLOCK_TAGS
107 PLACEHOLDER_CLASS: 'atto-tmp-class',
108 ALL_NODES_SELECTOR: '[style],font[face]',
109 FONT_FAMILY: 'fontFamily',
112 * The wrapper containing the editor.
121 * A reference to the content editable Node.
129 * A reference to the original text area.
137 * A reference to the label associated with the original text area.
139 * @property textareaLabel
145 * A reference to the list of plugins.
153 * Event Handles to clear on editor destruction.
155 * @property _eventHandles
160 initializer: function() {
163 // Note - it is not safe to use a CSS selector like '#' + elementid because the id
164 // may have colons in it - e.g. quiz.
165 this.textarea = Y.one(document.getElementById(this.get('elementid')));
167 if (!this.textarea) {
168 // No text area found.
172 this._eventHandles = [];
174 this._wrapper = Y.Node.create('<div class="' + CSS.WRAPPER + '" />');
175 template = Y.Handlebars.compile('<div id="{{elementid}}editable" ' +
176 'contenteditable="true" ' +
178 'spellcheck="true" ' +
180 'class="{{CSS.CONTENT}}" ' +
182 this.editor = Y.Node.create(template({
183 elementid: this.get('elementid'),
187 // Add a labelled-by attribute to the contenteditable.
188 this.textareaLabel = Y.one('[for="' + this.get('elementid') + '"]');
189 if (this.textareaLabel) {
190 this.textareaLabel.generateID();
191 this.editor.setAttribute('aria-labelledby', this.textareaLabel.get("id"));
194 // Add everything to the wrapper.
197 // Editable content wrapper.
198 var content = Y.Node.create('<div class="' + CSS.CONTENTWRAPPER + '" />');
199 content.appendChild(this.editor);
200 this._wrapper.appendChild(content);
202 // Style the editor. According to the styles.css: 20 is the line-height, 8 is padding-top + padding-bottom.
203 this.editor.setStyle('minHeight', ((20 * this.textarea.getAttribute('rows')) + 8) + 'px');
206 // We set a height here to force the overflow because decent browsers allow the CSS property resize.
207 this.editor.setStyle('height', ((20 * this.textarea.getAttribute('rows')) + 8) + 'px');
210 // Disable odd inline CSS styles.
211 this.disableCssStyling();
213 // Use paragraphs not divs.
214 if (document.queryCommandSupported('DefaultParagraphSeparator')) {
215 document.execCommand('DefaultParagraphSeparator', false, 'p');
218 // Add the toolbar and editable zone to the page.
219 this.textarea.get('parentNode').insert(this._wrapper, this.textarea).
220 setAttribute('class', 'editor_atto_wrap');
222 // Hide the old textarea.
223 this.textarea.hide();
225 // Copy the text to the contenteditable div.
226 this.updateFromTextArea();
228 // Publish the events that are defined by this editor.
229 this.publishEvents();
231 // Add handling for saving and restoring selections on cursor/focus changes.
232 this.setupSelectionWatchers();
234 // Add polling to update the textarea periodically when typing long content.
235 this.setupAutomaticPolling();
240 // Initialize the auto-save timer.
241 this.setupAutosave();
242 // Preload the icons for the notifications.
243 this.setupNotifications();
247 * Focus on the editable area for this editor.
259 * Publish events for this editor instance.
261 * @method publishEvents
265 publishEvents: function() {
267 * Fired when changes are made within the editor.
271 this.publish('change', {
277 * Fired when all plugins have completed loading.
279 * @event pluginsloaded
281 this.publish('pluginsloaded', {
285 this.publish('atto:selectionchanged', {
293 * Set up automated polling of the text area to update the textarea.
295 * @method setupAutomaticPolling
298 setupAutomaticPolling: function() {
299 this._registerEventHandle(this.editor.on(['keyup', 'cut'], this.updateOriginal, this));
300 this._registerEventHandle(this.editor.on('paste', this.pasteCleanup, this));
302 // Call this.updateOriginal after dropped content has been processed.
303 this._registerEventHandle(this.editor.on('drop', this.updateOriginalDelayed, this));
309 * Calls updateOriginal on a short timer to allow native event handlers to run first.
311 * @method updateOriginalDelayed
314 updateOriginalDelayed: function() {
315 Y.soon(Y.bind(this.updateOriginal, this));
320 setupPlugins: function() {
321 // Clear the list of plugins.
324 var plugins = this.get('plugins');
332 for (groupIndex in plugins) {
333 group = plugins[groupIndex];
334 if (!group.plugins) {
335 // No plugins in this group - skip it.
338 for (pluginIndex in group.plugins) {
339 plugin = group.plugins[pluginIndex];
341 pluginConfig = Y.mix({
345 toolbar: this.toolbar,
349 // Add a reference to the current editor.
350 if (typeof Y.M['atto_' + plugin.name] === "undefined") {
353 this.plugins[plugin.name] = new Y.M['atto_' + plugin.name].Button(pluginConfig);
357 // Some plugins need to perform actions once all plugins have loaded.
358 this.fire('pluginsloaded');
363 enablePlugins: function(plugin) {
364 this._setPluginState(true, plugin);
367 disablePlugins: function(plugin) {
368 this._setPluginState(false, plugin);
371 _setPluginState: function(enable, plugin) {
372 var target = 'disableButtons';
374 target = 'enableButtons';
378 this.plugins[plugin][target]();
380 Y.Object.each(this.plugins, function(currentPlugin) {
381 currentPlugin[target]();
387 * Register an event handle for disposal in the destructor.
389 * @method _registerEventHandle
390 * @param {EventHandle} The Event Handle as returned by Y.on, and Y.delegate.
393 _registerEventHandle: function(handle) {
394 this._eventHandles.push(handle);
401 * The unique identifier for the form element representing the editor.
403 * @attribute elementid
413 * The contextid of the form.
415 * @attribute contextid
425 * Plugins with their configuration.
427 * The plugins structure is:
431 * "group": "groupName",
434 * "configKey": "configValue"
437 * "configKey": "configValue"
442 * "group": "groupName",
445 * "configKey": "configValue"
462 // The Editor publishes custom events that can be subscribed to.
463 Y.augment(Editor, Y.EventTarget);
465 Y.namespace('M.editor_atto').Editor = Editor;
467 // Function for Moodle's initialisation.
468 Y.namespace('M.editor_atto.Editor').init = function(config) {
469 return new Y.M.editor_atto.Editor(config);
471 // This file is part of Moodle - http://moodle.org/
473 // Moodle is free software: you can redistribute it and/or modify
474 // it under the terms of the GNU General Public License as published by
475 // the Free Software Foundation, either version 3 of the License, or
476 // (at your option) any later version.
478 // Moodle is distributed in the hope that it will be useful,
479 // but WITHOUT ANY WARRANTY; without even the implied warranty of
480 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
481 // GNU General Public License for more details.
483 // You should have received a copy of the GNU General Public License
484 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
487 * A notify function for the Atto editor.
489 * @module moodle-editor_atto-notify
491 * @package editor_atto
492 * @copyright 2014 Damyon Wiese
493 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
496 var LOGNAME_NOTIFY = 'moodle-editor_atto-editor-notify',
497 NOTIFY_INFO = 'info',
498 NOTIFY_WARNING = 'warning';
500 function EditorNotify() {}
502 EditorNotify.ATTRS= {
505 EditorNotify.prototype = {
508 * A single Y.Node for this editor. There is only ever one - it is replaced if a new message comes in.
510 * @property messageOverlay
513 messageOverlay: null,
516 * A single timer object that can be used to cancel the hiding behaviour.
518 * @property hideTimer
524 * Initialize the notifications.
526 * @method setupNotifications
529 setupNotifications: function() {
530 var preload1 = new Image(),
531 preload2 = new Image();
533 preload1.src = M.util.image_url('i/warning', 'moodle');
534 preload2.src = M.util.image_url('i/info', 'moodle');
540 * Show a notification in a floaty overlay somewhere in the atto editor text area.
542 * @method showMessage
543 * @param {String} message The translated message (use get_string)
544 * @param {String} type Must be either "info" or "warning"
545 * @param {Number} timeout Time in milliseconds to show this message for.
548 showMessage: function(message, type, timeout) {
549 var messageTypeIcon = '',
553 if (this.messageOverlay === null) {
554 this.messageOverlay = Y.Node.create('<div class="editor_atto_notification"></div>');
556 this.messageOverlay.hide(true);
557 this.textarea.get('parentNode').append(this.messageOverlay);
559 this.messageOverlay.on('click', function() {
560 this.messageOverlay.hide(true);
564 if (this.hideTimer !== null) {
565 this.hideTimer.cancel();
568 if (type === NOTIFY_WARNING) {
569 messageTypeIcon = '<img src="' +
570 M.util.image_url('i/warning', 'moodle') +
571 '" alt="' + M.util.get_string('warning', 'moodle') + '"/>';
572 } else if (type === NOTIFY_INFO) {
573 messageTypeIcon = '<img src="' +
574 M.util.image_url('i/info', 'moodle') +
575 '" alt="' + M.util.get_string('info', 'moodle') + '"/>';
579 // Parse the timeout value.
580 intTimeout = parseInt(timeout, 10);
581 if (intTimeout <= 0) {
585 // Convert class to atto_info (for example).
586 type = 'atto_' + type;
588 bodyContent = Y.Node.create('<div class="' + type + '" role="alert" aria-live="assertive">' +
589 messageTypeIcon + ' ' +
590 Y.Escape.html(message) +
592 this.messageOverlay.empty();
593 this.messageOverlay.append(bodyContent);
594 this.messageOverlay.show(true);
596 this.hideTimer = Y.later(intTimeout, this, function() {
597 this.hideTimer = null;
598 this.messageOverlay.hide(true);
606 Y.Base.mix(Y.M.editor_atto.Editor, [EditorNotify]);
607 // This file is part of Moodle - http://moodle.org/
609 // Moodle is free software: you can redistribute it and/or modify
610 // it under the terms of the GNU General Public License as published by
611 // the Free Software Foundation, either version 3 of the License, or
612 // (at your option) any later version.
614 // Moodle is distributed in the hope that it will be useful,
615 // but WITHOUT ANY WARRANTY; without even the implied warranty of
616 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
617 // GNU General Public License for more details.
619 // You should have received a copy of the GNU General Public License
620 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
623 * @module moodle-editor_atto-editor
624 * @submodule textarea
628 * Textarea functions for the Atto editor.
630 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
632 * @namespace M.editor_atto
633 * @class EditorTextArea
636 function EditorTextArea() {}
638 EditorTextArea.ATTRS= {
641 EditorTextArea.prototype = {
644 * Return the appropriate empty content value for the current browser.
646 * Different browsers use a different content when they are empty and
647 * we must set this reliable across the board.
649 * @method _getEmptyContent
650 * @return String The content to use representing no user-provided content
653 _getEmptyContent: function() {
654 if (Y.UA.ie && Y.UA.ie < 10) {
657 return '<p><br></p>';
662 * Copy and clean the text from the textarea into the contenteditable div.
664 * If the text is empty, provide a default paragraph tag to hold the content.
666 * @method updateFromTextArea
669 updateFromTextArea: function() {
671 this.editor.setHTML('');
673 // Copy text to editable div.
674 this.editor.append(this.textarea.get('value'));
677 this.cleanEditorHTML();
679 // Insert a paragraph in the empty contenteditable div.
680 if (this.editor.getHTML() === '') {
681 this.editor.setHTML(this._getEmptyContent());
686 * Copy the text from the contenteditable to the textarea which it replaced.
688 * @method updateOriginal
691 updateOriginal : function() {
692 // Get the previous and current value to compare them.
693 var oldValue = this.textarea.get('value'),
694 newValue = this.getCleanHTML();
696 if (newValue === "" && this.isActive()) {
697 // The content was entirely empty so get the empty content placeholder.
698 newValue = this._getEmptyContent();
701 // Only call this when there has been an actual change to reduce processing.
702 if (oldValue !== newValue) {
703 // Insert the cleaned content.
704 this.textarea.set('value', newValue);
706 // Trigger the onchange callback on the textarea, essentially to notify moodle-core-formchangechecker.
707 this.textarea.simulate('change');
709 // Trigger handlers for this action.
717 Y.Base.mix(Y.M.editor_atto.Editor, [EditorTextArea]);
718 // This file is part of Moodle - http://moodle.org/
720 // Moodle is free software: you can redistribute it and/or modify
721 // it under the terms of the GNU General Public License as published by
722 // the Free Software Foundation, either version 3 of the License, or
723 // (at your option) any later version.
725 // Moodle is distributed in the hope that it will be useful,
726 // but WITHOUT ANY WARRANTY; without even the implied warranty of
727 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
728 // GNU General Public License for more details.
730 // You should have received a copy of the GNU General Public License
731 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
734 * A autosave function for the Atto editor.
736 * @module moodle-editor_atto-autosave
737 * @submodule autosave-base
738 * @package editor_atto
739 * @copyright 2014 Damyon Wiese
740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
743 var SUCCESS_MESSAGE_TIMEOUT = 5000,
744 RECOVER_MESSAGE_TIMEOUT = 60000,
745 LOGNAME_AUTOSAVE = 'moodle-editor_atto-editor-autosave';
747 function EditorAutosave() {}
749 EditorAutosave.ATTRS= {
751 * Enable/Disable auto save for this instance.
753 * @attribute autosaveEnabled
763 * The time between autosaves (in seconds).
765 * @attribute autosaveFrequency
776 * Unique hash for this page instance. Calculated from $PAGE->url in php.
778 * @attribute pageHash
788 * The relative path to the ajax script.
790 * @attribute autosaveAjaxScript
792 * @default '/lib/editor/atto/autosave-ajax.php'
795 autosaveAjaxScript: {
796 value: '/lib/editor/atto/autosave-ajax.php',
801 EditorAutosave.prototype = {
804 * The text that was auto saved in the last request.
814 * @property autosaveInstance
817 autosaveInstance: null,
820 * Initialize the autosave process
822 * @method setupAutosave
825 setupAutosave: function() {
829 options = this.get('filepickeroptions'),
833 if (!this.get('autosaveEnabled')) {
834 // Autosave disabled for this instance.
838 this.autosaveInstance = Y.stamp(this);
839 for (optiontype in options) {
840 if (typeof options[optiontype].itemid !== "undefined") {
841 draftid = options[optiontype].itemid;
845 // First see if there are any saved drafts.
846 // Make an ajax request.
847 url = M.cfg.wwwroot + this.get('autosaveAjaxScript');
849 sesskey: M.cfg.sesskey,
850 contextid: this.get('contextid'),
854 elementid: this.get('elementid'),
855 pageinstance: this.autosaveInstance,
856 pagehash: this.get('pageHash')
864 success: function(id,o) {
866 if (typeof o.responseText !== "undefined" && o.responseText !== "") {
867 response_json = JSON.parse(o.responseText);
869 // Revert untouched editor contents to an empty string.
870 // Check for FF and Chrome.
871 if (response_json.result === '<p></p>' || response_json.result === '<p><br></p>' ||
872 response_json.result === '<br>') {
873 response_json.result = '';
876 // Check for IE 9 and 10.
877 if (response_json.result === '<p> </p>' || response_json.result === '<p><br> </p>') {
878 response_json.result = '';
881 if (response_json.error || typeof response_json.result === 'undefined') {
882 this.showMessage(M.util.get_string('errortextrecovery', 'editor_atto'),
883 NOTIFY_WARNING, RECOVER_MESSAGE_TIMEOUT);
884 } else if (response_json.result !== this.textarea.get('value') &&
885 response_json.result !== '') {
886 this.recoverText(response_json.result);
888 this._fireSelectionChanged();
891 failure: function() {
892 this.showMessage(M.util.get_string('errortextrecovery', 'editor_atto'),
893 NOTIFY_WARNING, RECOVER_MESSAGE_TIMEOUT);
898 // Now setup the timer for periodic saves.
900 var delay = parseInt(this.get('autosaveFrequency'), 10) * 1000;
901 Y.later(delay, this, this.saveDraft, false, true);
903 // Now setup the listener for form submission.
904 form = this.textarea.ancestor('form');
906 form.on('submit', this.resetAutosave, this);
912 * Clear the autosave text because the form was submitted normally.
914 * @method resetAutosave
917 resetAutosave: function() {
918 // Make an ajax request to reset the autosaved text.
919 var url = M.cfg.wwwroot + this.get('autosaveAjaxScript');
921 sesskey: M.cfg.sesskey,
922 contextid: this.get('contextid'),
924 elementid: this.get('elementid'),
925 pageinstance: this.autosaveInstance,
926 pagehash: this.get('pageHash')
939 * Recover a previous version of this text and show a message.
941 * @method recoverText
942 * @param {String} text
945 recoverText: function(text) {
946 this.editor.setHTML(text);
947 this.saveSelection();
948 this.updateOriginal();
949 this.lastText = text;
951 this.showMessage(M.util.get_string('textrecovered', 'editor_atto'),
952 NOTIFY_INFO, RECOVER_MESSAGE_TIMEOUT);
958 * Save a single draft via ajax.
963 saveDraft: function() {
965 // Only copy the text from the div to the textarea if the textarea is not currently visible.
966 if (!this.editor.get('hidden')) {
967 this.updateOriginal();
969 var newText = this.textarea.get('value');
971 if (newText !== this.lastText) {
973 // Make an ajax request.
974 url = M.cfg.wwwroot + this.get('autosaveAjaxScript');
976 sesskey: M.cfg.sesskey,
977 contextid: this.get('contextid'),
980 elementid: this.get('elementid'),
981 pagehash: this.get('pageHash'),
982 pageinstance: this.autosaveInstance
985 // Reusable error handler - must be passed the correct context.
986 var ajaxErrorFunction = function(code, response) {
987 var errorDuration = parseInt(this.get('autosaveFrequency'), 10) * 1000;
988 this.showMessage(M.util.get_string('autosavefailed', 'editor_atto'), NOTIFY_WARNING, errorDuration);
996 error: ajaxErrorFunction,
997 failure: ajaxErrorFunction,
998 success: function(code, response) {
999 if (response.responseText !== "") {
1000 Y.soon(Y.bind(ajaxErrorFunction, this, [code, response]));
1003 this.lastText = newText;
1004 this.showMessage(M.util.get_string('autosavesucceeded', 'editor_atto'),
1005 NOTIFY_INFO, SUCCESS_MESSAGE_TIMEOUT);
1015 Y.Base.mix(Y.M.editor_atto.Editor, [EditorAutosave]);
1016 // This file is part of Moodle - http://moodle.org/
1018 // Moodle is free software: you can redistribute it and/or modify
1019 // it under the terms of the GNU General Public License as published by
1020 // the Free Software Foundation, either version 3 of the License, or
1021 // (at your option) any later version.
1023 // Moodle is distributed in the hope that it will be useful,
1024 // but WITHOUT ANY WARRANTY; without even the implied warranty of
1025 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1026 // GNU General Public License for more details.
1028 // You should have received a copy of the GNU General Public License
1029 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
1032 * @module moodle-editor_atto-editor
1037 * Functions for the Atto editor to clean the generated content.
1039 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
1041 * @namespace M.editor_atto
1042 * @class EditorClean
1045 function EditorClean() {}
1047 EditorClean.ATTRS= {
1050 EditorClean.prototype = {
1052 * Clean the generated HTML content without modifying the editor content.
1054 * This includes removes all YUI ids from the generated content.
1056 * @return {string} The cleaned HTML content.
1058 getCleanHTML: function() {
1059 // Clone the editor so that we don't actually modify the real content.
1060 var editorClone = this.editor.cloneNode(true),
1063 // Remove all YUI IDs.
1064 Y.each(editorClone.all('[id^="yui"]'), function(node) {
1065 node.removeAttribute('id');
1068 editorClone.all('.atto_control').remove(true);
1069 html = editorClone.get('innerHTML');
1071 // Revert untouched editor contents to an empty string.
1072 if (html === '<p></p>' || html === '<p><br></p>') {
1076 // Remove any and all nasties from source.
1077 return this._cleanHTML(html);
1081 * Clean the HTML content of the editor.
1083 * @method cleanEditorHTML
1086 cleanEditorHTML: function() {
1087 var startValue = this.editor.get('innerHTML');
1088 this.editor.set('innerHTML', this._cleanHTML(startValue));
1094 * Clean the specified HTML content and remove any content which could cause issues.
1096 * @method _cleanHTML
1098 * @param {String} content The content to clean
1099 * @return {String} The cleaned HTML
1101 _cleanHTML: function(content) {
1102 // Removing limited things that can break the page or a disallowed, like unclosed comments, style blocks, etc.
1105 // Remove any style blocks. Some browsers do not work well with them in a contenteditable.
1106 // Plus style blocks are not allowed in body html, except with "scoped", which most browsers don't support as of 2015.
1107 // Reference: "http://stackoverflow.com/questions/1068280/javascript-regex-multiline-flag-doesnt-work"
1108 {regex: /<style[^>]*>[\s\S]*?<\/style>/gi, replace: ""},
1110 // Remove any open HTML comment opens that are not followed by a close. This can completely break page layout.
1111 {regex: /<!--(?![\s\S]*?-->)/gi, replace: ""},
1113 // Source: "http://www.codinghorror.com/blog/2006/01/cleaning-words-nasty-html.html"
1114 // Remove forbidden tags for content, title, meta, style, st0-9, head, font, html, body, link.
1115 {regex: /<\/?(?:title|meta|style|st\d|head|font|html|body|link)[^>]*?>/gi, replace: ""}
1118 return this._filterContentWithRules(content, rules);
1122 * Take the supplied content and run on the supplied regex rules.
1124 * @method _filterContentWithRules
1126 * @param {String} content The content to clean
1127 * @param {Array} rules An array of structures: [ {regex: /something/, replace: "something"}, {...}, ...]
1128 * @return {String} The cleaned content
1130 _filterContentWithRules: function(content, rules) {
1132 for (i = 0; i < rules.length; i++) {
1133 content = content.replace(rules[i].regex, rules[i].replace);
1140 * Intercept and clean html paste events.
1142 * @method pasteCleanup
1143 * @param {Object} sourceEvent The YUI EventFacade object
1144 * @return {Boolean} True if the passed event should continue, false if not.
1146 pasteCleanup: function(sourceEvent) {
1147 // We only expect paste events, but we will check anyways.
1148 if (sourceEvent.type === 'paste') {
1149 // The YUI event wrapper doesn't provide paste event info, so we need the underlying event.
1150 var event = sourceEvent._event;
1151 // Check if we have a valid clipboardData object in the event.
1152 // IE has a clipboard object at window.clipboardData, but as of IE 11, it does not provide HTML content access.
1153 if (event && event.clipboardData && event.clipboardData.getData) {
1154 // Check if there is HTML type to be pasted, this is all we care about.
1155 var types = event.clipboardData.types;
1157 // Different browsers use different things to hold the types, so test various functions.
1160 } else if (typeof types.contains === 'function') {
1161 isHTML = types.contains('text/html');
1162 } else if (typeof types.indexOf === 'function') {
1163 isHTML = (types.indexOf('text/html') > -1);
1165 if ((types.indexOf('com.apple.webarchive') > -1) || (types.indexOf('com.apple.iWork.TSPNativeData') > -1)) {
1166 // This is going to be a specialized Apple paste paste. We cannot capture this, so clean everything.
1167 this.fallbackPasteCleanupDelayed();
1172 // We don't know how to handle the clipboard info, so wait for the clipboard event to finish then fallback.
1173 this.fallbackPasteCleanupDelayed();
1178 // Get the clipboard content.
1181 content = event.clipboardData.getData('text/html');
1183 // Something went wrong. Fallback.
1184 this.fallbackPasteCleanupDelayed();
1188 // Stop the original paste.
1189 sourceEvent.preventDefault();
1191 // Scrub the paste content.
1192 content = this._cleanPasteHTML(content);
1194 // Save the current selection.
1195 // Using saveSelection as it produces a more consistent experience.
1196 var selection = window.rangy.saveSelection();
1198 // Insert the content.
1199 this.insertContentAtFocusPoint(content);
1201 // Restore the selection, and collapse to end.
1202 window.rangy.restoreSelection(selection);
1203 window.rangy.getSelection().collapseToEnd();
1205 // Update the text area.
1206 this.updateOriginal();
1209 // This is a non-html paste event, we can just let this continue on and call updateOriginalDelayed.
1210 this.updateOriginalDelayed();
1214 // If we reached a here, this probably means the browser has limited (or no) clipboard support.
1215 // Wait for the clipboard event to finish then fallback.
1216 this.fallbackPasteCleanupDelayed();
1221 // We should never get here - we must have received a non-paste event for some reason.
1222 // Um, just call updateOriginalDelayed() - it's safe.
1223 this.updateOriginalDelayed();
1228 * Cleanup code after a paste event if we couldn't intercept the paste content.
1230 * @method fallbackPasteCleanup
1233 fallbackPasteCleanup: function() {
1235 // Save the current selection (cursor position).
1236 var selection = window.rangy.saveSelection();
1238 // Get, clean, and replace the content in the editable.
1239 var content = this.editor.get('innerHTML');
1240 this.editor.set('innerHTML', this._cleanPasteHTML(content));
1242 // Update the textarea.
1243 this.updateOriginal();
1245 // Restore the selection (cursor position).
1246 window.rangy.restoreSelection(selection);
1252 * Calls fallbackPasteCleanup on a short timer to allow the paste event handlers to complete.
1254 * @method fallbackPasteCleanupDelayed
1257 fallbackPasteCleanupDelayed: function() {
1258 Y.soon(Y.bind(this.fallbackPasteCleanup, this));
1264 * Cleanup html that comes from WYSIWYG paste events. These are more likely to contain messy code that we should strip.
1266 * @method _cleanPasteHTML
1268 * @param {String} content The html content to clean
1269 * @return {String} The cleaned HTML
1271 _cleanPasteHTML: function(content) {
1272 // Return an empty string if passed an invalid or empty object.
1273 if (!content || content.length === 0) {
1277 // Rules that get rid of the real-nasties and don't care about normalize code (correct quotes, white spaces, etc).
1279 // Stuff that is specifically from MS Word and similar office packages.
1280 // Remove all garbage after closing html tag.
1281 {regex: /<\s*\/html\s*>([\s\S]+)$/gi, replace: ""},
1282 // Remove if comment blocks.
1283 {regex: /<!--\[if[\s\S]*?endif\]-->/gi, replace: ""},
1284 // Remove start and end fragment comment blocks.
1285 {regex: /<!--(Start|End)Fragment-->/gi, replace: ""},
1286 // Remove any xml blocks.
1287 {regex: /<xml[^>]*>[\s\S]*?<\/xml>/gi, replace: ""},
1288 // Remove any <?xml><\?xml> blocks.
1289 {regex: /<\?xml[^>]*>[\s\S]*?<\\\?xml>/gi, replace: ""},
1290 // Remove <o:blah>, <\o:blah>.
1291 {regex: /<\/?\w+:[^>]*>/gi, replace: ""}
1294 // Apply the first set of harsher rules.
1295 content = this._filterContentWithRules(content, rules);
1297 // Apply the standard rules, which mainly cleans things like headers, links, and style blocks.
1298 content = this._cleanHTML(content);
1300 // Check if the string is empty or only contains whitespace.
1301 if (content.length === 0 || !content.match(/\S/)) {
1305 // Now we let the browser normalize the code by loading it into the DOM and then get the html back.
1306 // This gives us well quoted, well formatted code to continue our work on. Word may provide very poorly formatted code.
1307 var holder = document.createElement('div');
1308 holder.innerHTML = content;
1309 content = holder.innerHTML;
1310 // Free up the DOM memory.
1311 holder.innerHTML = "";
1313 // Run some more rules that care about quotes and whitespace.
1315 // Remove MSO-blah, MSO:blah in style attributes. Only removes one or more that appear in succession.
1316 {regex: /(<[^>]*?style\s*?=\s*?"[^>"]*?)(?:[\s]*MSO[-:][^>;"]*;?)+/gi, replace: "$1"},
1317 // Remove MSO classes in class attributes. Only removes one or more that appear in succession.
1318 {regex: /(<[^>]*?class\s*?=\s*?"[^>"]*?)(?:[\s]*MSO[_a-zA-Z0-9\-]*)+/gi, replace: "$1"},
1319 // Remove Apple- classes in class attributes. Only removes one or more that appear in succession.
1320 {regex: /(<[^>]*?class\s*?=\s*?"[^>"]*?)(?:[\s]*Apple-[_a-zA-Z0-9\-]*)+/gi, replace: "$1"},
1321 // Remove OLE_LINK# anchors that may litter the code.
1322 {regex: /<a [^>]*?name\s*?=\s*?"OLE_LINK\d*?"[^>]*?>\s*?<\/a>/gi, replace: ""},
1323 // Remove empty spans, but not ones from Rangy.
1324 {regex: /<span(?![^>]*?rangySelectionBoundary[^>]*?)[^>]*>( |\s)*<\/span>/gi, replace: ""}
1328 content = this._filterContentWithRules(content, rules);
1330 // Reapply the standard cleaner to the content.
1331 content = this._cleanHTML(content);
1337 Y.Base.mix(Y.M.editor_atto.Editor, [EditorClean]);
1338 // This file is part of Moodle - http://moodle.org/
1340 // Moodle is free software: you can redistribute it and/or modify
1341 // it under the terms of the GNU General Public License as published by
1342 // the Free Software Foundation, either version 3 of the License, or
1343 // (at your option) any later version.
1345 // Moodle is distributed in the hope that it will be useful,
1346 // but WITHOUT ANY WARRANTY; without even the implied warranty of
1347 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1348 // GNU General Public License for more details.
1350 // You should have received a copy of the GNU General Public License
1351 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
1354 * @module moodle-editor_atto-editor
1355 * @submodule toolbar
1359 * Toolbar functions for the Atto editor.
1361 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
1363 * @namespace M.editor_atto
1364 * @class EditorToolbar
1367 function EditorToolbar() {}
1369 EditorToolbar.ATTRS= {
1372 EditorToolbar.prototype = {
1374 * A reference to the toolbar Node.
1382 * A reference to any currently open menus in the toolbar.
1384 * @property openMenus
1390 * Setup the toolbar on the editor.
1392 * @method setupToolbar
1395 setupToolbar: function() {
1396 this.toolbar = Y.Node.create('<div class="' + CSS.TOOLBAR + '" role="toolbar" aria-live="off"/>');
1397 this.openMenus = [];
1398 this._wrapper.appendChild(this.toolbar);
1400 if (this.textareaLabel) {
1401 this.toolbar.setAttribute('aria-labelledby', this.textareaLabel.get("id"));
1404 // Add keyboard navigation for the toolbar.
1405 this.setupToolbarNavigation();
1411 Y.Base.mix(Y.M.editor_atto.Editor, [EditorToolbar]);
1412 // This file is part of Moodle - http://moodle.org/
1414 // Moodle is free software: you can redistribute it and/or modify
1415 // it under the terms of the GNU General Public License as published by
1416 // the Free Software Foundation, either version 3 of the License, or
1417 // (at your option) any later version.
1419 // Moodle is distributed in the hope that it will be useful,
1420 // but WITHOUT ANY WARRANTY; without even the implied warranty of
1421 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1422 // GNU General Public License for more details.
1424 // You should have received a copy of the GNU General Public License
1425 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
1428 * @module moodle-editor_atto-editor
1429 * @submodule toolbarnav
1433 * Toolbar Navigation functions for the Atto editor.
1435 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
1437 * @namespace M.editor_atto
1438 * @class EditorToolbarNav
1441 function EditorToolbarNav() {}
1443 EditorToolbarNav.ATTRS= {
1446 EditorToolbarNav.prototype = {
1448 * The current focal point for tabbing.
1450 * @property _tabFocus
1458 * Set up the watchers for toolbar navigation.
1460 * @method setupToolbarNavigation
1463 setupToolbarNavigation: function() {
1464 // Listen for Arrow left and Arrow right keys.
1465 this._wrapper.delegate('key',
1466 this.toolbarKeyboardNavigation,
1470 this._wrapper.delegate('focus',
1472 this._setTabFocus(e.currentTarget);
1473 }, '.' + CSS.TOOLBAR + ' button', this);
1479 * Implement arrow key navigation for the buttons in the toolbar.
1481 * @method toolbarKeyboardNavigation
1482 * @param {EventFacade} e - the keyboard event.
1484 toolbarKeyboardNavigation: function(e) {
1485 // Prevent the default browser behaviour.
1488 // On cursor moves we loops through the buttons.
1489 var buttons = this.toolbar.all('button'),
1492 current = e.target.ancestor('button', true);
1494 if (e.keyCode === 37) {
1495 // Moving left so reverse the direction.
1499 button = this._findFirstFocusable(buttons, current, direction);
1502 this._setTabFocus(button);
1508 * Find the first focusable button.
1510 * @param {NodeList} buttons A list of nodes.
1511 * @param {Node} startAt The node in the list to start the search from.
1512 * @param {Number} direction The direction in which to search (1 or -1).
1513 * @return {Node | Undefined} The Node or undefined.
1514 * @method _findFirstFocusable
1517 _findFirstFocusable: function(buttons, startAt, direction) {
1524 // Determine which button to start the search from.
1525 index = buttons.indexOf(startAt);
1530 // Try to find the next.
1531 while (checkCount < buttons.size()) {
1534 index = buttons.size() - 1;
1535 } else if (index >= buttons.size()) {
1540 candidate = buttons.item(index);
1542 // Add a counter to ensure we don't get stuck in a loop if there's only one visible menu item.
1546 // * we haven't checked every button;
1547 // * the button is hidden or disabled;
1548 // * the group is hidden.
1549 if (candidate.hasAttribute('hidden') || candidate.hasAttribute('disabled')) {
1552 group = candidate.ancestor('.atto_group');
1553 if (group.hasAttribute('hidden')) {
1565 * Check the tab focus.
1567 * When we disable or hide a button, we should call this method to ensure that the
1568 * focus is not currently set on an inaccessible button, otherwise tabbing to the toolbar
1569 * would be impossible.
1571 * @method checkTabFocus
1574 checkTabFocus: function() {
1575 if (this._tabFocus) {
1576 if (this._tabFocus.hasAttribute('disabled') || this._tabFocus.hasAttribute('hidden')
1577 || this._tabFocus.ancestor('.atto_group').hasAttribute('hidden')) {
1578 // Find first available button.
1579 var button = this._findFirstFocusable(this.toolbar.all('button'), this._tabFocus, -1);
1581 if (this._tabFocus.compareTo(document.activeElement)) {
1582 // We should also move the focus, because the inaccessible button also has the focus.
1585 this._setTabFocus(button);
1593 * Sets tab focus for the toolbar to the specified Node.
1595 * @method _setTabFocus
1596 * @param {Node} button The node that focus should now be set to
1600 _setTabFocus: function(button) {
1601 if (this._tabFocus) {
1602 // Unset the previous entry.
1603 this._tabFocus.setAttribute('tabindex', '-1');
1606 // Set up the new entry.
1607 this._tabFocus = button;
1608 this._tabFocus.setAttribute('tabindex', 0);
1610 // And update the activedescendant to point at the currently selected button.
1611 this.toolbar.setAttribute('aria-activedescendant', this._tabFocus.generateID());
1617 Y.Base.mix(Y.M.editor_atto.Editor, [EditorToolbarNav]);
1618 // This file is part of Moodle - http://moodle.org/
1620 // Moodle is free software: you can redistribute it and/or modify
1621 // it under the terms of the GNU General Public License as published by
1622 // the Free Software Foundation, either version 3 of the License, or
1623 // (at your option) any later version.
1625 // Moodle is distributed in the hope that it will be useful,
1626 // but WITHOUT ANY WARRANTY; without even the implied warranty of
1627 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1628 // GNU General Public License for more details.
1630 // You should have received a copy of the GNU General Public License
1631 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
1634 * @module moodle-editor_atto-editor
1635 * @submodule selection
1639 * Selection functions for the Atto editor.
1641 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
1643 * @namespace M.editor_atto
1644 * @class EditorSelection
1647 function EditorSelection() {}
1649 EditorSelection.ATTRS= {
1652 EditorSelection.prototype = {
1655 * List of saved selections per editor instance.
1657 * @property _selections
1663 * A unique identifier for the last selection recorded.
1665 * @property _lastSelection
1666 * @param lastselection
1670 _lastSelection: null,
1673 * Whether focus came from a click event.
1675 * This is used to determine whether to restore the selection or not.
1677 * @property _focusFromClick
1682 _focusFromClick: false,
1685 * Set up the watchers for selection save and restoration.
1687 * @method setupSelectionWatchers
1690 setupSelectionWatchers: function() {
1691 // Save the selection when a change was made.
1692 this.on('atto:selectionchanged', this.saveSelection, this);
1694 this.editor.on('focus', this.restoreSelection, this);
1696 // Do not restore selection when focus is from a click event.
1697 this.editor.on('mousedown', function() {
1698 this._focusFromClick = true;
1701 // Copy the current value back to the textarea when focus leaves us and save the current selection.
1702 this.editor.on('blur', function() {
1703 // Clear the _focusFromClick value.
1704 this._focusFromClick = false;
1706 // Update the original text area.
1707 this.updateOriginal();
1710 this.editor.on(['keyup', 'focus'], function(e) {
1711 Y.soon(Y.bind(this._hasSelectionChanged, this, e));
1714 // To capture both mouseup and touchend events, we need to track the gesturemoveend event in standAlone mode. Without
1715 // standAlone, it will only fire if we listened to a gesturemovestart too.
1716 this.editor.on('gesturemoveend', function(e) {
1717 Y.soon(Y.bind(this._hasSelectionChanged, this, e));
1726 * Work out if the cursor is in the editable area for this editor instance.
1731 isActive: function() {
1732 var range = rangy.createRange(),
1733 selection = rangy.getSelection();
1735 if (!selection.rangeCount) {
1736 // If there was no range count, then there is no selection.
1740 // We can't be active if the editor doesn't have focus at the moment.
1741 if (!document.activeElement ||
1742 !(this.editor.compareTo(document.activeElement) || this.editor.contains(document.activeElement))) {
1746 // Check whether the range intersects the editor selection.
1747 range.selectNode(this.editor.getDOMNode());
1748 return range.intersectsRange(selection.getRangeAt(0));
1752 * Create a cross browser selection object that represents a YUI node.
1754 * @method getSelectionFromNode
1755 * @param {Node} YUI Node to base the selection upon.
1756 * @return {[rangy.Range]}
1758 getSelectionFromNode: function(node) {
1759 var range = rangy.createRange();
1760 range.selectNode(node.getDOMNode());
1765 * Save the current selection to an internal property.
1767 * This allows more reliable return focus, helping improve keyboard navigation.
1769 * Should be used in combination with {{#crossLink "M.editor_atto.EditorSelection/restoreSelection"}}{{/crossLink}}.
1771 * @method saveSelection
1773 saveSelection: function() {
1774 if (this.isActive()) {
1775 this._selections = this.getSelection();
1780 * Restore any stored selection when the editor gets focus again.
1782 * Should be used in combination with {{#crossLink "M.editor_atto.EditorSelection/saveSelection"}}{{/crossLink}}.
1784 * @method restoreSelection
1786 restoreSelection: function() {
1787 if (!this._focusFromClick) {
1788 if (this._selections) {
1789 this.setSelection(this._selections);
1792 this._focusFromClick = false;
1796 * Get the selection object that can be passed back to setSelection.
1798 * @method getSelection
1799 * @return {array} An array of rangy ranges.
1801 getSelection: function() {
1802 return rangy.getSelection().getAllRanges();
1806 * Check that a YUI node it at least partly contained by the current selection.
1808 * @method selectionContainsNode
1809 * @param {Node} The node to check.
1812 selectionContainsNode: function(node) {
1813 return rangy.getSelection().containsNode(node.getDOMNode(), true);
1817 * Runs a filter on each node in the selection, and report whether the
1818 * supplied selector(s) were found in the supplied Nodes.
1820 * By default, all specified nodes must match the selection, but this
1821 * can be controlled with the requireall property.
1823 * @method selectionFilterMatches
1824 * @param {String} selector
1825 * @param {NodeList} [selectednodes] For performance this should be passed. If not passed, this will be looked up each time.
1826 * @param {Boolean} [requireall=true] Used to specify that "any" match is good enough.
1829 selectionFilterMatches: function(selector, selectednodes, requireall) {
1830 if (typeof requireall === 'undefined') {
1833 if (!selectednodes) {
1834 // Find this because it was not passed as a param.
1835 selectednodes = this.getSelectedNodes();
1837 var allmatch = selectednodes.size() > 0,
1840 var editor = this.editor,
1841 stopFn = function(node) {
1842 // The function getSelectedNodes only returns nodes within the editor, so this test is safe.
1843 return node === editor;
1846 // If we do not find at least one match in the editor, no point trying to find them in the selection.
1847 if (!editor.one(selector)) {
1851 selectednodes.each(function(node){
1852 // Check each node, if it doesn't match the tags AND is not within the specified tags then fail this thing.
1854 // Check for at least one failure.
1855 if (!allmatch || !node.ancestor(selector, true, stopFn)) {
1859 // Check for at least one match.
1860 if (!anymatch && node.ancestor(selector, true, stopFn)) {
1873 * Get the deepest possible list of nodes in the current selection.
1875 * @method getSelectedNodes
1876 * @return {NodeList}
1878 getSelectedNodes: function() {
1879 var results = new Y.NodeList(),
1886 selection = rangy.getSelection();
1888 if (selection.rangeCount) {
1889 range = selection.getRangeAt(0);
1892 range = rangy.createRange();
1895 if (range.collapsed) {
1896 // We do not want to select all the nodes in the editor if we managed to
1897 // have a collapsed selection directly in the editor.
1898 // It's also possible for the commonAncestorContainer to be the document, which selectNode does not handle
1899 // so we must filter that out here too.
1900 if (range.commonAncestorContainer !== this.editor.getDOMNode()
1901 && range.commonAncestorContainer !== Y.config.doc) {
1902 range = range.cloneRange();
1903 range.selectNode(range.commonAncestorContainer);
1907 nodes = range.getNodes();
1909 for (i = 0; i < nodes.length; i++) {
1910 node = Y.one(nodes[i]);
1911 if (this.editor.contains(node)) {
1919 * Check whether the current selection has changed since this method was last called.
1921 * If the selection has changed, the atto:selectionchanged event is also fired.
1923 * @method _hasSelectionChanged
1925 * @param {EventFacade} e
1928 _hasSelectionChanged: function(e) {
1929 var selection = rangy.getSelection(),
1933 if (selection.rangeCount) {
1934 range = selection.getRangeAt(0);
1937 range = rangy.createRange();
1940 if (this._lastSelection) {
1941 if (!this._lastSelection.equals(range)) {
1943 return this._fireSelectionChanged(e);
1946 this._lastSelection = range;
1951 * Fires the atto:selectionchanged event.
1953 * When the selectionchanged event is fired, the following arguments are provided:
1954 * - event : the original event that lead to this event being fired.
1955 * - selectednodes : an array containing nodes that are entirely selected of contain partially selected content.
1957 * @method _fireSelectionChanged
1959 * @param {EventFacade} e
1961 _fireSelectionChanged: function(e) {
1962 this.fire('atto:selectionchanged', {
1964 selectedNodes: this.getSelectedNodes()
1969 * Get the DOM node representing the common anscestor of the selection nodes.
1971 * @method getSelectionParentNode
1972 * @return {Element|boolean} The DOM Node for this parent, or false if no seletion was made.
1974 getSelectionParentNode: function() {
1975 var selection = rangy.getSelection();
1976 if (selection.rangeCount) {
1977 return selection.getRangeAt(0).commonAncestorContainer;
1983 * Set the current selection. Used to restore a selection.
1986 * @param {array} ranges A list of rangy.range objects in the selection.
1988 setSelection: function(ranges) {
1989 var selection = rangy.getSelection();
1990 selection.setRanges(ranges);
1994 * Inserts the given HTML into the editable content at the currently focused point.
1996 * @method insertContentAtFocusPoint
1997 * @param {String} html
1998 * @return {Node} The YUI Node object added to the DOM.
2000 insertContentAtFocusPoint: function(html) {
2001 var selection = rangy.getSelection(),
2003 node = Y.Node.create(html);
2004 if (selection.rangeCount) {
2005 range = selection.getRangeAt(0);
2008 range.deleteContents();
2009 range.insertNode(node.getDOMNode());
2016 Y.Base.mix(Y.M.editor_atto.Editor, [EditorSelection]);
2017 // This file is part of Moodle - http://moodle.org/
2019 // Moodle is free software: you can redistribute it and/or modify
2020 // it under the terms of the GNU General Public License as published by
2021 // the Free Software Foundation, either version 3 of the License, or
2022 // (at your option) any later version.
2024 // Moodle is distributed in the hope that it will be useful,
2025 // but WITHOUT ANY WARRANTY; without even the implied warranty of
2026 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2027 // GNU General Public License for more details.
2029 // You should have received a copy of the GNU General Public License
2030 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
2033 * @module moodle-editor_atto-editor
2034 * @submodule styling
2038 * Editor styling functions for the Atto editor.
2040 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
2042 * @namespace M.editor_atto
2043 * @class EditorStyling
2046 function EditorStyling() {}
2048 EditorStyling.ATTRS= {
2051 EditorStyling.prototype = {
2053 * Disable CSS styling.
2055 * @method disableCssStyling
2057 disableCssStyling: function() {
2059 document.execCommand("styleWithCSS", 0, false);
2062 document.execCommand("useCSS", 0, true);
2065 document.execCommand('styleWithCSS', false, false);
2074 * Enable CSS styling.
2076 * @method enableCssStyling
2078 enableCssStyling: function() {
2080 document.execCommand("styleWithCSS", 0, true);
2083 document.execCommand("useCSS", 0, false);
2086 document.execCommand('styleWithCSS', false, true);
2095 * Change the formatting for the current selection.
2097 * This will wrap the selection in span tags, adding the provided classes.
2099 * If the selection covers multiple block elements, multiple spans will be inserted to preserve the original structure.
2101 * @method toggleInlineSelectionClass
2102 * @param {Array} toggleclasses - Class names to be toggled on or off.
2104 toggleInlineSelectionClass: function(toggleclasses) {
2105 var classname = toggleclasses.join(" ");
2106 var originalSelection = this.getSelection();
2107 var cssApplier = rangy.createCssClassApplier(classname, {normalize: true});
2109 cssApplier.toggleSelection();
2111 this.setSelection(originalSelection);
2115 * Change the formatting for the current selection.
2117 * This will set inline styles on the current selection.
2119 * @method toggleInlineSelectionClass
2120 * @param {Array} styles - Style attributes to set on the nodes.
2122 formatSelectionInlineStyle: function(styles) {
2123 var classname = this.PLACEHOLDER_CLASS;
2124 var originalSelection = this.getSelection();
2125 var cssApplier = rangy.createCssClassApplier(classname, {normalize: true});
2127 cssApplier.applyToSelection();
2129 this.editor.all('.' + classname).each(function (node) {
2130 node.removeClass(classname).setStyles(styles);
2133 this.setSelection(originalSelection);
2137 * Change the formatting for the current selection.
2139 * Also changes the selection to the newly formatted block (allows applying multiple styles to a block).
2141 * @method formatSelectionBlock
2142 * @param {String} [blocktag] Change the block level tag to this. Empty string, means do not change the tag.
2143 * @param {Object} [attributes] The keys and values for attributes to be added/changed in the block tag.
2144 * @return {Node|boolean} The Node that was formatted if a change was made, otherwise false.
2146 formatSelectionBlock: function(blocktag, attributes) {
2147 // First find the nearest ancestor of the selection that is a block level element.
2148 var selectionparentnode = this.getSelectionParentNode(),
2156 if (!selectionparentnode) {
2157 // No selection, nothing to format.
2161 boundary = this.editor;
2163 selectionparentnode = Y.one(selectionparentnode);
2165 // If there is a table cell in between the selectionparentnode and the boundary,
2166 // move the boundary to the table cell.
2167 // This is because we might have a table in a div, and we select some text in a cell,
2168 // want to limit the change in style to the table cell, not the entire table (via the outer div).
2169 cell = selectionparentnode.ancestor(function (node) {
2170 var tagname = node.get('tagName');
2172 tagname = tagname.toLowerCase();
2174 return (node === boundary) ||
2175 (tagname === 'td') ||
2180 // Limit the scope to the table cell.
2184 nearestblock = selectionparentnode.ancestor(this.BLOCK_TAGS.join(', '), true);
2186 // Check that the block is contained by the boundary.
2187 match = nearestblock.ancestor(function (node) {
2188 return node === boundary;
2192 nearestblock = false;
2196 // No valid block element - make one.
2197 if (!nearestblock) {
2198 // There is no block node in the content, wrap the content in a p and use that.
2199 newcontent = Y.Node.create('<p></p>');
2200 boundary.get('childNodes').each(function (child) {
2201 newcontent.append(child.remove());
2203 boundary.append(newcontent);
2204 nearestblock = newcontent;
2207 // Guaranteed to have a valid block level element contained in the contenteditable region.
2208 // Change the tag to the new block level tag.
2209 if (blocktag && blocktag !== '') {
2210 // Change the block level node for a new one.
2211 replacement = Y.Node.create('<' + blocktag + '></' + blocktag + '>');
2212 // Copy all attributes.
2213 replacement.setAttrs(nearestblock.getAttrs());
2214 // Copy all children.
2215 nearestblock.get('childNodes').each(function (child) {
2217 replacement.append(child);
2220 nearestblock.replace(replacement);
2221 nearestblock = replacement;
2224 // Set the attributes on the block level tag.
2226 nearestblock.setAttrs(attributes);
2229 // Change the selection to the modified block. This makes sense when we might apply multiple styles
2231 var selection = this.getSelectionFromNode(nearestblock);
2232 this.setSelection(selection);
2234 return nearestblock;
2239 Y.Base.mix(Y.M.editor_atto.Editor, [EditorStyling]);
2240 // This file is part of Moodle - http://moodle.org/
2242 // Moodle is free software: you can redistribute it and/or modify
2243 // it under the terms of the GNU General Public License as published by
2244 // the Free Software Foundation, either version 3 of the License, or
2245 // (at your option) any later version.
2247 // Moodle is distributed in the hope that it will be useful,
2248 // but WITHOUT ANY WARRANTY; without even the implied warranty of
2249 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2250 // GNU General Public License for more details.
2252 // You should have received a copy of the GNU General Public License
2253 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
2256 * @module moodle-editor_atto-editor
2257 * @submodule filepicker
2261 * Filepicker options for the Atto editor.
2263 * See {{#crossLink "M.editor_atto.Editor"}}{{/crossLink}} for details.
2265 * @namespace M.editor_atto
2266 * @class EditorFilepicker
2269 function EditorFilepicker() {}
2271 EditorFilepicker.ATTRS= {
2273 * The options for the filepicker.
2275 * @attribute filepickeroptions
2279 filepickeroptions: {
2284 EditorFilepicker.prototype = {
2286 * Should we show the filepicker for this filetype?
2288 * @method canShowFilepicker
2289 * @param string type The media type for the file picker.
2292 canShowFilepicker: function(type) {
2293 return (typeof this.get('filepickeroptions')[type] !== 'undefined');
2297 * Show the filepicker.
2299 * This depends on core_filepicker, and then call that modules show function.
2301 * @method showFilepicker
2302 * @param {string} type The media type for the file picker.
2303 * @param {function} callback The callback to use when selecting an item of media.
2304 * @param {object} [context] The context from which to call the callback.
2306 showFilepicker: function(type, callback, context) {
2308 Y.use('core_filepicker', function (Y) {
2309 var options = Y.clone(self.get('filepickeroptions')[type], true);
2310 options.formcallback = callback;
2312 options.magicscope = context;
2315 M.core_filepicker.show(Y, options);
2320 Y.Base.mix(Y.M.editor_atto.Editor, [EditorFilepicker]);
2334 "moodle-core-notification-dialogue",
2335 "moodle-core-notification-confirm",
2336 "moodle-editor_atto-rangy",