MDL-43853 Atto: Performance. Turbocharge the loader.
[moodle.git] / lib / editor / atto / yui / build / moodle-editor_atto-editor / moodle-editor_atto-editor.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/>.
17
18/**
19 * Atto editor.
20 *
21 * @package editor_atto
22 * @copyright 2013 Damyon Wiese <damyon@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26/**
27 * Classes constants.
28 */
29CSS = {
30 CONTENT: 'editor_atto_content',
31 CONTENTWRAPPER: 'editor_atto_content_wrap',
32 TOOLBAR: 'editor_atto_toolbar',
33 WRAPPER: 'editor_atto'
34};
35
36/**
37 * Atto editor main class.
38 * Common functions required by editor plugins.
39 *
40 * @package editor_atto
41 * @copyright 2013 Damyon Wiese <damyon@moodle.com>
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 */
44M.editor_atto = M.editor_atto || {
45
46 /**
47 * List of attached button handlers to prevent duplicates.
48 */
49 buttonhandlers : {},
50
51 /**
52 * List of attached handlers to add inline editing controls to content.
53 */
54 textupdatedhandlers : {},
55
56 /**
57 * List of YUI overlays for custom menus.
58 */
59 menus : {},
60
61 /**
62 * List of attached menu handlers to prevent duplicates.
63 */
64 menuhandlers : {},
65
66 /**
67 * List of file picker options for specific editor instances.
68 */
69 filepickeroptions : {},
70
71 /**
72 * List of buttons and menus that have been added to the toolbar.
73 */
74 widgets : {},
75
76 /**
77 * Toggle a menu.
78 * @param event e
79 */
80 showhide_menu_handler : function(e) {
81 e.preventDefault();
82 var disabled = this.getAttribute('disabled');
83 var overlayid = this.getAttribute('data-menu');
84 var overlay = M.editor_atto.menus[overlayid];
85 var menu = overlay.get('bodyContent');
86 if (overlay.get('visible') || disabled) {
87 overlay.hide();
88 menu.detach('clickoutside');
89 } else {
90 menu.on('clickoutside', function(ev) {
91 if ((ev.target.ancestor() !== this) && (ev.target !== this)) {
92 if (overlay.get('visible')) {
93 menu.detach('clickoutside');
94 overlay.hide();
95 }
96 }
97 }, this);
98 overlay.show();
99 overlay.bodyNode.one('a').focus();
100 }
101 },
102
103 /**
104 * Handle clicks on editor buttons.
105 * @param event e
106 */
107 buttonclicked_handler : function(e) {
108 var elementid = this.getAttribute('data-editor');
109 var plugin = this.getAttribute('data-plugin');
110 var handler = this.getAttribute('data-handler');
111 var overlay = M.editor_atto.menus[plugin + '_' + elementid];
112
113 if (overlay) {
114 overlay.hide();
115 }
116
117 if (M.editor_atto.is_enabled(elementid, plugin)) {
118 // Pass it on.
119 handler = M.editor_atto.buttonhandlers[handler];
120 return handler(e, elementid);
121 }
122 },
123
124 /**
125 * Determine if the specified toolbar button/menu is enabled.
126 * @param string elementid, the element id of this editor.
127 * @param string plugin, the plugin that created the button/menu.
128 */
129 is_enabled : function(elementid, plugin) {
130 var element = Y.one('#' + elementid + '_toolbar .atto_' + plugin + '_button');
131
132 return !element.hasAttribute('disabled');
133 },
134 /**
135 * Disable all buttons and menus in the toolbar.
136 * @param string elementid, the element id of this editor.
137 */
138 disable_all_widgets : function(elementid) {
139 var plugin, element;
140 for (plugin in M.editor_atto.widgets) {
141 element = Y.one('#' + elementid + '_toolbar .atto_' + plugin + '_button');
142
143 if (element) {
144 element.setAttribute('disabled', 'true');
145 }
146 }
147 },
148
149 /**
150 * Enable a single widget in the toolbar.
151 * @param string elementid, the element id of this editor.
152 * @param string plugin, the name of the plugin that created the widget.
153 */
154 enable_widget : function(elementid, plugin) {
155 var element = Y.one('#' + elementid + '_toolbar .atto_' + plugin + '_button');
156
157 if (element) {
158 element.removeAttribute('disabled');
159 }
160 },
161
162 /**
163 * Enable all buttons and menus in the toolbar.
164 * @param string elementid, the element id of this editor.
165 */
166 enable_all_widgets : function(elementid) {
167 var plugin, element;
168 for (plugin in M.editor_atto.widgets) {
169 element = Y.one('#' + elementid + '_toolbar .atto_' + plugin + '_button');
170
171 if (element) {
172 element.removeAttribute('disabled');
173 }
174 }
175 },
176
177 /**
178 * Add a content update handler to be called whenever the content is updated.
179 * This is used to add inline editing controls to the content that are cleaned on submission.
180 *
181 * @param string elementid - the id of the textarea we created this editor from.
182 * @handler function callback - The function to do the cleaning.
183 * @param object context - the context to set for the callback.
184 * @handler function handler - A function to call when the button is clicked.
185 */
186 add_text_updated_handler : function(elementid, callback) {
187 if (!(elementid in M.editor_atto.textupdatedhandlers)) {
188 M.editor_atto.textupdatedhandlers[elementid] = [];
189 }
190 M.editor_atto.textupdatedhandlers[elementid].push(callback);
191 },
192
193 /**
194 * Add a button to the toolbar belonging to the editor for element with id "elementid".
195 * @param string elementid - the id of the textarea we created this editor from.
196 * @param string plugin - the plugin defining the button
197 * @param string icon - the html used for the content of the button
198 * @param string groupname - the group the button should be appended to.
199 * @param array entries - List of menu entries with the string (entry.text) and the handlers (entry.handler).
200 */
55c0403c 201 add_toolbar_menu : function(elementid, plugin, iconurl, groupname, entries) {
adca7326
DW
202 var toolbar = Y.one('#' + elementid + '_toolbar'),
203 group = Y.one('#' + elementid + '_toolbar .atto_group.' + groupname + '_group'),
204 currentfocus,
205 button,
adca7326
DW
206 expimgurl;
207
208 if (!group) {
209 group = Y.Node.create('<div class="atto_group ' + groupname + '_group"></div>');
210 toolbar.append(group);
211 }
adca7326
DW
212 expimgurl = M.util.image_url('t/expanded', 'moodle');
213 button = Y.Node.create('<button class="atto_' + plugin + '_button atto_hasmenu" ' +
214 'data-editor="' + Y.Escape.html(elementid) + '" ' +
215 'tabindex="-1" ' +
216 'data-menu="' + plugin + '_' + elementid + '" ' +
217 'title="' + Y.Escape.html(M.util.get_string('pluginname', 'atto_' + plugin)) + '">' +
55c0403c 218 '<img class="icon" aria-hidden="true" role="presentation" width="16" height="16" src="' + iconurl + '"/>' +
adca7326
DW
219 '<img class="icon" aria-hidden="true" role="presentation" width="16" height="16" src="' + expimgurl + '"/>' +
220 '</button>');
221
222 group.append(button);
223
224 currentfocus = toolbar.getAttribute('aria-activedescendant');
225 if (!currentfocus) {
226 button.setAttribute('tabindex', '0');
227 toolbar.setAttribute('aria-activedescendant', button.generateID());
228 }
229
230 // Save the name of the plugin.
231 M.editor_atto.widgets[plugin] = plugin;
232
233 var menu = Y.Node.create('<div class="atto_' + plugin + '_menu' +
234 ' atto_menu" data-editor="' + Y.Escape.html(elementid) + '"></div>');
235 var i = 0, entry = {};
236
237 for (i = 0; i < entries.length; i++) {
238 entry = entries[i];
239
240 menu.append(Y.Node.create('<div class="atto_menuentry">' +
241 '<a href="#" class="atto_' + plugin + '_action_' + i + '" ' +
242 'data-editor="' + Y.Escape.html(elementid) + '" ' +
243 'data-plugin="' + Y.Escape.html(plugin) + '" ' +
244 'data-handler="' + Y.Escape.html(plugin + '_action_' + i) + '">' +
245 entry.text +
246 '</a>' +
247 '</div>'));
248 if (!M.editor_atto.buttonhandlers[plugin + '_action_' + i]) {
249 Y.one('body').delegate('click', M.editor_atto.buttonclicked_handler, '.atto_' + plugin + '_action_' + i);
250 Y.one('body').delegate('key', M.editor_atto.buttonclicked_handler, 'space,enter', '.atto_' + plugin + '_action_' + i);
251 M.editor_atto.buttonhandlers[plugin + '_action_' + i] = entry.handler;
252 }
253 }
254
255 if (!M.editor_atto.buttonhandlers[plugin]) {
256 Y.one('body').delegate('click', M.editor_atto.showhide_menu_handler, '.atto_' + plugin + '_button');
257 M.editor_atto.buttonhandlers[plugin] = true;
258 }
259
260 var overlay = new M.core.dialogue({
261 bodyContent : menu,
262 visible : false,
263 width: '14em',
264 zindex: 100,
265 lightbox: false,
266 closeButton: false,
55c0403c 267 center : false
adca7326
DW
268 });
269
270 M.editor_atto.menus[plugin + '_' + elementid] = overlay;
271 overlay.render();
55c0403c 272 overlay.align(button, [Y.WidgetPositionAlign.TL, Y.WidgetPositionAlign.BL]);
adca7326
DW
273 overlay.hide();
274 overlay.headerNode.hide();
275 },
276
277 /**
278 * Add a button to the toolbar belonging to the editor for element with id "elementid".
279 * @param string elementid - the id of the textarea we created this editor from.
280 * @param string plugin - the plugin defining the button.
55c0403c 281 * @param string icon - the url to the image for the icon
adca7326
DW
282 * @param string groupname - the group the button should be appended to.
283 * @handler function handler- A function to call when the button is clicked.
284 */
55c0403c 285 add_toolbar_button : function(elementid, plugin, iconurl, groupname, handler) {
adca7326
DW
286 var toolbar = Y.one('#' + elementid + '_toolbar'),
287 group = Y.one('#' + elementid + '_toolbar .atto_group.' + groupname + '_group'),
288 button,
55c0403c 289 currentfocus;
adca7326
DW
290
291 if (!group) {
292 group = Y.Node.create('<div class="atto_group ' + groupname +'_group"></div>');
293 toolbar.append(group);
294 }
adca7326
DW
295 button = Y.Node.create('<button class="atto_' + plugin + '_button" ' +
296 'data-editor="' + Y.Escape.html(elementid) + '" ' +
297 'data-plugin="' + Y.Escape.html(plugin) + '" ' +
298 'tabindex="-1" ' +
299 'data-handler="' + Y.Escape.html(plugin) + '" ' +
300 'title="' + Y.Escape.html(M.util.get_string('pluginname', 'atto_' + plugin)) + '">' +
55c0403c 301 '<img class="icon" aria-hidden="true" role="presentation" width="16" height="16" src="' + iconurl + '"/>' +
adca7326
DW
302 '</button>');
303
304 group.append(button);
305
306 currentfocus = toolbar.getAttribute('aria-activedescendant');
307 if (!currentfocus) {
308 button.setAttribute('tabindex', '0');
309 toolbar.setAttribute('aria-activedescendant', button.generateID());
310 }
311
312 // We only need to attach this once.
313 if (!M.editor_atto.buttonhandlers[plugin]) {
314 Y.one('body').delegate('click', M.editor_atto.buttonclicked_handler, '.atto_' + plugin + '_button');
315 M.editor_atto.buttonhandlers[plugin] = handler;
316 }
317
318 // Save the name of the plugin.
319 M.editor_atto.widgets[plugin] = plugin;
320
321 },
322
323 /**
324 * Work out if the cursor is in the editable area for this editor instance.
325 * @param string elementid of this editor
326 * @return bool
327 */
328 is_active : function(elementid) {
329 var selection = M.editor_atto.get_selection();
330
331 if (selection.length) {
332 selection = selection.pop();
333 }
334
335 var node = null;
336 if (selection.parentElement) {
337 node = Y.one(selection.parentElement());
338 } else {
339 node = Y.one(selection.startContainer);
340 }
341
342 return node && node.ancestor('#' + elementid + 'editable') !== null;
343 },
344
345 /**
346 * Focus on the editable area for this editor.
347 * @param string elementid of this editor
348 */
349 focus : function(elementid) {
350 Y.one('#' + elementid + 'editable').focus();
351 },
352
353 /**
354 * Initialise the editor
355 * @param object params for this editor instance.
356 */
357 init : function(params) {
358 var textarea = Y.one('#' +params.elementid);
359 var wrapper = Y.Node.create('<div class="' + CSS.WRAPPER + '" />');
360 var atto = Y.Node.create('<div id="' + params.elementid + 'editable" ' +
361 'contenteditable="true" ' +
362 'spellcheck="true" ' +
363 'class="' + CSS.CONTENT + '" />');
364
365 var cssfont = '';
366 var toolbar = Y.Node.create('<div class="' + CSS.TOOLBAR + '" id="' + params.elementid + '_toolbar" role="toolbar"/>');
367
368 // Editable content wrapper.
369 var content = Y.Node.create('<div class="' + CSS.CONTENTWRAPPER + '" />');
370 content.appendChild(atto);
371
372 // Add everything to the wrapper.
373 wrapper.appendChild(toolbar);
374 wrapper.appendChild(content);
375
376 // Bleh - why are we sent a url and not the css to apply directly?
377 var css = Y.io(params.content_css, { sync: true });
378 var pos = css.responseText.indexOf('font:');
379 if (pos) {
380 cssfont = css.responseText.substring(pos + 'font:'.length, css.responseText.length - 1);
381 atto.setStyle('font', cssfont);
382 }
383 atto.setStyle('minHeight', (1.2 * (textarea.getAttribute('rows'))) + 'em');
384
385 // Copy text to editable div.
386 atto.append(textarea.get('value'));
387
388 // Add the toolbar and editable zone to the page.
389 textarea.get('parentNode').insert(wrapper, textarea);
390 atto.setStyle('color', textarea.getStyle('color'));
391 atto.setStyle('lineHeight', textarea.getStyle('lineHeight'));
392 atto.setStyle('fontSize', textarea.getStyle('fontSize'));
393 // Hide the old textarea.
394 textarea.hide();
395
396 // Copy the current value back to the textarea when focus leaves us.
397 atto.on('blur', function() {
398 this.text_updated(params.elementid);
399 }, this);
400
401 // Listen for Arrow left and Arrow right keys.
402 Y.one(Y.config.doc.body).delegate('key',
403 this.keyboard_navigation,
404 'down:37,39',
405 '#' + params.elementid + '_toolbar',
406 this,
407 params.elementid);
408
409 // Save the file picker options for later.
410 M.editor_atto.filepickeroptions[params.elementid] = params.filepickeroptions;
55c0403c
DW
411
412 // Init each of the plugins
413 var i, j;
414 for (i = 0; i < params.plugins.length; i++) {
415 var group = params.plugins[i].group;
416 for (j = 0; j < params.plugins[i].plugins.length; j++) {
417 var plugin = params.plugins[i].plugins[j];
418 plugin.params.elementid = params.elementid;
419 plugin.params.group = group;
420
421 M['atto_' + plugin.name].init(plugin.params);
422 }
423 }
adca7326
DW
424 },
425
426 /**
427 * The text in the contenteditable region has been updated,
428 * clean and copy the buffer to the text area.
429 * @param string elementid - the id of the textarea we created this editor from.
430 */
431 text_updated : function(elementid) {
432 var textarea = Y.one('#' + elementid),
433 cleancontent = this.get_clean_html(elementid);
434 textarea.set('value', cleancontent);
435 // Trigger handlers for this action.
436 var i = 0;
437 if (elementid in M.editor_atto.textupdatedhandlers) {
438 for (i = 0; i < M.editor_atto.textupdatedhandlers[elementid].length; i++) {
439 var callback = M.editor_atto.textupdatedhandlers[elementid][i];
440 callback(elementid);
441 }
442 }
443 },
444
445 /**
446 * Remove all YUI ids from the generated HTML.
447 * @param string elementid - the id of the textarea we created this editor from.
448 * @return string HTML stripped of YUI ids
449 */
450 get_clean_html : function(elementid) {
451 var atto = Y.one('#' + elementid + 'editable').cloneNode(true);
452
453 Y.each(atto.all('[id]'), function(node) {
454 var id = node.get('id');
455 if (id.indexOf('yui') === 0) {
456 node.removeAttribute('id');
457 }
458 });
459
460 Y.each(atto.all('.atto_control'), function(node) {
461 node.remove(true);
462 });
463
464 return atto.getHTML();
465 },
466
467 /**
468 * Implement arrow key navigation for the buttons in the toolbar.
469 * @param Event e - the keyboard event.
470 * @param string elementid - the id of the textarea we created this editor from.
471 */
472 keyboard_navigation : function(e, elementid) {
473 var buttons,
474 current,
475 currentid,
476 currentindex;
477
478 e.preventDefault();
479
480 buttons = Y.all('#' + elementid + '_toolbar button');
481 currentid = Y.one('#' + elementid + '_toolbar').getAttribute('aria-activedescendant');
482 if (!currentid) {
483 return;
484 }
485 current = Y.one('#' + currentid);
486 current.setAttribute('tabindex', '-1');
487
488 currentindex = buttons.indexOf(current);
489
490 if (e.keyCode === 37) {
491 // Left
492 currentindex--;
493 if (currentindex < 0) {
494 currentindex = buttons.size()-1;
495 }
496 } else {
497 // Right
498 currentindex++;
499 if (currentindex >= buttons.size()) {
500 currentindex = 0;
501 }
502 }
503
504 current = buttons.item(currentindex);
505 current.setAttribute('tabindex', '0');
506 current.focus();
507 Y.one('#' + elementid + '_toolbar').setAttribute('aria-activedescendant', current.generateID());
508 },
509
510 /**
511 * Show the filepicker.
512 * @param string elementid for this editor instance.
513 * @param string type The media type for the file picker
514 * @param function callback
515 */
516 show_filepicker : function(elementid, type, callback) {
517 Y.use('core_filepicker', function (Y) {
518 var options = M.editor_atto.filepickeroptions[elementid][type];
519
520 options.formcallback = callback;
521 options.editor_target = Y.one(elementid);
522
523 M.core_filepicker.show(Y, options);
524 });
525 },
526
527 /**
528 * Create a cross browser selection object that represents a yui node.
529 * @param Node yui node for the selection
530 * @return range (browser dependent)
531 */
532 get_selection_from_node: function(node) {
533 var range;
534
535 if (window.getSelection) {
536 range = document.createRange();
537
538 range.setStartBefore(node.getDOMNode());
539 range.setEndAfter(node.getDOMNode());
540 return [range];
541 } else if (document.selection) {
542 range = document.body.createTextRange();
543 range.moveToElementText(node.getDOMNode());
544 return range;
545 }
546 return false;
547 },
548
549 /**
550 * Get the selection object that can be passed back to set_selection.
551 * @return range (browser dependent)
552 */
553 get_selection : function() {
554 if (window.getSelection) {
555 var sel = window.getSelection();
556 var ranges = [], i = 0;
557 for (i = 0; i < sel.rangeCount; i++) {
558 ranges.push(sel.getRangeAt(i));
559 }
560 return ranges;
561 } else if (document.selection) {
562 // IE < 9
563 if (document.selection.createRange) {
564 return document.selection.createRange();
565 }
566 }
567 return false;
568 },
569
570 /**
571 * Check that a YUI node it at least partly contained by the selection.
572 * @param Range selection
573 * @param Y.Node node
574 * @return boolean
575 */
576 selection_contains_node : function(node) {
577 var range, sel;
578 if (window.getSelection) {
579 sel = window.getSelection();
580
581 if (sel.containsNode) {
582 return sel.containsNode(node.getDOMNode(), true);
583 }
584 }
585 sel = document.selection.createRange();
586 range = sel.duplicate();
587 range.moveToElementText(node.getDOMNode());
588 return sel.inRange(range);
589 },
590
591 /**
592 * Get the dom node representing the common anscestor of the selection nodes.
593 * @return DOMNode
594 */
595 get_selection_parent_node : function() {
596 var selection = M.editor_atto.get_selection();
597 if (selection.length > 0) {
598 return selection[0].commonAncestorContainer;
599 }
600 },
601
602 /**
603 * Get the list of child nodes of the selection.
604 * @return DOMNode[]
605 */
606 get_selection_text : function() {
607 var selection = M.editor_atto.get_selection();
608 if (selection.length > 0 && selection[0].cloneContents) {
609 return selection[0].cloneContents();
610 }
611 },
612
613 /**
614 * Set the current selection. Used to restore a selection.
615 */
616 set_selection : function(selection) {
617 var sel, i;
618
619 if (window.getSelection) {
620 sel = window.getSelection();
621 sel.removeAllRanges();
622 for (i = 0; i < selection.length; i++) {
623 sel.addRange(selection[i]);
624 }
625 } else if (document.selection) {
626 // IE < 9
627 if (selection.select) {
628 selection.select();
629 }
630 }
631 }
632
633};
634var CONTROLMENU_NAME = "Controlmenu",
635 CONTROLMENU;
636
637/**
638 * CONTROLMENU
639 * This is a drop down list of buttons triggered (and aligned to) a button.
640 *
641 * @namespace M.editor_atto.controlmenu
642 * @class controlmenu
643 * @constructor
644 * @extends M.core.dialogue
645 */
646CONTROLMENU = function(config) {
647 config.draggable = false;
55c0403c 648 config.center = false;
adca7326
DW
649 config.width = 'auto';
650 config.lightbox = false;
adca7326
DW
651 config.footerContent = '';
652 CONTROLMENU.superclass.constructor.apply(this, [config]);
653};
654
655Y.extend(CONTROLMENU, M.core.dialogue, {
656
657 /**
658 * Initialise the menu.
659 *
660 * @method initializer
661 * @return void
662 */
663 initializer : function(config) {
664 var body, headertext, bb;
665 CONTROLMENU.superclass.initializer.call(this, config);
666
667 bb = this.get('boundingBox');
668 bb.addClass('editor_atto_controlmenu');
669
670 // Close the menu when clicked outside (excluding the button that opened the menu).
671 body = this.bodyNode;
672
673 headertext = Y.Node.create('<h3/>');
674 headertext.addClass('accesshide');
675 headertext.setHTML(this.get('headerText'));
676 body.prepend(headertext);
677
678 body.on('clickoutside', function(e) {
679 if (this.get('visible')) {
680 // Note: we need to compare ids because for some reason - sometimes button is an Object, not a Y.Node.
681 if (!e.target.ancestor('.atto_control')) {
682 e.preventDefault();
683 this.hide();
684 }
685 }
686 }, this);
687 }
688
689}, {
690 NAME : CONTROLMENU_NAME,
691 ATTRS : {
692 /**
693 * The header for the drop down (only accessible to screen readers).
694 *
695 * @attribute headerText
696 * @type String
697 * @default ''
698 */
699 headerText : {
700 value : ''
701 }
702
703 }
704});
705
706M.editor_atto = M.editor_atto || {};
707M.editor_atto.controlmenu = CONTROLMENU;
708
709
710}, '@VERSION@', {"requires": ["node", "io", "overlay", "escape", "event", "moodle-core-notification"]});