]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/quicktags.js
Wordpress 3.7
[autoinstalls/wordpress.git] / wp-includes / js / quicktags.js
1 /*
2  * Quicktags
3  *
4  * This is the HTML editor in WordPress. It can be attached to any textarea and will
5  * append a toolbar above it. This script is self-contained (does not require external libraries).
6  *
7  * Run quicktags(settings) to initialize it, where settings is an object containing up to 3 properties:
8  * settings = {
9  *   id : 'my_id',          the HTML ID of the textarea, required
10  *   buttons: ''            Comma separated list of the names of the default buttons to show. Optional.
11  *                          Current list of default button names: 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close';
12  * }
13  *
14  * The settings can also be a string quicktags_id.
15  *
16  * quicktags_id string The ID of the textarea that will be the editor canvas
17  * buttons string Comma separated list of the default buttons names that will be shown in that instance.
18  */
19
20 // new edit toolbar used with permission
21 // by Alex King
22 // http://www.alexking.org/
23
24 var QTags, edButtons = [], edCanvas,
25
26 /**
27  * Back-compat
28  *
29  * Define all former global functions so plugins that hack quicktags.js directly don't cause fatal errors.
30  */
31 edAddTag = function(){},
32 edCheckOpenTags = function(){},
33 edCloseAllTags = function(){},
34 edInsertImage = function(){},
35 edInsertLink = function(){},
36 edInsertTag = function(){},
37 edLink = function(){},
38 edQuickLink = function(){},
39 edRemoveTag = function(){},
40 edShowButton = function(){},
41 edShowLinks = function(){},
42 edSpell = function(){},
43 edToolbar = function(){};
44
45 /**
46  * Initialize new instance of the Quicktags editor
47  */
48 function quicktags(settings) {
49         return new QTags(settings);
50 }
51
52 /**
53  * Inserts content at the caret in the active editor (textarea)
54  *
55  * Added for back compatibility
56  * @see QTags.insertContent()
57  */
58 function edInsertContent(bah, txt) {
59         return QTags.insertContent(txt);
60 }
61
62 /**
63  * Adds a button to all instances of the editor
64  *
65  * Added for back compatibility, use QTags.addButton() as it gives more flexibility like type of button, button placement, etc.
66  * @see QTags.addButton()
67  */
68 function edButton(id, display, tagStart, tagEnd, access, open) {
69         return QTags.addButton( id, display, tagStart, tagEnd, access, '', -1 );
70 }
71
72 (function(){
73         // private stuff is prefixed with an underscore
74         var _domReady = function(func) {
75                 var t, i,  DOMContentLoaded;
76
77                 if ( typeof jQuery != 'undefined' ) {
78                         jQuery(document).ready(func);
79                 } else {
80                         t = _domReady;
81                         t.funcs = [];
82
83                         t.ready = function() {
84                                 if ( ! t.isReady ) {
85                                         t.isReady = true;
86                                         for ( i = 0; i < t.funcs.length; i++ ) {
87                                                 t.funcs[i]();
88                                         }
89                                 }
90                         };
91
92                         if ( t.isReady ) {
93                                 func();
94                         } else {
95                                 t.funcs.push(func);
96                         }
97
98                         if ( ! t.eventAttached ) {
99                                 if ( document.addEventListener ) {
100                                         DOMContentLoaded = function(){document.removeEventListener('DOMContentLoaded', DOMContentLoaded, false);t.ready();};
101                                         document.addEventListener('DOMContentLoaded', DOMContentLoaded, false);
102                                         window.addEventListener('load', t.ready, false);
103                                 } else if ( document.attachEvent ) {
104                                         DOMContentLoaded = function(){if (document.readyState === 'complete'){ document.detachEvent('onreadystatechange', DOMContentLoaded);t.ready();}};
105                                         document.attachEvent('onreadystatechange', DOMContentLoaded);
106                                         window.attachEvent('onload', t.ready);
107
108                                         (function(){
109                                                 try {
110                                                         document.documentElement.doScroll("left");
111                                                 } catch(e) {
112                                                         setTimeout(arguments.callee, 50);
113                                                         return;
114                                                 }
115
116                                                 t.ready();
117                                         })();
118                                 }
119
120                                 t.eventAttached = true;
121                         }
122                 }
123         },
124
125         _datetime = (function() {
126                 var now = new Date(), zeroise;
127
128                 zeroise = function(number) {
129                         var str = number.toString();
130
131                         if ( str.length < 2 )
132                                 str = "0" + str;
133
134                         return str;
135                 }
136
137                 return now.getUTCFullYear() + '-' +
138                         zeroise( now.getUTCMonth() + 1 ) + '-' +
139                         zeroise( now.getUTCDate() ) + 'T' +
140                         zeroise( now.getUTCHours() ) + ':' +
141                         zeroise( now.getUTCMinutes() ) + ':' +
142                         zeroise( now.getUTCSeconds() ) +
143                         '+00:00';
144         })(),
145         qt;
146
147         qt = QTags = function(settings) {
148                 if ( typeof(settings) == 'string' )
149                         settings = {id: settings};
150                 else if ( typeof(settings) != 'object' )
151                         return false;
152
153                 var t = this,
154                         id = settings.id,
155                         canvas = document.getElementById(id),
156                         name = 'qt_' + id,
157                         tb, onclick, toolbar_id;
158
159                 if ( !id || !canvas )
160                         return false;
161
162                 t.name = name;
163                 t.id = id;
164                 t.canvas = canvas;
165                 t.settings = settings;
166
167                 if ( id == 'content' && typeof(adminpage) == 'string' && ( adminpage == 'post-new-php' || adminpage == 'post-php' ) ) {
168                         // back compat hack :-(
169                         edCanvas = canvas;
170                         toolbar_id = 'ed_toolbar';
171                 } else {
172                         toolbar_id = name + '_toolbar';
173                 }
174
175                 tb = document.createElement('div');
176                 tb.id = toolbar_id;
177                 tb.className = 'quicktags-toolbar';
178
179                 canvas.parentNode.insertBefore(tb, canvas);
180                 t.toolbar = tb;
181
182                 // listen for click events
183                 onclick = function(e) {
184                         e = e || window.event;
185                         var target = e.target || e.srcElement, visible = target.clientWidth || target.offsetWidth, i;
186
187                         // don't call the callback on pressing the accesskey when the button is not visible
188                         if ( !visible )
189                                 return;
190
191                         // as long as it has the class ed_button, execute the callback
192                         if ( / ed_button /.test(' ' + target.className + ' ') ) {
193                                 // we have to reassign canvas here
194                                 t.canvas = canvas = document.getElementById(id);
195                                 i = target.id.replace(name + '_', '');
196
197                                 if ( t.theButtons[i] )
198                                         t.theButtons[i].callback.call(t.theButtons[i], target, canvas, t);
199                         }
200                 };
201
202                 if ( tb.addEventListener ) {
203                         tb.addEventListener('click', onclick, false);
204                 } else if ( tb.attachEvent ) {
205                         tb.attachEvent('onclick', onclick);
206                 }
207
208                 t.getButton = function(id) {
209                         return t.theButtons[id];
210                 };
211
212                 t.getButtonElement = function(id) {
213                         return document.getElementById(name + '_' + id);
214                 };
215
216                 qt.instances[id] = t;
217
218                 if ( !qt.instances[0] ) {
219                         qt.instances[0] = qt.instances[id];
220                         _domReady( function(){ qt._buttonsInit(); } );
221                 }
222         };
223
224         qt.instances = {};
225
226         qt.getInstance = function(id) {
227                 return qt.instances[id];
228         };
229
230         qt._buttonsInit = function() {
231                 var t = this, canvas, name, settings, theButtons, html, inst, ed, id, i, use,
232                         defaults = ',strong,em,link,block,del,ins,img,ul,ol,li,code,more,close,';
233
234                 for ( inst in t.instances ) {
235                         if ( inst == 0 )
236                                 continue;
237
238                         ed = t.instances[inst];
239                         canvas = ed.canvas;
240                         name = ed.name;
241                         settings = ed.settings;
242                         html = '';
243                         theButtons = {};
244                         use = '';
245
246                         // set buttons
247                         if ( settings.buttons )
248                                 use = ','+settings.buttons+',';
249
250                         for ( i in edButtons ) {
251                                 if ( !edButtons[i] )
252                                         continue;
253
254                                 id = edButtons[i].id;
255                                 if ( use && defaults.indexOf(','+id+',') != -1 && use.indexOf(','+id+',') == -1 )
256                                         continue;
257
258                                 if ( !edButtons[i].instance || edButtons[i].instance == inst ) {
259                                         theButtons[id] = edButtons[i];
260
261                                         if ( edButtons[i].html )
262                                                 html += edButtons[i].html(name + '_');
263                                 }
264                         }
265
266                         if ( use && use.indexOf(',fullscreen,') != -1 ) {
267                                 theButtons['fullscreen'] = new qt.FullscreenButton();
268                                 html += theButtons['fullscreen'].html(name + '_');
269                         }
270
271
272                         if ( 'rtl' == document.getElementsByTagName('html')[0].dir ) {
273                                 theButtons['textdirection'] = new qt.TextDirectionButton();
274                                 html += theButtons['textdirection'].html(name + '_');
275                         }
276
277                         ed.toolbar.innerHTML = html;
278                         ed.theButtons = theButtons;
279                 }
280                 t.buttonsInitDone = true;
281         };
282
283         /**
284          * Main API function for adding a button to Quicktags
285          *
286          * Adds qt.Button or qt.TagButton depending on the args. The first three args are always required.
287          * To be able to add button(s) to Quicktags, your script should be enqueued as dependent
288          * on "quicktags" and outputted in the footer. If you are echoing JS directly from PHP,
289          * use add_action( 'admin_print_footer_scripts', 'output_my_js', 100 ) or add_action( 'wp_footer', 'output_my_js', 100 )
290          *
291          * Minimum required to add a button that calls an external function:
292          *     QTags.addButton( 'my_id', 'my button', my_callback );
293          *     function my_callback() { alert('yeah!'); }
294          *
295          * Minimum required to add a button that inserts a tag:
296          *     QTags.addButton( 'my_id', 'my button', '<span>', '</span>' );
297          *     QTags.addButton( 'my_id2', 'my button', '<br />' );
298          *
299          * @param string id Required. Button HTML ID
300          * @param string display Required. Button's value="..."
301          * @param string|function arg1 Required. Either a starting tag to be inserted like "<span>" or a callback that is executed when the button is clicked.
302          * @param string arg2 Optional. Ending tag like "</span>"
303          * @param string access_key Optional. Access key for the button.
304          * @param string title Optional. Button's title="..."
305          * @param int priority Optional. Number representing the desired position of the button in the toolbar. 1 - 9 = first, 11 - 19 = second, 21 - 29 = third, etc.
306          * @param string instance Optional. Limit the button to a specifric instance of Quicktags, add to all instances if not present.
307          * @return mixed null or the button object that is needed for back-compat.
308          */
309         qt.addButton = function( id, display, arg1, arg2, access_key, title, priority, instance ) {
310                 var btn;
311
312                 if ( !id || !display )
313                         return;
314
315                 priority = priority || 0;
316                 arg2 = arg2 || '';
317
318                 if ( typeof(arg1) === 'function' ) {
319                         btn = new qt.Button(id, display, access_key, title, instance);
320                         btn.callback = arg1;
321                 } else if ( typeof(arg1) === 'string' ) {
322                         btn = new qt.TagButton(id, display, arg1, arg2, access_key, title, instance);
323                 } else {
324                         return;
325                 }
326
327                 if ( priority == -1 ) // back-compat
328                         return btn;
329
330                 if ( priority > 0 ) {
331                         while ( typeof(edButtons[priority]) != 'undefined' ) {
332                                 priority++
333                         }
334
335                         edButtons[priority] = btn;
336                 } else {
337                         edButtons[edButtons.length] = btn;
338                 }
339
340                 if ( this.buttonsInitDone )
341                         this._buttonsInit(); // add the button HTML to all instances toolbars if addButton() was called too late
342         };
343
344         qt.insertContent = function(content) {
345                 var sel, startPos, endPos, scrollTop, text, canvas = document.getElementById(wpActiveEditor);
346
347                 if ( !canvas )
348                         return false;
349
350                 if ( document.selection ) { //IE
351                         canvas.focus();
352                         sel = document.selection.createRange();
353                         sel.text = content;
354                         canvas.focus();
355                 } else if ( canvas.selectionStart || canvas.selectionStart == '0' ) { // FF, WebKit, Opera
356                         text = canvas.value;
357                         startPos = canvas.selectionStart;
358                         endPos = canvas.selectionEnd;
359                         scrollTop = canvas.scrollTop;
360
361                         canvas.value = text.substring(0, startPos) + content + text.substring(endPos, text.length);
362
363                         canvas.focus();
364                         canvas.selectionStart = startPos + content.length;
365                         canvas.selectionEnd = startPos + content.length;
366                         canvas.scrollTop = scrollTop;
367                 } else {
368                         canvas.value += content;
369                         canvas.focus();
370                 }
371                 return true;
372         };
373
374         // a plain, dumb button
375         qt.Button = function(id, display, access, title, instance) {
376                 var t = this;
377                 t.id = id;
378                 t.display = display;
379                 t.access = access;
380                 t.title = title || '';
381                 t.instance = instance || '';
382         };
383         qt.Button.prototype.html = function(idPrefix) {
384                 var access = this.access ? ' accesskey="' + this.access + '"' : '';
385                 return '<input type="button" id="' + idPrefix + this.id + '"' + access + ' class="ed_button" title="' + this.title + '" value="' + this.display + '" />';
386         };
387         qt.Button.prototype.callback = function(){};
388
389         // a button that inserts HTML tag
390         qt.TagButton = function(id, display, tagStart, tagEnd, access, title, instance) {
391                 var t = this;
392                 qt.Button.call(t, id, display, access, title, instance);
393                 t.tagStart = tagStart;
394                 t.tagEnd = tagEnd;
395         };
396         qt.TagButton.prototype = new qt.Button();
397         qt.TagButton.prototype.openTag = function(e, ed) {
398                 var t = this;
399
400                 if ( ! ed.openTags ) {
401                         ed.openTags = [];
402                 }
403                 if ( t.tagEnd ) {
404                         ed.openTags.push(t.id);
405                         e.value = '/' + e.value;
406                 }
407         };
408         qt.TagButton.prototype.closeTag = function(e, ed) {
409                 var t = this, i = t.isOpen(ed);
410
411                 if ( i !== false ) {
412                         ed.openTags.splice(i, 1);
413                 }
414
415                 e.value = t.display;
416         };
417         // whether a tag is open or not. Returns false if not open, or current open depth of the tag
418         qt.TagButton.prototype.isOpen = function (ed) {
419                 var t = this, i = 0, ret = false;
420                 if ( ed.openTags ) {
421                         while ( ret === false && i < ed.openTags.length ) {
422                                 ret = ed.openTags[i] == t.id ? i : false;
423                                 i ++;
424                         }
425                 } else {
426                         ret = false;
427                 }
428                 return ret;
429         };
430         qt.TagButton.prototype.callback = function(element, canvas, ed) {
431                 var t = this, startPos, endPos, cursorPos, scrollTop, v = canvas.value, l, r, i, sel, endTag = v ? t.tagEnd : '';
432
433                 if ( document.selection ) { // IE
434                         canvas.focus();
435                         sel = document.selection.createRange();
436                         if ( sel.text.length > 0 ) {
437                                 if ( !t.tagEnd )
438                                         sel.text = sel.text + t.tagStart;
439                                 else
440                                         sel.text = t.tagStart + sel.text + endTag;
441                         } else {
442                                 if ( !t.tagEnd ) {
443                                         sel.text = t.tagStart;
444                                 } else if ( t.isOpen(ed) === false ) {
445                                         sel.text = t.tagStart;
446                                         t.openTag(element, ed);
447                                 } else {
448                                         sel.text = endTag;
449                                         t.closeTag(element, ed);
450                                 }
451                         }
452                         canvas.focus();
453                 } else if ( canvas.selectionStart || canvas.selectionStart == '0' ) { // FF, WebKit, Opera
454                         startPos = canvas.selectionStart;
455                         endPos = canvas.selectionEnd;
456                         cursorPos = endPos;
457                         scrollTop = canvas.scrollTop;
458                         l = v.substring(0, startPos); // left of the selection
459                         r = v.substring(endPos, v.length); // right of the selection
460                         i = v.substring(startPos, endPos); // inside the selection
461                         if ( startPos != endPos ) {
462                                 if ( !t.tagEnd ) {
463                                         canvas.value = l + i + t.tagStart + r; // insert self closing tags after the selection
464                                         cursorPos += t.tagStart.length;
465                                 } else {
466                                         canvas.value = l + t.tagStart + i + endTag + r;
467                                         cursorPos += t.tagStart.length + endTag.length;
468                                 }
469                         } else {
470                                 if ( !t.tagEnd ) {
471                                         canvas.value = l + t.tagStart + r;
472                                         cursorPos = startPos + t.tagStart.length;
473                                 } else if ( t.isOpen(ed) === false ) {
474                                         canvas.value = l + t.tagStart + r;
475                                         t.openTag(element, ed);
476                                         cursorPos = startPos + t.tagStart.length;
477                                 } else {
478                                         canvas.value = l + endTag + r;
479                                         cursorPos = startPos + endTag.length;
480                                         t.closeTag(element, ed);
481                                 }
482                         }
483
484                         canvas.focus();
485                         canvas.selectionStart = cursorPos;
486                         canvas.selectionEnd = cursorPos;
487                         canvas.scrollTop = scrollTop;
488                 } else { // other browsers?
489                         if ( !endTag ) {
490                                 canvas.value += t.tagStart;
491                         } else if ( t.isOpen(ed) !== false ) {
492                                 canvas.value += t.tagStart;
493                                 t.openTag(element, ed);
494                         } else {
495                                 canvas.value += endTag;
496                                 t.closeTag(element, ed);
497                         }
498                         canvas.focus();
499                 }
500         };
501
502         // removed
503         qt.SpellButton = function() {};
504
505         // the close tags button
506         qt.CloseButton = function() {
507                 qt.Button.call(this, 'close', quicktagsL10n.closeTags, '', quicktagsL10n.closeAllOpenTags);
508         };
509
510         qt.CloseButton.prototype = new qt.Button();
511
512         qt._close = function(e, c, ed) {
513                 var button, element, tbo = ed.openTags;
514
515                 if ( tbo ) {
516                         while ( tbo.length > 0 ) {
517                                 button = ed.getButton(tbo[tbo.length - 1]);
518                                 element = document.getElementById(ed.name + '_' + button.id);
519
520                                 if ( e )
521                                         button.callback.call(button, element, c, ed);
522                                 else
523                                         button.closeTag(element, ed);
524                         }
525                 }
526         };
527
528         qt.CloseButton.prototype.callback = qt._close;
529
530         qt.closeAllTags = function(editor_id) {
531                 var ed = this.getInstance(editor_id);
532                 qt._close('', ed.canvas, ed);
533         };
534
535         // the link button
536         qt.LinkButton = function() {
537                 qt.TagButton.call(this, 'link', 'link', '', '</a>', 'a');
538         };
539         qt.LinkButton.prototype = new qt.TagButton();
540         qt.LinkButton.prototype.callback = function(e, c, ed, defaultValue) {
541                 var URL, t = this;
542
543                 if ( typeof(wpLink) != 'undefined' ) {
544                         wpLink.open();
545                         return;
546                 }
547
548                 if ( ! defaultValue )
549                         defaultValue = 'http://';
550
551                 if ( t.isOpen(ed) === false ) {
552                         URL = prompt(quicktagsL10n.enterURL, defaultValue);
553                         if ( URL ) {
554                                 t.tagStart = '<a href="' + URL + '">';
555                                 qt.TagButton.prototype.callback.call(t, e, c, ed);
556                         }
557                 } else {
558                         qt.TagButton.prototype.callback.call(t, e, c, ed);
559                 }
560         };
561
562         // the img button
563         qt.ImgButton = function() {
564                 qt.TagButton.call(this, 'img', 'img', '', '', 'm');
565         };
566         qt.ImgButton.prototype = new qt.TagButton();
567         qt.ImgButton.prototype.callback = function(e, c, ed, defaultValue) {
568                 if ( ! defaultValue ) {
569                         defaultValue = 'http://';
570                 }
571                 var src = prompt(quicktagsL10n.enterImageURL, defaultValue), alt;
572                 if ( src ) {
573                         alt = prompt(quicktagsL10n.enterImageDescription, '');
574                         this.tagStart = '<img src="' + src + '" alt="' + alt + '" />';
575                         qt.TagButton.prototype.callback.call(this, e, c, ed);
576                 }
577         };
578
579         qt.FullscreenButton = function() {
580                 qt.Button.call(this, 'fullscreen', quicktagsL10n.fullscreen, 'f', quicktagsL10n.toggleFullscreen);
581         };
582         qt.FullscreenButton.prototype = new qt.Button();
583         qt.FullscreenButton.prototype.callback = function(e, c) {
584                 if ( !c.id || typeof(fullscreen) == 'undefined' )
585                         return;
586
587                 fullscreen.on();
588         };
589
590         qt.TextDirectionButton = function() {
591                 qt.Button.call(this, 'textdirection', quicktagsL10n.textdirection, '', quicktagsL10n.toggleTextdirection)
592         };
593         qt.TextDirectionButton.prototype = new qt.Button();
594         qt.TextDirectionButton.prototype.callback = function(e, c) {
595                 var isRTL = ( 'rtl' == document.getElementsByTagName('html')[0].dir ),
596                         currentDirection = c.style.direction;
597
598                 if ( ! currentDirection )
599                         currentDirection = ( isRTL ) ? 'rtl' : 'ltr';
600
601                 c.style.direction = ( 'rtl' == currentDirection ) ? 'ltr' : 'rtl';
602                 c.focus();
603         }
604
605         // ensure backward compatibility
606         edButtons[10] = new qt.TagButton('strong','b','<strong>','</strong>','b');
607         edButtons[20] = new qt.TagButton('em','i','<em>','</em>','i'),
608         edButtons[30] = new qt.LinkButton(), // special case
609         edButtons[40] = new qt.TagButton('block','b-quote','\n\n<blockquote>','</blockquote>\n\n','q'),
610         edButtons[50] = new qt.TagButton('del','del','<del datetime="' + _datetime + '">','</del>','d'),
611         edButtons[60] = new qt.TagButton('ins','ins','<ins datetime="' + _datetime + '">','</ins>','s'),
612         edButtons[70] = new qt.ImgButton(), // special case
613         edButtons[80] = new qt.TagButton('ul','ul','<ul>\n','</ul>\n\n','u'),
614         edButtons[90] = new qt.TagButton('ol','ol','<ol>\n','</ol>\n\n','o'),
615         edButtons[100] = new qt.TagButton('li','li','\t<li>','</li>\n','l'),
616         edButtons[110] = new qt.TagButton('code','code','<code>','</code>','c'),
617         edButtons[120] = new qt.TagButton('more','more','<!--more-->','','t'),
618         edButtons[140] = new qt.CloseButton()
619
620 })();