]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/tinymce/plugins/wordpress/plugin.js
WordPress 4.4
[autoinstalls/wordpress.git] / wp-includes / js / tinymce / plugins / wordpress / plugin.js
1 /* global getUserSetting, setUserSetting */
2 ( function( tinymce ) {
3 // Set the minimum value for the modals z-index higher than #wpadminbar (100000)
4 tinymce.ui.FloatPanel.zIndex = 100100;
5
6 tinymce.PluginManager.add( 'wordpress', function( editor ) {
7         var wpAdvButton, style,
8                 DOM = tinymce.DOM,
9                 each = tinymce.each,
10                 __ = editor.editorManager.i18n.translate,
11                 $ = window.jQuery,
12                 wp = window.wp,
13                 hasWpautop = ( wp && wp.editor && wp.editor.autop && editor.getParam( 'wpautop', true ) );
14
15         if ( $ ) {
16                 $( document ).triggerHandler( 'tinymce-editor-setup', [ editor ] );
17         }
18
19         function toggleToolbars( state ) {
20                 var iframe, initial, toolbars,
21                         pixels = 0;
22
23                 initial = ( state === 'hide' );
24
25                 if ( editor.theme.panel ) {
26                         toolbars = editor.theme.panel.find('.toolbar:not(.menubar)');
27                 }
28
29                 if ( ! toolbars || toolbars.length < 2 || ( state === 'hide' && ! toolbars[1].visible() ) ) {
30                         return;
31                 }
32
33                 if ( ! state && toolbars[1].visible() ) {
34                         state = 'hide';
35                 }
36
37                 each( toolbars, function( toolbar, i ) {
38                         if ( i > 0 ) {
39                                 if ( state === 'hide' ) {
40                                         toolbar.hide();
41                                         pixels += 30;
42                                 } else {
43                                         toolbar.show();
44                                         pixels -= 30;
45                                 }
46                         }
47                 });
48
49                 if ( pixels && ! initial ) {
50                         // Resize iframe, not needed in iOS
51                         if ( ! tinymce.Env.iOS ) {
52                                 iframe = editor.getContentAreaContainer().firstChild;
53                                 DOM.setStyle( iframe, 'height', iframe.clientHeight + pixels );
54                         }
55
56                         if ( state === 'hide' ) {
57                                 setUserSetting('hidetb', '0');
58                                 wpAdvButton && wpAdvButton.active( false );
59                         } else {
60                                 setUserSetting('hidetb', '1');
61                                 wpAdvButton && wpAdvButton.active( true );
62                         }
63                 }
64
65                 editor.fire( 'wp-toolbar-toggle' );
66         }
67
68         // Add the kitchen sink button :)
69         editor.addButton( 'wp_adv', {
70                 tooltip: 'Toolbar Toggle',
71                 cmd: 'WP_Adv',
72                 onPostRender: function() {
73                         wpAdvButton = this;
74                         wpAdvButton.active( getUserSetting( 'hidetb' ) === '1' ? true : false );
75                 }
76         });
77
78         // Hide the toolbars after loading
79         editor.on( 'PostRender', function() {
80                 if ( editor.getParam( 'wordpress_adv_hidden', true ) && getUserSetting( 'hidetb', '0' ) === '0' ) {
81                         toggleToolbars( 'hide' );
82                 }
83         });
84
85         editor.addCommand( 'WP_Adv', function() {
86                 toggleToolbars();
87         });
88
89         editor.on( 'focus', function() {
90         window.wpActiveEditor = editor.id;
91     });
92
93         // Replace Read More/Next Page tags with images
94         editor.on( 'BeforeSetContent', function( event ) {
95                 var title;
96
97                 if ( event.content ) {
98                         if ( event.content.indexOf( '<!--more' ) !== -1 ) {
99                                 title = __( 'Read more...' );
100
101                                 event.content = event.content.replace( /<!--more(.*?)-->/g, function( match, moretext ) {
102                                         return '<img src="' + tinymce.Env.transparentSrc + '" data-wp-more="more" data-wp-more-text="' + moretext + '" ' +
103                                                 'class="wp-more-tag mce-wp-more" alt="" title="' + title + '" data-mce-resize="false" data-mce-placeholder="1" />';
104                                 });
105                         }
106
107                         if ( event.content.indexOf( '<!--nextpage-->' ) !== -1 ) {
108                                 title = __( 'Page break' );
109
110                                 event.content = event.content.replace( /<!--nextpage-->/g,
111                                         '<img src="' + tinymce.Env.transparentSrc + '" data-wp-more="nextpage" class="wp-more-tag mce-wp-nextpage" ' +
112                                                 'alt="" title="' + title + '" data-mce-resize="false" data-mce-placeholder="1" />' );
113                         }
114
115                         if ( event.load && event.format !== 'raw' && hasWpautop ) {
116                                 event.content = wp.editor.autop( event.content );
117                         }
118
119                         // Remove spaces from empty paragraphs.
120                         event.content = event.content.replace( /<p>(?:&nbsp;|\u00a0|\uFEFF|\s)+<\/p>/gi, '<p><br /></p>' );
121                 }
122         });
123
124         // Replace images with tags
125         editor.on( 'PostProcess', function( e ) {
126                 if ( e.get ) {
127                         e.content = e.content.replace(/<img[^>]+>/g, function( image ) {
128                                 var match, moretext = '';
129
130                                 if ( image.indexOf( 'data-wp-more="more"' ) !== -1 ) {
131                                         if ( match = image.match( /data-wp-more-text="([^"]+)"/ ) ) {
132                                                 moretext = match[1];
133                                         }
134
135                                         image = '<!--more' + moretext + '-->';
136                                 } else if ( image.indexOf( 'data-wp-more="nextpage"' ) !== -1 ) {
137                                         image = '<!--nextpage-->';
138                                 }
139
140                                 return image;
141                         });
142                 }
143         });
144
145         // Display the tag name instead of img in element path
146         editor.on( 'ResolveName', function( event ) {
147                 var attr;
148
149                 if ( event.target.nodeName === 'IMG' && ( attr = editor.dom.getAttrib( event.target, 'data-wp-more' ) ) ) {
150                         event.name = attr;
151                 }
152         });
153
154         // Register commands
155         editor.addCommand( 'WP_More', function( tag ) {
156                 var parent, html, title,
157                         classname = 'wp-more-tag',
158                         dom = editor.dom,
159                         node = editor.selection.getNode();
160
161                 tag = tag || 'more';
162                 classname += ' mce-wp-' + tag;
163                 title = tag === 'more' ? 'Read more...' : 'Next page';
164                 title = __( title );
165                 html = '<img src="' + tinymce.Env.transparentSrc + '" alt="" title="' + title + '" class="' + classname + '" ' +
166                         'data-wp-more="' + tag + '" data-mce-resize="false" data-mce-placeholder="1" />';
167
168                 // Most common case
169                 if ( node.nodeName === 'BODY' || ( node.nodeName === 'P' && node.parentNode.nodeName === 'BODY' ) ) {
170                         editor.insertContent( html );
171                         return;
172                 }
173
174                 // Get the top level parent node
175                 parent = dom.getParent( node, function( found ) {
176                         if ( found.parentNode && found.parentNode.nodeName === 'BODY' ) {
177                                 return true;
178                         }
179
180                         return false;
181                 }, editor.getBody() );
182
183                 if ( parent ) {
184                         if ( parent.nodeName === 'P' ) {
185                                 parent.appendChild( dom.create( 'p', null, html ).firstChild );
186                         } else {
187                                 dom.insertAfter( dom.create( 'p', null, html ), parent );
188                         }
189
190                         editor.nodeChanged();
191                 }
192         });
193
194         editor.addCommand( 'WP_Code', function() {
195                 editor.formatter.toggle('code');
196         });
197
198         editor.addCommand( 'WP_Page', function() {
199                 editor.execCommand( 'WP_More', 'nextpage' );
200         });
201
202         editor.addCommand( 'WP_Help', function() {
203                 var access = tinymce.Env.mac ? __( 'Ctrl + Alt + letter:' ) : __( 'Shift + Alt + letter:' ),
204                         meta = tinymce.Env.mac ? __( 'Cmd + letter:' ) : __( 'Ctrl + letter:' ),
205                         table1 = [],
206                         table2 = [],
207                         header, html, dialog, $wrap;
208
209                 each( [
210                         { c: 'Copy',      x: 'Cut'              },
211                         { v: 'Paste',     a: 'Select all'       },
212                         { z: 'Undo',      y: 'Redo'             },
213                         { b: 'Bold',      i: 'Italic'           },
214                         { u: 'Underline', k: 'Insert/edit link' }
215                 ], function( row ) {
216                         table1.push( tr( row ) );
217                 } );
218
219                 each( [
220                         { 1: 'Heading 1',             2: 'Heading 2'                     },
221                         { 3: 'Heading 3',             4: 'Heading 4'                     },
222                         { 5: 'Heading 5',             6: 'Heading 6'                     },
223                         { l: 'Align left',            c: 'Align center'                  },
224                         { r: 'Align right',           j: 'Justify'                       },
225                         { d: 'Strikethrough',         q: 'Blockquote'                    },
226                         { u: 'Bullet list',           o: 'Numbered list'                 },
227                         { a: 'Insert/edit link',      s: 'Remove link'                   },
228                         { m: 'Insert/edit image',     t: 'Insert Read More tag'          },
229                         { h: 'Keyboard Shortcuts',    x: 'Code'                          },
230                         { p: 'Insert Page Break tag', w: 'Distraction-free writing mode' }
231                 ], function( row ) {
232                         table2.push( tr( row ) );
233                 } );
234
235                 function tr( row ) {
236                         var out = '<tr>';
237
238                         each( row, function( text, key ) {
239                                 if ( ! text ) {
240                                         out += '<td></td><td></td>';
241                                 } else {
242                                         out += '<td><kbd>' + key + '</kbd></td><td>' + __( text ) + '</td>';
243                                 }
244                         });
245
246                         return out + '</tr>';
247                 }
248
249                 header = [ __( 'Letter' ), __( 'Action' ), __( 'Letter' ), __( 'Action' ) ];
250                 header = '<tr><th>' + header.join( '</th><th>' ) + '</th></tr>';
251
252                 html = '<div class="wp-editor-help">';
253
254                 // Main section, default and additional shortcuts
255                 html = html +
256                         '<h2>' + __( 'Default shortcuts,' ) + ' ' + meta + '</h2>' +
257                         '<table class="wp-help-th-center">' +
258                                 header +
259                                 table1.join('') +
260                         '</table>' +
261                         '<h2>' + __( 'Additional shortcuts,' ) + ' ' + access + '</h2>' +
262                         '<table class="wp-help-th-center">' +
263                                 header +
264                                 table2.join('') +
265                         '</table>';
266
267                 if ( editor.plugins.wptextpattern ) {
268                         // Text pattern section
269                         html = html +
270                                 '<h2>' + __( 'When starting a new paragraph with one of these formatting shortcuts followed by a space, the formatting will be applied automatically. Press Backspace or Escape to undo.' ) + '</h2>' +
271                                 '<table>' +
272                                         tr({ '*':  'Bullet list' }) +
273                                         tr({ '-':  'Bullet list' }) +
274                                         tr({ '1.':  'Numbered list' }) +
275                                         tr({ '1)':  'Numbered list' }) +
276                                 '</table>';
277
278                         html = html +
279                                 '<h2>' + __( 'The following formatting shortcuts are replaced when pressing Enter. Press Escape or the Undo button to undo.' ) + '</h2>' +
280                                 '<table>' +
281                                         tr({ '>': 'Blockquote' }) +
282                                         tr({ '##': 'Heading 2' }) +
283                                         tr({ '###': 'Heading 3' }) +
284                                         tr({ '####': 'Heading 4' }) +
285                                         tr({ '#####': 'Heading 5' }) +
286                                         tr({ '######': 'Heading 6' }) +
287                                 '</table>';
288                 }
289
290                 // Focus management section
291                 html = html +
292                         '<h2>' + __( 'Focus shortcuts:' ) + '</h2>' +
293                         '<table>' +
294                                 tr({ 'Alt + F8':  'Inline toolbar (when an image, link or preview is selected)' }) +
295                                 tr({ 'Alt + F9':  'Editor menu (when enabled)' }) +
296                                 tr({ 'Alt + F10': 'Editor toolbar' }) +
297                                 tr({ 'Alt + F11': 'Elements path' }) +
298                         '</table>' +
299                         '<p>' + __( 'To move focus to other buttons use Tab or the arrow keys. To return focus to the editor press Escape or use one of the buttons.' ) + '</p>';
300
301                 html += '</div>';
302
303                 dialog = editor.windowManager.open( {
304                         title: 'Keyboard Shortcuts',
305                         items: {
306                                 type: 'container',
307                                 classes: 'wp-help',
308                                 html: html
309                         },
310                         buttons: {
311                                 text: 'Close',
312                                 onclick: 'close'
313                         }
314                 } );
315
316                 if ( dialog.$el ) {
317                         dialog.$el.find( 'div[role="application"]' ).attr( 'role', 'document' );
318                         $wrap = dialog.$el.find( '.mce-wp-help' );
319
320                         if ( $wrap[0] ) {
321                                 $wrap.attr( 'tabindex', '0' );
322                                 $wrap[0].focus();
323                                 $wrap.on( 'keydown', function( event ) {
324                                         // Prevent use of: page up, page down, end, home, left arrow, up arrow, right arrow, down arrow
325                                         // in the dialog keydown handler.
326                                         if ( event.keyCode >= 33 && event.keyCode <= 40 ) {
327                                                 event.stopPropagation();
328                                         }
329                                 });
330                         }
331                 }
332         } );
333
334         editor.addCommand( 'WP_Medialib', function() {
335                 if ( wp && wp.media && wp.media.editor ) {
336                         wp.media.editor.open( editor.id );
337                 }
338         });
339
340         // Register buttons
341         editor.addButton( 'wp_more', {
342                 tooltip: 'Insert Read More tag',
343                 onclick: function() {
344                         editor.execCommand( 'WP_More', 'more' );
345                 }
346         });
347
348         editor.addButton( 'wp_page', {
349                 tooltip: 'Page break',
350                 onclick: function() {
351                         editor.execCommand( 'WP_More', 'nextpage' );
352                 }
353         });
354
355         editor.addButton( 'wp_help', {
356                 tooltip: 'Keyboard Shortcuts',
357                 cmd: 'WP_Help'
358         });
359
360         editor.addButton( 'wp_code', {
361                 tooltip: 'Code',
362                 cmd: 'WP_Code',
363                 stateSelector: 'code'
364         });
365
366         // Menubar
367         // Insert->Add Media
368         if ( wp && wp.media && wp.media.editor ) {
369                 editor.addMenuItem( 'add_media', {
370                         text: 'Add Media',
371                         icon: 'wp-media-library',
372                         context: 'insert',
373                         cmd: 'WP_Medialib'
374                 });
375         }
376
377         // Insert "Read More..."
378         editor.addMenuItem( 'wp_more', {
379                 text: 'Insert Read More tag',
380                 icon: 'wp_more',
381                 context: 'insert',
382                 onclick: function() {
383                         editor.execCommand( 'WP_More', 'more' );
384                 }
385         });
386
387         // Insert "Next Page"
388         editor.addMenuItem( 'wp_page', {
389                 text: 'Page break',
390                 icon: 'wp_page',
391                 context: 'insert',
392                 onclick: function() {
393                         editor.execCommand( 'WP_More', 'nextpage' );
394                 }
395         });
396
397         editor.on( 'BeforeExecCommand', function(e) {
398                 if ( tinymce.Env.webkit && ( e.command === 'InsertUnorderedList' || e.command === 'InsertOrderedList' ) ) {
399                         if ( ! style ) {
400                                 style = editor.dom.create( 'style', {'type': 'text/css'},
401                                         '#tinymce,#tinymce span,#tinymce li,#tinymce li>span,#tinymce p,#tinymce p>span{font:medium sans-serif;color:#000;line-height:normal;}');
402                         }
403
404                         editor.getDoc().head.appendChild( style );
405                 }
406         });
407
408         editor.on( 'ExecCommand', function( e ) {
409                 if ( tinymce.Env.webkit && style &&
410                         ( 'InsertUnorderedList' === e.command || 'InsertOrderedList' === e.command ) ) {
411
412                         editor.dom.remove( style );
413                 }
414         });
415
416         editor.on( 'init', function() {
417                 var env = tinymce.Env,
418                         bodyClass = ['mceContentBody'], // back-compat for themes that use this in editor-style.css...
419                         doc = editor.getDoc(),
420                         dom = editor.dom;
421
422                 if ( env.iOS ) {
423                         dom.addClass( doc.documentElement, 'ios' );
424                 }
425
426                 if ( editor.getParam( 'directionality' ) === 'rtl' ) {
427                         bodyClass.push('rtl');
428                         dom.setAttrib( doc.documentElement, 'dir', 'rtl' );
429                 }
430
431                 dom.setAttrib( doc.documentElement, 'lang', editor.getParam( 'wp_lang_attr' ) );
432
433                 if ( env.ie ) {
434                         if ( parseInt( env.ie, 10 ) === 9 ) {
435                                 bodyClass.push('ie9');
436                         } else if ( parseInt( env.ie, 10 ) === 8 ) {
437                                 bodyClass.push('ie8');
438                         } else if ( env.ie < 8 ) {
439                                 bodyClass.push('ie7');
440                         }
441                 } else if ( env.webkit ) {
442                         bodyClass.push('webkit');
443                 }
444
445                 bodyClass.push('wp-editor');
446
447                 each( bodyClass, function( cls ) {
448                         if ( cls ) {
449                                 dom.addClass( doc.body, cls );
450                         }
451                 });
452
453                 // Remove invalid parent paragraphs when inserting HTML
454                 editor.on( 'BeforeSetContent', function( event ) {
455                         if ( event.content ) {
456                                 event.content = event.content.replace( /<p>\s*<(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre)( [^>]*)?>/gi, '<$1$2>' )
457                                         .replace( /<\/(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre)>\s*<\/p>/gi, '</$1>' );
458                         }
459                 });
460
461                 if ( $ ) {
462                         $( document ).triggerHandler( 'tinymce-editor-init', [editor] );
463                 }
464
465                 if ( window.tinyMCEPreInit && window.tinyMCEPreInit.dragDropUpload ) {
466                         dom.bind( doc, 'dragstart dragend dragover drop', function( event ) {
467                                 if ( $ ) {
468                                         // Trigger the jQuery handlers.
469                                         $( document ).trigger( new $.Event( event ) );
470                                 }
471                         });
472                 }
473
474                 if ( editor.getParam( 'wp_paste_filters', true ) ) {
475                         editor.on( 'PastePreProcess', function( event ) {
476                                 // Remove trailing <br> added by WebKit browsers to the clipboard
477                                 event.content = event.content.replace( /<br class="?Apple-interchange-newline"?>/gi, '' );
478
479                                 // In WebKit this is handled by removeWebKitStyles()
480                                 if ( ! tinymce.Env.webkit ) {
481                                         // Remove all inline styles
482                                         event.content = event.content.replace( /(<[^>]+) style="[^"]*"([^>]*>)/gi, '$1$2' );
483
484                                         // Put back the internal styles
485                                         event.content = event.content.replace(/(<[^>]+) data-mce-style=([^>]+>)/gi, '$1 style=$2' );
486                                 }
487                         });
488
489                         editor.on( 'PastePostProcess', function( event ) {
490                                 // Remove empty paragraphs
491                                 each( dom.select( 'p', event.node ), function( node ) {
492                                         if ( dom.isEmpty( node ) ) {
493                                                 dom.remove( node );
494                                         }
495                                 });
496                         });
497                 }
498         });
499
500         editor.on( 'SaveContent', function( event ) {
501                 // If editor is hidden, we just want the textarea's value to be saved
502                 if ( ! editor.inline && editor.isHidden() ) {
503                         event.content = event.element.value;
504                         return;
505                 }
506
507                 // Keep empty paragraphs :(
508                 event.content = event.content.replace( /<p>(?:<br ?\/?>|\u00a0|\uFEFF| )*<\/p>/g, '<p>&nbsp;</p>' );
509
510                 if ( hasWpautop ) {
511                         event.content = wp.editor.removep( event.content );
512                 }
513         });
514
515         editor.on( 'preInit', function() {
516                 var validElementsSetting = '@[id|accesskey|class|dir|lang|style|tabindex|' +
517                         'title|contenteditable|draggable|dropzone|hidden|spellcheck|translate],' + // Global attributes.
518                         'i,' + // Don't replace <i> with <em> and <b> with <strong> and don't remove them when empty.
519                         'b,' +
520                         'script[src|async|defer|type|charset|crossorigin|integrity]'; // Add support for <script>.
521
522                 editor.schema.addValidElements( validElementsSetting );
523
524                 if ( tinymce.Env.iOS ) {
525                         editor.settings.height = 300;
526                 }
527
528                 each( {
529                         c: 'JustifyCenter',
530                         r: 'JustifyRight',
531                         l: 'JustifyLeft',
532                         j: 'JustifyFull',
533                         q: 'mceBlockQuote',
534                         u: 'InsertUnorderedList',
535                         o: 'InsertOrderedList',
536                         s: 'unlink',
537                         m: 'WP_Medialib',
538                         z: 'WP_Adv',
539                         t: 'WP_More',
540                         d: 'Strikethrough',
541                         h: 'WP_Help',
542                         p: 'WP_Page',
543                         x: 'WP_Code'
544                 }, function( command, key ) {
545                         editor.shortcuts.add( 'access+' + key, '', command );
546                 } );
547
548                 editor.addShortcut( 'meta+s', '', function() {
549                         if ( wp && wp.autosave ) {
550                                 wp.autosave.server.triggerSave();
551                         }
552                 } );
553         } );
554
555         /**
556          * Experimental: create a floating toolbar.
557          * This functionality will change in the next releases. Not recommended for use by plugins.
558          */
559         editor.on( 'preinit', function() {
560                 var Factory = tinymce.ui.Factory,
561                         settings = editor.settings,
562                         activeToolbar,
563                         currentSelection,
564                         timeout,
565                         container = editor.getContainer(),
566                         wpAdminbar = document.getElementById( 'wpadminbar' ),
567                         mceIframe = document.getElementById( editor.id + '_ifr' ),
568                         mceToolbar,
569                         mceStatusbar,
570                         wpStatusbar;
571
572                         if ( container ) {
573                                 mceToolbar = tinymce.$( '.mce-toolbar-grp', container )[0];
574                                 mceStatusbar = tinymce.$( '.mce-statusbar', container )[0];
575                         }
576
577                         if ( editor.id === 'content' ) {
578                                 wpStatusbar = document.getElementById( 'post-status-info' );
579                         }
580
581                 function create( buttons, bottom ) {
582                         var toolbar,
583                                 toolbarItems = [],
584                                 buttonGroup;
585
586                         each( buttons, function( item ) {
587                                 var itemName;
588
589                                 function bindSelectorChanged() {
590                                         var selection = editor.selection;
591
592                                         if ( itemName === 'bullist' ) {
593                                                 selection.selectorChanged( 'ul > li', function( state, args ) {
594                                                         var i = args.parents.length,
595                                                                 nodeName;
596
597                                                         while ( i-- ) {
598                                                                 nodeName = args.parents[ i ].nodeName;
599
600                                                                 if ( nodeName === 'OL' || nodeName == 'UL' ) {
601                                                                         break;
602                                                                 }
603                                                         }
604
605                                                         item.active( state && nodeName === 'UL' );
606                                                 } );
607                                         }
608
609                                         if ( itemName === 'numlist' ) {
610                                                 selection.selectorChanged( 'ol > li', function( state, args ) {
611                                                         var i = args.parents.length,
612                                                                 nodeName;
613
614                                                         while ( i-- ) {
615                                                                 nodeName = args.parents[ i ].nodeName;
616
617                                                                 if ( nodeName === 'OL' || nodeName === 'UL' ) {
618                                                                         break;
619                                                                 }
620                                                         }
621
622                                                         item.active( state && nodeName === 'OL' );
623                                                 } );
624                                         }
625
626                                         if ( item.settings.stateSelector ) {
627                                                 selection.selectorChanged( item.settings.stateSelector, function( state ) {
628                                                         item.active( state );
629                                                 }, true );
630                                         }
631
632                                         if ( item.settings.disabledStateSelector ) {
633                                                 selection.selectorChanged( item.settings.disabledStateSelector, function( state ) {
634                                                         item.disabled( state );
635                                                 } );
636                                         }
637                                 }
638
639                                 if ( item === '|' ) {
640                                         buttonGroup = null;
641                                 } else {
642                                         if ( Factory.has( item ) ) {
643                                                 item = {
644                                                         type: item
645                                                 };
646
647                                                 if ( settings.toolbar_items_size ) {
648                                                         item.size = settings.toolbar_items_size;
649                                                 }
650
651                                                 toolbarItems.push( item );
652
653                                                 buttonGroup = null;
654                                         } else {
655                                                 if ( ! buttonGroup ) {
656                                                         buttonGroup = {
657                                                                 type: 'buttongroup',
658                                                                 items: []
659                                                         };
660
661                                                         toolbarItems.push( buttonGroup );
662                                                 }
663
664                                                 if ( editor.buttons[ item ] ) {
665                                                         itemName = item;
666                                                         item = editor.buttons[ itemName ];
667
668                                                         if ( typeof item === 'function' ) {
669                                                                 item = item();
670                                                         }
671
672                                                         item.type = item.type || 'button';
673
674                                                         if ( settings.toolbar_items_size ) {
675                                                                 item.size = settings.toolbar_items_size;
676                                                         }
677
678                                                         item = Factory.create( item );
679
680                                                         buttonGroup.items.push( item );
681
682                                                         if ( editor.initialized ) {
683                                                                 bindSelectorChanged();
684                                                         } else {
685                                                                 editor.on( 'init', bindSelectorChanged );
686                                                         }
687                                                 }
688                                         }
689                                 }
690                         } );
691
692                         toolbar = Factory.create( {
693                                 type: 'panel',
694                                 layout: 'stack',
695                                 classes: 'toolbar-grp inline-toolbar-grp',
696                                 ariaRoot: true,
697                                 ariaRemember: true,
698                                 items: [ {
699                                         type: 'toolbar',
700                                         layout: 'flow',
701                                         items: toolbarItems
702                                 } ]
703                         } );
704
705                         toolbar.bottom = bottom;
706
707                         function reposition() {
708                                 if ( ! currentSelection ) {
709                                         return this;
710                                 }
711
712                                 var scrollX = window.pageXOffset || document.documentElement.scrollLeft,
713                                         scrollY = window.pageYOffset || document.documentElement.scrollTop,
714                                         windowWidth = window.innerWidth,
715                                         windowHeight = window.innerHeight,
716                                         iframeRect = mceIframe ? mceIframe.getBoundingClientRect() : {
717                                                 top: 0,
718                                                 right: windowWidth,
719                                                 bottom: windowHeight,
720                                                 left: 0,
721                                                 width: windowWidth,
722                                                 height: windowHeight
723                                         },
724                                         toolbar = this.getEl(),
725                                         toolbarWidth = toolbar.offsetWidth,
726                                         toolbarHeight = toolbar.offsetHeight,
727                                         selection = currentSelection.getBoundingClientRect(),
728                                         selectionMiddle = ( selection.left + selection.right ) / 2,
729                                         buffer = 5,
730                                         margin = 8,
731                                         spaceNeeded = toolbarHeight + margin + buffer,
732                                         wpAdminbarBottom = wpAdminbar ? wpAdminbar.getBoundingClientRect().bottom : 0,
733                                         mceToolbarBottom = mceToolbar ? mceToolbar.getBoundingClientRect().bottom : 0,
734                                         mceStatusbarTop = mceStatusbar ? windowHeight - mceStatusbar.getBoundingClientRect().top : 0,
735                                         wpStatusbarTop = wpStatusbar ? windowHeight - wpStatusbar.getBoundingClientRect().top : 0,
736                                         blockedTop = Math.max( 0, wpAdminbarBottom, mceToolbarBottom, iframeRect.top ),
737                                         blockedBottom = Math.max( 0, mceStatusbarTop, wpStatusbarTop, windowHeight - iframeRect.bottom ),
738                                         spaceTop = selection.top + iframeRect.top - blockedTop,
739                                         spaceBottom = windowHeight - iframeRect.top - selection.bottom - blockedBottom,
740                                         editorHeight = windowHeight - blockedTop - blockedBottom,
741                                         className = '',
742                                         iosOffsetTop = 0,
743                                         iosOffsetBottom = 0,
744                                         top, left;
745
746                                 if ( spaceTop >= editorHeight || spaceBottom >= editorHeight ) {
747                                         return this.hide();
748                                 }
749
750                                 // Add offset in iOS to move the menu over the image, out of the way of the default iOS menu.
751                                 if ( tinymce.Env.iOS && currentSelection.nodeName === 'IMG' ) {
752                                         iosOffsetTop = 54;
753                                         iosOffsetBottom = 46;
754                                 }
755
756                                 if ( this.bottom ) {
757                                         if ( spaceBottom >= spaceNeeded ) {
758                                                 className = ' mce-arrow-up';
759                                                 top = selection.bottom + iframeRect.top + scrollY - iosOffsetBottom;
760                                         } else if ( spaceTop >= spaceNeeded ) {
761                                                 className = ' mce-arrow-down';
762                                                 top = selection.top + iframeRect.top + scrollY - toolbarHeight - margin + iosOffsetTop;
763                                         }
764                                 } else {
765                                         if ( spaceTop >= spaceNeeded ) {
766                                                 className = ' mce-arrow-down';
767                                                 top = selection.top + iframeRect.top + scrollY - toolbarHeight - margin + iosOffsetTop;
768                                         } else if ( spaceBottom >= spaceNeeded && editorHeight / 2 > selection.bottom + iframeRect.top - blockedTop ) {
769                                                 className = ' mce-arrow-up';
770                                                 top = selection.bottom + iframeRect.top + scrollY - iosOffsetBottom;
771                                         }
772                                 }
773
774                                 if ( typeof top === 'undefined' ) {
775                                         top = scrollY + blockedTop + buffer + iosOffsetBottom;
776                                 }
777
778                                 left = selectionMiddle - toolbarWidth / 2 + iframeRect.left + scrollX;
779
780                                 if ( selection.left < 0 || selection.right > iframeRect.width ) {
781                                         left = iframeRect.left + scrollX + ( iframeRect.width - toolbarWidth ) / 2;
782                                 } else if ( toolbarWidth >= windowWidth ) {
783                                         className += ' mce-arrow-full';
784                                         left = 0;
785                                 } else if ( ( left < 0 && selection.left + toolbarWidth > windowWidth ) || ( left + toolbarWidth > windowWidth && selection.right - toolbarWidth < 0 ) ) {
786                                         left = ( windowWidth - toolbarWidth ) / 2;
787                                 } else if ( left < iframeRect.left + scrollX ) {
788                                         className += ' mce-arrow-left';
789                                         left = selection.left + iframeRect.left + scrollX;
790                                 } else if ( left + toolbarWidth > iframeRect.width + iframeRect.left + scrollX ) {
791                                         className += ' mce-arrow-right';
792                                         left = selection.right - toolbarWidth + iframeRect.left + scrollX;
793                                 }
794
795                                 // No up/down arrows on the menu over images in iOS.
796                                 if ( tinymce.Env.iOS && currentSelection.nodeName === 'IMG' ) {
797                                         className = className.replace( / ?mce-arrow-(up|down)/g, '' );
798                                 }
799
800                                 toolbar.className = toolbar.className.replace( / ?mce-arrow-[\w]+/g, '' ) + className;
801
802                                 DOM.setStyles( toolbar, {
803                                         'left': left,
804                                         'top': top
805                                 } );
806
807                                 return this;
808                         }
809
810                         toolbar.on( 'show', function() {
811                                 this.reposition();
812                         } );
813
814                         toolbar.on( 'keydown', function( event ) {
815                                 if ( event.keyCode === 27 ) {
816                                         this.hide();
817                                         editor.focus();
818                                 }
819                         } );
820
821                         editor.on( 'remove', function() {
822                                 toolbar.remove();
823                         } );
824
825                         toolbar.reposition = reposition;
826                         toolbar.hide().renderTo( document.body );
827
828                         return toolbar;
829                 }
830
831                 editor.shortcuts.add( 'alt+119', '', function() {
832                         var node;
833
834                         if ( activeToolbar ) {
835                                 node = activeToolbar.find( 'toolbar' )[0];
836                                 node && node.focus( true );
837                         }
838                 } );
839
840                 editor.on( 'nodechange', function( event ) {
841                         var collapsed = editor.selection.isCollapsed();
842
843                         var args = {
844                                 element: event.element,
845                                 parents: event.parents,
846                                 collapsed: collapsed
847                         };
848
849                         editor.fire( 'wptoolbar', args );
850
851                         currentSelection = args.selection || args.element;
852
853                         if ( activeToolbar ) {
854                                 activeToolbar.hide();
855                         }
856
857                         if ( args.toolbar ) {
858                                 activeToolbar = args.toolbar;
859                                 activeToolbar.show();
860                         } else {
861                                 activeToolbar = false;
862                         }
863                 } );
864
865                 editor.on( 'focus', function() {
866                         if ( activeToolbar ) {
867                                 activeToolbar.show();
868                         }
869                 } );
870
871                 function hide( event ) {
872                         if ( activeToolbar ) {
873                                 activeToolbar.hide();
874
875                                 if ( event.type === 'hide' ) {
876                                         activeToolbar = false;
877                                 } else if ( event.type === 'resize' || event.type === 'scroll' ) {
878                                         clearTimeout( timeout );
879
880                                         timeout = setTimeout( function() {
881                                                 if ( activeToolbar && typeof activeToolbar.show === 'function' ) {
882                                                         activeToolbar.show();
883                                                 }
884                                         }, 250 );
885                                 }
886                         }
887                 }
888
889                 DOM.bind( window, 'resize scroll', hide );
890                 editor.dom.bind( editor.getWin(), 'resize scroll', hide );
891
892                 editor.on( 'remove', function() {
893                         DOM.unbind( window, 'resize scroll', hide );
894                         editor.dom.unbind( editor.getWin(), 'resize scroll', hide );
895                 } );
896
897                 editor.on( 'blur hide', hide );
898
899                 editor.wp = editor.wp || {};
900                 editor.wp._createToolbar = create;
901         }, true );
902
903         function noop() {}
904
905         // Expose some functions (back-compat)
906         return {
907                 _showButtons: noop,
908                 _hideButtons: noop,
909                 _setEmbed: noop,
910                 _getEmbed: noop
911         };
912 });
913
914 }( window.tinymce ));