]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/tinymce/plugins/wordpress/plugin.js
WordPress 4.3-scripts
[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" 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                                                 '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 + '" 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                 if ( env.ie ) {
432                         if ( parseInt( env.ie, 10 ) === 9 ) {
433                                 bodyClass.push('ie9');
434                         } else if ( parseInt( env.ie, 10 ) === 8 ) {
435                                 bodyClass.push('ie8');
436                         } else if ( env.ie < 8 ) {
437                                 bodyClass.push('ie7');
438                         }
439                 } else if ( env.webkit ) {
440                         bodyClass.push('webkit');
441                 }
442
443                 bodyClass.push('wp-editor');
444
445                 each( bodyClass, function( cls ) {
446                         if ( cls ) {
447                                 dom.addClass( doc.body, cls );
448                         }
449                 });
450
451                 // Remove invalid parent paragraphs when inserting HTML
452                 editor.on( 'BeforeSetContent', function( event ) {
453                         if ( event.content ) {
454                                 event.content = event.content.replace( /<p>\s*<(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre)( [^>]*)?>/gi, '<$1$2>' )
455                                         .replace( /<\/(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre)>\s*<\/p>/gi, '</$1>' );
456                         }
457                 });
458
459                 if ( $ ) {
460                         $( document ).triggerHandler( 'tinymce-editor-init', [editor] );
461                 }
462
463                 if ( window.tinyMCEPreInit && window.tinyMCEPreInit.dragDropUpload ) {
464                         dom.bind( doc, 'dragstart dragend dragover drop', function( event ) {
465                                 if ( $ ) {
466                                         // Trigger the jQuery handlers.
467                                         $( document ).trigger( new $.Event( event ) );
468                                 }
469                         });
470                 }
471
472                 if ( editor.getParam( 'wp_paste_filters', true ) ) {
473                         if ( ! tinymce.Env.webkit ) {
474                                 // In WebKit handled by removeWebKitStyles()
475                                 editor.on( 'PastePreProcess', function( event ) {
476                                         // Remove all inline styles
477                                         event.content = event.content.replace( /(<[^>]+) style="[^"]*"([^>]*>)/gi, '$1$2' );
478
479                                         // Put back the internal styles
480                                         event.content = event.content.replace(/(<[^>]+) data-mce-style=([^>]+>)/gi, '$1 style=$2' );
481                                 });
482                         }
483
484                         editor.on( 'PastePostProcess', function( event ) {
485                                 // Remove empty paragraphs
486                                 each( dom.select( 'p', event.node ), function( node ) {
487                                         if ( dom.isEmpty( node ) ) {
488                                                 dom.remove( node );
489                                         }
490                                 });
491                         });
492                 }
493         });
494
495         editor.on( 'SaveContent', function( event ) {
496                 // If editor is hidden, we just want the textarea's value to be saved
497                 if ( ! editor.inline && editor.isHidden() ) {
498                         event.content = event.element.value;
499                         return;
500                 }
501
502                 // Keep empty paragraphs :(
503                 event.content = event.content.replace( /<p>(?:<br ?\/?>|\u00a0|\uFEFF| )*<\/p>/g, '<p>&nbsp;</p>' );
504
505                 if ( hasWpautop ) {
506                         event.content = wp.editor.removep( event.content );
507                 }
508         });
509
510         editor.on( 'preInit', function() {
511                 var validElementsSetting = '@[id|accesskey|class|dir|lang|style|tabindex|' +
512                         'title|contenteditable|draggable|dropzone|hidden|spellcheck|translate],' + // Global attributes.
513                         'i,' + // Don't replace <i> with <em> and <b> with <strong> and don't remove them when empty.
514                         'b,' +
515                         'script[src|async|defer|type|charset|crossorigin|integrity]'; // Add support for <script>.
516
517                 editor.schema.addValidElements( validElementsSetting );
518
519                 if ( tinymce.Env.iOS ) {
520                         editor.settings.height = 300;
521                 }
522
523                 each( {
524                         c: 'JustifyCenter',
525                         r: 'JustifyRight',
526                         l: 'JustifyLeft',
527                         j: 'JustifyFull',
528                         q: 'mceBlockQuote',
529                         u: 'InsertUnorderedList',
530                         o: 'InsertOrderedList',
531                         s: 'unlink',
532                         m: 'WP_Medialib',
533                         z: 'WP_Adv',
534                         t: 'WP_More',
535                         d: 'Strikethrough',
536                         h: 'WP_Help',
537                         p: 'WP_Page',
538                         x: 'WP_Code'
539                 }, function( command, key ) {
540                         editor.shortcuts.add( 'access+' + key, '', command );
541                 } );
542
543                 editor.addShortcut( 'meta+s', '', function() {
544                         if ( wp && wp.autosave ) {
545                                 wp.autosave.server.triggerSave();
546                         }
547                 } );
548         } );
549
550         /**
551          * Experimental: create a floating toolbar.
552          * This functionality will change in the next releases. Not recommended for use by plugins.
553          */
554         editor.on( 'preinit', function() {
555                 var Factory = tinymce.ui.Factory,
556                         settings = editor.settings,
557                         activeToolbar,
558                         currentSelection,
559                         timeout,
560                         container = editor.getContainer(),
561                         wpAdminbar = document.getElementById( 'wpadminbar' ),
562                         mceIframe = document.getElementById( editor.id + '_ifr' ),
563                         mceToolbar,
564                         mceStatusbar,
565                         wpStatusbar;
566
567                         if ( container ) {
568                                 mceToolbar = tinymce.$( '.mce-toolbar-grp', container )[0];
569                                 mceStatusbar = tinymce.$( '.mce-statusbar', container )[0];
570                         }
571
572                         if ( editor.id === 'content' ) {
573                                 wpStatusbar = document.getElementById( 'post-status-info' );
574                         }
575
576                 function create( buttons, bottom ) {
577                         var toolbar,
578                                 toolbarItems = [],
579                                 buttonGroup;
580
581                         each( buttons, function( item ) {
582                                 var itemName;
583
584                                 function bindSelectorChanged() {
585                                         var selection = editor.selection;
586
587                                         if ( itemName === 'bullist' ) {
588                                                 selection.selectorChanged( 'ul > li', function( state, args ) {
589                                                         var i = args.parents.length,
590                                                                 nodeName;
591
592                                                         while ( i-- ) {
593                                                                 nodeName = args.parents[ i ].nodeName;
594
595                                                                 if ( nodeName === 'OL' || nodeName == 'UL' ) {
596                                                                         break;
597                                                                 }
598                                                         }
599
600                                                         item.active( state && nodeName === 'UL' );
601                                                 } );
602                                         }
603
604                                         if ( itemName === 'numlist' ) {
605                                                 selection.selectorChanged( 'ol > li', function( state, args ) {
606                                                         var i = args.parents.length,
607                                                                 nodeName;
608
609                                                         while ( i-- ) {
610                                                                 nodeName = args.parents[ i ].nodeName;
611
612                                                                 if ( nodeName === 'OL' || nodeName === 'UL' ) {
613                                                                         break;
614                                                                 }
615                                                         }
616
617                                                         item.active( state && nodeName === 'OL' );
618                                                 } );
619                                         }
620
621                                         if ( item.settings.stateSelector ) {
622                                                 selection.selectorChanged( item.settings.stateSelector, function( state ) {
623                                                         item.active( state );
624                                                 }, true );
625                                         }
626
627                                         if ( item.settings.disabledStateSelector ) {
628                                                 selection.selectorChanged( item.settings.disabledStateSelector, function( state ) {
629                                                         item.disabled( state );
630                                                 } );
631                                         }
632                                 }
633
634                                 if ( item === '|' ) {
635                                         buttonGroup = null;
636                                 } else {
637                                         if ( Factory.has( item ) ) {
638                                                 item = {
639                                                         type: item
640                                                 };
641
642                                                 if ( settings.toolbar_items_size ) {
643                                                         item.size = settings.toolbar_items_size;
644                                                 }
645
646                                                 toolbarItems.push( item );
647
648                                                 buttonGroup = null;
649                                         } else {
650                                                 if ( ! buttonGroup ) {
651                                                         buttonGroup = {
652                                                                 type: 'buttongroup',
653                                                                 items: []
654                                                         };
655
656                                                         toolbarItems.push( buttonGroup );
657                                                 }
658
659                                                 if ( editor.buttons[ item ] ) {
660                                                         itemName = item;
661                                                         item = editor.buttons[ itemName ];
662
663                                                         if ( typeof item === 'function' ) {
664                                                                 item = item();
665                                                         }
666
667                                                         item.type = item.type || 'button';
668
669                                                         if ( settings.toolbar_items_size ) {
670                                                                 item.size = settings.toolbar_items_size;
671                                                         }
672
673                                                         item = Factory.create( item );
674
675                                                         buttonGroup.items.push( item );
676
677                                                         if ( editor.initialized ) {
678                                                                 bindSelectorChanged();
679                                                         } else {
680                                                                 editor.on( 'init', bindSelectorChanged );
681                                                         }
682                                                 }
683                                         }
684                                 }
685                         } );
686
687                         toolbar = Factory.create( {
688                                 type: 'panel',
689                                 layout: 'stack',
690                                 classes: 'toolbar-grp inline-toolbar-grp',
691                                 ariaRoot: true,
692                                 ariaRemember: true,
693                                 items: [ {
694                                         type: 'toolbar',
695                                         layout: 'flow',
696                                         items: toolbarItems
697                                 } ]
698                         } );
699
700                         toolbar.bottom = bottom;
701
702                         function reposition() {
703                                 if ( ! currentSelection ) {
704                                         return this;
705                                 }
706
707                                 var scrollX = window.pageXOffset || document.documentElement.scrollLeft,
708                                         scrollY = window.pageYOffset || document.documentElement.scrollTop,
709                                         windowWidth = window.innerWidth,
710                                         windowHeight = window.innerHeight,
711                                         iframeRect = mceIframe ? mceIframe.getBoundingClientRect() : {
712                                                 top: 0,
713                                                 right: windowWidth,
714                                                 bottom: windowHeight,
715                                                 left: 0,
716                                                 width: windowWidth,
717                                                 height: windowHeight
718                                         },
719                                         toolbar = this.getEl(),
720                                         toolbarWidth = toolbar.offsetWidth,
721                                         toolbarHeight = toolbar.offsetHeight,
722                                         selection = currentSelection.getBoundingClientRect(),
723                                         selectionMiddle = ( selection.left + selection.right ) / 2,
724                                         buffer = 5,
725                                         margin = 8,
726                                         spaceNeeded = toolbarHeight + margin + buffer,
727                                         wpAdminbarBottom = wpAdminbar ? wpAdminbar.getBoundingClientRect().bottom : 0,
728                                         mceToolbarBottom = mceToolbar ? mceToolbar.getBoundingClientRect().bottom : 0,
729                                         mceStatusbarTop = mceStatusbar ? windowHeight - mceStatusbar.getBoundingClientRect().top : 0,
730                                         wpStatusbarTop = wpStatusbar ? windowHeight - wpStatusbar.getBoundingClientRect().top : 0,
731                                         blockedTop = Math.max( 0, wpAdminbarBottom, mceToolbarBottom, iframeRect.top ),
732                                         blockedBottom = Math.max( 0, mceStatusbarTop, wpStatusbarTop, windowHeight - iframeRect.bottom ),
733                                         spaceTop = selection.top + iframeRect.top - blockedTop,
734                                         spaceBottom = windowHeight - iframeRect.top - selection.bottom - blockedBottom,
735                                         editorHeight = windowHeight - blockedTop - blockedBottom,
736                                         className = '',
737                                         top, left;
738
739                                 if ( spaceTop >= editorHeight || spaceBottom >= editorHeight ) {
740                                         return this.hide();
741                                 }
742
743                                 if ( this.bottom ) {
744                                         if ( spaceBottom >= spaceNeeded ) {
745                                                 className = ' mce-arrow-up';
746                                                 top = selection.bottom + iframeRect.top + scrollY;
747                                         } else if ( spaceTop >= spaceNeeded ) {
748                                                 className = ' mce-arrow-down';
749                                                 top = selection.top + iframeRect.top + scrollY - toolbarHeight - margin;
750                                         }
751                                 } else {
752                                         if ( spaceTop >= spaceNeeded ) {
753                                                 className = ' mce-arrow-down';
754                                                 top = selection.top + iframeRect.top + scrollY - toolbarHeight - margin;
755                                         } else if ( spaceBottom >= spaceNeeded && editorHeight / 2 > selection.bottom + iframeRect.top - blockedTop ) {
756                                                 className = ' mce-arrow-up';
757                                                 top = selection.bottom + iframeRect.top + scrollY;
758                                         }
759                                 }
760
761                                 if ( typeof top === 'undefined' ) {
762                                         top = scrollY + blockedTop + buffer;
763                                 }
764
765                                 left = selectionMiddle - toolbarWidth / 2 + iframeRect.left + scrollX;
766
767                                 if ( selection.left < 0 || selection.right > iframeRect.width ) {
768                                         left = iframeRect.left + scrollX + ( iframeRect.width - toolbarWidth ) / 2;
769                                 } else if ( toolbarWidth >= windowWidth ) {
770                                         className += ' mce-arrow-full';
771                                         left = 0;
772                                 } else if ( ( left < 0 && selection.left + toolbarWidth > windowWidth ) || ( left + toolbarWidth > windowWidth && selection.right - toolbarWidth < 0 ) ) {
773                                         left = ( windowWidth - toolbarWidth ) / 2;
774                                 } else if ( left < iframeRect.left + scrollX ) {
775                                         className += ' mce-arrow-left';
776                                         left = selection.left + iframeRect.left + scrollX;
777                                 } else if ( left + toolbarWidth > iframeRect.width + iframeRect.left + scrollX ) {
778                                         className += ' mce-arrow-right';
779                                         left = selection.right - toolbarWidth + iframeRect.left + scrollX;
780                                 }
781
782                                 toolbar.className = toolbar.className.replace( / ?mce-arrow-[\w]+/g, '' ) + className;
783
784                                 DOM.setStyles( toolbar, {
785                                         'left': left,
786                                         'top': top
787                                 } );
788
789                                 return this;
790                         }
791
792                         toolbar.on( 'show', function() {
793                                 this.reposition();
794                         } );
795
796                         toolbar.on( 'keydown', function( event ) {
797                                 if ( event.keyCode === 27 ) {
798                                         this.hide();
799                                         editor.focus();
800                                 }
801                         } );
802
803                         editor.on( 'remove', function() {
804                                 toolbar.remove();
805                         } );
806
807                         toolbar.reposition = reposition;
808                         toolbar.hide().renderTo( document.body );
809
810                         return toolbar;
811                 }
812
813                 editor.shortcuts.add( 'alt+119', '', function() {
814                         var node;
815
816                         if ( activeToolbar ) {
817                                 node = activeToolbar.find( 'toolbar' )[0];
818                                 node && node.focus( true );
819                         }
820                 } );
821
822                 editor.on( 'nodechange', function( event ) {
823                         var collapsed = editor.selection.isCollapsed();
824
825                         var args = {
826                                 element: event.element,
827                                 parents: event.parents,
828                                 collapsed: collapsed
829                         };
830
831                         editor.fire( 'wptoolbar', args );
832
833                         currentSelection = args.selection || args.element;
834
835                         if ( activeToolbar ) {
836                                 activeToolbar.hide();
837                         }
838
839                         if ( args.toolbar ) {
840                                 activeToolbar = args.toolbar;
841                                 activeToolbar.show();
842                         } else {
843                                 activeToolbar = false;
844                         }
845                 } );
846
847                 editor.on( 'focus', function() {
848                         if ( activeToolbar ) {
849                                 activeToolbar.show();
850                         }
851                 } );
852
853                 function hide( event ) {
854                         if ( activeToolbar ) {
855                                 activeToolbar.hide();
856
857                                 if ( event.type === 'hide' ) {
858                                         activeToolbar = false;
859                                 } else if ( event.type === 'resize' || event.type === 'scroll' ) {
860                                         clearTimeout( timeout );
861
862                                         timeout = setTimeout( function() {
863                                                 if ( activeToolbar && typeof activeToolbar.show === 'function' ) {
864                                                         activeToolbar.show();
865                                                 }
866                                         }, 250 );
867                                 }
868                         }
869                 }
870
871                 DOM.bind( window, 'resize scroll', hide );
872                 editor.dom.bind( editor.getWin(), 'resize scroll', hide );
873
874                 editor.on( 'remove', function() {
875                         DOM.unbind( window, 'resize scroll', hide );
876                         editor.dom.unbind( editor.getWin(), 'resize scroll', hide );
877                 } );
878
879                 editor.on( 'blur hide', hide );
880
881                 editor.wp = editor.wp || {};
882                 editor.wp._createToolbar = create;
883         }, true );
884
885         function noop() {}
886
887         // Expose some functions (back-compat)
888         return {
889                 _showButtons: noop,
890                 _hideButtons: noop,
891                 _setEmbed: noop,
892                 _getEmbed: noop
893         };
894 });
895
896 }( window.tinymce ));