MDL-43842: Import atto back into core
[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 */
201 add_toolbar_menu : function(elementid, plugin, icon, groupname, entries) {
202 var toolbar = Y.one('#' + elementid + '_toolbar'),
203 group = Y.one('#' + elementid + '_toolbar .atto_group.' + groupname + '_group'),
204 currentfocus,
205 button,
206 imgurl,
207 expimgurl;
208
209 if (!group) {
210 group = Y.Node.create('<div class="atto_group ' + groupname + '_group"></div>');
211 toolbar.append(group);
212 }
213 imgurl = M.util.image_url(icon[0], icon[1]);
214 expimgurl = M.util.image_url('t/expanded', 'moodle');
215 button = Y.Node.create('<button class="atto_' + plugin + '_button atto_hasmenu" ' +
216 'data-editor="' + Y.Escape.html(elementid) + '" ' +
217 'tabindex="-1" ' +
218 'data-menu="' + plugin + '_' + elementid + '" ' +
219 'title="' + Y.Escape.html(M.util.get_string('pluginname', 'atto_' + plugin)) + '">' +
220 '<img class="icon" aria-hidden="true" role="presentation" width="16" height="16" src="' + imgurl + '"/>' +
221 '<img class="icon" aria-hidden="true" role="presentation" width="16" height="16" src="' + expimgurl + '"/>' +
222 '</button>');
223
224 group.append(button);
225
226 currentfocus = toolbar.getAttribute('aria-activedescendant');
227 if (!currentfocus) {
228 button.setAttribute('tabindex', '0');
229 toolbar.setAttribute('aria-activedescendant', button.generateID());
230 }
231
232 // Save the name of the plugin.
233 M.editor_atto.widgets[plugin] = plugin;
234
235 var menu = Y.Node.create('<div class="atto_' + plugin + '_menu' +
236 ' atto_menu" data-editor="' + Y.Escape.html(elementid) + '"></div>');
237 var i = 0, entry = {};
238
239 for (i = 0; i < entries.length; i++) {
240 entry = entries[i];
241
242 menu.append(Y.Node.create('<div class="atto_menuentry">' +
243 '<a href="#" class="atto_' + plugin + '_action_' + i + '" ' +
244 'data-editor="' + Y.Escape.html(elementid) + '" ' +
245 'data-plugin="' + Y.Escape.html(plugin) + '" ' +
246 'data-handler="' + Y.Escape.html(plugin + '_action_' + i) + '">' +
247 entry.text +
248 '</a>' +
249 '</div>'));
250 if (!M.editor_atto.buttonhandlers[plugin + '_action_' + i]) {
251 Y.one('body').delegate('click', M.editor_atto.buttonclicked_handler, '.atto_' + plugin + '_action_' + i);
252 Y.one('body').delegate('key', M.editor_atto.buttonclicked_handler, 'space,enter', '.atto_' + plugin + '_action_' + i);
253 M.editor_atto.buttonhandlers[plugin + '_action_' + i] = entry.handler;
254 }
255 }
256
257 if (!M.editor_atto.buttonhandlers[plugin]) {
258 Y.one('body').delegate('click', M.editor_atto.showhide_menu_handler, '.atto_' + plugin + '_button');
259 M.editor_atto.buttonhandlers[plugin] = true;
260 }
261
262 var overlay = new M.core.dialogue({
263 bodyContent : menu,
264 visible : false,
265 width: '14em',
266 zindex: 100,
267 lightbox: false,
268 closeButton: false,
269 centered : false,
270 align: {node: button, points: [Y.WidgetPositionAlign.TL, Y.WidgetPositionAlign.BL]}
271 });
272
273 M.editor_atto.menus[plugin + '_' + elementid] = overlay;
274 overlay.render();
275 overlay.hide();
276 overlay.headerNode.hide();
277 },
278
279 /**
280 * Add a button to the toolbar belonging to the editor for element with id "elementid".
281 * @param string elementid - the id of the textarea we created this editor from.
282 * @param string plugin - the plugin defining the button.
283 * @param string icon - the html used for the content of the button.
284 * @param string groupname - the group the button should be appended to.
285 * @handler function handler- A function to call when the button is clicked.
286 */
287 add_toolbar_button : function(elementid, plugin, icon, groupname, handler) {
288 var toolbar = Y.one('#' + elementid + '_toolbar'),
289 group = Y.one('#' + elementid + '_toolbar .atto_group.' + groupname + '_group'),
290 button,
291 currentfocus,
292 imgurl;
293
294 if (!group) {
295 group = Y.Node.create('<div class="atto_group ' + groupname +'_group"></div>');
296 toolbar.append(group);
297 }
298 imgurl = M.util.image_url(icon[0], icon[1]);
299 button = Y.Node.create('<button class="atto_' + plugin + '_button" ' +
300 'data-editor="' + Y.Escape.html(elementid) + '" ' +
301 'data-plugin="' + Y.Escape.html(plugin) + '" ' +
302 'tabindex="-1" ' +
303 'data-handler="' + Y.Escape.html(plugin) + '" ' +
304 'title="' + Y.Escape.html(M.util.get_string('pluginname', 'atto_' + plugin)) + '">' +
305 '<img class="icon" aria-hidden="true" role="presentation" width="16" height="16" src="' + imgurl + '"/>' +
306 '</button>');
307
308 group.append(button);
309
310 currentfocus = toolbar.getAttribute('aria-activedescendant');
311 if (!currentfocus) {
312 button.setAttribute('tabindex', '0');
313 toolbar.setAttribute('aria-activedescendant', button.generateID());
314 }
315
316 // We only need to attach this once.
317 if (!M.editor_atto.buttonhandlers[plugin]) {
318 Y.one('body').delegate('click', M.editor_atto.buttonclicked_handler, '.atto_' + plugin + '_button');
319 M.editor_atto.buttonhandlers[plugin] = handler;
320 }
321
322 // Save the name of the plugin.
323 M.editor_atto.widgets[plugin] = plugin;
324
325 },
326
327 /**
328 * Work out if the cursor is in the editable area for this editor instance.
329 * @param string elementid of this editor
330 * @return bool
331 */
332 is_active : function(elementid) {
333 var selection = M.editor_atto.get_selection();
334
335 if (selection.length) {
336 selection = selection.pop();
337 }
338
339 var node = null;
340 if (selection.parentElement) {
341 node = Y.one(selection.parentElement());
342 } else {
343 node = Y.one(selection.startContainer);
344 }
345
346 return node && node.ancestor('#' + elementid + 'editable') !== null;
347 },
348
349 /**
350 * Focus on the editable area for this editor.
351 * @param string elementid of this editor
352 */
353 focus : function(elementid) {
354 Y.one('#' + elementid + 'editable').focus();
355 },
356
357 /**
358 * Initialise the editor
359 * @param object params for this editor instance.
360 */
361 init : function(params) {
362 var textarea = Y.one('#' +params.elementid);
363 var wrapper = Y.Node.create('<div class="' + CSS.WRAPPER + '" />');
364 var atto = Y.Node.create('<div id="' + params.elementid + 'editable" ' +
365 'contenteditable="true" ' +
366 'spellcheck="true" ' +
367 'class="' + CSS.CONTENT + '" />');
368
369 var cssfont = '';
370 var toolbar = Y.Node.create('<div class="' + CSS.TOOLBAR + '" id="' + params.elementid + '_toolbar" role="toolbar"/>');
371
372 // Editable content wrapper.
373 var content = Y.Node.create('<div class="' + CSS.CONTENTWRAPPER + '" />');
374 content.appendChild(atto);
375
376 // Add everything to the wrapper.
377 wrapper.appendChild(toolbar);
378 wrapper.appendChild(content);
379
380 // Bleh - why are we sent a url and not the css to apply directly?
381 var css = Y.io(params.content_css, { sync: true });
382 var pos = css.responseText.indexOf('font:');
383 if (pos) {
384 cssfont = css.responseText.substring(pos + 'font:'.length, css.responseText.length - 1);
385 atto.setStyle('font', cssfont);
386 }
387 atto.setStyle('minHeight', (1.2 * (textarea.getAttribute('rows'))) + 'em');
388
389 // Copy text to editable div.
390 atto.append(textarea.get('value'));
391
392 // Add the toolbar and editable zone to the page.
393 textarea.get('parentNode').insert(wrapper, textarea);
394 atto.setStyle('color', textarea.getStyle('color'));
395 atto.setStyle('lineHeight', textarea.getStyle('lineHeight'));
396 atto.setStyle('fontSize', textarea.getStyle('fontSize'));
397 // Hide the old textarea.
398 textarea.hide();
399
400 // Copy the current value back to the textarea when focus leaves us.
401 atto.on('blur', function() {
402 this.text_updated(params.elementid);
403 }, this);
404
405 // Listen for Arrow left and Arrow right keys.
406 Y.one(Y.config.doc.body).delegate('key',
407 this.keyboard_navigation,
408 'down:37,39',
409 '#' + params.elementid + '_toolbar',
410 this,
411 params.elementid);
412
413 // Save the file picker options for later.
414 M.editor_atto.filepickeroptions[params.elementid] = params.filepickeroptions;
415 },
416
417 /**
418 * The text in the contenteditable region has been updated,
419 * clean and copy the buffer to the text area.
420 * @param string elementid - the id of the textarea we created this editor from.
421 */
422 text_updated : function(elementid) {
423 var textarea = Y.one('#' + elementid),
424 cleancontent = this.get_clean_html(elementid);
425 textarea.set('value', cleancontent);
426 // Trigger handlers for this action.
427 var i = 0;
428 if (elementid in M.editor_atto.textupdatedhandlers) {
429 for (i = 0; i < M.editor_atto.textupdatedhandlers[elementid].length; i++) {
430 var callback = M.editor_atto.textupdatedhandlers[elementid][i];
431 callback(elementid);
432 }
433 }
434 },
435
436 /**
437 * Remove all YUI ids from the generated HTML.
438 * @param string elementid - the id of the textarea we created this editor from.
439 * @return string HTML stripped of YUI ids
440 */
441 get_clean_html : function(elementid) {
442 var atto = Y.one('#' + elementid + 'editable').cloneNode(true);
443
444 Y.each(atto.all('[id]'), function(node) {
445 var id = node.get('id');
446 if (id.indexOf('yui') === 0) {
447 node.removeAttribute('id');
448 }
449 });
450
451 Y.each(atto.all('.atto_control'), function(node) {
452 node.remove(true);
453 });
454
455 return atto.getHTML();
456 },
457
458 /**
459 * Implement arrow key navigation for the buttons in the toolbar.
460 * @param Event e - the keyboard event.
461 * @param string elementid - the id of the textarea we created this editor from.
462 */
463 keyboard_navigation : function(e, elementid) {
464 var buttons,
465 current,
466 currentid,
467 currentindex;
468
469 e.preventDefault();
470
471 buttons = Y.all('#' + elementid + '_toolbar button');
472 currentid = Y.one('#' + elementid + '_toolbar').getAttribute('aria-activedescendant');
473 if (!currentid) {
474 return;
475 }
476 current = Y.one('#' + currentid);
477 current.setAttribute('tabindex', '-1');
478
479 currentindex = buttons.indexOf(current);
480
481 if (e.keyCode === 37) {
482 // Left
483 currentindex--;
484 if (currentindex < 0) {
485 currentindex = buttons.size()-1;
486 }
487 } else {
488 // Right
489 currentindex++;
490 if (currentindex >= buttons.size()) {
491 currentindex = 0;
492 }
493 }
494
495 current = buttons.item(currentindex);
496 current.setAttribute('tabindex', '0');
497 current.focus();
498 Y.one('#' + elementid + '_toolbar').setAttribute('aria-activedescendant', current.generateID());
499 },
500
501 /**
502 * Show the filepicker.
503 * @param string elementid for this editor instance.
504 * @param string type The media type for the file picker
505 * @param function callback
506 */
507 show_filepicker : function(elementid, type, callback) {
508 Y.use('core_filepicker', function (Y) {
509 var options = M.editor_atto.filepickeroptions[elementid][type];
510
511 options.formcallback = callback;
512 options.editor_target = Y.one(elementid);
513
514 M.core_filepicker.show(Y, options);
515 });
516 },
517
518 /**
519 * Create a cross browser selection object that represents a yui node.
520 * @param Node yui node for the selection
521 * @return range (browser dependent)
522 */
523 get_selection_from_node: function(node) {
524 var range;
525
526 if (window.getSelection) {
527 range = document.createRange();
528
529 range.setStartBefore(node.getDOMNode());
530 range.setEndAfter(node.getDOMNode());
531 return [range];
532 } else if (document.selection) {
533 range = document.body.createTextRange();
534 range.moveToElementText(node.getDOMNode());
535 return range;
536 }
537 return false;
538 },
539
540 /**
541 * Get the selection object that can be passed back to set_selection.
542 * @return range (browser dependent)
543 */
544 get_selection : function() {
545 if (window.getSelection) {
546 var sel = window.getSelection();
547 var ranges = [], i = 0;
548 for (i = 0; i < sel.rangeCount; i++) {
549 ranges.push(sel.getRangeAt(i));
550 }
551 return ranges;
552 } else if (document.selection) {
553 // IE < 9
554 if (document.selection.createRange) {
555 return document.selection.createRange();
556 }
557 }
558 return false;
559 },
560
561 /**
562 * Check that a YUI node it at least partly contained by the selection.
563 * @param Range selection
564 * @param Y.Node node
565 * @return boolean
566 */
567 selection_contains_node : function(node) {
568 var range, sel;
569 if (window.getSelection) {
570 sel = window.getSelection();
571
572 if (sel.containsNode) {
573 return sel.containsNode(node.getDOMNode(), true);
574 }
575 }
576 sel = document.selection.createRange();
577 range = sel.duplicate();
578 range.moveToElementText(node.getDOMNode());
579 return sel.inRange(range);
580 },
581
582 /**
583 * Get the dom node representing the common anscestor of the selection nodes.
584 * @return DOMNode
585 */
586 get_selection_parent_node : function() {
587 var selection = M.editor_atto.get_selection();
588 if (selection.length > 0) {
589 return selection[0].commonAncestorContainer;
590 }
591 },
592
593 /**
594 * Get the list of child nodes of the selection.
595 * @return DOMNode[]
596 */
597 get_selection_text : function() {
598 var selection = M.editor_atto.get_selection();
599 if (selection.length > 0 && selection[0].cloneContents) {
600 return selection[0].cloneContents();
601 }
602 },
603
604 /**
605 * Set the current selection. Used to restore a selection.
606 */
607 set_selection : function(selection) {
608 var sel, i;
609
610 if (window.getSelection) {
611 sel = window.getSelection();
612 sel.removeAllRanges();
613 for (i = 0; i < selection.length; i++) {
614 sel.addRange(selection[i]);
615 }
616 } else if (document.selection) {
617 // IE < 9
618 if (selection.select) {
619 selection.select();
620 }
621 }
622 }
623
624};
625var CONTROLMENU_NAME = "Controlmenu",
626 CONTROLMENU;
627
628/**
629 * CONTROLMENU
630 * This is a drop down list of buttons triggered (and aligned to) a button.
631 *
632 * @namespace M.editor_atto.controlmenu
633 * @class controlmenu
634 * @constructor
635 * @extends M.core.dialogue
636 */
637CONTROLMENU = function(config) {
638 config.draggable = false;
639 config.centered = false;
640 config.width = 'auto';
641 config.lightbox = false;
642 //config.visible = false;
643 config.footerContent = '';
644 CONTROLMENU.superclass.constructor.apply(this, [config]);
645};
646
647Y.extend(CONTROLMENU, M.core.dialogue, {
648
649 /**
650 * Initialise the menu.
651 *
652 * @method initializer
653 * @return void
654 */
655 initializer : function(config) {
656 var body, headertext, bb;
657 CONTROLMENU.superclass.initializer.call(this, config);
658
659 bb = this.get('boundingBox');
660 bb.addClass('editor_atto_controlmenu');
661
662 // Close the menu when clicked outside (excluding the button that opened the menu).
663 body = this.bodyNode;
664
665 headertext = Y.Node.create('<h3/>');
666 headertext.addClass('accesshide');
667 headertext.setHTML(this.get('headerText'));
668 body.prepend(headertext);
669
670 body.on('clickoutside', function(e) {
671 if (this.get('visible')) {
672 // Note: we need to compare ids because for some reason - sometimes button is an Object, not a Y.Node.
673 if (!e.target.ancestor('.atto_control')) {
674 e.preventDefault();
675 this.hide();
676 }
677 }
678 }, this);
679 }
680
681}, {
682 NAME : CONTROLMENU_NAME,
683 ATTRS : {
684 /**
685 * The header for the drop down (only accessible to screen readers).
686 *
687 * @attribute headerText
688 * @type String
689 * @default ''
690 */
691 headerText : {
692 value : ''
693 }
694
695 }
696});
697
698M.editor_atto = M.editor_atto || {};
699M.editor_atto.controlmenu = CONTROLMENU;
700
701
702}, '@VERSION@', {"requires": ["node", "io", "overlay", "escape", "event", "moodle-core-notification"]});