Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * @module moodle-editor_atto-plugin
18
 * @submodule buttons
19
 */
20
 
21
/**
22
 * Button functions for an Atto Plugin.
23
 *
24
 * See {{#crossLink "M.editor_atto.EditorPlugin"}}{{/crossLink}} for details.
25
 *
26
 * @namespace M.editor_atto
27
 * @class EditorPluginButtons
28
 */
29
 
30
var MENUTEMPLATE = '' +
31
        '<button class="{{buttonClass}} atto_hasmenu" ' +
32
            'id="{{id}}" ' +
33
            'tabindex="-1" ' +
34
            'title="{{title}}" ' +
35
            'aria-label="{{title}}" ' +
36
            'type="button" ' +
37
            'aria-haspopup="true" ' +
38
            'aria-controls="{{id}}_menu">' +
39
            '<span class="editor_atto_menu_icon"></span>' +
40
            '<span class="editor_atto_menu_expand"></span>' +
41
        '</button>';
42
 
43
var DISABLED = 'disabled',
44
    HIGHLIGHT = 'highlight',
45
    LOGNAME = 'moodle-editor_atto-editor-plugin',
46
    CSS = {
47
        EDITORWRAPPER: '.editor_atto_content',
48
        MENUICON: '.editor_atto_menu_icon',
49
        MENUEXPAND: '.editor_atto_menu_expand'
50
    };
51
 
52
function EditorPluginButtons() {}
53
 
54
EditorPluginButtons.ATTRS = {
55
};
56
 
57
EditorPluginButtons.prototype = {
58
    /**
59
     * All of the buttons that belong to this plugin instance.
60
     *
61
     * Buttons are stored by button name.
62
     *
63
     * @property buttons
64
     * @type object
65
     */
66
    buttons: null,
67
 
68
    /**
69
     * A list of each of the button names.
70
     *
71
     * @property buttonNames
72
     * @type array
73
     */
74
    buttonNames: null,
75
 
76
    /**
77
     * A read-only view of the current state for each button. Mappings are stored by name.
78
     *
79
     * Possible states are:
80
     * <ul>
81
     * <li>{{#crossLink "M.editor_atto.EditorPluginButtons/ENABLED:property"}}{{/crossLink}}; and</li>
82
     * <li>{{#crossLink "M.editor_atto.EditorPluginButtons/DISABLED:property"}}{{/crossLink}}.</li>
83
     * </ul>
84
     *
85
     * @property buttonStates
86
     * @type object
87
     */
88
    buttonStates: null,
89
 
90
    /**
91
     * The menus belonging to this plugin instance.
92
     *
93
     * @property menus
94
     * @type object
95
     */
96
    menus: null,
97
 
98
    /**
99
     * The state for a disabled button.
100
     *
101
     * @property DISABLED
102
     * @type Number
103
     * @static
104
     * @value 0
105
     */
106
    DISABLED: 0,
107
 
108
    /**
109
     * The state for an enabled button.
110
     *
111
     * @property ENABLED
112
     * @type Number
113
     * @static
114
     * @value 1
115
     */
116
    ENABLED: 1,
117
 
118
    /**
119
     * The list of Event Handlers for buttons.
120
     *
121
     * @property _buttonHandlers
122
     * @protected
123
     * @type array
124
     */
125
    _buttonHandlers: null,
126
 
127
    /**
128
     * Hide handlers which are cancelled when the menu is hidden.
129
     *
130
     * @property _menuHideHandlers
131
     * @protected
132
     * @type array
133
     */
134
    _menuHideHandlers: null,
135
 
136
    /**
137
     * A textual description of the primary keyboard shortcut for this
138
     * plugin.
139
     *
140
     * This will be null if no keyboard shortcut has been registered.
141
     *
142
     * @property _primaryKeyboardShortcut
143
     * @protected
144
     * @type String
145
     * @default null
146
     */
147
    _primaryKeyboardShortcut: null,
148
 
149
    /**
150
     * An list of objects returned by Y.soon().
151
     *
152
     * The keys will be the buttonName of the button, and the value the Y.soon() object.
153
     *
154
     * @property _highlightQueue
155
     * @protected
156
     * @type Object
157
     * @default null
158
     */
159
    _highlightQueue: null,
160
 
161
    /**
162
     * Add a button for this plugin to the toolbar.
163
     *
164
     * @method addButton
165
     * @param {object} config The configuration for this button
166
     * @param {string} [config.iconurl] The URL for the icon. If not specified, then the icon and component will be used instead.
167
     * @param {string} [config.icon] The icon identifier.
168
     * @param {string} [config.iconComponent='core'] The icon component.
169
     * @param {string} [config.keys] The shortcut key that can call this plugin from the keyboard.
170
     * @param {string} [config.keyDescription] An optional description for the keyboard shortcuts.
171
     * If not specified, this is automatically generated based on config.keys.
172
     * If multiple key bindings are supplied to config.keys, then only the first is used.
173
     * If set to false, then no description is added to the title.
174
     * @param {string} [config.tags] The tags that trigger this button to be highlighted.
175
     * @param {boolean} [config.tagMatchRequiresAll=true] Working in combination with the tags parameter, when true
176
     * every tag of the selection has to match. When false, only one match is needed. Only set this to false when
177
     * necessary as it is much less efficient.
178
     * See {{#crossLink "M.editor_atto.EditorSelection/selectionFilterMatches:method"}}{{/crossLink}} for more information.
179
     * @param {string} [config.title=this.name] The string identifier in the plugin's language file.
180
     * @param {string} [config.buttonName=this.name] The name of the button. This is used in the buttons object, and if
181
     * specified, in the class for the button.
182
     * @param {function} config.callback A callback function to call when the button is clicked.
183
     * @param {object} [config.callbackArgs] Any arguments to pass to the callback.
184
     * @param {boolean} [config.inlineFormat] Delay callback for text input if selection is collapsed.
185
     * @return {Node} The Node representing the newly created button.
186
     */
187
    addButton: function(config) {
188
        var group = this.get('group'),
189
            pluginname = this.name,
190
            buttonClass = 'atto_' + pluginname + '_button',
191
            button,
192
            host = this.get('host');
193
 
194
        if (config.exec) {
195
            buttonClass = buttonClass + '_' + config.exec;
196
        }
197
 
198
        if (!config.buttonName) {
199
            // Set a default button name - this is used as an identifier in the button object.
200
            config.buttonName = config.exec || pluginname;
201
        } else {
202
            buttonClass = buttonClass + '_' + config.buttonName;
203
        }
204
        config.buttonClass = buttonClass;
205
 
206
        // Normalize icon configuration.
207
        config = this._normalizeIcon(config);
208
 
209
        if (!config.title) {
210
            config.title = 'pluginname';
211
        }
212
        var title = M.util.get_string(config.title, 'atto_' + pluginname);
213
 
214
        // Create the actual button.
215
        button = Y.Node.create('<button type="button" class="' + buttonClass + '"' +
216
                'tabindex="-1"></button>');
217
        button.setAttribute('title', title);
218
        button.setAttribute('aria-label', title);
219
        window.require(['core/templates'], function(Templates) {
220
            // The button already has title and label, so no need to set them again on the icon.
221
            Templates.renderPix(config.icon, config.iconComponent, '').then(function(iconhtml) {
222
                button.append(iconhtml);
223
            });
224
        });
225
 
226
        // Append it to the group.
227
        group.append(button);
228
 
229
        var currentfocus = this.toolbar.getAttribute('aria-activedescendant');
230
        if (!currentfocus) {
231
            // Initially set the first button in the toolbar to be the default on keyboard focus.
232
            button.setAttribute('tabindex', '0');
233
            this.toolbar.setAttribute('aria-activedescendant', button.generateID());
234
            this.get('host')._tabFocus = button;
235
        }
236
 
237
        // Normalize the callback parameters.
238
        config = this._normalizeCallback(config);
239
 
240
        // Add the standard click handler to the button.
241
        this._buttonHandlers.push(
242
            this.toolbar.delegate('click', config.callback, '.' + buttonClass, this)
243
        );
244
 
245
        // Handle button click via shortcut key.
246
        if (config.keys) {
247
            if (typeof config.keyDescription !== 'undefined') {
248
                // A keyboard shortcut description was specified - use it.
249
                this._primaryKeyboardShortcut[buttonClass] = config.keyDescription;
250
            }
251
            this._addKeyboardListener(config.callback, config.keys, buttonClass);
252
 
253
            if (this._primaryKeyboardShortcut[buttonClass]) {
254
                // If we have a valid keyboard shortcut description, then set it with the title.
255
                title = M.util.get_string('plugin_title_shortcut', 'editor_atto', {
256
                    title: title,
257
                    shortcut: this._primaryKeyboardShortcut[buttonClass]
258
                });
259
                button.setAttribute('title', title);
260
                button.setAttribute('aria-label', title);
261
            }
262
        }
263
 
264
        // Handle highlighting of the button.
265
        if (config.tags) {
266
            var tagMatchRequiresAll = true;
267
            if (typeof config.tagMatchRequiresAll === 'boolean') {
268
                tagMatchRequiresAll = config.tagMatchRequiresAll;
269
            }
270
            this._buttonHandlers.push(
271
                host.on(['atto:selectionchanged', 'change'], function(e) {
272
                    if (typeof this._highlightQueue[config.buttonName] !== 'undefined') {
273
                        this._highlightQueue[config.buttonName].cancel();
274
                    }
275
                    // Async the highlighting.
276
                    this._highlightQueue[config.buttonName] = Y.soon(Y.bind(function(e) {
277
                        if (host.selectionFilterMatches(config.tags, e.selectedNodes, tagMatchRequiresAll)) {
278
                            this.highlightButtons(config.buttonName);
279
                        } else {
280
                            this.unHighlightButtons(config.buttonName);
281
                        }
282
                    }, this, e));
283
                }, this)
284
            );
285
        }
286
 
287
        // Add the button reference to the buttons array for later reference.
288
        this.buttonNames.push(config.buttonName);
289
        this.buttons[config.buttonName] = button;
290
        this.buttonStates[config.buttonName] = this.ENABLED;
291
        return button;
292
    },
293
 
294
    /**
295
     * Add a basic button which ties into the execCommand.
296
     *
297
     * See {{#crossLink "M.editor_atto.EditorPluginButtons/addButton:method"}}addButton{{/crossLink}}
298
     * for full details of the optional parameters.
299
     *
300
     * @method addBasicButton
301
     * @param {object} config The button configuration
302
     * @param {string} config.exec The execCommand to call on the document.
303
     * @param {string} [config.iconurl] The URL for the icon. If not specified, then the icon and component will be used instead.
304
     * @param {string} [config.icon] The icon identifier.
305
     * @param {string} [config.iconComponent='core'] The icon component.
306
     * @param {string} [config.keys] The shortcut key that can call this plugin from the keyboard.
307
     * @param {string} [config.tags] The tags that trigger this button to be highlighted.
308
     * @param {boolean} [config.tagMatchRequiresAll=false] Working in combination with the tags parameter, highlight
309
     * this button when any match is good enough.
310
     *
311
     * See {{#crossLink "M.editor_atto.EditorSelection/selectionFilterMatches:method"}}{{/crossLink}} for more information.
312
     * @param {string} [config.title=this.name] The string identifier in the plugin's language file.
313
     * @param {string} [config.buttonName=this.name] The name of the button. This is used in the buttons object, and if
314
     * specified, in the class for the button.
315
     * @return {Node} The Node representing the newly created button.
316
     */
317
    addBasicButton: function(config) {
318
        if (!config.exec) {
319
            Y.log('No exec command specified. Cannot proceed.',
320
                    'warn', 'moodle-editor_atto-plugin');
321
            return null;
322
        }
323
 
324
        // The default icon - true for most core plugins.
325
        if (!config.icon) {
326
            config.icon = 'e/' + config.exec;
327
        }
328
 
329
        // The default callback.
330
        config.callback = function() {
331
            document.execCommand(config.exec, false, null);
332
 
333
            // And mark the text area as updated.
334
            this.markUpdated();
335
        };
336
 
337
        // Return the newly created button.
338
        return this.addButton(config);
339
    },
340
 
341
    /**
342
     * Add a menu for this plugin to the editor toolbar.
343
     *
344
     * @method addToolbarMenu
345
     * @param {object} config The configuration for this button
346
     * @param {string} [config.iconurl] The URL for the icon. If not specified, then the icon and component will be used instead.
347
     * @param {string} [config.icon] The icon identifier.
348
     * @param {string} [config.iconComponent='core'] The icon component.
349
     * @param {string} [config.title=this.name] The string identifier in the plugin's language file.
350
     * @param {string} [config.buttonName=this.name] The name of the button. This is used in the buttons object, and if
351
     * specified, in the class for the button.
352
     * @param {function} config.callback A callback function to call when the button is clicked.
353
     * @param {object} [config.callbackArgs] Any arguments to pass to the callback.
354
     * @param {boolean} [config.inlineFormat] Delay callback for text input if selection is collapsed.
355
     * @param {array} config.entries List of menu entries with the string (entry.text) and the handlers (entry.handler).
356
     * @param {number} [config.overlayWidth=14] The width of the menu. This will be suffixed with the 'em' unit.
357
     * @param {string} [config.menuColor] menu icon background color
358
     * @return {Node} The Node representing the newly created button.
359
     */
360
    addToolbarMenu: function(config) {
361
        var group = this.get('group'),
362
            pluginname = this.name,
363
            buttonClass = 'atto_' + pluginname + '_button',
364
            button,
365
            currentFocus;
366
 
367
        if (!config.buttonName) {
368
            // Set a default button name - this is used as an identifier in the button object.
369
            config.buttonName = pluginname;
370
        } else {
371
            buttonClass = buttonClass + '_' + config.buttonName;
372
        }
373
        config.buttonClass = buttonClass;
374
 
375
        // Normalize icon configuration.
376
        config = this._normalizeIcon(config);
377
 
378
        if (!config.title) {
379
            config.title = 'pluginname';
380
        }
381
        var title = M.util.get_string(config.title, 'atto_' + pluginname);
382
 
383
        if (!config.menuColor) {
384
            config.menuColor = 'transparent';
385
        }
386
 
387
        // Create the actual button.
388
        var id = 'atto_' + pluginname + '_menubutton_' + Y.stamp(this);
389
        var template = Y.Handlebars.compile(MENUTEMPLATE);
390
        button = Y.Node.create(template({
391
            buttonClass: buttonClass,
392
            config: config,
393
            title: title,
394
            id: id
395
        }));
396
 
397
        // Add this button id to the config. It will be used in the menu later.
398
        config.buttonId = id;
399
 
400
        window.require(['core/templates'], function(Templates) {
401
            // The button already has title and label, so no need to set them again on the icon.
402
            Templates.renderPix(config.icon, config.iconComponent, '').then(function(iconhtml) {
403
                button.one(CSS.MENUICON).append(iconhtml);
404
            });
405
            Templates.renderPix('t/expanded', 'core', '').then(function(iconhtml) {
406
                button.one(CSS.MENUEXPAND).append(iconhtml);
407
            });
408
        });
409
 
410
        // Append it to the group.
411
        group.append(button);
412
        group.append(Y.Node.create('<div class="menuplaceholder" id="' + id + '_menu"></div>'));
413
        config.attachmentPoint = '#' + id + '_menu';
414
 
415
        currentFocus = this.toolbar.getAttribute('aria-activedescendant');
416
        if (!currentFocus) {
417
            // Initially set the first button in the toolbar to be the default on keyboard focus.
418
            button.setAttribute('tabindex', '0');
419
            this.toolbar.setAttribute('aria-activedescendant', button.generateID());
420
        }
421
 
422
        // Add the standard click handler to the menu.
423
        this._buttonHandlers.push(
424
            this.toolbar.delegate('click', this._showToolbarMenu, '.' + buttonClass, this, config),
425
            this.toolbar.delegate('key', this._showToolbarMenuAndFocus, '40, 32, enter', '.' + buttonClass, this, config)
426
        );
427
 
428
        // Add the button reference to the buttons array for later reference.
429
        this.buttonNames.push(config.buttonName);
430
        this.buttons[config.buttonName] = button;
431
        this.buttonStates[config.buttonName] = this.ENABLED;
432
 
433
        return button;
434
    },
435
 
436
    /**
437
     * Display a toolbar menu.
438
     *
439
     * @method _showToolbarMenu
440
     * @param {EventFacade} e
441
     * @param {object} config The configuration for the whole toolbar.
442
     * @param {Number} [config.overlayWidth=14] The width of the menu
443
     * @private
444
     */
445
    _showToolbarMenu: function(e, config) {
446
        // Prevent default primarily to prevent arrow press changes.
447
        e.preventDefault();
448
 
449
        if (!this.isEnabled()) {
450
            // Exit early if the plugin is disabled.
451
            return;
452
        }
453
 
454
        // Ensure menu button was clicked, and isn't itself disabled.
455
        var menuButton = e.currentTarget.ancestor('button', true);
456
        if (menuButton === null || menuButton.hasAttribute(DISABLED)) {
457
            return;
458
        }
459
 
460
        var menuDialogue;
461
 
462
        if (!this.menus[config.buttonClass]) {
463
            if (!config.overlayWidth) {
464
                config.overlayWidth = '14';
465
            }
466
 
467
            if (!config.innerOverlayWidth) {
468
                config.innerOverlayWidth = parseInt(config.overlayWidth, 10) - 2 + 'em';
469
            }
470
            config.overlayWidth = parseInt(config.overlayWidth, 10) + 'em';
471
 
472
            this.menus[config.buttonClass] = new Y.M.editor_atto.Menu(config);
473
 
474
            this.menus[config.buttonClass].get('contentBox').delegate('click',
475
                    this._chooseMenuItem, '.atto_menuentry a', this, config);
476
        }
477
 
478
        // Clear the focusAfterHide for any other menus which may be open.
479
        Y.Array.each(this.get('host').openMenus, function(menu) {
480
            menu.set('focusAfterHide', null);
481
        });
482
 
483
        // Ensure that we focus on this button next time.
484
        var creatorButton = this.buttons[config.buttonName];
485
        creatorButton.focus();
486
        this.get('host')._setTabFocus(creatorButton);
487
 
488
        // Get a reference to the menu dialogue.
489
        menuDialogue = this.menus[config.buttonClass];
490
 
491
        // Focus on the button by default after hiding this menu.
492
        menuDialogue.set('focusAfterHide', creatorButton);
493
 
494
        // Display the menu.
495
        menuDialogue.show();
496
 
497
        // Indicate that the menu is expanded.
498
        menuButton.setAttribute("aria-expanded", true);
499
 
500
        // Position it next to the button which opened it.
501
        menuDialogue.align(this.buttons[config.buttonName], [Y.WidgetPositionAlign.TL, Y.WidgetPositionAlign.BL]);
502
 
503
        this.get('host').openMenus = [menuDialogue];
504
    },
505
 
506
    /**
507
     * Display a toolbar menu and focus upon the first item.
508
     *
509
     * @method _showToolbarMenuAndFocus
510
     * @param {EventFacade} e
511
     * @param {object} config The configuration for the whole toolbar.
512
     * @param {Number} [config.overlayWidth=14] The width of the menu
513
     * @private
514
     */
515
    _showToolbarMenuAndFocus: function(e, config) {
516
        this._showToolbarMenu(e, config);
517
 
518
        // Focus on the first element in the menu.
519
        this.menus[config.buttonClass].get('boundingBox').one('a').focus();
520
    },
521
 
522
    /**
523
     * Select a menu item and call the appropriate callbacks.
524
     *
525
     * @method _chooseMenuItem
526
     * @param {EventFacade} e
527
     * @param {object} config
528
     * @param {M.core.dialogue} menuDialogue The Dialogue to hide.
529
     * @private
530
     */
531
    _chooseMenuItem: function(e, config, menuDialogue) {
532
        // Get the index from the clicked anchor.
533
        var index = e.target.ancestor('a', true).getData('index'),
534
 
535
            // And the normalized callback configuration.
536
            buttonConfig = this._normalizeCallback(config.items[index], config.globalItemConfig);
537
 
538
            menuDialogue = this.menus[config.buttonClass];
539
 
540
        // Prevent the dialogue to be closed because of some browser weirdness.
541
        menuDialogue.set('preventHideMenu', true);
542
 
543
        // Call the callback for this button.
544
        buttonConfig.callback(e, buttonConfig._callback, buttonConfig.callbackArgs);
545
 
546
        // Cancel the hide menu prevention.
547
        menuDialogue.set('preventHideMenu', false);
548
 
549
        // Set the focus after hide so that focus is returned to the editor and changes are made correctly.
550
        menuDialogue.set('focusAfterHide', this.get('host').editor);
551
        menuDialogue.hide(e);
552
    },
553
 
554
    /**
555
     * Normalize and sanitize the configuration variables relating to callbacks.
556
     *
557
     * @method _normalizeCallback
558
     * @param {object} config
559
     * @param {function} config.callback A callback function to call when the button is clicked.
560
     * @param {object} [config.callbackArgs] Any arguments to pass to the callback.
561
     * @param {boolean} [config.inlineFormat] Delay callback for text input if selection is collapsed.
562
     * @param {object} [inheritFrom] A parent configuration that this configuration may inherit from.
563
     * @return {object} The normalized configuration
564
     * @private
565
     */
566
    _normalizeCallback: function(config, inheritFrom) {
567
        if (config._callbackNormalized) {
568
            // Return early if the callback has already been normalized.
569
            return config;
570
        }
571
 
572
        if (!inheritFrom) {
573
            // Create an empty inheritFrom to make life easier below.
574
            inheritFrom = {};
575
        }
576
 
577
 
578
        // First we wrap the callback in function to handle formating of text inserted into collapsed selection.
579
        config.inlineFormat = config.inlineFormat || inheritFrom.inlineFormat;
580
        config._inlineCallback = config.callback || inheritFrom.callback;
581
        config._callback = config.callback || inheritFrom.callback;
582
        if (config.inlineFormat && typeof config._inlineCallback === 'function') {
583
            config._callback = function(e, args) {
584
                this.get('host').applyFormat(e, config._inlineCallback, this, args);
585
            };
586
        }
587
        // We wrap the callback in function to prevent the default action, check whether the editor is
588
        // active and focus it, and then mark the field as updated.
589
        config.callback = Y.rbind(this._callbackWrapper, this, config._callback, config.callbackArgs);
590
 
591
        config._callbackNormalized = true;
592
 
593
        return config;
594
    },
595
 
596
    /**
597
     * Normalize and sanitize the configuration variables relating to icons.
598
     *
599
     * @method _normalizeIcon
600
     * @param {object} config
601
     * @param {string} [config.iconurl] The URL for the icon. If not specified, then the icon and component will be used instead.
602
     * @param {string} [config.icon] The icon identifier.
603
     * @param {string} [config.iconComponent='core'] The icon component.
604
     * @return {object} The normalized configuration
605
     * @private
606
     */
607
    _normalizeIcon: function(config) {
608
        if (!config.iconurl) {
609
            // The default icon component.
610
            if (!config.iconComponent || config.iconComponent == 'moodle') {
611
                config.iconComponent = 'core';
612
            }
613
            config.iconurl = M.util.image_url(config.icon, config.iconComponent);
614
        }
615
 
616
        return config;
617
    },
618
 
619
    /**
620
     * A wrapper in which to run the callbacks.
621
     *
622
     * This handles common functionality such as:
623
     * <ul>
624
     *  <li>preventing the default action; and</li>
625
     *  <li>focusing the editor if relevant.</li>
626
     * </ul>
627
     *
628
     * @method _callbackWrapper
629
     * @param {EventFacade} e
630
     * @param {Function} callback The function to call which makes the relevant changes.
631
     * @param {Array} [callbackArgs] The arguments passed to this callback.
632
     * @return {Mixed} The value returned by the callback.
633
     * @private
634
     */
635
    _callbackWrapper: function(e, callback, callbackArgs) {
636
        e.preventDefault();
637
 
638
        if (!this.isEnabled()) {
639
            // Exit early if the plugin is disabled.
640
            return;
641
        }
642
 
643
        var creatorButton = e.currentTarget.ancestor('button', true);
644
 
645
        if (creatorButton && creatorButton.hasAttribute(DISABLED)) {
646
            // Exit early if the clicked button was disabled.
647
            return;
648
        }
649
 
650
        if (!(YUI.Env.UA.android || this.get('host').isActive())) {
651
            // We must not focus for Android here, even if the editor is not active because the keyboard auto-completion
652
            // changes the cursor position.
653
            // If we save that change, then when we restore the change later we get put in the wrong place.
654
            // Android is fine to save the selection without the editor being in focus.
655
            this.get('host').focus();
656
        }
657
 
658
        // Save the selection.
659
        this.get('host').saveSelection();
660
 
661
        // Ensure that we focus on this button next time.
662
        if (creatorButton) {
663
            this.get('host')._setTabFocus(creatorButton);
664
        }
665
 
666
        // Build the arguments list, but remove the callback we're calling.
667
        var args = [e, callbackArgs];
668
 
669
        // Restore selection before making changes.
670
        this.get('host').restoreSelection();
671
 
672
        // Actually call the callback now.
673
        return callback.apply(this, args);
674
    },
675
 
676
    /**
677
     * Add a keyboard listener to call the callback.
678
     *
679
     * The keyConfig will take either an array of keyConfigurations, in
680
     * which case _addKeyboardListener is called multiple times; an object
681
     * containing an optional eventtype, optional container, and a set of
682
     * keyCodes, or just a string containing the keyCodes. When keyConfig is
683
     * not an object, it is wrapped around a function that ensures that
684
     * only the expected key modifiers were used. For instance, it checks
685
     * that space+ctrl is not triggered when the user presses ctrl+shift+space.
686
     * When using an object, the developer should check that manually.
687
     *
688
     * @method _addKeyboardListener
689
     * @param {function} callback
690
     * @param {array|object|string} keyConfig
691
     * @param {string} [keyConfig.eventtype=key] The type of event
692
     * @param {string} [keyConfig.container=.editor_atto_content] The containing element.
693
     * @param {string} keyConfig.keyCodes The keycodes to user for the event.
694
     * @private
695
     *
696
     */
697
    _addKeyboardListener: function(callback, keyConfig, buttonName) {
698
        var eventtype = 'key',
699
            container = CSS.EDITORWRAPPER,
700
            keys,
701
            handler,
702
            modifier;
703
 
704
        if (Y.Lang.isArray(keyConfig)) {
705
            // If an Array was specified, call the add function for each element.
706
            Y.Array.each(keyConfig, function(config) {
707
                this._addKeyboardListener(callback, config);
708
            }, this);
709
 
710
            return this;
711
 
712
        } else if (typeof keyConfig === "object") {
713
            if (keyConfig.eventtype) {
714
                eventtype = keyConfig.eventtype;
715
            }
716
 
717
            if (keyConfig.container) {
718
                container = keyConfig.container;
719
            }
720
 
721
            // Must be specified.
722
            keys = keyConfig.keyCodes;
723
            handler = callback;
724
 
725
        } else {
726
            modifier = this._getDefaultMetaKey();
727
            keys = this._getKeyEvent() + keyConfig + '+' + modifier;
728
            if (typeof this._primaryKeyboardShortcut[buttonName] === 'undefined') {
729
                this._primaryKeyboardShortcut[buttonName] = this._getDefaultMetaKeyDescription(keyConfig);
730
            }
731
 
732
            // Wrap the callback into a handler to check if it uses the specified modifiers, not more.
733
            handler = Y.bind(function(modifiers, e) {
734
                if (this._eventUsesExactKeyModifiers(modifiers, e)) {
735
                    callback.apply(this, [e]);
736
                }
737
            }, this, [modifier]);
738
        }
739
 
740
        this._buttonHandlers.push(
741
            this.editor.delegate(
742
                eventtype,
743
                handler,
744
                keys,
745
                container,
746
                this
747
            )
748
        );
749
 
750
        Y.log('Atto shortcut registered: ' + keys + ' now triggers for ' + buttonName,
751
                'debug', LOGNAME);
752
    },
753
 
754
    /**
755
     * Checks if a key event was strictly defined for the modifiers passed.
756
     *
757
     * @method _eventUsesExactKeyModifiers
758
     * @param  {Array} modifiers List of key modifiers to check for (alt, ctrl, meta or shift).
759
     * @param  {EventFacade} e The event facade.
760
     * @return {Boolean} True if the event was stricly using the modifiers specified.
761
     */
762
    _eventUsesExactKeyModifiers: function(modifiers, e) {
763
        var exactMatch = true,
764
            hasKey;
765
 
766
        if (e.type !== 'key') {
767
            return false;
768
        }
769
 
770
        hasKey = Y.Array.indexOf(modifiers, 'alt') > -1;
771
        exactMatch = exactMatch && ((e.altKey && hasKey) || (!e.altKey && !hasKey));
772
        hasKey = Y.Array.indexOf(modifiers, 'ctrl') > -1;
773
        exactMatch = exactMatch && ((e.ctrlKey && hasKey) || (!e.ctrlKey && !hasKey));
774
        hasKey = Y.Array.indexOf(modifiers, 'meta') > -1;
775
        exactMatch = exactMatch && ((e.metaKey && hasKey) || (!e.metaKey && !hasKey));
776
        hasKey = Y.Array.indexOf(modifiers, 'shift') > -1;
777
        exactMatch = exactMatch && ((e.shiftKey && hasKey) || (!e.shiftKey && !hasKey));
778
 
779
        return exactMatch;
780
    },
781
 
782
    /**
783
     * Determine if this plugin is enabled, based upon the state of it's buttons.
784
     *
785
     * @method isEnabled
786
     * @return {boolean}
787
     */
788
    isEnabled: function() {
789
        // The first instance of an undisabled button will make this return true.
790
        var found = Y.Object.some(this.buttonStates, function(button) {
791
            return (button === this.ENABLED);
792
        }, this);
793
 
794
        return found;
795
    },
796
 
797
    /**
798
     * Enable one button, or all buttons relating to this Plugin.
799
     *
800
     * If no button is specified, all buttons are disabled.
801
     *
802
     * @method disableButtons
803
     * @param {String} [button] The name of a specific plugin to enable.
804
     * @chainable
805
     */
806
    disableButtons: function(button) {
807
        return this._setButtonState(false, button);
808
    },
809
 
810
    /**
811
     * Enable one button, or all buttons relating to this Plugin.
812
     *
813
     * If no button is specified, all buttons are enabled.
814
     *
815
     * @method enableButtons
816
     * @param {String} [button] The name of a specific plugin to enable.
817
     * @chainable
818
     */
819
    enableButtons: function(button) {
820
        return this._setButtonState(true, button);
821
    },
822
 
823
    /**
824
     * Set the button state for one button, or all buttons associated with this plugin.
825
     *
826
     * @method _setButtonState
827
     * @param {Boolean} enable Whether to enable this button.
828
     * @param {String} [button] The name of a specific plugin to set state for.
829
     * @chainable
830
     * @private
831
     */
832
    _setButtonState: function(enable, button) {
833
        var attributeChange = 'setAttribute';
834
        if (enable) {
835
            attributeChange = 'removeAttribute';
836
        }
837
        if (button) {
838
            if (this.buttons[button]) {
839
                this.buttons[button][attributeChange](DISABLED, DISABLED);
840
                this.buttonStates[button] = enable ? this.ENABLED : this.DISABLED;
841
            }
842
        } else {
843
            Y.Array.each(this.buttonNames, function(button) {
844
                this.buttons[button][attributeChange](DISABLED, DISABLED);
845
                this.buttonStates[button] = enable ? this.ENABLED : this.DISABLED;
846
            }, this);
847
        }
848
 
849
        this.get('host').checkTabFocus();
850
        return this;
851
    },
852
 
853
    /**
854
     * Highlight a button, or buttons in the toolbar.
855
     *
856
     * If no button is specified, all buttons are highlighted.
857
     *
858
     * @method highlightButtons
859
     * @param {string} [button] If a plugin has multiple buttons, the specific button to highlight.
860
     * @chainable
861
     */
862
    highlightButtons: function(button) {
863
        return this._changeButtonHighlight(true, button);
864
    },
865
 
866
    /**
867
     * Un-highlight a button, or buttons in the toolbar.
868
     *
869
     * If no button is specified, all buttons are un-highlighted.
870
     *
871
     * @method unHighlightButtons
872
     * @param {string} [button] If a plugin has multiple buttons, the specific button to highlight.
873
     * @chainable
874
     */
875
    unHighlightButtons: function(button) {
876
        return this._changeButtonHighlight(false, button);
877
    },
878
 
879
    /**
880
     * Highlight a button, or buttons in the toolbar.
881
     *
882
     * @method _changeButtonHighlight
883
     * @param {boolean} highlight true
884
     * @param {string} [button] If a plugin has multiple buttons, the specific button to highlight.
885
     * @protected
886
     * @chainable
887
     */
888
    _changeButtonHighlight: function(highlight, button) {
889
        var method = 'addClass';
890
 
891
        if (!highlight) {
892
            method = 'removeClass';
893
        }
894
        if (button) {
895
            if (this.buttons[button]) {
896
                this.buttons[button][method](HIGHLIGHT);
897
                this.buttons[button].setAttribute('aria-pressed', highlight ? 'true' : 'false');
898
                this._buttonHighlightToggled(button, highlight);
899
            }
900
        } else {
901
            Y.Object.each(this.buttons, function(button) {
902
                button[method](HIGHLIGHT);
903
                button.setAttribute('aria-pressed', highlight ? 'true' : 'false');
904
                this._buttonHighlightToggled(button, highlight);
905
            }, this);
906
        }
907
 
908
        return this;
909
    },
910
 
911
    /**
912
     * Fires a custom event that notifies listeners that a button's highlight has been toggled.
913
     *
914
     * @param {String} buttonName The button name.
915
     * @param {Boolean} highlight True when the button was highlighted. False, otherwise.
916
     * @private
917
     */
918
    _buttonHighlightToggled: function(buttonName, highlight) {
919
        var toggledButton = this.buttons[buttonName];
920
        if (toggledButton) {
921
            // Fire an event that the button highlight was toggled.
922
            require(['editor_atto/events'], function(attoEvents) {
923
                attoEvents.notifyButtonHighlightToggled(toggledButton.getDOMNode(), buttonName, highlight);
924
            });
925
        }
926
    },
927
 
928
    /**
929
     * Get the default meta key to use with keyboard events.
930
     *
931
     * On a Mac, this will be the 'meta' key for Command; otherwise it will
932
     * be the Control key.
933
     *
934
     * @method _getDefaultMetaKey
935
     * @return {string}
936
     * @private
937
     */
938
    _getDefaultMetaKey: function() {
939
        if (Y.UA.os === 'macintosh') {
940
            return 'meta';
941
        } else {
942
            return 'ctrl';
943
        }
944
    },
945
 
946
    /**
947
     * Get the user-visible description of the meta key to use with keyboard events.
948
     *
949
     * On a Mac, this will be 'Command' ; otherwise it will be 'Control'.
950
     *
951
     * @method _getDefaultMetaKeyDescription
952
     * @return {string}
953
     * @private
954
     */
955
    _getDefaultMetaKeyDescription: function(keyCode) {
956
        if (Y.UA.os === 'macintosh') {
957
            return M.util.get_string('editor_command_keycode', 'editor_atto', String.fromCharCode(keyCode).toLowerCase());
958
        } else {
959
            return M.util.get_string('editor_control_keycode', 'editor_atto', String.fromCharCode(keyCode).toLowerCase());
960
        }
961
    },
962
 
963
    /**
964
     * Get the standard key event to use for keyboard events.
965
     *
966
     * @method _getKeyEvent
967
     * @return {string}
968
     * @private
969
     */
970
    _getKeyEvent: function() {
971
        return 'down:';
972
    }
973
};
974
 
975
Y.Base.mix(Y.M.editor_atto.EditorPlugin, [EditorPluginButtons]);